diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c6dfb0ebda4..fb542222c0d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,7 @@ # web + desktop packages packages/app/ @Hona @Brendonovich packages/desktop/ @Hona @Brendonovich + +# CI and releases. Release jobs that hold secrets run only .github/workflows/release.yml and .github/release/, +# which makes this path the release security boundary. +/.github/ @anomalyco/ci-owners diff --git a/.github/publish-python-sdk.yml b/.github/publish-python-sdk.yml deleted file mode 100644 index 151ecb9944b..00000000000 --- a/.github/publish-python-sdk.yml +++ /dev/null @@ -1,71 +0,0 @@ -# -# This file is intentionally in the wrong dir, will move and add later.... -# - -# name: publish-python-sdk - -# on: -# release: -# types: [published] -# workflow_dispatch: - -# jobs: -# publish: -# runs-on: ubuntu-latest -# permissions: -# contents: read -# steps: -# - name: Checkout repository -# uses: actions/checkout@v4 - -# - name: Setup Bun -# uses: oven-sh/setup-bun@v1 -# with: -# bun-version: 1.2.21 - -# - name: Install dependencies (JS/Bun) -# run: bun install - -# - name: Install uv -# shell: bash -# run: curl -LsSf https://astral.sh/uv/install.sh | sh - -# - name: Generate Python SDK from OpenAPI (CLI) -# shell: bash -# run: | -# ~/.local/bin/uv run --project packages/sdk/python python packages/sdk/python/scripts/generate.py --source cli - -# - name: Sync Python dependencies -# shell: bash -# run: | -# ~/.local/bin/uv sync --dev --project packages/sdk/python - -# - name: Set version from release tag -# shell: bash -# run: | -# TAG="${GITHUB_REF_NAME:-}" -# if [ -z "$TAG" ]; then -# TAG="$(git describe --tags --abbrev=0 || echo 0.0.0)" -# fi -# echo "Using version: $TAG" -# VERSION="$TAG" ~/.local/bin/uv run --project packages/sdk/python python - <<'PY' -# import os, re, pathlib -# root = pathlib.Path('packages/sdk/python') -# pt = (root / 'pyproject.toml').read_text() -# version = os.environ.get('VERSION','0.0.0').lstrip('v') -# pt = re.sub(r'(?m)^(version\s*=\s*")[^"]+("\s*)$', f"\\1{version}\\2", pt) -# (root / 'pyproject.toml').write_text(pt) -# # Also update generator config override for consistency -# cfgp = root / 'openapi-python-client.yaml' -# if cfgp.exists(): -# cfg = cfgp.read_text() -# cfg = re.sub(r'(?m)^(package_version_override:\s*)\S+$', f"\\1{version}", cfg) -# cfgp.write_text(cfg) -# PY - -# - name: Build and publish to PyPI -# env: -# PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} -# shell: bash -# run: | -# ~/.local/bin/uv run --project packages/sdk/python python packages/sdk/python/scripts/publish.py diff --git a/.github/release/download/action.yml b/.github/release/download/action.yml new file mode 100644 index 00000000000..de159d799b1 --- /dev/null +++ b/.github/release/download/action.yml @@ -0,0 +1,21 @@ +name: Download release artifacts +description: Downloads artifacts into $RUNNER_TEMP/in/ and verifies each against its SHA256SUMS. +inputs: + pattern: + description: Artifact name pattern + required: true + digests: + description: Space-separated name=digest pairs for artifacts made by sign jobs, from their job outputs + required: false + default: "" +runs: + using: composite + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: ${{ inputs.pattern }} + path: ${{ runner.temp }}/in + - shell: bash + run: bash "${GITHUB_ACTION_PATH//\\//}/../verify-artifacts.sh" "$RUNNER_TEMP/in" + env: + OPENCODE_DIGESTS: ${{ inputs.digests }} diff --git a/packages/cli/script/entitlements.plist b/.github/release/entitlements/cli.plist similarity index 100% rename from packages/cli/script/entitlements.plist rename to .github/release/entitlements/cli.plist diff --git a/packages/desktop/resources/entitlements.cli.plist b/.github/release/entitlements/desktop-cli.plist similarity index 100% rename from packages/desktop/resources/entitlements.cli.plist rename to .github/release/entitlements/desktop-cli.plist diff --git a/packages/desktop/resources/entitlements.plist b/.github/release/entitlements/desktop.plist similarity index 100% rename from packages/desktop/resources/entitlements.plist rename to .github/release/entitlements/desktop.plist diff --git a/.github/release/lib.sh b/.github/release/lib.sh new file mode 100644 index 00000000000..de0d95b0f48 --- /dev/null +++ b/.github/release/lib.sh @@ -0,0 +1,109 @@ +# Shared helpers for the release scripts. Sourced, never executed. +# +# These scripts run in sign and publish jobs that hold secrets. They must never execute repository code +# or artifact contents: artifacts are data, and every value that names a destination comes from the +# environment the workflow sets (OPENCODE_VERSION, OPENCODE_CHANNEL, OPENCODE_DRY_RUN, ...). + +set -euo pipefail + +# shellcheck disable=SC2034 # used by the scripts that source this file +release_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) + +die() { + echo "::error::$*" >&2 + exit 1 +} + +dry_run() { + [ "${OPENCODE_DRY_RUN:-false}" = true ] +} + +sha256() { + if command -v sha256sum > /dev/null; then sha256sum "$@"; else shasum -a 256 "$@"; fi +} + +# Windows runners pass D:\a\_temp style paths; Git Bash tools want /d/a/_temp. +posix() { + if command -v cygpath > /dev/null; then cygpath -u "$1"; else printf '%s' "$1"; fi +} + +size() { + wc -c < "$1" | tr -d ' ' +} + +# Uploads files to opencode.ai/files/bin// and prints the update-server file map. +upload_files() { + local credentials=false + for file in "$@"; do + test -s "$file" || die "Missing release file: $file" + local name type + name=$(basename "$file") + case "$name" in + *.tar.gz) type=application/gzip ;; + *.zip) type=application/zip ;; + *) type=application/octet-stream ;; + esac + if dry_run; then + echo "dry-run upload: bin/$OPENCODE_VERSION/$name" >&2 + else + if [ "$credentials" = false ]; then + r2_credentials + credentials=true + fi + aws s3 cp "$file" "s3://opencode-production-files/bin/$OPENCODE_VERSION/$name" --only-show-errors \ + --endpoint-url "https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com" \ + --content-type "$type" --content-disposition "attachment; filename=\"$name\"" \ + --cache-control "public, max-age=31536000, immutable" >&2 + fi + jq -n --arg name "$name" --arg url "https://opencode.ai/files/bin/$OPENCODE_VERSION/$name" \ + --arg sha256 "$(sha256 "$file" | cut -c1-64)" --argjson size "$(size "$file")" \ + '{($name): {url: $url, sha256: $sha256, size: $size}}' + done | jq -s 'add' +} + +# R2 accepts the API token ID as the access key and SHA-256(token) as the secret. +r2_credentials() { + local id + id=$(curl -fsS -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/tokens/verify" | jq -er .result.id) + export AWS_ACCESS_KEY_ID="$id" + AWS_SECRET_ACCESS_KEY=$(printf '%s' "$CLOUDFLARE_API_TOKEN" | sha256 | cut -c1-64) + export AWS_SECRET_ACCESS_KEY + export AWS_DEFAULT_REGION=auto AWS_REQUEST_CHECKSUM_CALCULATION=when_required AWS_RESPONSE_CHECKSUM_VALIDATION=when_required +} + +# Registers one artifact with the update server: publish_update . +publish_update() { + local body status token attempt + body=$(jq -n --arg channel "$OPENCODE_CHANNEL" --arg version "$OPENCODE_VERSION" --arg name "$1" --arg distribution "$2" \ + --argjson metadata "$3" '{channel: $channel, name: $name, distribution: $distribution, version: $version, metadata: $metadata}') + echo "$body" | jq . + if dry_run; then return; fi + token=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ + "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://update.opencode.ai" | jq -er .value) + for attempt in 1 2 3; do + status=$(curl -sS -o "$RUNNER_TEMP/update-response" -w '%{http_code}' -X POST https://opencode.ai/update/api/publish \ + -H "Authorization: Bearer $token" -H "Content-Type: application/json" --data "$body") + if [ "$status" -lt 300 ]; then return; fi + cat "$RUNNER_TEMP/update-response" + # D1 can commit the upsert and still time out. Replaying the same artifact is safe. + if [ "$status" -lt 500 ] || [ "$attempt" = 3 ]; then die "Update server returned $status"; fi + sleep "$attempt" + done +} + +# Clones a repository, lets a render script fill it, then commits and pushes any change: +# push_git [args...]. Dry runs render into an empty directory. +push_git() { + local url=$1 message=$2 dir + shift 2 + dir=$(mktemp -d) + if ! dry_run; then git clone -q "$url" "$dir"; fi + "$@" "$dir" + if dry_run; then return; fi + git -C "$dir" add -A + if git -C "$dir" diff --cached --quiet; then return; fi + git -C "$dir" -c user.name="opencode-agent[bot]" -c user.email="opencode-agent[bot]@users.noreply.github.com" \ + commit -q -m "$message" + git -C "$dir" push -q origin HEAD:master +} diff --git a/.github/release/plan-release.sh b/.github/release/plan-release.sh new file mode 100755 index 00000000000..3c069a7508f --- /dev/null +++ b/.github/release/plan-release.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# plan-release.sh: decides version, channel and npm dist-tag from the event, ref and dispatch inputs +# (INPUT_BUMP, INPUT_VERSION) only, and writes them to $GITHUB_OUTPUT. Nothing here reads repository files. +# +# push or dispatch on dev -> dev 0.0.0-dev- npm tag dev +# dispatch on dev with bump/version -> latest x.y.z npm tag latest +# push or dispatch on beta -> beta 0.0.0-beta- desktop only +# pull_request -> pr 0.0.0-pr- everything, dry run +. "$(dirname "$0")/lib.sh" + +versioned=false +if [ -n "${INPUT_BUMP:-}" ] || [ -n "${INPUT_VERSION:-}" ]; then versioned=true; fi +case "$GITHUB_EVENT_NAME:$GITHUB_REF:$versioned" in + push:refs/heads/dev:false | workflow_dispatch:refs/heads/dev:false) channel="dev" ;; + workflow_dispatch:refs/heads/dev:true) channel="latest" ;; + push:refs/heads/beta:false | workflow_dispatch:refs/heads/beta:false) channel="beta" ;; + pull_request:*:false) channel="pr" ;; + *) die "$GITHUB_EVENT_NAME on $GITHUB_REF cannot publish (versioned: $versioned)" ;; +esac + +if [ "$channel" = latest ] && [ -n "${INPUT_VERSION:-}" ]; then + version=$INPUT_VERSION +elif [ "$channel" = latest ]; then + current=$(curl -fsS https://registry.npmjs.org/-/package/@opencode%2fcli/dist-tags | jq -r .latest) + [[ "$current" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] || die "Unexpected latest version: $current" + major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]} + case "$INPUT_BUMP" in + major) version="$((major + 1)).0.0" ;; + minor) version="$major.$((minor + 1)).0" ;; + *) version="$major.$minor.$((patch + 1))" ;; + esac + if [ "$major" -lt 2 ]; then version=2.0.0; fi +else + version="0.0.0-$channel-$GITHUB_RUN_NUMBER" + if [ "$GITHUB_RUN_ATTEMPT" != 1 ]; then version="$version.$GITHUB_RUN_ATTEMPT"; fi +fi + +if [ "$channel" = latest ]; then + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || [[ "$version" == 0.0.0-* ]]; then + die "Invalid release version: $version" + fi + status=$(curl -sS -o /dev/null -w '%{http_code}' "https://registry.npmjs.org/@opencode%2fcli/$version") + [ "$status" != 200 ] || die "@opencode/cli@$version is already published" +fi + +# What each channel builds and publishes. +case "$channel" in + latest) npm_tag=latest cli=true desktop=true node=false release=true ;; + dev) npm_tag=dev cli=true desktop=false node=true release=false ;; + beta) npm_tag="" cli=false desktop=true node=false release=false ;; + pr) npm_tag=pr cli=true desktop=true node=true release=true ;; +esac +dry_run=false +if [ "$channel" = pr ]; then dry_run=true; fi + +{ + echo "version=$version" + echo "channel=$channel" + echo "npm_tag=$npm_tag" + echo "dry_run=$dry_run" + echo "cli=$cli" + echo "desktop=$desktop" + echo "node=$node" + echo "release=$release" +} | tee -a "$GITHUB_OUTPUT" diff --git a/.github/release/publish-aur.sh b/.github/release/publish-aur.sh new file mode 100755 index 00000000000..3d1a8ec1912 --- /dev/null +++ b/.github/release/publish-aur.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# publish-aur.sh : updates opencode-beta on the AUR over SSH (AUR_KEY, pinned host key) and +# registers the aur update artifact. +. "$(dirname "$0")/lib.sh" + +if ! dry_run; then + mkdir -p ~/.ssh + printf '%s\n' "$AUR_KEY" > ~/.ssh/aur + chmod 600 ~/.ssh/aur + echo "aur.archlinux.org ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEuBKrPzbawxA/k2g6NcyV5jmqwJ2s+zpgZGZ7tpLIcN" > ~/.ssh/known_hosts + export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/aur -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes" +fi +push_git ssh://aur@aur.archlinux.org/opencode-beta.git "chore: update opencode-beta to ${OPENCODE_VERSION//-/.}" \ + bash "$release_dir/render-aur.sh" "$1" +publish_update cli aur '{"package": "opencode-beta"}' diff --git a/.github/release/publish-cli.sh b/.github/release/publish-cli.sh new file mode 100755 index 00000000000..de398ebbc2f --- /dev/null +++ b/.github/release/publish-cli.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# publish-cli.sh : uploads the standalone CLI +# archives to opencode.ai/files and registers the cli (and, off latest, cli-node) update artifacts. +. "$(dirname "$0")/lib.sh" + +archives=$1 macos=$2 windows=$3 +cli=() +for target in linux-arm64 linux-x64 linux-x64-baseline linux-arm64-musl linux-x64-musl linux-x64-baseline-musl; do cli+=("$archives/opencode-$target.tar.gz"); done +for target in darwin-arm64 darwin-x64 darwin-x64-baseline; do cli+=("$macos/opencode-$target.zip"); done +for target in windows-arm64 windows-x64 windows-x64-baseline; do cli+=("$windows/opencode-$target.zip"); done + +files=$(upload_files "${cli[@]}") +publish_update cli npm '{"package": "@opencode/cli"}' +publish_update cli opencode "$(jq -n --argjson files "$files" '{files: $files}')" + +if [ "$OPENCODE_CHANNEL" != latest ]; then + node=() + for target in linux-arm64 linux-x64; do node+=("$archives/opencode2-node-$target.tar.gz"); done + for target in darwin-arm64 windows-arm64 windows-x64; do node+=("$archives/opencode2-node-$target.zip"); done + files=$(upload_files "${node[@]}") + publish_update cli-node npm '{"package": "@opencode/cli-node"}' + publish_update cli-node opencode "$(jq -n --argjson files "$files" '{files: $files}')" +fi diff --git a/.github/release/publish-desktop.sh b/.github/release/publish-desktop.sh new file mode 100755 index 00000000000..75aa5a12c93 --- /dev/null +++ b/.github/release/publish-desktop.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# publish-desktop.sh +# : uploads the desktop builds to opencode.ai/files and registers the desktop update +# artifact. The electron-updater feeds (latest*.yml) are computed here from the final signed files. +. "$(dirname "$0")/lib.sh" + +macos=$1 windows=$2 linux_x64=$3 linux_arm64=$4 +win=("$windows/opencode-desktop-win-arm64.exe" "$windows/opencode-desktop-win-x64.exe") +mac=("$macos/opencode-desktop-mac-arm64.zip" "$macos/opencode-desktop-mac-arm64.dmg" "$macos/opencode-desktop-mac-x64.zip" "$macos/opencode-desktop-mac-x64.dmg") +linux=("$linux_x64/opencode-desktop-linux-x86_64.AppImage" "$linux_x64/opencode-desktop-linux-amd64.deb" "$linux_x64/opencode-desktop-linux-x86_64.rpm") +linux_arm=("$linux_arm64/opencode-desktop-linux-arm64.AppImage" "$linux_arm64/opencode-desktop-linux-arm64.deb" "$linux_arm64/opencode-desktop-linux-aarch64.rpm") +# Beta skips the .app.tar.gz, which only the retired Tauri updater feed read. +bundles=() +if [ "$OPENCODE_CHANNEL" != beta ]; then + bundles=("$macos/opencode-desktop-mac-arm64.app.tar.gz" "$macos/opencode-desktop-mac-x64.app.tar.gz") +fi + +feed() { + for file in "$@"; do + jq -n --arg url "https://opencode.ai/files/bin/$OPENCODE_VERSION/$(basename "$file")" \ + --arg sha512 "$(openssl dgst -sha512 -binary "$file" | base64 | tr -d '\n')" --argjson size "$(size "$file")" \ + '{url: $url, sha512: $sha512, size: $size}' + done | jq -s --arg date "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" '{files: ., releaseDate: $date}' +} + +files=$(upload_files "${win[@]}" "${mac[@]}" "${linux[@]}" "${linux_arm[@]}" "${bundles[@]}") +manifests=$(jq -n --argjson win "$(feed "${win[@]}")" --argjson mac "$(feed "${mac[@]}")" \ + --argjson linux "$(feed "${linux[@]}")" --argjson linux_arm64 "$(feed "${linux_arm[@]}")" \ + '{"desktop.yml": $win, "desktop-mac.yml": $mac, "desktop-linux.yml": $linux, "desktop-linux-arm64.yml": $linux_arm64}') +publish_update desktop opencode "$(jq -n --argjson files "$files" --argjson manifests "$manifests" '{files: $files, manifests: $manifests}')" diff --git a/.github/release/publish-docker.sh b/.github/release/publish-docker.sh new file mode 100755 index 00000000000..d6702fde29e --- /dev/null +++ b/.github/release/publish-docker.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# publish-docker.sh : pushes the multi-arch OCI image to ghcr.io/anomalyco/opencode: +# without building anything (GH_TOKEN with packages: write). +. "$(dirname "$0")/lib.sh" + +image="$1/opencode-image.tar" +skopeo inspect --raw "oci-archive:$image" | jq . +if dry_run; then exit 0; fi +printf '%s' "$GH_TOKEN" | skopeo login ghcr.io --username "$GITHUB_ACTOR" --password-stdin +skopeo copy --all "oci-archive:$image" "docker://ghcr.io/anomalyco/opencode:$OPENCODE_VERSION" diff --git a/.github/release/publish-github-release.sh b/.github/release/publish-github-release.sh new file mode 100755 index 00000000000..f57963dd448 --- /dev/null +++ b/.github/release/publish-github-release.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# publish-github-release.sh ...: attaches the CLI archives and desktop builds in the given artifact dirs, plus +# a SHA256SUMS, to the v GitHub release with OPENCODE_RELEASE_NOTES. Immutable releases lock assets once +# published, so they go to a draft first. +. "$(dirname "$0")/lib.sh" + +assets=$(mktemp -d) +for dir in "$@"; do + find "$dir" -maxdepth 1 -type f \( -name 'opencode-*.zip' -o -name 'opencode-*.tar.gz' -o -name 'opencode-desktop-*' \) \ + ! -name '*.tgz' ! -name '*.app.tar' -exec cp {} "$assets/" \; +done +(cd "$assets" && sha256 -- * > SHA256SUMS && cat SHA256SUMS) +printf '%s\n' "${OPENCODE_RELEASE_NOTES:-}" > "$assets.md" +if dry_run; then exit 0; fi + +tag="v$OPENCODE_VERSION" +gh release view "$tag" > /dev/null 2>&1 || gh release create "$tag" --draft --verify-tag --title "$tag" --notes-file "$assets.md" +gh release upload "$tag" "$assets"/* --clobber +gh release edit "$tag" --draft=false diff --git a/.github/release/publish-homebrew.sh b/.github/release/publish-homebrew.sh new file mode 100755 index 00000000000..59f39bdc77a --- /dev/null +++ b/.github/release/publish-homebrew.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# publish-homebrew.sh : updates opencode-v2 in anomalyco/homebrew-tap +# (HOMEBREW_TOKEN) and registers the homebrew update artifact. +. "$(dirname "$0")/lib.sh" + +push_git "https://x-access-token:${HOMEBREW_TOKEN:-}@github.com/anomalyco/homebrew-tap.git" \ + "chore: update opencode-v2 to $OPENCODE_VERSION" bash "$release_dir/render-homebrew.sh" "$1" "$2" +publish_update cli homebrew '{"package": "anomalyco/tap/opencode-v2"}' diff --git a/.github/release/publish-npm.sh b/.github/release/publish-npm.sh new file mode 100755 index 00000000000..ed63a4a0aa4 --- /dev/null +++ b/.github/release/publish-npm.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# publish-npm.sh ...: publishes every release tarball to npm with OPENCODE_NPM_TAG. +# Names, the version and the package set come from this script, never from the tarballs: each tarball's +# package.json is read as data and must match. macOS and Windows CLI packages must come from a signed dir. +. "$(dirname "$0")/lib.sh" + +npm_dir=$1 +shift +targets="linux-arm64 linux-x64 linux-x64-baseline linux-arm64-musl linux-x64-musl linux-x64-baseline-musl darwin-arm64 darwin-x64 darwin-x64-baseline windows-arm64 windows-x64 windows-x64-baseline" +expected="@opencode/cli" +for target in $targets; do expected="$expected @opencode/cli-$target"; done +for lib in schema codemode theme ai util protocol client plugin plugin-browser core simulation server sdk ui; do expected="$expected @opencode/$lib"; done +if [ "$OPENCODE_CHANNEL" != latest ]; then + expected="$expected @opencode/cli-node" + for target in linux-arm64 linux-x64 darwin-arm64 windows-arm64 windows-x64; do expected="$expected @opencode/cli-node-$target"; done +fi + +if ! dry_run; then + for file in "$npm_dir"/*.tgz; do + gh attestation verify "$file" --repo anomalyco/opencode --signer-workflow anomalyco/opencode/.github/workflows/release.yml > /dev/null + done +fi + +shopt -s nullglob +files=() +for dir in "$@"; do files+=("$dir"/*.tgz); done +files+=("$npm_dir"/*.tgz) +list=$(mktemp) +for file in "${files[@]}"; do + IFS=$'\t' read -r name version config install < <(tar -xzOf "$file" package/package.json | + jq -r '[.name, .version, ((.publishConfig // {}) | keys - ["access"] | length > 0), + ((.scripts // {}) | (has("preinstall") or has("install") or has("postinstall")))] | @tsv') + # shellcheck disable=SC2086 # $expected is a word list + printf '%s\n' $expected | grep -qxF -- "$name" || die "Unexpected package $name in $file" + # The signed copy of a macOS or Windows CLI package replaces the unsigned one from the build. + if cut -f1 "$list" | grep -qxF -- "$name"; then continue; fi + case "$name:$file" in + @opencode/cli-darwin-*:"$npm_dir"/* | @opencode/cli-windows-*:"$npm_dir"/*) die "$name is not signed" ;; + esac + [ "$version" = "$OPENCODE_VERSION" ] || die "$name has version $version, expected $OPENCODE_VERSION" + [ "$config" = false ] || die "$name sets publishConfig beyond access" + [ "$install" = false ] || [ "$name" = @opencode/cli ] || [ "$name" = @opencode/cli-node ] || die "$name has an install script" + printf '%s\t%s\n' "$name" "$file" >> "$list" +done +for name in $expected; do cut -f1 "$list" | grep -qxF -- "$name" || die "Missing package $name"; done + +# The CLI wrappers resolve their platform packages, so they publish last. +order=$(mktemp) +{ grep -vP '^@opencode/cli(-node)?\t' "$list" || true; grep -P '^@opencode/cli(-node)?\t' "$list"; } > "$order" +cat "$order" + +# A clean directory and config, so nothing from an artifact can redirect the registry. +printf 'registry=https://registry.npmjs.org/\n' > "$RUNNER_TEMP/npmrc" +export NPM_CONFIG_USERCONFIG="$RUNNER_TEMP/npmrc" +cd "$(mktemp -d)" +flags=(--tag "$OPENCODE_NPM_TAG" --access public --ignore-scripts) +if dry_run; then flags+=(--dry-run); else flags+=(--provenance); fi +while IFS=$'\t' read -r name file; do + if ! dry_run && npm view "$name@$OPENCODE_VERSION" version > /dev/null 2>&1; then + echo "already published $name@$OPENCODE_VERSION" + continue + fi + npm publish "$file" "${flags[@]}" +done < "$order" diff --git a/.github/release/publish-version-pr.sh b/.github/release/publish-version-pr.sh new file mode 100755 index 00000000000..e1a37776641 --- /dev/null +++ b/.github/release/publish-version-pr.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# publish-version-pr.sh : opens the pull request that brings the release commit (versions and changelog) back to dev. +# Pushing to dev is blocked by rulesets, so this never merges. +. "$(dirname "$0")/lib.sh" + +branch="release-v$OPENCODE_VERSION" +gh api "repos/$GH_REPO/git/refs" -f "ref=refs/heads/$branch" -f "sha=$1" > /dev/null || + gh api "repos/$GH_REPO/git/refs/heads/$branch" > /dev/null +body="Brings the versions and changelog of the published \`v$OPENCODE_VERSION\` release back to \`dev\`. The \`v$OPENCODE_VERSION\` tag points at this commit." +gh pr create --base dev --head "$branch" --title "release: v$OPENCODE_VERSION" --body "$body" || + echo "::warning::Could not open the release PR. Open it by hand: gh pr create --base dev --head $branch" diff --git a/.github/release/render-aur.sh b/.github/release/render-aur.sh new file mode 100755 index 00000000000..7b6818b20df --- /dev/null +++ b/.github/release/render-aur.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# render-aur.sh : writes PKGBUILD, .SRCINFO and the opencode2 shim for opencode-beta. +# The package installs the published npm tarballs, so their hashes come from the build-npm artifact. +# LICENSE comes from the AUR repository itself. +. "$(dirname "$0")/lib.sh" + +npm=$1 aur=$2 +name=opencode-beta +pkgver="${OPENCODE_VERSION//-/.}" +if dry_run && [ ! -f "$aur/LICENSE" ]; then printf 'MIT License\n' > "$aur/LICENSE"; fi +test -s "$aur/LICENSE" || die "The AUR repository has no LICENSE" +printf '#!/bin/sh\nexec "$(dirname "$0")/opencode" "$@"\n' > "$aur/opencode2" +sum() { sha256 "$1" | cut -c1-64; } +x64=$(sum "$npm/opencode-cli-linux-x64-baseline-$OPENCODE_VERSION.tgz") +arm64=$(sum "$npm/opencode-cli-linux-arm64-$OPENCODE_VERSION.tgz") +x64_url="https://registry.npmjs.org/@opencode/cli-linux-x64-baseline/-/cli-linux-x64-baseline-$OPENCODE_VERSION.tgz" +arm64_url="https://registry.npmjs.org/@opencode/cli-linux-arm64/-/cli-linux-arm64-$OPENCODE_VERSION.tgz" +license=$(sum "$aur/LICENSE") +shim=$(sum "$aur/opencode2") + +# Stripping a compiled Bun executable can damage its embedded application. +cat > "$aur/PKGBUILD" < +pkgname=$name +pkgver=$pkgver +pkgrel=1 +pkgdesc='OpenCode beta - the AI coding agent for the terminal' +url='https://github.com/anomalyco/opencode' +arch=('x86_64' 'aarch64') +license=('MIT') +depends=('glibc' 'gcc-libs' 'ripgrep') +provides=('opencode' 'opencode2') +conflicts=('opencode' 'opencode2') +options=('!strip' '!debug') +source=('LICENSE' 'opencode2') +sha256sums=('$license' '$shim') +source_x86_64=('$name-$pkgver-x86_64.tgz::$x64_url') +sha256sums_x86_64=('$x64') +source_aarch64=('$name-$pkgver-aarch64.tgz::$arm64_url') +sha256sums_aarch64=('$arm64') + +package() { + install -Dm755 "\$srcdir/package/bin/opencode" "\$pkgdir/usr/bin/opencode" + install -Dm755 "\$srcdir/opencode2" "\$pkgdir/usr/bin/opencode2" + install -Dm644 "\$srcdir/LICENSE" "\$pkgdir/usr/share/licenses/\$pkgname/LICENSE" +} +PKGBUILD + +# What makepkg --printsrcinfo prints for the PKGBUILD above. +t=$'\t' +cat > "$aur/.SRCINFO" < : writes Formula opencode-v2.rb with the +# hashes of the signed macOS and the Linux archives. +. "$(dirname "$0")/lib.sh" + +macos=$1 archives=$2 tap=$3 +sum() { sha256 "$1" | cut -c1-64; } +base="https://opencode.ai/files/bin/$OPENCODE_VERSION" +cat > "$tap/opencode-v2.rb" < : writes the WinGet manifests for +# Anomaly.OpenCode and Anomaly.OpenCode.Desktop. Submission to microsoft/winget-pkgs is paused until the packages +# are accepted, so the workflow only uploads them. +. "$(dirname "$0")/lib.sh" + +cli=$1 desktop=$2 out=$3 +sum() { sha256 "$1" | cut -c1-64 | tr a-f A-F; } +base="https://opencode.ai/files/bin/$OPENCODE_VERSION" +date=$(date -u +%F) +header() { + printf '# yaml-language-server: $schema=https://aka.ms/winget-manifest.%s.1.12.0.schema.json\n\nPackageIdentifier: %s\nPackageVersion: %s\n' \ + "$2" "$1" "$OPENCODE_VERSION" +} +footer() { printf 'ManifestType: %s\nManifestVersion: 1.12.0\n' "$1"; } +manifests() { + local id=$1 name=$2 description=$3 moniker=$4 + shift 4 + mkdir -p "$out/$id" + { header "$id" version; echo "DefaultLocale: en-US"; footer version; } > "$out/$id/$id.yaml" + { header "$id" installer; printf '%s\n' "$@" "ReleaseDate: $date"; footer installer; } > "$out/$id/$id.installer.yaml" + { + header "$id" defaultLocale + printf '%s\n' "PackageLocale: en-US" "Publisher: OpenCode" "PublisherUrl: https://anoma.ly/" \ + "PublisherSupportUrl: https://github.com/anomalyco/opencode/issues" "PrivacyUrl: https://opencode.ai/legal/privacy-policy" \ + "PackageName: $name" "PackageUrl: https://opencode.ai/" "License: MIT" "LicenseUrl: https://github.com/anomalyco/opencode/blob/HEAD/LICENSE" \ + "ShortDescription: $description" "Moniker: $moniker" "Tags:" "- ai" "- coding-agent" "- developer-tools" \ + "Documentations:" "- DocumentLabel: Docs" " DocumentUrl: https://opencode.ai/v2/docs" + footer defaultLocale + } > "$out/$id/$id.locale.en-US.yaml" +} + +manifests Anomaly.OpenCode "OpenCode CLI" "The open source AI coding agent for the terminal." opencode \ + "InstallerType: zip" "NestedInstallerType: portable" "NestedInstallerFiles:" \ + "- RelativeFilePath: opencode.exe" " PortableCommandAlias: opencode" "Commands:" "- opencode" "Installers:" \ + "- Architecture: x64" " InstallerUrl: $base/opencode-windows-x64-baseline.zip" " InstallerSha256: $(sum "$cli/opencode-windows-x64-baseline.zip")" \ + "- Architecture: arm64" " InstallerUrl: $base/opencode-windows-arm64.zip" " InstallerSha256: $(sum "$cli/opencode-windows-arm64.zip")" + +# The display name and uninstall key match what the NSIS installer registers for ai.opencode.desktop. +manifests Anomaly.OpenCode.Desktop "OpenCode" "The open source AI coding agent as a desktop app." opencode-desktop \ + "InstallerType: nullsoft" "Scope: user" "UpgradeBehavior: install" "ProductCode: d074f30d-5f88-5885-b075-be1348cc7676" \ + "Protocols:" "- opencode" "Installers:" \ + "- Architecture: x64" " InstallerUrl: $base/opencode-desktop-win-x64.exe" " InstallerSha256: $(sum "$desktop/opencode-desktop-win-x64.exe")" \ + "- Architecture: arm64" " InstallerUrl: $base/opencode-desktop-win-arm64.exe" " InstallerSha256: $(sum "$desktop/opencode-desktop-win-arm64.exe")" +tail -n +1 "$out"/*/* diff --git a/.github/release/repack-windows.sh b/.github/release/repack-windows.sh new file mode 100755 index 00000000000..4c9b9284e64 --- /dev/null +++ b/.github/release/repack-windows.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# repack-windows.sh : checks every signature in , then writes the signed CLI back +# into npm tarballs and opencode-.zip archives in . +. "$(dirname "$0")/lib.sh" + +work=$(posix "$1") out=$(posix "$2") +bash "$release_dir/verify-signatures-windows.sh" "$work" +mkdir -p "$out" +if [ ! -d "$work/cli" ]; then exit 0; fi +for target in windows-arm64 windows-x64 windows-x64-baseline; do + tar -czf "$out/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work/cli/$target" package + powershell -NoProfile -Command "Compress-Archive -Path '$(cygpath -w "$work/cli/$target/package/bin/opencode.exe")' -DestinationPath '$(cygpath -w "$out/opencode-$target.zip")'" +done diff --git a/.github/release/sign-cli-macos.sh b/.github/release/sign-cli-macos.sh new file mode 100755 index 00000000000..34dfb603d10 --- /dev/null +++ b/.github/release/sign-cli-macos.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# sign-cli-macos.sh : signs the three macOS CLI binaries inside their npm tarballs with +# the Developer ID in build.keychain, then writes the re-packed tarballs and the opencode-.zip archives. +# Dry runs sign ad-hoc. +. "$(dirname "$0")/lib.sh" + +in=$1 out=$2 +mkdir -p "$out" +identity=- timestamp=--timestamp=none +if ! dry_run; then + identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1) + [ -n "$identity" ] || die "Developer ID Application identity not found" + timestamp=--timestamp +fi + +export COPYFILE_DISABLE=1 +for target in darwin-arm64 darwin-x64 darwin-x64-baseline; do + work=$(mktemp -d) + tar -xzf "$in/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work" + bin="$work/package/bin/opencode" + file -b "$bin" | grep -q '^Mach-O' || die "$target is not a Mach-O binary" + chmod 755 "$bin" + codesign --force "$timestamp" --options runtime --entitlements "$release_dir/entitlements/cli.plist" --sign "$identity" "$bin" + codesign --verify --strict --verbose=2 "$bin" + tar --no-mac-metadata -czf "$out/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work" package + touch -t 198001010000 "$bin" + (cd "$work/package/bin" && zip -X -q "$out/opencode-$target.zip" opencode) +done diff --git a/.github/release/sign-desktop-macos.sh b/.github/release/sign-desktop-macos.sh new file mode 100755 index 00000000000..6d8cfe59465 --- /dev/null +++ b/.github/release/sign-desktop-macos.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# sign-desktop-macos.sh ...: signs each unsigned .app inside-out with hardened runtime, +# notarizes them in one submission, staples them, and only then builds opencode-desktop-mac-.{zip,dmg,app.tar.gz} +# from the stapled apps. Dry runs sign ad-hoc and skip notarization. Beta trades larger files for faster packaging +# (zip and dmg at zlib level 1) and skips the .app.tar.gz, which only the retired Tauri updater feed read. +# Notarization reads APPLE_API_KEY_CONTENT, APPLE_API_KEY_ID and APPLE_API_ISSUER. +. "$(dirname "$0")/lib.sh" + +out=$1 +shift +mkdir -p "$out" +apps=$(mktemp -d) +identity=- timestamp=--timestamp=none +zip_level=() dmg_level=() +if [ "$OPENCODE_CHANNEL" = beta ]; then zip_level=(--zlibCompressionLevel 1) dmg_level=(-imagekey zlib-level=1); fi +if ! dry_run; then + identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1) + [ -n "$identity" ] || die "Developer ID Application identity not found" + timestamp=--timestamp +fi +sign() { + codesign --force "$timestamp" --options runtime --entitlements "$2" --sign "$identity" "$1" +} +bundle() { + find "$apps/$1" -mindepth 1 -maxdepth 1 -name '*.app' -type d +} + +for tarball in "$@"; do + arch=$(basename "$tarball" .app.tar) + arch=${arch#opencode-desktop-mac-} + [ "$arch" = arm64 ] || [ "$arch" = x64 ] || die "Unexpected app tarball: $tarball" + mkdir -p "$apps/$arch" + tar -xf "$tarball" -C "$apps/$arch" + if [ "$(find "$apps/$arch" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')" != 1 ] || [ -z "$(bundle "$arch")" ]; then + die "Expected exactly one .app bundle in $tarball" + fi + app=$(bundle "$arch") + + # Every nested Mach-O file and bundle, deepest first, then the app itself. + list=$(mktemp) + { + find "$app/Contents" -type f -print0 | while IFS= read -r -d '' file; do + case "$(file -b --mime-type "$file")" in application/x-mach-binary*) printf '%s\n' "$file" ;; esac + done + find "$app/Contents" -type d \( -name '*.app' -o -name '*.framework' \) -print + } | awk -F/ '{ print NF "\t" $0 }' | sort -t "$(printf '\t')" -k1,1nr | cut -f2- > "$list" + echo "Signing $(wc -l < "$list" | tr -d ' ') items in $app" + while IFS= read -r item; do + if [ "$item" = "$app/Contents/Resources/opencode-cli" ]; then + # The bundled Bun CLI loads bun-pty's native library; Electron and its helpers do not need this exception. + sign "$item" "$release_dir/entitlements/desktop-cli.plist" + else + sign "$item" "$release_dir/entitlements/desktop.plist" + fi + done < "$list" + sign "$app" "$release_dir/entitlements/desktop.plist" + codesign --verify --deep --strict --verbose=2 "$app" +done + +if ! dry_run; then + key=$(mktemp) + printf '%s\n' "$APPLE_API_KEY_CONTENT" > "$key" + ditto -c -k --sequesterRsrc "$apps" "$apps.zip" + xcrun notarytool submit "$apps.zip" --key "$key" --key-id "$APPLE_API_KEY_ID" --issuer "$APPLE_API_ISSUER" \ + --wait --timeout 60m --output-format json > "$apps.json" + rm -f "$key" + cat "$apps.json" + [ "$(jq -r .status "$apps.json")" = Accepted ] || die "Notarization was not accepted" +fi + +for dir in "$apps"/*; do + arch=$(basename "$dir") + app=$(bundle "$arch") + name=$(basename "$app") + if ! dry_run; then + xcrun stapler staple "$app" + xcrun stapler validate "$app" + spctl --assess --type execute --verbose=2 "$app" + fi + ditto -c -k ${zip_level[@]+"${zip_level[@]}"} --sequesterRsrc --keepParent "$app" "$out/opencode-desktop-mac-$arch.zip" + staging=$(mktemp -d) + ditto "$app" "$staging/$name" + ln -s /Applications "$staging/Applications" + hdiutil create -volname "${name%.app}" -srcfolder "$staging" -fs HFS+ -format UDZO ${dmg_level[@]+"${dmg_level[@]}"} -ov "$out/opencode-desktop-mac-$arch.dmg" + if [ "$OPENCODE_CHANNEL" = beta ]; then continue; fi + COPYFILE_DISABLE=1 tar --no-mac-metadata -czf "$out/opencode-desktop-mac-$arch.app.tar.gz" -C "$dir" "$name" +done diff --git a/.github/release/tag-release.sh b/.github/release/tag-release.sh new file mode 100755 index 00000000000..29da48314ba --- /dev/null +++ b/.github/release/tag-release.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# tag-release.sh: in a checkout of the dispatched dev commit, commits the release versions and changelog +# (OPENCODE_RELEASE_NOTES) and pushes only the v tag at it. Writes sha= to $GITHUB_OUTPUT. +# Runs git only, with hooks disabled; no repository code. +. "$(dirname "$0")/lib.sh" + +tag="v$OPENCODE_VERSION" +git ls-files -z -- '*package.json' bun.lock | xargs -0 sed -i -E "s/\"version\": \"[^\"]+\"/\"version\": \"$OPENCODE_VERSION\"/g" + +if [ -n "${OPENCODE_RELEASE_NOTES:-}" ] && ! grep -qF -x "## $tag" CHANGELOG.md && ! grep -qF "## $tag " CHANGELOG.md; then + notes=$(mktemp) + printf '%s\n' "$OPENCODE_RELEASE_NOTES" > "$notes" + awk -v entry="## $tag — $(date -u +%F)" -v notes="$notes" ' + function emit() { print entry; print ""; while ((getline line < notes) > 0) print line; print ""; done = 1 } + !done && /^## / { emit() } + { print } + END { if (!done) { print ""; emit() } } + ' CHANGELOG.md > "$notes.md" + mv "$notes.md" CHANGELOG.md +fi + +if git diff --name-only | grep -vE '(^|/)package\.json$|^bun\.lock$|^CHANGELOG\.md$'; then + die "The release commit may only change versions and the changelog" +fi + +git -c core.hooksPath=/dev/null \ + -c user.name="github-actions[bot]" \ + -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit --no-verify -q -am "release: $tag" + +# A rerun reuses the tag when it holds the same tree. +existing=$(git ls-remote origin "refs/tags/$tag" | cut -f1) +if [ -n "$existing" ]; then + git fetch -q --depth=1 origin "refs/tags/$tag" + [ "$(git rev-parse "$existing^{tree}")" = "$(git rev-parse "HEAD^{tree}")" ] || die "Tag $tag already exists with different contents" + echo "sha=$existing" >> "$GITHUB_OUTPUT" + exit 0 +fi +git push -q origin "HEAD:refs/tags/$tag" +echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" diff --git a/.github/release/unpack-windows.sh b/.github/release/unpack-windows.sh new file mode 100755 index 00000000000..afb760026f8 --- /dev/null +++ b/.github/release/unpack-windows.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# unpack-windows.sh : lays out what the signing action signs in : +# cli//package from the Windows CLI npm tarballs, and desktop-/ from the unpacked desktop apps. +. "$(dirname "$0")/lib.sh" + +in=$(posix "$1") work=$(posix "$2") +mkdir -p "$work" +if [ -d "$in/build-npm" ]; then + for target in windows-arm64 windows-x64 windows-x64-baseline; do + mkdir -p "$work/cli/$target" + tar -xzf "$in/build-npm/opencode-cli-$target-$OPENCODE_VERSION.tgz" -C "$work/cli/$target" + test -s "$work/cli/$target/package/bin/opencode.exe" || die "Missing opencode.exe for $target" + done +fi +for target in windows-arm64 windows-x64; do + if [ -d "$in/build-desktop-$target" ]; then mkdir -p "$work/desktop-$target" && cp -R "$in/build-desktop-$target/app" "$work/desktop-$target/app"; fi +done diff --git a/.github/release/upload/action.yml b/.github/release/upload/action.yml new file mode 100644 index 00000000000..bd03680f3a1 --- /dev/null +++ b/.github/release/upload/action.yml @@ -0,0 +1,26 @@ +name: Upload a release artifact +description: Writes SHA256SUMS for a directory, uploads it, and outputs the manifest digest. +inputs: + name: + description: Artifact name, - + required: true + path: + description: Directory to upload + required: true +outputs: + digest: + description: SHA-256 of the artifact's SHA256SUMS + value: ${{ steps.checksum.outputs.digest }} +runs: + using: composite + steps: + - id: checksum + shell: bash + run: echo "digest=$(bash "${GITHUB_ACTION_PATH//\\//}/../write-checksums.sh" "$UPLOAD_PATH")" >> "$GITHUB_OUTPUT" + env: + UPLOAD_PATH: ${{ inputs.path }} + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: ${{ inputs.name }} + path: ${{ inputs.path }} + if-no-files-found: error diff --git a/.github/release/verify-artifacts.sh b/.github/release/verify-artifacts.sh new file mode 100755 index 00000000000..aeba5091f80 --- /dev/null +++ b/.github/release/verify-artifacts.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# verify-artifacts.sh : checks every artifact downloaded into / against its SHA256SUMS and that it +# holds exactly the listed files. Artifacts made by sign jobs (sign-*) must also match the manifest digest their +# job reported (OPENCODE_DIGESTS="name=digest ..."), so an artifact replaced after that job finished is rejected. +. "$(dirname "$0")/lib.sh" + +root=$(posix "$1") +for dir in "$root"/*/; do + name=$(basename "$dir") + digest="" + for pair in ${OPENCODE_DIGESTS:-}; do + if [ "${pair%%=*}" = "$name" ]; then digest=${pair#*=}; fi + done + case "$name" in sign-*) [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || die "Missing digest for $name" ;; esac + ( + cd "$dir" + if [ -n "$digest" ] && [ "$(sha256 SHA256SUMS | cut -c1-64)" != "$digest" ]; then die "SHA256SUMS digest mismatch in $name"; fi + sha256 -c SHA256SUMS > /dev/null || die "Checksum mismatch in $name" + diff <(find . -type f ! -name SHA256SUMS | sed 's|^\./||' | LC_ALL=C sort) <(cut -c67- SHA256SUMS | LC_ALL=C sort) || + die "Unexpected files in $name" + ) + echo "verified $name${digest:+ ($digest)}" +done diff --git a/.github/release/verify-signatures-windows.sh b/.github/release/verify-signatures-windows.sh new file mode 100755 index 00000000000..14d554df09b --- /dev/null +++ b/.github/release/verify-signatures-windows.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# verify-signatures-windows.sh : fails unless every .exe and .node under has a valid Authenticode signature. +. "$(dirname "$0")/lib.sh" + +if dry_run; then + echo "dry-run: not verifying signatures in $1" + exit 0 +fi +powershell -NoProfile -Command " + \$ErrorActionPreference = 'Stop' + \$files = Get-ChildItem '$(cygpath -w "$(posix "$1")")' -Recurse -Include *.exe, *.node + if (-not \$files) { throw 'No signed files found' } + foreach (\$file in \$files) { + \$sig = Get-AuthenticodeSignature \$file.FullName + if (\$sig.Status -ne 'Valid') { throw \"Invalid signature for \$(\$file.FullName): \$(\$sig.Status)\" } + } + Write-Output \"verified \$(\$files.Count) signatures\" +" diff --git a/.github/release/write-checksums.sh b/.github/release/write-checksums.sh new file mode 100755 index 00000000000..b7a44278a29 --- /dev/null +++ b/.github/release/write-checksums.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# write-checksums.sh : writes /SHA256SUMS for every file under and prints its digest. +# Every artifact carries this manifest; trusted jobs pass the digest on through job outputs. +. "$(dirname "$0")/lib.sh" + +cd "$(posix "$1")" +manifest=$(mktemp) +find . -type f ! -name SHA256SUMS | sed 's|^\./||' | LC_ALL=C sort | while IFS= read -r file; do sha256 "$file"; done > "$manifest" +mv "$manifest" SHA256SUMS +cat SHA256SUMS >&2 +sha256 SHA256SUMS | cut -c1-64 diff --git a/.github/workflows/bot-docs-locale.yml b/.github/workflows/bot-docs-locale.yml index 82e81de204b..c90ad57cd89 100644 --- a/.github/workflows/bot-docs-locale.yml +++ b/.github/workflows/bot-docs-locale.yml @@ -12,6 +12,7 @@ jobs: if: false #if: github.actor != 'opencode-agent[bot]' runs-on: blacksmith-4vcpu-ubuntu-2404 + environment: release permissions: contents: write steps: diff --git a/.github/workflows/bot-nix-hashes.yml b/.github/workflows/bot-nix-hashes.yml index e63309e4674..24af010e506 100644 --- a/.github/workflows/bot-nix-hashes.yml +++ b/.github/workflows/bot-nix-hashes.yml @@ -1,7 +1,7 @@ name: bot-nix-hashes permissions: - contents: write + contents: read on: workflow_dispatch: @@ -91,6 +91,7 @@ jobs: needs: compute-hash if: github.event_name != 'pull_request' runs-on: blacksmith-4vcpu-ubuntu-2404 + environment: release steps: - name: Checkout repository diff --git a/.github/workflows/check-test.yml b/.github/workflows/check-test.yml index 0daa9fd3c4b..71e1b4f83ed 100644 --- a/.github/workflows/check-test.yml +++ b/.github/workflows/check-test.yml @@ -119,10 +119,10 @@ jobs: TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }} TURBO_SCM_HEAD: ${{ github.sha }} - - name: Verify published codemode package + - name: Verify packed codemode package if: runner.os == 'Linux' working-directory: packages/codemode - run: bun run script/publish.ts --dry-run + run: bun run pack - name: Verify packed workerd SDK if: runner.os == 'Linux' diff --git a/.github/workflows/deploy-changelog.yml b/.github/workflows/deploy-changelog.yml index 66ec7be03ad..7956e1526fa 100644 --- a/.github/workflows/deploy-changelog.yml +++ b/.github/workflows/deploy-changelog.yml @@ -20,6 +20,7 @@ jobs: deploy: if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev' runs-on: blacksmith-4vcpu-ubuntu-2404 + environment: release steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 diff --git a/.github/workflows/deploy-files.yml b/.github/workflows/deploy-files.yml index 34e292821b6..4d903aec525 100644 --- a/.github/workflows/deploy-files.yml +++ b/.github/workflows/deploy-files.yml @@ -18,7 +18,7 @@ jobs: deploy: if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production') runs-on: blacksmith-4vcpu-ubuntu-2404 - environment: ${{ github.ref_name == 'production' && 'production' || '' }} + environment: ${{ github.ref_name == 'production' && 'production' || 'release' }} steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 diff --git a/.github/workflows/deploy-www.yml b/.github/workflows/deploy-www.yml index 8752fcadc99..3e768e92d2b 100644 --- a/.github/workflows/deploy-www.yml +++ b/.github/workflows/deploy-www.yml @@ -18,7 +18,7 @@ jobs: deploy: if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production') runs-on: blacksmith-4vcpu-ubuntu-2404 - environment: ${{ github.ref_name == 'production' && 'production' || '' }} + environment: ${{ github.ref_name == 'production' && 'production' || 'release' }} steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 42c49c4df07..01149333e50 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,13 +12,16 @@ concurrency: ${{ github.workflow }}-${{ github.ref }} permissions: contents: read - id-token: write jobs: deploy: if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production' || github.ref_name == 'beta') runs-on: blacksmith-4vcpu-ubuntu-2404 - environment: ${{ github.ref_name }} + # production keeps its own environment so dev and beta pushes can never reach production credentials. + environment: ${{ github.ref_name == 'production' && 'production' || 'release' }} + permissions: + contents: read + id-token: write steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 diff --git a/.github/workflows/notify-discord.yml b/.github/workflows/notify-discord.yml deleted file mode 100644 index 0b2b1cde051..00000000000 --- a/.github/workflows/notify-discord.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: notify-discord - -on: - release: - types: [released] # fires when a draft release is published - -jobs: - notify: - runs-on: blacksmith-4vcpu-ubuntu-2404 - steps: - - name: Send nicely-formatted embed to Discord - uses: SethCohen/github-releases-to-discord@24d166886aee4646d448c8a389ff9e1ebcab3682 # v1.20.0 - with: - webhook_url: ${{ secrets.DISCORD_WEBHOOK }} diff --git a/.github/workflows/publish-vscode.yml b/.github/workflows/publish-vscode.yml deleted file mode 100644 index 547d4ace64a..00000000000 --- a/.github/workflows/publish-vscode.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: publish-vscode - -on: - workflow_dispatch: - push: - tags: - - "vscode-v*.*.*" - -concurrency: ${{ github.workflow }}-${{ github.ref }} - -permissions: - contents: write - -jobs: - publish: - runs-on: blacksmith-4vcpu-ubuntu-2404 - environment: release - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - with: - fetch-depth: 0 - - - uses: ./.github/actions/setup-bun - - - run: git fetch --force --tags - - run: bun install -g @vscode/vsce - - - name: Install extension dependencies - run: bun install - working-directory: ./sdks/vscode - - - name: Publish - run: | - ./script/publish - working-directory: ./sdks/vscode - env: - VSCE_PAT: ${{ secrets.VSCE_PAT }} - OPENVSX_TOKEN: ${{ secrets.OPENVSX_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 66dce550775..00000000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,910 +0,0 @@ -name: publish -run-name: "${{ format('release {0}', inputs.bump) }}" - -on: - push: - branches: - - dev - - beta - workflow_dispatch: - inputs: - bump: - description: "Bump major, minor, or patch" - required: false - type: choice - options: - - major - - minor - - patch - version: - description: "Override version (optional)" - required: false - type: string - release_notes: - description: "Reviewed V2 release notes for CHANGELOG.md and the Discord announcement (optional)" - required: false - type: string - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ (github.ref_name == 'dev' && (inputs.version || inputs.bump) && 'release') || inputs.version || inputs.bump }} - # Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only - # its publish job records a release, in one request. - cancel-in-progress: ${{ github.ref_name == 'beta' }} - -permissions: - id-token: write - contents: write - packages: write - # Beta desktop jobs poll this run's artifacts while the CLI builds. - actions: read - # Beta desktop builds read who made each change and what it does for "What's new in beta". - pull-requests: read - -env: - OPENCODE_CHANNEL: ${{ (github.ref_name == 'dev' && !inputs.bump && !inputs.version && 'dev') || '' }} - -jobs: - version: - runs-on: blacksmith-4vcpu-ubuntu-2404 - if: github.repository == 'anomalyco/opencode' - # Versioned releases wait for approval in the release environment, which only allows dev. - environment: ${{ (inputs.bump || inputs.version) && 'release' || '' }} - env: - BETA: ${{ github.ref_name == 'beta' }} - steps: - # A beta version only depends on the run number, so beta computes it without a checkout or an install. - - name: Beta version - id: beta - if: env.BETA == 'true' - run: | - # Matches packages/script: 0.0.0--[.] for preview channels. - version="0.0.0-beta-${GITHUB_RUN_NUMBER}" - if [ "$GITHUB_RUN_ATTEMPT" != "1" ]; then version="${version}.${GITHUB_RUN_ATTEMPT}"; fi - { - echo "version=$version" - echo "release=true" - echo "tag=v$version" - } >> "$GITHUB_OUTPUT" - - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - if: env.BETA != 'true' - with: - fetch-depth: 0 - - - uses: ./.github/actions/setup-bun - if: env.BETA != 'true' - - - name: Setup git committer - id: committer - if: env.BETA != 'true' - uses: ./.github/actions/setup-git-committer - with: - opencode-app-id: ${{ vars.OPENCODE_APP_ID }} - opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }} - - - name: Install OpenCode - if: inputs.bump || inputs.version - run: bun i -g opencode-ai - - - id: version - if: env.BETA != 'true' - run: | - ./script/version.ts - env: - GH_TOKEN: ${{ steps.committer.outputs.token }} - OPENCODE_BUMP: ${{ inputs.bump }} - OPENCODE_VERSION: ${{ inputs.version }} - OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} - outputs: - version: ${{ steps.version.outputs.version || steps.beta.outputs.version }} - release: ${{ steps.version.outputs.release || steps.beta.outputs.release }} - tag: ${{ steps.version.outputs.tag || steps.beta.outputs.tag }} - - models-catalog: - runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 10 - if: github.repository == 'anomalyco/opencode' - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: ./.github/actions/setup-bun - - - name: Fetch models.dev catalog - run: bun packages/core/script/update-models-snapshot.ts .cache/models-catalog/api.json - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: models-catalog - path: .cache/models-catalog/api.json - if-no-files-found: error - - build-cli: - needs: - - version - - models-catalog - runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 30 - # Beta builds only the CLIs its desktop app bundles, in build-cli-beta. - if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' - env: - OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - with: - fetch-tags: true - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: models-catalog - path: .cache/models-catalog - - - uses: ./.github/actions/setup-bun - with: - bun-version: 1.4.4 - - - name: Setup git committer - id: committer - uses: ./.github/actions/setup-git-committer - with: - opencode-app-id: ${{ vars.OPENCODE_APP_ID }} - opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }} - - - name: Build legacy CLI - if: github.ref_name != 'dev' && github.ref_name != 'beta' - run: ./packages/opencode/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }} - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - GH_REPO: ${{ github.repository }} - GH_TOKEN: ${{ steps.committer.outputs.token }} - - - name: Build preview CLI - id: build - run: ./packages/cli/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }} - env: - BUN_COMPILE_RELEASE: bun-v1.4.4 - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }} - GH_REPO: ${{ github.repository }} - GH_TOKEN: ${{ steps.committer.outputs.token }} - - - name: Verify bundled models catalog - run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64/bin/opencode - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - if: github.ref_name != 'dev' && github.ref_name != 'beta' - with: - name: opencode-cli - path: | - packages/opencode/dist/opencode-darwin* - packages/opencode/dist/opencode-linux* - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - if: github.ref_name != 'dev' && github.ref_name != 'beta' - with: - name: opencode-cli-windows - path: packages/opencode/dist/opencode-windows* - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-preview-cli-unsigned - path: packages/cli/dist/cli-* - - outputs: - version: ${{ needs.version.outputs.version }} - - # Beta publishes only the desktop app, so it builds just the 6 CLIs the desktop bundles, each in its own job and - # artifact. Desktop jobs start alongside and wait for their CLI only when they need it. - build-cli-beta: - needs: - - version - - models-catalog - runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 30 - if: github.repository == 'anomalyco/opencode' && github.ref_name == 'beta' - env: - OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json - strategy: - fail-fast: false - matrix: - # macOS first: notarization makes those desktop jobs the longest. - target: - - darwin-x64-baseline - - darwin-arm64 - - linux-arm64 - - windows-arm64 - - windows-x64-baseline - - linux-x64-baseline - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: ./.github/actions/setup-bun - with: - bun-version: 1.4.4 - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: models-catalog - path: .cache/models-catalog - - - name: Build CLI - run: ./packages/cli/script/build.ts --target=opencode-${{ matrix.target }} - env: - BUN_COMPILE_RELEASE: bun-v1.4.4 - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - GH_REPO: ${{ github.repository }} - GH_TOKEN: ${{ github.token }} - - - name: Verify bundled models catalog - if: matrix.target == 'linux-x64-baseline' - run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64-baseline/bin/opencode - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-cli-unsigned-cli-${{ matrix.target }} - path: packages/cli/dist/cli-${{ matrix.target }} - # Deflate level 1 compresses a CLI binary twice as fast as the default for 7% more bytes. - compression-level: 1 - if-no-files-found: error - - sign-cli-macos: - needs: build-cli - runs-on: macos-26 - # Beta publishes only the desktop app, which signs the CLI it bundles. - if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0 - with: - keychain: build - p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} - p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: opencode-preview-cli-unsigned - path: packages/cli/dist - - - name: Sign macOS CLI binaries - run: | - identity=$(security find-identity -v -p codesigning build.keychain | sed -n 's/.*"\(Developer ID Application:.*\)"/\1/p' | head -n 1) - if [ -z "$identity" ]; then - echo "Developer ID Application identity not found" - exit 1 - fi - - found=0 - for file in packages/cli/dist/cli-darwin-*/bin/opencode; do - if [ ! -f "$file" ]; then - continue - fi - found=1 - codesign \ - --force \ - --timestamp \ - --options runtime \ - --entitlements packages/cli/script/entitlements.plist \ - --sign "$identity" \ - "$file" - codesign --verify --deep --strict --verbose=4 "$file" - codesign --display --requirements - "$file" - done - - if [ "$found" -eq 0 ]; then - echo "No macOS CLI binaries found" - exit 1 - fi - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-preview-cli-macos - path: packages/cli/dist/cli-* - if-no-files-found: error - - build-node-app-archive: - needs: version - runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 30 - if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version)) - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: ./.github/actions/setup-bun - - - name: Build app archive - run: bun packages/cli/script/build-node.ts --app-archive-only --app-archive=.cache/app-archive.bin --skip-install - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-node-app-archive - path: packages/cli/.cache/app-archive.bin - if-no-files-found: error - - build-node-cli: - needs: - - version - - models-catalog - - build-node-app-archive - if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version)) - strategy: - fail-fast: false - matrix: - settings: - - target: linux-arm64 - host: blacksmith-4vcpu-ubuntu-2404-arm - - target: linux-x64 - host: blacksmith-4vcpu-ubuntu-2404 - - target: darwin-arm64 - host: macos-26 - - target: windows-arm64 - host: blacksmith-4vcpu-windows-2025 - bun_install_flags: --cpu=* - - target: windows-x64 - host: blacksmith-4vcpu-windows-2025 - runs-on: ${{ matrix.settings.host }} - env: - OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: ./.github/actions/setup-bun - with: - install-flags: ${{ matrix.settings.bun_install_flags }} - - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 - with: - node-version: "26.4.0" - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: opencode-node-app-archive - path: packages/cli/.cache - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: models-catalog - path: .cache/models-catalog - - - name: Build - run: bun packages/cli/script/build-node.ts --target=${{ matrix.settings.target }} --skip-install --outdir=dist/node --app-archive=.cache/app-archive.bin - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }} - - - name: Verify service lifecycle - if: matrix.settings.target != 'windows-arm64' - working-directory: packages/cli - run: bun run script/service-smoke.ts --node - - - name: Verify bundled models catalog - if: matrix.settings.target != 'windows-arm64' - run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/node/cli-node-${{ matrix.settings.target }}/bin/opencode2-node${{ startsWith(matrix.settings.target, 'windows') && '.exe' || '' }} - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-node-cli-${{ matrix.settings.target }} - path: packages/cli/dist/node/cli-node-* - if-no-files-found: error - - sign-cli-windows: - needs: - - sign-cli-macos - runs-on: blacksmith-4vcpu-windows-2025 - if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev' - env: - AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} - AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} - AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: opencode-preview-cli-macos - path: packages/cli/dist - - - name: Azure login - uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0 - with: - client-id: ${{ env.AZURE_CLIENT_ID }} - tenant-id: ${{ env.AZURE_TENANT_ID }} - subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }} - - - uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0 - with: - endpoint: ${{ env.AZURE_TRUSTED_SIGNING_ENDPOINT }} - signing-account-name: ${{ env.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} - certificate-profile-name: ${{ env.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} - files: | - ${{ github.workspace }}\packages\cli\dist\cli-windows-arm64\bin\opencode.exe - ${{ github.workspace }}\packages\cli\dist\cli-windows-x64\bin\opencode.exe - ${{ github.workspace }}\packages\cli\dist\cli-windows-x64-baseline\bin\opencode.exe - exclude-environment-credential: true - exclude-workload-identity-credential: true - exclude-managed-identity-credential: true - exclude-shared-token-cache-credential: true - exclude-visual-studio-credential: true - exclude-visual-studio-code-credential: true - exclude-azure-cli-credential: false - exclude-azure-powershell-credential: true - exclude-azure-developer-cli-credential: true - exclude-interactive-browser-credential: true - - - name: Verify Windows CLI signatures - shell: pwsh - run: | - $files = @( - "${{ github.workspace }}\packages\cli\dist\cli-windows-arm64\bin\opencode.exe", - "${{ github.workspace }}\packages\cli\dist\cli-windows-x64\bin\opencode.exe", - "${{ github.workspace }}\packages\cli\dist\cli-windows-x64-baseline\bin\opencode.exe" - ) - - foreach ($file in $files) { - $sig = Get-AuthenticodeSignature $file - if ($sig.Status -ne "Valid") { - throw "Invalid signature for ${file}: $($sig.Status)" - } - } - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-preview-cli - path: packages/cli/dist/cli-* - if-no-files-found: error - - build-electron: - # Desktop packaging re-signs the bundled CLI on macOS and Windows, so it starts from the unsigned build. - # Beta skips build-cli and waits for its own CLI from build-cli-beta just before Prepare. - needs: - - version - - build-cli - if: ${{ !cancelled() && !failure() && github.repository == 'anomalyco/opencode' && ((github.ref_name == 'dev' && needs.version.outputs.release != '') || github.ref_name == 'beta') }} - continue-on-error: false - env: - AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} - AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} - AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} - strategy: - fail-fast: false - matrix: - # Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith. electron-builder's afterPack rejects - # a bundle whose CLI or node-pty does not match the target CPU. - settings: - - host: ${{ (github.ref_name == 'beta' && 'macos-26') || 'macos-26-intel' }} - target: x86_64-apple-darwin - cli: darwin-x64-baseline - platform_flag: --mac --x64 - bun_install_flags: ${{ (github.ref_name == 'beta' && '--os=darwin --cpu=*') || '--os=darwin --cpu=x64' }} - - host: macos-26 - target: aarch64-apple-darwin - cli: darwin-arm64 - platform_flag: --mac --arm64 - bun_install_flags: --os=darwin --cpu=arm64 - # Releases keep github-hosted Windows from the Tauri build, which needed an ARM64 MSVC toolchain; Electron - # packaging compiles nothing. - - host: ${{ (github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025') || 'windows-2025' }} - target: aarch64-pc-windows-msvc - cli: windows-arm64 - platform_flag: --win --arm64 - bun_install_flags: --cpu=* - - host: "blacksmith-4vcpu-windows-2025" - target: x86_64-pc-windows-msvc - cli: windows-x64-baseline - platform_flag: --win - - host: "blacksmith-4vcpu-ubuntu-2404" - target: x86_64-unknown-linux-gnu - cli: linux-x64-baseline - platform_flag: --linux - - host: "blacksmith-4vcpu-ubuntu-2404-arm" - target: aarch64-unknown-linux-gnu - cli: linux-arm64 - platform_flag: --linux --arm64 - runs-on: ${{ matrix.settings.host }} - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name != 'beta' - with: - name: opencode-preview-cli-unsigned - path: packages/cli/dist - - - uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0 - if: runner.os == 'macOS' - with: - keychain: build - p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} - p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - - - name: Setup Apple API Key - if: runner.os == 'macOS' - run: echo "${{ secrets.APPLE_API_KEY_PATH }}" > $RUNNER_TEMP/apple-api-key.p8 - - - uses: ./.github/actions/setup-bun - with: - install-flags: ${{ matrix.settings.bun_install_flags }} - - - name: Azure login - if: runner.os == 'Windows' - uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0 - with: - client-id: ${{ env.AZURE_CLIENT_ID }} - tenant-id: ${{ env.AZURE_TENANT_ID }} - subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }} - - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 - with: - node-version: "24" - - - name: Cache apt packages - if: contains(matrix.settings.host, 'ubuntu') - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: ~/apt-cache - key: ${{ runner.os }}-${{ matrix.settings.target }}-apt-electron-${{ hashFiles('.github/workflows/publish.yml') }} - restore-keys: | - ${{ runner.os }}-${{ matrix.settings.target }}-apt-electron- - - - name: Install dependencies (ubuntu only) - if: contains(matrix.settings.host, 'ubuntu') - run: | - mkdir -p ~/apt-cache && chmod -R a+rw ~/apt-cache - sudo apt-get update - sudo apt-get install -y --no-install-recommends -o dir::cache::archives="$HOME/apt-cache" rpm - sudo chmod -R a+rw ~/apt-cache - - - name: Setup git committer - id: committer - uses: ./.github/actions/setup-git-committer - with: - opencode-app-id: ${{ vars.OPENCODE_APP_ID }} - opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }} - - # Beta trades larger installers for faster packaging. These variables must stay unset elsewhere: - # electron-builder rejects an empty ELECTRON_BUILDER_COMPRESSION_LEVEL. - - name: Beta packaging settings - if: github.ref_name == 'beta' - shell: bash - run: | - # fpm sets XZ_OPT for the deb and rpm level, but xz still reads XZ_DEFAULTS, so it uses every CPU. - if [ "$RUNNER_OS" = "Linux" ]; then echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV"; fi - # The macOS zip (7z deflate, default -mx=7) and DMG (UDZO zlib, default level 9) at level 1. - if [ "$RUNNER_OS" = "macOS" ]; then echo "ELECTRON_BUILDER_COMPRESSION_LEVEL=1" >> "$GITHUB_ENV"; fi - - # The beta build embeds the subjects of its newest commits for "What's new in beta" - # (packages/desktop/scripts/beta-notes.ts), with their pull requests' authors and descriptions from GitHub. - # Commits without file contents are enough. - - name: Fetch beta history (beta) - if: github.ref_name == 'beta' - shell: bash - run: git fetch --no-tags --filter=blob:none --depth=300 origin "$GITHUB_SHA" - - # Beta builds the app before its CLI exists. `bun run build` would run the prebuild hook, which copies the CLI; - # Prepare runs it once the CLI is here. - - name: Build (beta) - if: github.ref_name == 'beta' - run: bun run electron-vite build - working-directory: packages/desktop - env: - NODE_OPTIONS: --max-old-space-size=4096 - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_CHANNEL: beta - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - SENTRY_ORG: ${{ vars.SENTRY_ORG }} - SENTRY_PROJECT: ${{ vars.WEB_SENTRY_PROJECT }} - SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }} - VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }} - VITE_SENTRY_ENVIRONMENT: beta - VITE_SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }} - OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - GITHUB_TOKEN: ${{ github.token }} - - - name: Wait for the CLI (beta) - if: github.ref_name == 'beta' - run: bun ./script/wait-for-artifact.ts opencode-cli-unsigned-cli-${{ matrix.settings.cli }} "build-cli-beta (${{ matrix.settings.cli }})" - env: - GITHUB_TOKEN: ${{ github.token }} - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name == 'beta' - with: - name: opencode-cli-unsigned-cli-${{ matrix.settings.cli }} - path: packages/cli/dist/cli-${{ matrix.settings.cli }} - - - name: Prepare - run: bun ./scripts/prepare.ts - working-directory: packages/desktop - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} - OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - OPENCODE_CLI_DIST: ${{ github.workspace }}/packages/cli/dist - - - name: Build - if: github.ref_name != 'beta' - run: bun run build - working-directory: packages/desktop - env: - NODE_OPTIONS: --max-old-space-size=4096 - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - SENTRY_ORG: ${{ vars.SENTRY_ORG }} - SENTRY_PROJECT: ${{ vars.WEB_SENTRY_PROJECT }} - SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }} - VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }} - VITE_SENTRY_ENVIRONMENT: ${{ (github.ref_name == 'beta' && 'beta') || 'production' }} - VITE_SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }} - OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - OPENCODE_CLI_DIST: ${{ github.workspace }}/packages/cli/dist - - - name: Package - if: needs.version.outputs.release - run: npx electron-builder ${{ matrix.settings.platform_flag }} --publish never --config electron-builder.config.ts - working-directory: packages/desktop - timeout-minutes: 60 - env: - OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} - OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - GH_TOKEN: ${{ steps.committer.outputs.token }} - CSC_KEYCHAIN: build.keychain - APPLE_API_KEY: ${{ runner.temp }}/apple-api-key.p8 - APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }} - APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} - - - name: Package (no publish) - if: ${{ !needs.version.outputs.release }} - run: npx electron-builder ${{ matrix.settings.platform_flag }} --publish never --config electron-builder.config.ts - working-directory: packages/desktop - timeout-minutes: 60 - env: - OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} - OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - - - name: Create macOS .app.tar.gz - # Only the retired Tauri updater feed read these archives. - if: runner.os == 'macOS' && needs.version.outputs.release && github.ref_name != 'beta' - working-directory: packages/desktop/dist - run: | - if [[ "${{ matrix.settings.target }}" == "x86_64-apple-darwin" ]]; then - APP_DIR="mac" - OUT_NAME="opencode-desktop-mac-x64.app.tar.gz" - elif [[ "${{ matrix.settings.target }}" == "aarch64-apple-darwin" ]]; then - APP_DIR="mac-arm64" - OUT_NAME="opencode-desktop-mac-arm64.app.tar.gz" - else - echo "Unknown macOS target: ${{ matrix.settings.target }}" - exit 1 - fi - APP_PATH=$(find "$APP_DIR" -maxdepth 1 -name "*.app" -type d | head -1) - if [ -z "$APP_PATH" ]; then - echo "No .app bundle found in $APP_DIR" - exit 1 - fi - tar -czf "$OUT_NAME" -C "$(dirname "$APP_PATH")" "$(basename "$APP_PATH")" - - - name: Verify signed Windows Electron artifacts - if: runner.os == 'Windows' - shell: pwsh - run: | - $files = @() - $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*.exe" | Select-Object -ExpandProperty FullName - $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\*.exe" | Select-Object -ExpandProperty FullName - $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\resources\opencode-cli.exe" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName - - foreach ($file in $files | Select-Object -Unique) { - $sig = Get-AuthenticodeSignature $file - if ($sig.Status -ne "Valid") { - throw "Invalid signature for ${file}: $($sig.Status)" - } - } - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - if: github.ref_name != 'beta' - with: - name: opencode-desktop-${{ matrix.settings.target }} - path: packages/desktop/dist/* - - # Beta uploads its installers to R2 here instead of passing them through an artifact to publish, which only - # records the release from the returned file list. - - name: Upload to R2 (beta) - if: github.ref_name == 'beta' - run: bun ./scripts/upload.ts dist dist/uploaded-${{ matrix.settings.target }}.json - working-directory: packages/desktop - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968 - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - if: github.ref_name == 'beta' - with: - name: desktop-uploaded-${{ matrix.settings.target }} - path: packages/desktop/dist/uploaded-${{ matrix.settings.target }}.json - if-no-files-found: error - - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - if: needs.version.outputs.release - with: - name: latest-yml-${{ matrix.settings.target }} - path: packages/desktop/dist/latest*.yml - - publish: - needs: - - version - - models-catalog - - build-cli - - build-cli-beta - - sign-cli-macos - - build-node-app-archive - - build-node-cli - - sign-cli-windows - - build-electron - if: always() && !failure() && !cancelled() - runs-on: blacksmith-4vcpu-ubuntu-2404 - # Versioned and beta releases wait for approval in the release environment; dev previews do not. - environment: ${{ needs.version.outputs.release && 'release' || '' }} - env: - OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json - steps: - - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - - - uses: ./.github/actions/setup-bun - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - with: - name: models-catalog - path: .cache/models-catalog - - # Beta only records the desktop release, so it skips the Docker, git and AUR setup. - - name: Login to GitHub Container Registry - if: github.ref_name != 'beta' - uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Set up QEMU - if: github.ref_name != 'beta' - uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 - - - name: Set up Docker Buildx - if: github.ref_name != 'beta' - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 - - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 - with: - node-version: "24" - registry-url: "https://registry.npmjs.org" - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name != 'dev' && github.ref_name != 'beta' - with: - name: opencode-cli - path: packages/opencode/dist - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name != 'dev' && github.ref_name != 'beta' - with: - name: opencode-cli-windows - path: packages/opencode/dist - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name != 'dev' && github.ref_name != 'beta' - with: - name: opencode-cli-signed-windows - path: packages/opencode/dist - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name != 'beta' - with: - name: opencode-preview-cli - path: packages/cli/dist - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: needs.build-node-cli.result == 'success' - with: - pattern: opencode-node-cli-* - path: packages/cli/dist/node - merge-multiple: true - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: needs.version.outputs.release - with: - pattern: latest-yml-* - path: /tmp/latest-yml - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: needs.version.outputs.release && github.ref_name != 'beta' - with: - pattern: opencode-desktop-* - path: /tmp/desktop - merge-multiple: true - - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - if: github.ref_name == 'beta' - with: - pattern: desktop-uploaded-* - path: /tmp/desktop-uploaded - merge-multiple: true - - - name: Setup git committer - id: committer - if: github.ref_name != 'beta' - uses: ./.github/actions/setup-git-committer - with: - opencode-app-id: ${{ vars.OPENCODE_APP_ID }} - opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }} - - - name: Cache apt packages (AUR) - if: github.ref_name != 'beta' - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: /var/cache/apt/archives - key: ${{ runner.os }}-apt-aur-${{ hashFiles('.github/workflows/publish.yml') }} - restore-keys: | - ${{ runner.os }}-apt-aur- - - - name: Setup SSH for AUR - if: github.ref_name != 'beta' - run: | - sudo apt-get update - sudo apt-get install -y pacman-package-manager - mkdir -p ~/.ssh - echo "${{ secrets.AUR_KEY }}" > ~/.ssh/id_rsa - chmod 600 ~/.ssh/id_rsa - git config --global user.email "opencode@sst.dev" - git config --global user.name "opencode" - ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts || true - - - run: ./script/publish.ts - env: - OPENCODE_VERSION: ${{ needs.version.outputs.version }} - OPENCODE_RELEASE: ${{ needs.version.outputs.release }} - OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }} - AUR_KEY: ${{ secrets.AUR_KEY }} - GITHUB_TOKEN: ${{ steps.committer.outputs.token }} - GH_REPO: ${{ github.repository }} - NPM_CONFIG_PROVENANCE: false - LATEST_YML_DIR: /tmp/latest-yml - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} - OPENCODE_DESKTOP_DIST: /tmp/desktop - OPENCODE_DESKTOP_UPLOADED: ${{ (github.ref_name == 'beta' && '/tmp/desktop-uploaded') || '' }} - WINGET_GITHUB_TOKEN: ${{ secrets.WINGET_GITHUB_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968 - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - - notify-discord-v2: - needs: - - version - - publish - if: ${{ !cancelled() && github.repository == 'anomalyco/opencode' && github.ref_name == 'dev' && needs.version.outputs.release && needs.publish.result == 'success' }} - runs-on: blacksmith-4vcpu-ubuntu-2404 - environment: release - steps: - # Unlike dev, V2 publishes a tag rather than a GitHub Release event. - - name: Announce V2 release in Discord - uses: SethCohen/github-releases-to-discord@24d166886aee4646d448c8a389ff9e1ebcab3682 # v1.20.0 - with: - webhook_url: ${{ secrets.DISCORD_WEBHOOK }} - release_name: OpenCode V2 ${{ needs.version.outputs.tag }} - release_body: ${{ inputs.release_notes }} - release_html_url: https://github.com/${{ github.repository }}/tree/${{ needs.version.outputs.tag }} diff --git a/.github/workflows/release-dry-run.yml b/.github/workflows/release-dry-run.yml new file mode 100644 index 00000000000..7a35035e7e5 --- /dev/null +++ b/.github/workflows/release-dry-run.yml @@ -0,0 +1,727 @@ +name: release-dry-run +run-name: "${{ format('release {0}{1}', inputs.bump, inputs.version) }}" + +# Builds are separated from signing and publishing. +# - build-* jobs run repository code (`bun run build`, `bun run pack`) with no environment, secrets or id-token. +# - sign-* and publish-* jobs run in the release environment, check out only .github/release/, and run those +# scripts on verified artifacts, which they treat as data. They never execute repository code. +# - plan decides version, channel and npm dist-tag from the event, inputs and ref; only a dispatch with a bump or +# version on dev reaches latest. +# .github/release/ and this file are the security boundary for releases. + +# TEMPORARY copy of release.yml for this PR's dry run: GitHub does not start runs for the release.yml path on +# pull requests (it is the old name of publish.yml). Delete before merging. +on: + pull_request: + paths: [.github/workflows/release.yml, .github/workflows/release-dry-run.yml, .github/release/**] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ (inputs.bump || inputs.version) && 'release' || 'build' }} + # Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only + # publish-desktop records a release, in one request. + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.ref_name == 'beta' }} + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + plan: + if: github.repository == 'anomalyco/opencode' + runs-on: ubuntu-24.04 + permissions: {} + outputs: + version: ${{ steps.plan.outputs.version }} + channel: ${{ steps.plan.outputs.channel }} + npm_tag: ${{ steps.plan.outputs.npm_tag }} + dry_run: ${{ steps.plan.outputs.dry_run }} + cli: ${{ steps.plan.outputs.cli }} + desktop: ${{ steps.plan.outputs.desktop }} + node: ${{ steps.plan.outputs.node }} + release: ${{ steps.plan.outputs.release }} + steps: + - &checkout-release + name: Check out release scripts + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + ref: ${{ github.sha }} + sparse-checkout: /.github/release/ + sparse-checkout-cone-mode: false + persist-credentials: false + - id: plan + name: Plan + run: bash .github/release/plan-release.sh + env: + INPUT_BUMP: ${{ inputs.bump }} + INPUT_VERSION: ${{ inputs.version }} + + # A versioned release builds from a commit with its versions and changelog on the dispatched dev commit, + # tagged v. Runs git only. + tag: + needs: plan + runs-on: ubuntu-24.04 + permissions: + contents: write + env: &env + OPENCODE_VERSION: ${{ needs.plan.outputs.version }} + OPENCODE_CHANNEL: ${{ needs.plan.outputs.channel }} + OPENCODE_NPM_TAG: ${{ needs.plan.outputs.npm_tag }} + OPENCODE_DRY_RUN: ${{ needs.plan.outputs.dry_run }} + outputs: + sha: ${{ steps.tag.outputs.sha || github.sha }} + steps: + - name: Check out + if: needs.plan.outputs.channel == 'latest' + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - id: tag + name: Tag + if: needs.plan.outputs.channel == 'latest' + run: bash .github/release/tag-release.sh + env: + OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + + # ---- Build: repository code; no environment, secrets or id-token -------------------------------------------- + + # Fetches the models.dev catalog once per run, so every CLI bundles the same copy. + models-catalog: + needs: [plan, tag] + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 10 + env: *env + steps: + - &checkout + name: Check out + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + ref: ${{ needs.tag.outputs.sha }} + persist-credentials: false + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Fetch + run: bun packages/core/script/update-models-snapshot.ts .cache/models-catalog/api.json + - name: Upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: models-catalog + path: .cache/models-catalog/api.json + if-no-files-found: error + + build-cli: + needs: [plan, tag, models-catalog] + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + bun-version: 1.4.4 + - &download-models-catalog + name: Download models catalog + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: models-catalog + path: .cache/models-catalog + - name: Build + working-directory: packages/cli + run: bun run build && rm -rf dist/.bun + env: + BUN_COMPILE_RELEASE: bun-v1.4.4 + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + OPENCODE_RELEASE_NOTES: ${{ needs.plan.outputs.channel == 'latest' && inputs.release_notes || '' }} + GH_TOKEN: ${{ github.token }} # read-only; raises the rate limit for Bun release downloads + - name: Verify bundled models catalog + run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64/bin/opencode + env: + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Upload + uses: ./.github/release/upload + with: + name: build-cli + path: packages/cli/dist + + build-node: + needs: [plan, tag, models-catalog] + if: needs.plan.outputs.node == 'true' + strategy: + fail-fast: false + matrix: + include: + - { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm } + - { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 } + - { target: darwin-arm64, host: macos-26 } + - { target: windows-arm64, host: blacksmith-4vcpu-windows-2025 } + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "26.4.0" + - *download-models-catalog + - name: Build + working-directory: packages/cli + run: bun run build:node + env: + OPENCODE_TARGET: ${{ matrix.target }} + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Test + if: matrix.target != 'windows-arm64' + working-directory: packages/cli + run: bun run script/service-smoke.ts --node + - name: Verify bundled models catalog + if: matrix.target != 'windows-arm64' + run: bun packages/cli/script/catalog-smoke.ts "packages/cli/dist/node/cli-node-$OPENCODE_TARGET/bin/opencode2-node$EXE" + env: + OPENCODE_TARGET: ${{ matrix.target }} + EXE: ${{ startsWith(matrix.target, 'windows') && '.exe' || '' }} + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Upload + uses: ./.github/release/upload + with: + name: build-node-${{ matrix.target }} + path: packages/cli/dist/node + + # `bun run pack` packs every npm package into dist/npm and the Linux and Node CLI archives into dist/archives. + # The macOS and Windows CLI packages and archives are re-packed after signing. + build-npm: + needs: [plan, tag, build-cli, build-node] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + - &download-cli + name: Download + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: build-cli + path: packages/cli/dist + - name: Download Node CLI + if: needs.plan.outputs.node == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: build-node-* + path: packages/cli/dist/node + merge-multiple: true + - name: Pack + run: rm packages/cli/dist/SHA256SUMS && bun run pack + - name: Upload + uses: ./.github/release/upload + with: + name: build-npm + path: dist/npm + - name: Upload archives + uses: ./.github/release/upload + with: + name: build-archives + path: dist/archives + + build-docker: + needs: [plan, tag, build-cli] + if: needs.plan.outputs.release == 'true' + runs-on: blacksmith-4vcpu-ubuntu-2404 + env: *env + steps: + - *checkout + - *download-cli + - name: Set up QEMU + uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 + - name: Set up Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Pack + working-directory: packages/cli + run: bun run pack:docker + - name: Upload + uses: ./.github/release/upload + with: + name: build-docker + path: dist/docker + + # macOS and Windows pack an unsigned app; Linux packs the final AppImage, deb and rpm. + # Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith for speed. electron-builder's afterPack + # rejects a bundle whose CLI or node-pty does not match the target CPU. + build-desktop: + needs: [plan, tag, build-cli] + if: needs.plan.outputs.desktop == 'true' + permissions: + contents: read + pull-requests: read # beta builds read who made each change and what it does for "What's new in beta" + strategy: + fail-fast: false + matrix: + include: + - target: darwin-x64 + host: ${{ github.ref_name == 'beta' && 'macos-26' || 'macos-26-intel' }} + install: ${{ github.ref_name == 'beta' && '--os=darwin --cpu=*' || '--os=darwin --cpu=x64' }} + - { target: darwin-arm64, host: macos-26, install: --os=darwin --cpu=arm64 } + # github-hosted: blacksmith lacks the ARM64 MSVC cross-compilation toolchain + - target: windows-arm64 + host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }} + install: --cpu=* + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + - { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 } + - { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - *download-cli + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + install-flags: ${{ matrix.install }} + - name: Set up rpm + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends rpm + # The beta build embeds the subjects of its newest commits for "What's new in beta" + # (packages/desktop/script/beta-notes.ts). Commits without file contents are enough. + - name: Fetch beta history + if: needs.plan.outputs.channel == 'beta' + run: git fetch --no-tags --filter=blob:none --depth=300 origin "$SHA" + env: + SHA: ${{ needs.tag.outputs.sha }} + # Beta trades larger packages for faster packaging. fpm sets XZ_OPT for the deb and rpm level, but xz still + # reads XZ_DEFAULTS, so it uses every CPU. + - name: Beta packaging settings + if: needs.plan.outputs.channel == 'beta' && runner.os == 'Linux' + run: echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV" + - name: Build + working-directory: packages/desktop + run: bun run build + env: + OPENCODE_TARGET: ${{ matrix.target }} + NODE_OPTIONS: --max-old-space-size=4096 + VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }} + VITE_SENTRY_ENVIRONMENT: ${{ needs.plan.outputs.channel == 'beta' && 'beta' || 'production' }} + VITE_SENTRY_RELEASE: desktop@${{ needs.plan.outputs.version }} + GITHUB_TOKEN: ${{ github.token }} # read-only; beta notes read pull request authors and descriptions + - name: Pack + working-directory: packages/desktop + timeout-minutes: 60 + run: bun run pack + env: + OPENCODE_TARGET: ${{ matrix.target }} + - name: Upload + uses: ./.github/release/upload + with: + name: build-desktop-${{ matrix.target }} + path: dist/desktop + + # Packs the NSIS installer around the signed app. This runs repository config, so it is a build job; the + # installer is signed next. + build-desktop-windows-installer: + needs: [plan, tag, sign-windows] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + strategy: + fail-fast: false + matrix: + include: + - target: windows-arm64 + host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }} + install: --cpu=* + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + install-flags: ${{ matrix.install }} + - name: Download + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: sign-desktop-${{ matrix.target }} + path: ${{ runner.temp }}/app + - name: Pack + working-directory: packages/desktop + timeout-minutes: 30 + run: bun run pack + env: + OPENCODE_TARGET: ${{ matrix.target }} + OPENCODE_DESKTOP_APP: ${{ runner.temp }}/app/app + - name: Upload + uses: ./.github/release/upload + with: + name: build-desktop-windows-installer-${{ matrix.target }} + path: dist/desktop + + # ---- Sign: release environment; only .github/release/ is checked out ---------------------------------------- + # Pull requests run sign and publish jobs without an environment, so steps that need a secret skip or dry-run. + + # Signs the macOS CLI; signs the desktop apps inside-out, notarizes them in one submission, staples them, and + # only then builds the zip, dmg and .app.tar.gz from the stapled apps. + sign-macos: + needs: [plan, build-npm, build-desktop] + if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }} + runs-on: macos-26 + timeout-minutes: 90 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-desktop-darwin-*}" + - name: Import certificate + if: needs.plan.outputs.dry_run != 'true' + uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0 + with: + keychain: build + p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} + p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + - name: Sign CLI + if: needs.plan.outputs.cli == 'true' + run: bash .github/release/sign-cli-macos.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/out" + - name: Sign desktop + if: needs.plan.outputs.desktop == 'true' + run: | + bash .github/release/sign-desktop-macos.sh "$RUNNER_TEMP/out" \ + "$RUNNER_TEMP"/in/build-desktop-darwin-*/opencode-desktop-mac-*.app.tar + env: + APPLE_API_KEY_CONTENT: ${{ secrets.APPLE_API_KEY_PATH }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + - id: upload + name: Upload + uses: ./.github/release/upload + with: + name: sign-macos + path: ${{ runner.temp }}/out + + # Signs the Windows CLI and every executable and native module of the unpacked desktop apps. + sign-windows: + needs: [plan, build-npm, build-desktop] + if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }} + runs-on: windows-2025 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-desktop-windows-*}" + - name: Unpack + run: bash .github/release/unpack-windows.sh "$RUNNER_TEMP/in" "$RUNNER_TEMP/work" + - &azure-login + name: Log in to Azure + if: needs.plan.outputs.dry_run != 'true' + uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0 + with: + client-id: ${{ secrets.AZURE_CLIENT_ID }} + tenant-id: ${{ secrets.AZURE_TENANT_ID }} + subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} + - &azure-sign + name: Sign + if: needs.plan.outputs.dry_run != 'true' + uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0 + with: + endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} + signing-account-name: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} + certificate-profile-name: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} + files-folder: ${{ runner.temp }}\work + files-folder-filter: exe,node + files-folder-recurse: true + exclude-environment-credential: true + exclude-workload-identity-credential: true + exclude-managed-identity-credential: true + exclude-shared-token-cache-credential: true + exclude-visual-studio-credential: true + exclude-visual-studio-code-credential: true + exclude-azure-cli-credential: false + exclude-azure-powershell-credential: true + exclude-azure-developer-cli-credential: true + exclude-interactive-browser-credential: true + - name: Repack + run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out" + - id: upload + name: Upload + if: needs.plan.outputs.cli == 'true' + uses: ./.github/release/upload + with: + name: sign-windows + path: ${{ runner.temp }}/out + - name: Upload arm64 app + if: needs.plan.outputs.desktop == 'true' + uses: ./.github/release/upload + with: + name: sign-desktop-windows-arm64 + path: ${{ runner.temp }}/work/desktop-windows-arm64 + - name: Upload x64 app + if: needs.plan.outputs.desktop == 'true' + uses: ./.github/release/upload + with: + name: sign-desktop-windows-x64 + path: ${{ runner.temp }}/work/desktop-windows-x64 + + sign-desktop-windows-installer: + needs: [plan, build-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + runs-on: windows-2025 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: build-desktop-windows-installer-* + - name: Unpack + run: mkdir -p "$RUNNER_TEMP/work" && cp "$RUNNER_TEMP"/in/build-desktop-windows-installer-*/*.exe "$RUNNER_TEMP/work/" + - *azure-login + - *azure-sign + - name: Repack + run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out" + - id: upload + name: Upload + uses: ./.github/release/upload + with: + name: sign-desktop-windows-installer + path: ${{ runner.temp }}/work + + # ---- Publish: release environment; only .github/release/ is checked out ------------------------------------- + # Destinations, names and channels come from plan and the scripts, never from artifacts. + + # Build provenance for the npm tarballs and Linux archives. No secrets; id-token only for Sigstore. + publish-attestations: + needs: [plan, build-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' && needs.plan.outputs.dry_run != 'true' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + id-token: write + attestations: write + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-archives}" + - name: Sign + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + ${{ runner.temp }}/in/build-npm/*.tgz + ${{ runner.temp }}/in/build-archives/opencode* + + publish-npm: + needs: [plan, sign-macos, sign-windows, publish-attestations] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + attestations: read + env: *env + steps: + - *checkout-release + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "24.11.0" + - &download-signed-cli + name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-archives,sign-macos,sign-windows}" + digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }} + - name: Publish + run: bash .github/release/publish-npm.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows" + env: + GH_TOKEN: ${{ github.token }} + + publish-cli: + needs: [plan, sign-macos, sign-windows, publish-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - name: Publish + run: bash .github/release/publish-cli.sh "$RUNNER_TEMP/in/build-archives" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows" + env: &cloudflare + CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968 + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + + publish-desktop: + needs: [plan, sign-macos, sign-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{sign-macos,sign-desktop-windows-installer,build-desktop-linux-*}" + digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Publish + run: | + bash .github/release/publish-desktop.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-desktop-windows-installer" \ + "$RUNNER_TEMP/in/build-desktop-linux-x64" "$RUNNER_TEMP/in/build-desktop-linux-arm64" + env: *cloudflare + + publish-docker: + needs: [plan, build-docker] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + packages: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: build-docker + - name: Publish + run: bash .github/release/publish-docker.sh "$RUNNER_TEMP/in/build-docker" + env: + GH_TOKEN: ${{ github.token }} + + publish-homebrew: + needs: [plan, sign-macos, sign-windows, publish-cli] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - id: token + name: Create token + if: needs.plan.outputs.dry_run != 'true' + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ vars.OPENCODE_APP_ID }} + private-key: ${{ secrets.OPENCODE_APP_SECRET }} + owner: anomalyco + repositories: homebrew-tap + - name: Publish + run: bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives" + env: + HOMEBREW_TOKEN: ${{ steps.token.outputs.token }} + + # The AUR package installs the published npm tarballs, so it follows the npm publish. + publish-aur: + needs: [plan, sign-macos, sign-windows, publish-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - name: Publish + run: bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm" + env: + AUR_KEY: ${{ secrets.AUR_KEY }} + + # WinGet manifests as data. Submission to microsoft/winget-pkgs stays paused until the packages are accepted. + publish-winget: + needs: [plan, sign-windows, sign-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{sign-windows,sign-desktop-windows-installer}" + digests: sign-windows=${{ needs.sign-windows.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Render + run: bash .github/release/render-winget.sh "$RUNNER_TEMP/in/sign-windows" "$RUNNER_TEMP/in/sign-desktop-windows-installer" "$RUNNER_TEMP/out" + - name: Upload + uses: ./.github/release/upload + with: + name: publish-winget + path: ${{ runner.temp }}/out + + publish-github-release: + needs: [plan, sign-macos, sign-windows, sign-desktop-windows-installer, publish-cli, publish-desktop] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-archives,build-desktop-linux-*,sign-macos,sign-windows,sign-desktop-windows-installer}" + digests: >- + sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }} + sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Publish + run: bash .github/release/publish-github-release.sh "$RUNNER_TEMP"/in/* + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + + # Brings the release commit back to dev. Pushing to dev is blocked by rulesets, so it opens a PR. + publish-version-pr: + needs: [plan, tag, publish-npm, publish-cli, publish-desktop, publish-github-release] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.channel == 'latest' }} + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + env: *env + steps: + - *checkout-release + - name: Publish + run: bash .github/release/publish-version-pr.sh "$SHA" + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + SHA: ${{ needs.tag.outputs.sha }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000000..6ef2a560509 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,740 @@ +name: release +run-name: "${{ format('release {0}{1}', inputs.bump, inputs.version) }}" + +# Builds are separated from signing and publishing. +# - build-* jobs run repository code (`bun run build`, `bun run pack`) with no environment, secrets or id-token. +# - sign-* and publish-* jobs run in the release environment, check out only .github/release/, and run those +# scripts on verified artifacts, which they treat as data. They never execute repository code. +# - plan decides version, channel and npm dist-tag from the event, inputs and ref; only a dispatch with a bump or +# version on dev reaches latest. +# .github/release/ and this file are the security boundary for releases. + +on: + push: + branches: [dev, beta] + workflow_dispatch: + inputs: + bump: + description: "Bump major, minor, or patch" + required: false + type: choice + options: [major, minor, patch] + version: + description: "Override version (optional)" + required: false + type: string + release_notes: + description: "Reviewed V2 release notes for CHANGELOG.md and the GitHub release (optional)" + required: false + type: string + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ (inputs.bump || inputs.version) && 'release' || 'build' }} + # Beta ships only the newest commit to the team. A cancelled beta run can leave unreferenced files in R2, but only + # publish-desktop records a release, in one request. + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.ref_name == 'beta' }} + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + plan: + if: github.repository == 'anomalyco/opencode' + runs-on: ubuntu-24.04 + permissions: {} + outputs: + version: ${{ steps.plan.outputs.version }} + channel: ${{ steps.plan.outputs.channel }} + npm_tag: ${{ steps.plan.outputs.npm_tag }} + dry_run: ${{ steps.plan.outputs.dry_run }} + cli: ${{ steps.plan.outputs.cli }} + desktop: ${{ steps.plan.outputs.desktop }} + node: ${{ steps.plan.outputs.node }} + release: ${{ steps.plan.outputs.release }} + steps: + - &checkout-release + name: Check out release scripts + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + ref: ${{ github.sha }} + sparse-checkout: /.github/release/ + sparse-checkout-cone-mode: false + persist-credentials: false + - id: plan + name: Plan + run: bash .github/release/plan-release.sh + env: + INPUT_BUMP: ${{ inputs.bump }} + INPUT_VERSION: ${{ inputs.version }} + + # A versioned release builds from a commit with its versions and changelog on the dispatched dev commit, + # tagged v. Runs git only. + tag: + needs: plan + runs-on: ubuntu-24.04 + permissions: + contents: write + env: &env + OPENCODE_VERSION: ${{ needs.plan.outputs.version }} + OPENCODE_CHANNEL: ${{ needs.plan.outputs.channel }} + OPENCODE_NPM_TAG: ${{ needs.plan.outputs.npm_tag }} + OPENCODE_DRY_RUN: ${{ needs.plan.outputs.dry_run }} + outputs: + sha: ${{ steps.tag.outputs.sha || github.sha }} + steps: + - name: Check out + if: needs.plan.outputs.channel == 'latest' + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - id: tag + name: Tag + if: needs.plan.outputs.channel == 'latest' + run: bash .github/release/tag-release.sh + env: + OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + + # ---- Build: repository code; no environment, secrets or id-token -------------------------------------------- + + # Fetches the models.dev catalog once per run, so every CLI bundles the same copy. + models-catalog: + needs: [plan, tag] + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 10 + env: *env + steps: + - &checkout + name: Check out + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + ref: ${{ needs.tag.outputs.sha }} + persist-credentials: false + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Fetch + run: bun packages/core/script/update-models-snapshot.ts .cache/models-catalog/api.json + - name: Upload + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: models-catalog + path: .cache/models-catalog/api.json + if-no-files-found: error + + build-cli: + needs: [plan, tag, models-catalog] + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + bun-version: 1.4.4 + - &download-models-catalog + name: Download models catalog + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: models-catalog + path: .cache/models-catalog + - name: Build + working-directory: packages/cli + run: bun run build && rm -rf dist/.bun + env: + BUN_COMPILE_RELEASE: bun-v1.4.4 + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + OPENCODE_RELEASE_NOTES: ${{ needs.plan.outputs.channel == 'latest' && inputs.release_notes || '' }} + GH_TOKEN: ${{ github.token }} # read-only; raises the rate limit for Bun release downloads + - name: Verify bundled models catalog + run: bun packages/cli/script/catalog-smoke.ts packages/cli/dist/cli-linux-x64/bin/opencode + env: + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Upload + uses: ./.github/release/upload + with: + name: build-cli + path: packages/cli/dist + + build-node: + needs: [plan, tag, models-catalog] + if: needs.plan.outputs.node == 'true' + strategy: + fail-fast: false + matrix: + include: + - { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm } + - { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 } + - { target: darwin-arm64, host: macos-26 } + - { target: windows-arm64, host: blacksmith-4vcpu-windows-2025 } + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "26.4.0" + - *download-models-catalog + - name: Build + working-directory: packages/cli + run: bun run build:node + env: + OPENCODE_TARGET: ${{ matrix.target }} + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Test + if: matrix.target != 'windows-arm64' + working-directory: packages/cli + run: bun run script/service-smoke.ts --node + - name: Verify bundled models catalog + if: matrix.target != 'windows-arm64' + run: bun packages/cli/script/catalog-smoke.ts "packages/cli/dist/node/cli-node-$OPENCODE_TARGET/bin/opencode2-node$EXE" + env: + OPENCODE_TARGET: ${{ matrix.target }} + EXE: ${{ startsWith(matrix.target, 'windows') && '.exe' || '' }} + OPENCODE_MODELS_SNAPSHOT: ${{ github.workspace }}/.cache/models-catalog/api.json + - name: Upload + uses: ./.github/release/upload + with: + name: build-node-${{ matrix.target }} + path: packages/cli/dist/node + + # `bun run pack` packs every npm package into dist/npm and the Linux and Node CLI archives into dist/archives. + # The macOS and Windows CLI packages and archives are re-packed after signing. + build-npm: + needs: [plan, tag, build-cli, build-node] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 30 + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + - &download-cli + name: Download + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: build-cli + path: packages/cli/dist + - name: Download Node CLI + if: needs.plan.outputs.node == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: build-node-* + path: packages/cli/dist/node + merge-multiple: true + - name: Pack + run: rm packages/cli/dist/SHA256SUMS && bun run pack + - name: Upload + uses: ./.github/release/upload + with: + name: build-npm + path: dist/npm + - name: Upload archives + uses: ./.github/release/upload + with: + name: build-archives + path: dist/archives + + build-docker: + needs: [plan, tag, build-cli] + if: needs.plan.outputs.release == 'true' + runs-on: blacksmith-4vcpu-ubuntu-2404 + env: *env + steps: + - *checkout + - *download-cli + - name: Set up QEMU + uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0 + - name: Set up Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 + - name: Set up Bun + uses: ./.github/actions/setup-bun + - name: Pack + working-directory: packages/cli + run: bun run pack:docker + - name: Upload + uses: ./.github/release/upload + with: + name: build-docker + path: dist/docker + + # macOS and Windows pack an unsigned app; Linux packs the final AppImage, deb and rpm. + # Beta packages macOS x64 on Apple Silicon and Windows arm64 on Blacksmith for speed. electron-builder's afterPack + # rejects a bundle whose CLI or node-pty does not match the target CPU. + build-desktop: + needs: [plan, tag, build-cli] + if: needs.plan.outputs.desktop == 'true' + permissions: + contents: read + pull-requests: read # beta builds read who made each change and what it does for "What's new in beta" + strategy: + fail-fast: false + matrix: + include: + - target: darwin-x64 + host: ${{ github.ref_name == 'beta' && 'macos-26' || 'macos-26-intel' }} + install: ${{ github.ref_name == 'beta' && '--os=darwin --cpu=*' || '--os=darwin --cpu=x64' }} + - { target: darwin-arm64, host: macos-26, install: --os=darwin --cpu=arm64 } + # github-hosted: blacksmith lacks the ARM64 MSVC cross-compilation toolchain + - target: windows-arm64 + host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }} + install: --cpu=* + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + - { target: linux-x64, host: blacksmith-4vcpu-ubuntu-2404 } + - { target: linux-arm64, host: blacksmith-4vcpu-ubuntu-2404-arm } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - *download-cli + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + install-flags: ${{ matrix.install }} + - name: Set up rpm + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends rpm + # The beta build embeds the subjects of its newest commits for "What's new in beta" + # (packages/desktop/script/beta-notes.ts). Commits without file contents are enough. + - name: Fetch beta history + if: needs.plan.outputs.channel == 'beta' + run: git fetch --no-tags --filter=blob:none --depth=300 origin "$SHA" + env: + SHA: ${{ needs.tag.outputs.sha }} + # Beta trades larger packages for faster packaging. fpm sets XZ_OPT for the deb and rpm level, but xz still + # reads XZ_DEFAULTS, so it uses every CPU. + - name: Beta packaging settings + if: needs.plan.outputs.channel == 'beta' && runner.os == 'Linux' + run: echo "XZ_DEFAULTS=-T0" >> "$GITHUB_ENV" + - name: Build + working-directory: packages/desktop + run: bun run build + env: + OPENCODE_TARGET: ${{ matrix.target }} + NODE_OPTIONS: --max-old-space-size=4096 + VITE_SENTRY_DSN: ${{ vars.WEB_SENTRY_DSN }} + VITE_SENTRY_ENVIRONMENT: ${{ needs.plan.outputs.channel == 'beta' && 'beta' || 'production' }} + VITE_SENTRY_RELEASE: desktop@${{ needs.plan.outputs.version }} + GITHUB_TOKEN: ${{ github.token }} # read-only; beta notes read pull request authors and descriptions + - name: Pack + working-directory: packages/desktop + timeout-minutes: 60 + run: bun run pack + env: + OPENCODE_TARGET: ${{ matrix.target }} + - name: Upload + uses: ./.github/release/upload + with: + name: build-desktop-${{ matrix.target }} + path: dist/desktop + + # Packs the NSIS installer around the signed app. This runs repository config, so it is a build job; the + # installer is signed next. + build-desktop-windows-installer: + needs: [plan, tag, sign-windows] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + strategy: + fail-fast: false + matrix: + include: + - target: windows-arm64 + host: ${{ github.ref_name == 'beta' && 'blacksmith-4vcpu-windows-2025' || 'windows-2025' }} + install: --cpu=* + - { target: windows-x64, host: blacksmith-4vcpu-windows-2025 } + runs-on: ${{ matrix.host }} + env: *env + steps: + - *checkout + - name: Set up Bun + uses: ./.github/actions/setup-bun + with: + install-flags: ${{ matrix.install }} + - name: Download + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: sign-desktop-${{ matrix.target }} + path: ${{ runner.temp }}/app + - name: Pack + working-directory: packages/desktop + timeout-minutes: 30 + run: bun run pack + env: + OPENCODE_TARGET: ${{ matrix.target }} + OPENCODE_DESKTOP_APP: ${{ runner.temp }}/app/app + - name: Upload + uses: ./.github/release/upload + with: + name: build-desktop-windows-installer-${{ matrix.target }} + path: dist/desktop + + # ---- Sign: release environment; only .github/release/ is checked out ---------------------------------------- + # Pull requests run sign and publish jobs without an environment, so steps that need a secret skip or dry-run. + + # Signs the macOS CLI; signs the desktop apps inside-out, notarizes them in one submission, staples them, and + # only then builds the zip, dmg and .app.tar.gz from the stapled apps. + sign-macos: + needs: [plan, build-npm, build-desktop] + if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }} + runs-on: macos-26 + timeout-minutes: 90 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-desktop-darwin-*}" + - name: Import certificate + if: needs.plan.outputs.dry_run != 'true' + uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0 + with: + keychain: build + p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }} + p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + - name: Sign CLI + if: needs.plan.outputs.cli == 'true' + run: bash .github/release/sign-cli-macos.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/out" + - name: Sign desktop + if: needs.plan.outputs.desktop == 'true' + run: | + bash .github/release/sign-desktop-macos.sh "$RUNNER_TEMP/out" \ + "$RUNNER_TEMP"/in/build-desktop-darwin-*/opencode-desktop-mac-*.app.tar + env: + APPLE_API_KEY_CONTENT: ${{ secrets.APPLE_API_KEY_PATH }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + - id: upload + name: Upload + uses: ./.github/release/upload + with: + name: sign-macos + path: ${{ runner.temp }}/out + + # Signs the Windows CLI and every executable and native module of the unpacked desktop apps. + sign-windows: + needs: [plan, build-npm, build-desktop] + if: ${{ !cancelled() && !failure() && (needs.plan.outputs.cli == 'true' || needs.plan.outputs.desktop == 'true') }} + runs-on: windows-2025 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-desktop-windows-*}" + - name: Unpack + run: bash .github/release/unpack-windows.sh "$RUNNER_TEMP/in" "$RUNNER_TEMP/work" + - &azure-login + name: Log in to Azure + if: needs.plan.outputs.dry_run != 'true' + uses: azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0 + with: + client-id: ${{ secrets.AZURE_CLIENT_ID }} + tenant-id: ${{ secrets.AZURE_TENANT_ID }} + subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} + - &azure-sign + name: Sign + if: needs.plan.outputs.dry_run != 'true' + uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0 + with: + endpoint: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} + signing-account-name: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} + certificate-profile-name: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }} + files-folder: ${{ runner.temp }}\work + files-folder-filter: exe,node + files-folder-recurse: true + exclude-environment-credential: true + exclude-workload-identity-credential: true + exclude-managed-identity-credential: true + exclude-shared-token-cache-credential: true + exclude-visual-studio-credential: true + exclude-visual-studio-code-credential: true + exclude-azure-cli-credential: false + exclude-azure-powershell-credential: true + exclude-azure-developer-cli-credential: true + exclude-interactive-browser-credential: true + - name: Repack + run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out" + - id: upload + name: Upload + if: needs.plan.outputs.cli == 'true' + uses: ./.github/release/upload + with: + name: sign-windows + path: ${{ runner.temp }}/out + - name: Upload arm64 app + if: needs.plan.outputs.desktop == 'true' + uses: ./.github/release/upload + with: + name: sign-desktop-windows-arm64 + path: ${{ runner.temp }}/work/desktop-windows-arm64 + - name: Upload x64 app + if: needs.plan.outputs.desktop == 'true' + uses: ./.github/release/upload + with: + name: sign-desktop-windows-x64 + path: ${{ runner.temp }}/work/desktop-windows-x64 + + sign-desktop-windows-installer: + needs: [plan, build-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + runs-on: windows-2025 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + outputs: + digest: ${{ steps.upload.outputs.digest }} + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: build-desktop-windows-installer-* + - name: Unpack + run: mkdir -p "$RUNNER_TEMP/work" && cp "$RUNNER_TEMP"/in/build-desktop-windows-installer-*/*.exe "$RUNNER_TEMP/work/" + - *azure-login + - *azure-sign + - name: Repack + run: bash .github/release/repack-windows.sh "$RUNNER_TEMP/work" "$RUNNER_TEMP/out" + - id: upload + name: Upload + uses: ./.github/release/upload + with: + name: sign-desktop-windows-installer + path: ${{ runner.temp }}/work + + # ---- Publish: release environment; only .github/release/ is checked out ------------------------------------- + # Destinations, names and channels come from plan and the scripts, never from artifacts. + + # Build provenance for the npm tarballs and Linux archives. No secrets; id-token only for Sigstore. + publish-attestations: + needs: [plan, build-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' && needs.plan.outputs.dry_run != 'true' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + id-token: write + attestations: write + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-archives}" + - name: Sign + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + ${{ runner.temp }}/in/build-npm/*.tgz + ${{ runner.temp }}/in/build-archives/opencode* + + publish-npm: + needs: [plan, sign-macos, sign-windows, publish-attestations] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + attestations: read + env: *env + steps: + - *checkout-release + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "24.11.0" + - &download-signed-cli + name: Download + uses: ./.github/release/download + with: + pattern: "{build-npm,build-archives,sign-macos,sign-windows}" + digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }} + - name: Publish + run: bash .github/release/publish-npm.sh "$RUNNER_TEMP/in/build-npm" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows" + env: + GH_TOKEN: ${{ github.token }} + + publish-cli: + needs: [plan, sign-macos, sign-windows, publish-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.cli == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - name: Publish + run: bash .github/release/publish-cli.sh "$RUNNER_TEMP/in/build-archives" "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-windows" + env: &cloudflare + CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968 + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + + publish-desktop: + needs: [plan, sign-macos, sign-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.desktop == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{sign-macos,sign-desktop-windows-installer,build-desktop-linux-*}" + digests: sign-macos=${{ needs.sign-macos.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Publish + run: | + bash .github/release/publish-desktop.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/sign-desktop-windows-installer" \ + "$RUNNER_TEMP/in/build-desktop-linux-x64" "$RUNNER_TEMP/in/build-desktop-linux-arm64" + env: *cloudflare + + publish-docker: + needs: [plan, build-docker] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + packages: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: build-docker + - name: Publish + run: bash .github/release/publish-docker.sh "$RUNNER_TEMP/in/build-docker" + env: + GH_TOKEN: ${{ github.token }} + + publish-homebrew: + needs: [plan, sign-macos, sign-windows, publish-cli] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - id: token + name: Create token + if: needs.plan.outputs.dry_run != 'true' + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ vars.OPENCODE_APP_ID }} + private-key: ${{ secrets.OPENCODE_APP_SECRET }} + owner: anomalyco + repositories: homebrew-tap + - name: Publish + run: bash .github/release/publish-homebrew.sh "$RUNNER_TEMP/in/sign-macos" "$RUNNER_TEMP/in/build-archives" + env: + HOMEBREW_TOKEN: ${{ steps.token.outputs.token }} + + # The AUR package installs the published npm tarballs, so it follows the npm publish. + publish-aur: + needs: [plan, sign-macos, sign-windows, publish-npm] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + id-token: write + env: *env + steps: + - *checkout-release + - *download-signed-cli + - name: Publish + run: bash .github/release/publish-aur.sh "$RUNNER_TEMP/in/build-npm" + env: + AUR_KEY: ${{ secrets.AUR_KEY }} + + # WinGet manifests as data. Submission to microsoft/winget-pkgs stays paused until the packages are accepted. + publish-winget: + needs: [plan, sign-windows, sign-desktop-windows-installer] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{sign-windows,sign-desktop-windows-installer}" + digests: sign-windows=${{ needs.sign-windows.outputs.digest }} sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Render + run: bash .github/release/render-winget.sh "$RUNNER_TEMP/in/sign-windows" "$RUNNER_TEMP/in/sign-desktop-windows-installer" "$RUNNER_TEMP/out" + - name: Upload + uses: ./.github/release/upload + with: + name: publish-winget + path: ${{ runner.temp }}/out + + publish-github-release: + needs: [plan, sign-macos, sign-windows, sign-desktop-windows-installer, publish-cli, publish-desktop] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: write + env: *env + steps: + - *checkout-release + - name: Download + uses: ./.github/release/download + with: + pattern: "{build-archives,build-desktop-linux-*,sign-macos,sign-windows,sign-desktop-windows-installer}" + digests: >- + sign-macos=${{ needs.sign-macos.outputs.digest }} sign-windows=${{ needs.sign-windows.outputs.digest }} + sign-desktop-windows-installer=${{ needs.sign-desktop-windows-installer.outputs.digest }} + - name: Publish + run: bash .github/release/publish-github-release.sh "$RUNNER_TEMP"/in/* + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + + # Brings the release commit back to dev. Pushing to dev is blocked by rulesets, so it opens a PR. + publish-version-pr: + needs: [plan, tag, publish-npm, publish-cli, publish-desktop, publish-github-release] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.channel == 'latest' }} + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + env: *env + steps: + - *checkout-release + - name: Publish + run: bash .github/release/publish-version-pr.sh "$SHA" + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + SHA: ${{ needs.tag.outputs.sha }} diff --git a/.opencode/skills/unit-tests/SKILL.md b/.opencode/skills/unit-tests/SKILL.md index edcdb7d67c4..6e8d967acf9 100644 --- a/.opencode/skills/unit-tests/SKILL.md +++ b/.opencode/skills/unit-tests/SKILL.md @@ -81,7 +81,7 @@ To avoid adding more: - Do not write per-file `git init` plus `git config` copies. server still has two (`packages/server/test/vcs.test.ts:215-218`, `packages/server/test/worktree.test.ts:131-133`); server already imports core fixtures such as `tmpdir`. - Use `-c user.name=… -c user.email=…` only for commits the test makes itself (`npm.test.ts:53`). Repos where production code commits later (snapshot, worktree, vcs) need repo-local identity. - Keep identity repo-local. The unit job's "Configure git identity" step sets a global identity, but core's `script/test.ts` and cli's `isolatedEnv` replace HOME, so it is invisible there and visible to server and tui. That HOME isolation keeps core's missing-identity coverage: do not depend on CI's identity, and do not add a global gitconfig in core. -- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/scripts/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch. +- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/script/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch. - **Size contention and thresholds to the claim.** `flock.test.ts:46` starts 16 bun workers; use only as many as still exceed the 4 CI vCPUs. A hard-coded threshold forces huge fixtures: `packages/core/test/git.test.ts:354` writes 2,100 files to cross `looseObjectLimit = 2048` (`packages/core/src/git.ts:50`), 2.7s locally and slower on Windows. Make the threshold an option with the production default, cross a small value in the test, and assert the default once. ## Windows-only failures diff --git a/README.ar.md b/README.ar.md index c7d0a701637..79b79db0bb1 100644 --- a/README.ar.md +++ b/README.ar.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.bn.md b/README.bn.md index 3b641fc8144..f684723d14d 100644 --- a/README.bn.md +++ b/README.bn.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.br.md b/README.br.md index c4baaa37edd..dd0ad403b7a 100644 --- a/README.br.md +++ b/README.br.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.bs.md b/README.bs.md index 901df6f95a8..a5bc0324a94 100644 --- a/README.bs.md +++ b/README.bs.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.da.md b/README.da.md index 8ef13be7c9d..a4596c025c5 100644 --- a/README.da.md +++ b/README.da.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.de.md b/README.de.md index e0e46026654..042c2b42815 100644 --- a/README.de.md +++ b/README.de.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.es.md b/README.es.md index c9ac6192af9..129619b7a04 100644 --- a/README.es.md +++ b/README.es.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.fr.md b/README.fr.md index 1b0d822f0a9..cab6c14b15f 100644 --- a/README.fr.md +++ b/README.fr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.gr.md b/README.gr.md index 1874b0669e1..4eb428ba745 100644 --- a/README.gr.md +++ b/README.gr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.it.md b/README.it.md index 3800448ee90..6d34ba64292 100644 --- a/README.it.md +++ b/README.it.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ja.md b/README.ja.md index f99f4881ec2..751fc8714c5 100644 --- a/README.ja.md +++ b/README.ja.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ko.md b/README.ko.md index c91395f2bd1..0d69b9eed6d 100644 --- a/README.ko.md +++ b/README.ko.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.md b/README.md index a8551f97c57..60adea0e397 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.no.md b/README.no.md index 66f219329b9..68b557df3b5 100644 --- a/README.no.md +++ b/README.no.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.pl.md b/README.pl.md index 0678de6068d..0618af87d61 100644 --- a/README.pl.md +++ b/README.pl.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.ru.md b/README.ru.md index a5ab7104944..e369c7f47de 100644 --- a/README.ru.md +++ b/README.ru.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.th.md b/README.th.md index f06abc17dc4..f1d7a6f356c 100644 --- a/README.th.md +++ b/README.th.md @@ -11,7 +11,7 @@

Discord npm - สถานะการสร้าง + สถานะการสร้าง

diff --git a/README.tr.md b/README.tr.md index ef084543fef..e009219bacc 100644 --- a/README.tr.md +++ b/README.tr.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.uk.md b/README.uk.md index 32852565a8f..6b38e51242f 100644 --- a/README.uk.md +++ b/README.uk.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.vi.md b/README.vi.md index 5295504cd84..d25173ac007 100644 --- a/README.vi.md +++ b/README.vi.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.zh.md b/README.zh.md index fbdfb9d3ed0..2f364601e4a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/README.zht.md b/README.zht.md index a22b6159e22..be90cb3cba6 100644 --- a/README.zht.md +++ b/README.zht.md @@ -11,7 +11,7 @@

Discord npm - Build status + Build status

diff --git a/bun.lock b/bun.lock index 3eb829c1b84..061f7188b61 100644 --- a/bun.lock +++ b/bun.lock @@ -340,7 +340,6 @@ "@opencode/schema": "workspace:*", "@opencode/ui": "workspace:*", "@sentry/solid": "catalog:", - "@sentry/vite-plugin": "catalog:", "@solidjs/router": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/nix/desktop.nix b/nix/desktop.nix index 73a4e806fe2..35ddfd03c53 100644 --- a/nix/desktop.nix +++ b/nix/desktop.nix @@ -96,7 +96,7 @@ stdenv.mkDerivation (finalAttrs: { cd packages/desktop export OPENCODE_CLI_DIST="$TMPDIR/desktop-cli" - cli_package=$(bun -e 'import { getCurrentCli } from "./scripts/utils.ts"; console.log(getCurrentCli().package.replace("@opencode/", ""))') + cli_package=$(bun -e 'import { getCurrentCli } from "./script/utils.ts"; console.log(getCurrentCli().package.replace("@opencode/", ""))') # copyBuiltCliToResources joins this dist with the npm package name getCurrentCli() # reports, not the Nix build's name. It reads only .version from the manifest and # writes it as opencode-cli.version beside the binary. diff --git a/package.json b/package.json index c66ce1f65bd..47fc91f7faa 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "check": "bun run lint && bun run typecheck", "typecheck:profile": "bun script/profile-typecheck.ts", "typecheck:profile:packages": "bun script/profile-typecheck-packages.ts", + "pack": "bun run script/pack.ts", "upgrade-opentui": "bun run script/upgrade-opentui.ts", "postinstall": "bun run --cwd packages/core fix-node-pty", "prepare": "husky", diff --git a/packages/ai/package.json b/packages/ai/package.json index 7d7f20b9d90..e4cf2415342 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -9,7 +9,8 @@ "test": "bun test --timeout 30000 --only-failures", "typecheck": "bun check --no-script && bun check --no-script -p tsconfig.types.json", "typecheck:tsc": "tsc --noEmit && tsc --noEmit -p tsconfig.types.json", - "build": "tsc -p tsconfig.build.json" + "build": "tsc -p tsconfig.build.json", + "pack": "bun run script/pack.ts" }, "files": [ "dist" diff --git a/packages/ai/script/pack.ts b/packages/ai/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/ai/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/ai/script/publish.ts b/packages/ai/script/publish.ts deleted file mode 100644 index 77eca8806a6..00000000000 --- a/packages/ai/script/publish.ts +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bun -import { Script } from "@opencode/script" -import { $ } from "bun" -import { fileURLToPath } from "url" - -const dir = fileURLToPath(new URL("..", import.meta.url)) -process.chdir(dir) - -async function published(name: string, version: string) { - return (await $`npm view ${name}@${version} version`.nothrow()).exitCode === 0 -} - -await $`bun run build` -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -if (await published(pkg.name, pkg.version)) { - console.log(`already published ${pkg.name}@${pkg.version}`) -} else { - for (const [key, value] of Object.entries(pkg.exports)) { - const file = value.replace("./src/", "./dist/").replace(".ts", "") - // @ts-ignore - pkg.exports[key] = { - import: file + ".js", - types: file + ".d.ts", - } - } - await Bun.write("package.json", JSON.stringify(pkg, null, 2)) - try { - await $`bun pm pack` - await $`npm publish *.tgz --tag ${Script.channel} --access public` - } finally { - await Bun.write("package.json", originalText) - } -} diff --git a/packages/app/README.md b/packages/app/README.md index 3e10fc3893d..90951727d6d 100644 --- a/packages/app/README.md +++ b/packages/app/README.md @@ -75,7 +75,7 @@ The `deploy` GitHub Actions workflow uses SST to deploy the web app to `beta.ope `beta` branch in `anomalyco/opencode`. The `dev` and `production` stages do not deploy the web app. `beta` is the team's dogfooding branch: `dev` merged in by hand, plus commits pushed directly to it. Do not rebase or -force-push it. Each push also runs the `publish` workflow, which ships the same commit as the OpenCode Beta desktop app +force-push it. Each push also runs the `release` workflow, which ships the same commit as the OpenCode Beta desktop app (see `packages/desktop/README.md`). The beta SST stage deploys only the web app, using the `WebApp` StaticSiteV2 definition in `infra/webapp.ts`. It sets diff --git a/packages/app/e2e/performance/devex/desktop-startup.ts b/packages/app/e2e/performance/devex/desktop-startup.ts index 14501c1e31b..e37b8c9fb0b 100644 --- a/packages/app/e2e/performance/devex/desktop-startup.ts +++ b/packages/app/e2e/performance/devex/desktop-startup.ts @@ -134,7 +134,7 @@ export function milestoneForLine(line: string): Milestone | undefined { const milestonePatterns: ReadonlyArray<{ name: Milestone; text: string }> = [ { name: "bunRootScript", text: "$ bun --cwd packages/desktop dev" }, - { name: "bunDesktopScript", text: "$ bun ./scripts/dev.ts" }, + { name: "bunDesktopScript", text: "$ bun run script/dev.ts" }, { name: "desktopPrepared", text: "Copied dev icons from" }, { name: "mainBundleReady", text: "electron main process built successfully" }, { name: "preloadBundleReady", text: "electron preload scripts built successfully" }, diff --git a/packages/app/e2e/performance/unit/desktop-startup.test.ts b/packages/app/e2e/performance/unit/desktop-startup.test.ts index cb395fe73aa..7e08823643b 100644 --- a/packages/app/e2e/performance/unit/desktop-startup.test.ts +++ b/packages/app/e2e/performance/unit/desktop-startup.test.ts @@ -12,7 +12,7 @@ describe("desktop startup benchmark", () => { test("recognizes startup milestones in colored output", () => { const cases = [ ["bunRootScript", "$ bun --cwd packages/desktop dev"], - ["bunDesktopScript", "$ bun ./scripts/dev.ts"], + ["bunDesktopScript", "$ bun run script/dev.ts"], ["desktopPrepared", "Copied dev icons from"], ["mainBundleReady", "electron main process built successfully"], ["preloadBundleReady", "electron preload scripts built successfully"], diff --git a/packages/cli/package.json b/packages/cli/package.json index 8d799cc6596..1498db30ca9 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -19,6 +19,8 @@ "scripts": { "build": "bun run script/build.ts", "build:node": "bun run script/build-node.ts", + "pack": "bun run script/pack.ts", + "pack:docker": "chmod +x dist/cli-linux-*-musl/bin/opencode && mkdir -p ../../dist/docker && docker buildx build --platform linux/amd64,linux/arm64 --output type=oci,dest=../../dist/docker/opencode-image.tar .", "dev": "bun run src/index.ts", "test": "bun test --timeout 30000 --only-failures", "typecheck": "bun check --no-script -b", diff --git a/packages/cli/script/build-node.ts b/packages/cli/script/build-node.ts index c3c185634bc..92330fdd5ee 100644 --- a/packages/cli/script/build-node.ts +++ b/packages/cli/script/build-node.ts @@ -21,7 +21,7 @@ const NODE_VERSION = "26.4.0" const dir = path.resolve(import.meta.dirname, "..") const outdir = path.resolve( dir, - process.argv.find((arg) => arg.startsWith("--outdir="))?.slice("--outdir=".length) ?? "dist", + process.argv.find((arg) => arg.startsWith("--outdir="))?.slice("--outdir=".length) ?? "dist/node", ) if (outdir === dir) throw new Error("--outdir must not be the package directory") if (outdir === path.join(dir, "dist-node")) { @@ -32,9 +32,9 @@ const single = process.argv.includes("--single") const skipInstall = process.argv.includes("--skip-install") const appArchiveOnly = process.argv.includes("--app-archive-only") const highlights = Script.preview ? undefined : embed(process.env.OPENCODE_RELEASE_NOTES) -const requestedArchive = process.argv.find((arg) => arg.startsWith("--app-archive="))?.slice("--app-archive=".length) +const requestedArchive = process.env.OPENCODE_APP_ARCHIVE const archivePath = requestedArchive ? path.resolve(dir, requestedArchive) : undefined -const requested = process.argv.find((arg) => arg.startsWith("--target="))?.slice("--target=".length) +const requested = process.env.OPENCODE_TARGET const allTargets = [ nodeTarget("linux", "arm64"), nodeTarget("linux", "x64"), @@ -51,7 +51,7 @@ const targets = requested process.chdir(dir) if (!skipInstall) run(process.execPath, ["install", "--os=*", "--cpu=*"]) if (appArchiveOnly) { - if (!archivePath) throw new Error("--app-archive-only requires --app-archive=") + if (!archivePath) throw new Error("--app-archive-only requires OPENCODE_APP_ARCHIVE") await mkdir(path.dirname(archivePath), { recursive: true }) await writeFile(archivePath, await buildAppArchive(Script.channel)) process.exit(0) diff --git a/packages/cli/script/build.ts b/packages/cli/script/build.ts index 75a1d948738..88cd3210245 100755 --- a/packages/cli/script/build.ts +++ b/packages/cli/script/build.ts @@ -28,7 +28,7 @@ await rm(outdir, { recursive: true, force: true }) const singleFlag = process.argv.includes("--single") const baselineFlag = process.argv.includes("--baseline") -const requestedTarget = process.argv.find((arg) => arg.startsWith("--target="))?.slice("--target=".length) +const requestedTarget = process.env.OPENCODE_TARGET const skipInstall = process.argv.includes("--skip-install") const skipWebUi = process.argv.includes("--skip-web-ui") const solidPlugin = createSolidTransformPlugin() @@ -58,7 +58,7 @@ const allTargets: { const targets = requestedTarget !== undefined - ? allTargets.filter((item) => targetName(item) === requestedTarget) + ? allTargets.filter((item) => targetName(item) === `${binary}-${requestedTarget}`) : singleFlag ? allTargets.filter((item) => { if (item.os !== process.platform || item.arch !== process.arch) return false diff --git a/packages/cli/script/catalog-smoke.ts b/packages/cli/script/catalog-smoke.ts index 7cd3211f4c8..b885504c6b8 100644 --- a/packages/cli/script/catalog-smoke.ts +++ b/packages/cli/script/catalog-smoke.ts @@ -5,7 +5,8 @@ import os from "node:os" import path from "node:path" const catalog = process.env.OPENCODE_MODELS_SNAPSHOT -const binary = process.argv[2] +// Resolved before spawning: the binary runs from a temporary directory. +const binary = process.argv[2] && path.resolve(process.argv[2]) if (!catalog || !binary) throw new Error("Usage: OPENCODE_MODELS_SNAPSHOT= catalog-smoke.ts ") const providers: Record = await Bun.file(catalog).json() diff --git a/packages/cli/script/publish.ts b/packages/cli/script/pack.ts similarity index 57% rename from packages/cli/script/publish.ts rename to packages/cli/script/pack.ts index b5ca32787eb..b66cfb2e349 100755 --- a/packages/cli/script/publish.ts +++ b/packages/cli/script/pack.ts @@ -2,38 +2,47 @@ import { $ } from "bun" import pkg from "../package.json" import { Script } from "@opencode/script" -import { fileURLToPath } from "url" +import { archiveDir, npmDir } from "@opencode/script/pack" import { existsSync } from "fs" -import { chmod, rm, utimes } from "node:fs/promises" +import { chmod, mkdir, rm, utimes } from "node:fs/promises" import path from "node:path" -import { UpdateArtifact } from "../../../script/update-artifact" -const dir = fileURLToPath(new URL("..", import.meta.url)) -const root = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(dir, "dist")) +// Packs the built CLI (dist/) into npm tarballs in dist/npm and standalone archives in dist/archives at +// the repository root. The release workflow signs the macOS and Windows packages and archives afterwards. +const dir = path.resolve(import.meta.dir, "..") +const root = path.join(dir, "dist") process.chdir(dir) -const dryRun = process.argv.includes("--dry-run") +await mkdir(npmDir, { recursive: true }) +await mkdir(archiveDir, { recursive: true }) -async function published(name: string, version: string) { - return (await $`npm view ${name}@${version} version`.nothrow()).exitCode === 0 +await packDistribution({ + root, + name: pkg.name, + command: "opencode", + legacyCommand: "opencode2", + binary: "opencode", + packagePrefix: "@opencode/cli-", + archive: (target) => target.startsWith("linux-"), +}) +if (existsSync(path.join(root, "node"))) { + await packDistribution({ + root: path.join(root, "node"), + name: "@opencode/cli-node", + command: "opencode2-node", + binary: "opencode2-node", + packagePrefix: "@opencode/cli-node-", + archive: () => true, + }) } -async function publish(dir: string, name: string, version: string) { - if (process.platform !== "win32") await $`chmod -R 755 .`.cwd(dir) - const exists = !dryRun && (await published(name, version)) - if (exists) console.log(`already published ${name}@${version}`) - // Keep local tarballs available to downstream publishers when retrying a release. - await $`bun pm pack`.cwd(dir) - if (!exists && !dryRun) await $`npm publish *.tgz --access public --tag ${Script.channel}`.cwd(dir) -} - -async function publishDistribution(input: { +async function packDistribution(input: { root: string name: string command: string legacyCommand?: string binary: string packagePrefix: string - artifact: string + archive: (target: string) => boolean }) { const binaries: Record = {} for (const filepath of new Bun.Glob("*/package.json").scanSync({ cwd: input.root })) { @@ -82,80 +91,28 @@ async function publishDistribution(input: { ), ) + await Promise.all(Object.keys(binaries).map((name) => pack(`${input.root}/${name.replace("@opencode/", "")}`))) + await pack(`${input.root}/${input.name}`) await Promise.all( - Object.entries(binaries).map(([name, version]) => - publish(`${input.root}/${name.replace("@opencode/", "")}`, name, version), - ), - ) - await publish(`${input.root}/${input.name}`, input.name, version) - const files = await UpdateArtifact.upload({ - version, - files: await Promise.all( - Object.keys(binaries).map((name) => + Object.keys(binaries) + .map((name) => name.slice(input.packagePrefix.length)) + .filter(input.archive) + .map((target) => archive( - path.join(input.root, name.replace("@opencode/", ""), "bin"), - name.slice(input.packagePrefix.length), + path.join(input.root, `${input.packagePrefix.replace("@opencode/", "")}${target}`, "bin"), + target, input.binary, - input.root, ), ), - ), - dryRun, - }) - const artifact = { - channel: Script.channel, - name: input.artifact, - distribution: "opencode", - version, - metadata: { files }, - } - if (dryRun) { - console.log(`dry-run artifact: ${JSON.stringify(artifact)}`) - return - } - await UpdateArtifact.publish({ - channel: Script.channel, - name: input.artifact, - distribution: "npm", - version, - metadata: { package: input.name }, - }) - await UpdateArtifact.publish(artifact) + ) } -await publishDistribution({ - root, - name: pkg.name, - command: "opencode", - legacyCommand: "opencode2", - binary: "opencode", - packagePrefix: "@opencode/cli-", - artifact: "cli", -}) -if (Script.channel !== "latest" && existsSync(path.join(root, "node"))) { - await publishDistribution({ - root: path.join(root, "node"), - name: "@opencode/cli-node", - command: "opencode2-node", - binary: "opencode2-node", - packagePrefix: "@opencode/cli-node-", - artifact: "cli-node", - }) +async function pack(directory: string) { + if (process.platform !== "win32") await $`chmod -R 755 .`.cwd(directory) + await $`bun pm pack --destination ${npmDir}`.cwd(directory) } -if (Script.channel === "latest" && Script.release && !dryRun) { - await $`docker buildx build --platform linux/amd64,linux/arm64 --tag ghcr.io/anomalyco/opencode:${Script.version} --push .` -} - -if ((Script.channel === "beta" || Script.channel === "latest") && Script.release) { - await $`bun ./script/publish-aur.ts ${dryRun ? ["--dry-run"] : []}`.env({ ...process.env, OPENCODE_CLI_DIST: root }) - await $`bun ./script/publish-homebrew.ts ${dryRun ? ["--dry-run"] : []}`.env({ - ...process.env, - OPENCODE_CLI_DIST: root, - }) -} - -async function archive(bin: string, target: string, binary: string, directory: string) { +async function archive(bin: string, target: string, binary: string) { const executable = `${binary}${target.startsWith("windows-") ? ".exe" : ""}` const source = path.join(bin, executable) if (!(await Bun.file(source).exists()) || !Bun.file(source).size) throw new Error(`Missing binary: ${source}`) @@ -163,7 +120,7 @@ async function archive(bin: string, target: string, binary: string, directory: s await chmod(source, 0o755) await utimes(source, new Date("1980-01-01T00:00:00Z"), new Date("1980-01-01T00:00:00Z")) const extension = target.startsWith("linux-") ? "tar.gz" : "zip" - const output = path.join(directory, `${binary}-${target}.${extension}`) + const output = path.join(archiveDir, `${binary}-${target}.${extension}`) await rm(output, { force: true }) if (extension === "tar.gz") { await $`tar --mtime=@0 --owner=0 --group=0 --numeric-owner -czf ${output} -C ${bin} ${executable}` diff --git a/packages/cli/script/publish-aur.ts b/packages/cli/script/publish-aur.ts deleted file mode 100644 index f18a294aeb3..00000000000 --- a/packages/cli/script/publish-aur.ts +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env bun -import { Script } from "@opencode/script" -import { $ } from "bun" -import { mkdir, rm } from "node:fs/promises" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { UpdateArtifact } from "../../../script/update-artifact" - -if (Script.channel !== "beta" && Script.channel !== "latest") { - throw new Error("AUR publishing requires the beta or latest channel") -} -const name = "opencode-beta" -const command = "opencode" -const valid = - Script.channel === "beta" - ? /^\d+\.\d+\.\d+-beta[.-]\d+(?:\.\d+)?$/.test(Script.version) - : /^\d+\.\d+\.\d+$/.test(Script.version) -if (!valid) throw new Error(`Expected a ${Script.channel} release version`) - -const dir = fileURLToPath(new URL("..", import.meta.url)) -const root = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(dir, "dist")) -const outdir = path.join(root, `aur-${name}`) -const dryRun = process.argv.includes("--dry-run") -const pkgver = Script.version.replaceAll("-", ".") -const license = Bun.file(path.join(dir, "..", "..", "LICENSE")) -const shim = `#!/bin/sh -exec "$(dirname "$0")/opencode" "$@" -` - -await rm(outdir, { recursive: true, force: true }) -await mkdir(path.dirname(outdir), { recursive: true }) -if (dryRun) await mkdir(outdir) -if (!dryRun) { - await $`git clone ${`ssh://aur@aur.archlinux.org/${name}.git`} ${outdir}` - await $`git checkout -B master`.cwd(outdir) -} - -const sources = await Promise.all( - [ - { arch: "x86_64", target: "linux-x64-baseline" }, - { arch: "aarch64", target: "linux-arm64" }, - ].map(async (item) => { - const directory = path.join(root, `cli-${item.target}`) - const pkg: { name: string; version: string } = await Bun.file(path.join(directory, "package.json")).json() - if (pkg.version !== Script.version) throw new Error(`Unexpected version for ${pkg.name}: ${pkg.version}`) - const archive = Bun.file(path.join(directory, `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz`)) - const filename = `${name}-${pkgver}-${item.arch}.tgz` - const url = `https://registry.npmjs.org/${pkg.name}/-/${pkg.name.split("/").at(-1)}-${pkg.version}.tgz` - const sha256 = new Bun.CryptoHasher("sha256").update(await archive.arrayBuffer()).digest("hex") - return [`source_${item.arch}=('${filename}::${url}')`, `sha256sums_${item.arch}=('${sha256}')`].join("\n") - }), -) - -await Bun.write(path.join(outdir, "LICENSE"), license) -await Bun.write(path.join(outdir, "opencode2"), shim) -await Bun.write( - path.join(outdir, "PKGBUILD"), - [ - "# Maintainer: Dax ", - `pkgname=${name}`, - `pkgver=${pkgver}`, - "pkgrel=1", - "pkgdesc='OpenCode beta - the AI coding agent for the terminal'", - "url='https://github.com/anomalyco/opencode'", - "arch=('x86_64' 'aarch64')", - "license=('MIT')", - "depends=('glibc' 'gcc-libs' 'ripgrep')", - `provides=('${command}' 'opencode2')`, - `conflicts=('${command}' 'opencode2')`, - // Stripping a compiled Bun executable can damage its embedded application. - "options=('!strip' '!debug')", - "source=('LICENSE' 'opencode2')", - `sha256sums=('${new Bun.CryptoHasher("sha256").update(await license.arrayBuffer()).digest("hex")}' '${new Bun.CryptoHasher("sha256").update(shim).digest("hex")}')`, - ...sources, - "", - "package() {", - ` install -Dm755 "$srcdir/package/bin/opencode" "$pkgdir/usr/bin/${command}"`, - ' install -Dm755 "$srcdir/opencode2" "$pkgdir/usr/bin/opencode2"', - ' install -Dm644 "$srcdir/LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"', - "}", - "", - ].join("\n"), -) -await Bun.write(path.join(outdir, ".SRCINFO"), await $`makepkg --printsrcinfo`.cwd(outdir).text()) -console.log(`Prepared ${name} ${pkgver} in ${outdir}`) -if (dryRun) process.exit(0) - -await $`git add PKGBUILD .SRCINFO LICENSE opencode2`.cwd(outdir) -if ((await $`git diff --cached --quiet`.cwd(outdir).nothrow()).exitCode !== 0) { - await $`git commit -m ${`chore: update ${name} to ${pkgver}`}`.cwd(outdir) - await $`git push origin master`.cwd(outdir) -} -await UpdateArtifact.publish({ - channel: Script.channel, - name: "cli", - distribution: "aur", - version: Script.version, - metadata: { package: name }, -}) diff --git a/packages/cli/script/publish-homebrew.ts b/packages/cli/script/publish-homebrew.ts deleted file mode 100644 index a9a7ed2f47a..00000000000 --- a/packages/cli/script/publish-homebrew.ts +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env bun -import { Script } from "@opencode/script" -import { $ } from "bun" -import { mkdir, rm } from "node:fs/promises" -import path from "node:path" -import { fileURLToPath } from "node:url" -import { UpdateArtifact } from "../../../script/update-artifact" - -if (Script.channel !== "beta" && Script.channel !== "latest") { - throw new Error("Homebrew publishing requires the beta or latest channel") -} -const valid = - Script.channel === "beta" - ? /^\d+\.\d+\.\d+-beta[.-]\d+(?:\.\d+)?$/.test(Script.version) - : /^\d+\.\d+\.\d+$/.test(Script.version) -if (!valid) throw new Error(`Expected a ${Script.channel} release version`) - -const dir = fileURLToPath(new URL("..", import.meta.url)) -const root = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(dir, "dist")) -const outdir = path.join(root, "homebrew-tap") -const dryRun = process.argv.includes("--dry-run") -const name = Script.channel === "beta" ? "opencode-beta" : "opencode-v2" -const formulaClass = Script.channel === "beta" ? "OpencodeBeta" : "OpencodeV2" - -const targets = await Promise.all( - [ - { name: "darwin-arm64", archive: "zip" }, - { name: "darwin-x64-baseline", archive: "zip" }, - { name: "linux-arm64", archive: "tar.gz" }, - { name: "linux-x64-baseline", archive: "tar.gz" }, - ].map(async (target) => { - const filename = `opencode-${target.name}.${target.archive}` - const file = Bun.file(path.join(root, filename)) - if (!(await file.exists()) || !file.size) throw new Error(`Missing Homebrew archive: ${filename}`) - const sha256 = new Bun.CryptoHasher("sha256") - for await (const chunk of file.stream()) sha256.update(chunk) - return { - ...target, - url: `https://opencode.ai/files/bin/${encodeURIComponent(Script.version)}/${filename}`, - sha256: sha256.digest("hex"), - } - }), -) - -await rm(outdir, { recursive: true, force: true }) -if (dryRun) await mkdir(outdir, { recursive: true }) -if (!dryRun) { - const token = process.env.GITHUB_TOKEN - if (!token) throw new Error("GITHUB_TOKEN is required to update the Homebrew tap") - await $`git clone ${`https://x-access-token:${token}@github.com/anomalyco/homebrew-tap.git`} ${outdir}` - await $`git checkout -B master`.cwd(outdir) -} - -const target = (name: string) => { - const result = targets.find((item) => item.name === name) - if (!result) throw new Error(`Missing Homebrew target: ${name}`) - return result -} -const macArm = target("darwin-arm64") -const macIntel = target("darwin-x64-baseline") -const linuxArm = target("linux-arm64") -const linuxIntel = target("linux-x64-baseline") - -await Bun.write( - path.join(outdir, `${name}.rb`), - [ - "# typed: false", - "# frozen_string_literal: true", - "", - `class ${formulaClass} < Formula`, - ` desc "OpenCode V2${Script.channel === "beta" ? " beta" : ""} - the AI coding agent for the terminal"`, - ' homepage "https://github.com/anomalyco/opencode"', - ` version "${Script.version}"`, - ' license "MIT"', - "", - ' depends_on "ripgrep"', - ' conflicts_with "opencode", because: "both install an opencode binary"', - "", - " on_macos do", - " if Hardware::CPU.arm?", - ` url "${macArm.url}"`, - ` sha256 "${macArm.sha256}"`, - " else", - ` url "${macIntel.url}"`, - ` sha256 "${macIntel.sha256}"`, - " end", - " end", - "", - " on_linux do", - " if Hardware::CPU.arm?", - ` url "${linuxArm.url}"`, - ` sha256 "${linuxArm.sha256}"`, - " else", - ` url "${linuxIntel.url}"`, - ` sha256 "${linuxIntel.sha256}"`, - " end", - " end", - "", - " def install", - ' bin.install "opencode"', - " end", - "end", - "", - ].join("\n"), -) -console.log(`Prepared ${name} ${Script.version} in ${outdir}`) -if (dryRun) process.exit(0) - -await $`git add ${name + ".rb"}`.cwd(outdir) -if ((await $`git diff --cached --quiet`.cwd(outdir).nothrow()).exitCode !== 0) { - await $`git commit -m ${`chore: update ${name} to ${Script.version}`}`.cwd(outdir) - await $`git push origin master`.cwd(outdir) -} -await UpdateArtifact.publish({ - channel: Script.channel, - name: "cli", - distribution: "homebrew", - version: Script.version, - metadata: { package: `anomalyco/tap/${name}` }, -}) diff --git a/packages/client/package.json b/packages/client/package.json index 0ef2d11bded..5573dc862af 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -27,8 +27,9 @@ "./mcp": "./src/mcp.ts" }, "scripts": { - "build": "bun run script/build-package.ts", - "generate": "bun run script/build.ts", + "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", + "generate": "bun run script/generate.ts", "check:generated": "bun run generate && git diff --exit-code -- src/promise/generated src/effect/generated src/effect/api", "test": "bun test --timeout 5000", "typecheck": "bun check --no-script", diff --git a/packages/client/script/build-package.ts b/packages/client/script/build-package.ts deleted file mode 100644 index b7ea4d851b2..00000000000 --- a/packages/client/script/build-package.ts +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bun - -import { $ } from "bun" -import path from "node:path" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -await $`rm -rf dist` -await $`bun tsc -p tsconfig.build.json` -const root = path.resolve("src") -const result = await Bun.build({ - entrypoints: await Array.fromAsync(new Bun.Glob("**/*.ts").scan({ cwd: root, absolute: true })).then((files) => - files.filter((file) => !file.endsWith(".d.ts")), - ), - root, - outdir: "dist", - target: "node", - format: "esm", - packages: "external", - splitting: true, - naming: { - entry: "[dir]/[name].[ext]", - chunk: "chunks/[name]-[hash].[ext]", - }, -}) -if (!result.success) throw new AggregateError(result.logs, "Failed to build Client") diff --git a/packages/client/script/build.ts b/packages/client/script/build.ts index 5068e32f1fa..b7ea4d851b2 100644 --- a/packages/client/script/build.ts +++ b/packages/client/script/build.ts @@ -1,141 +1,27 @@ -import { NodeFileSystem } from "@effect/platform-node" -import { compile, emitEffectImported, emitEffectShape, emitPromise, write } from "@opencode/httpapi-codegen" -import { ClientApi, effectOmitEndpoints, groupNames, promiseOmitEndpoints } from "@opencode/protocol/client" -import { Agent } from "@opencode/schema/agent" -import { Command } from "@opencode/schema/command" -import { Config } from "@opencode/schema/config" -import { Credential } from "@opencode/schema/credential" -import { Event } from "@opencode/schema/event" -import { EventLog } from "@opencode/schema/event-log" -import { FileDiff } from "@opencode/schema/file-diff" -import { FileSystem } from "@opencode/schema/filesystem" -import { Form } from "@opencode/schema/form" -import { Instruction } from "@opencode/schema/instruction" -import { InstructionEntry } from "@opencode/schema/instruction-entry" -import { Integration } from "@opencode/schema/integration" -import { Location } from "@opencode/schema/location" -import { Mcp } from "@opencode/schema/mcp" -import { Model } from "@opencode/schema/model" -import { Money } from "@opencode/schema/money" -import { Permission } from "@opencode/schema/permission" -import { PermissionSaved } from "@opencode/schema/permission-saved" -import { Plugin } from "@opencode/schema/plugin" -import { Project } from "@opencode/schema/project" -import { Worktree } from "@opencode/schema/worktree" -import { AgentAttachment, FileAttachment, Prompt, PromptMention } from "@opencode/schema/prompt" -import { PromptInput } from "@opencode/schema/prompt-input" -import { Provider } from "@opencode/schema/provider" -import { Pty } from "@opencode/schema/pty" -import { PtyTicket } from "@opencode/schema/pty-ticket" -import { Question } from "@opencode/schema/question" -import { Reference } from "@opencode/schema/reference" -import { AbsolutePath, RelativePath } from "@opencode/schema/schema" -import { Session } from "@opencode/schema/session" -import { SessionMessage } from "@opencode/schema/session-message" -import { SessionInbox } from "@opencode/schema/session-inbox" -import { Shell } from "@opencode/schema/shell" -import { Skill } from "@opencode/schema/skill" -import { Snapshot } from "@opencode/schema/snapshot" -import { UsageLimits } from "@opencode/schema/usage-limits" -import { Vcs } from "@opencode/schema/vcs" -import { WebSearch } from "@opencode/schema/websearch" -import { Workspace } from "@opencode/schema/workspace" -import { Effect, Schema } from "effect" -import { fileURLToPath } from "url" +#!/usr/bin/env bun -const promiseContract = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints }) -const effectContract = compile(ClientApi, { groupNames, omitEndpoints: effectOmitEndpoints }) -const effectTypeReferences = [ - ...namespaceTypes("Agent", "@opencode/schema/agent", Agent), - ...namespaceTypes("Command", "@opencode/schema/command", Command), - ...namespaceTypes("Config", "@opencode/schema/config", Config), - ...namespaceTypes("Credential", "@opencode/schema/credential", Credential), - ...namespaceTypes("Event", "@opencode/schema/event", Event), - ...namespaceTypes("EventLog", "@opencode/schema/event-log", EventLog), - ...namespaceTypes("FileDiff", "@opencode/schema/file-diff", FileDiff), - ...namespaceTypes("FileSystem", "@opencode/schema/filesystem", FileSystem), - ...namespaceTypes("Form", "@opencode/schema/form", Form), - ...namespaceTypes("Instruction", "@opencode/schema/instruction", Instruction), - ...namespaceTypes("InstructionEntry", "@opencode/schema/instruction-entry", InstructionEntry), - ...namespaceTypes("Integration", "@opencode/schema/integration", Integration), - typeReference("Location.PublicRef", "@opencode/schema/location", Location.PublicRef), - typeReference("Location.PublicInfo", "@opencode/schema/location", Location.PublicInfo), - ...namespaceTypes("Mcp", "@opencode/schema/mcp", Mcp), - ...namespaceTypes("Model", "@opencode/schema/model", Model), - ...namespaceTypes("Money", "@opencode/schema/money", Money), - ...namespaceTypes("Permission", "@opencode/schema/permission", Permission), - ...namespaceTypes("PermissionSaved", "@opencode/schema/permission-saved", PermissionSaved), - ...namespaceTypes("Plugin", "@opencode/schema/plugin", Plugin), - ...namespaceTypes("Project", "@opencode/schema/project", Project), - ...namespaceTypes("Worktree", "@opencode/schema/worktree", Worktree), - ...namespaceTypes("PromptInput", "@opencode/schema/prompt-input", PromptInput), - ...namespaceTypes("Provider", "@opencode/schema/provider", Provider), - ...namespaceTypes("Pty", "@opencode/schema/pty", Pty), - ...namespaceTypes("PtyTicket", "@opencode/schema/pty-ticket", PtyTicket), - ...namespaceTypes("Question", "@opencode/schema/question", Question), - ...namespaceTypes("Reference", "@opencode/schema/reference", Reference), - ...namespaceTypes("Session", "@opencode/schema/session", Session), - ...namespaceTypes("SessionMessage", "@opencode/schema/session-message", SessionMessage), - ...namespaceTypes("SessionInbox", "@opencode/schema/session-inbox", SessionInbox), - ...namespaceTypes("Shell", "@opencode/schema/shell", Shell), - ...namespaceTypes("Skill", "@opencode/schema/skill", Skill), - ...namespaceTypes("Snapshot", "@opencode/schema/snapshot", Snapshot), - ...namespaceTypes("UsageLimits", "@opencode/schema/usage-limits", UsageLimits), - ...namespaceTypes("Vcs", "@opencode/schema/vcs", Vcs), - ...namespaceTypes("WebSearch", "@opencode/schema/websearch", WebSearch), - ...namespaceTypes("Workspace", "@opencode/schema/workspace", Workspace), - typeReference("Prompt", "@opencode/schema/prompt", Prompt), - typeReference("PromptMention", "@opencode/schema/prompt", PromptMention), - typeReference("FileAttachment", "@opencode/schema/prompt", FileAttachment), - typeReference("AgentAttachment", "@opencode/schema/prompt", AgentAttachment), - typeReference("AbsolutePath", "@opencode/schema/schema", AbsolutePath), - typeReference("RelativePath", "@opencode/schema/schema", RelativePath), -] +import { $ } from "bun" +import path from "node:path" +import { fileURLToPath } from "node:url" -await Effect.runPromise( - Effect.all( - [ - write( - emitPromise(promiseContract, { - mutableOutputs: true, - }), - fileURLToPath(new URL("../src/promise/generated", import.meta.url)), - ), - write( - emitEffectImported(effectContract, { - module: "../../contract", - api: "ClientApi", - shapeModule: "../api/api.js", - }), - fileURLToPath(new URL("../src/effect/generated", import.meta.url)), - ), - write( - emitEffectShape(effectContract, { - typeReferences: effectTypeReferences, - outputTypes: { - "event.subscribe": { - name: "OpenCodeEvent", - import: 'import type { OpenCodeEvent } from "@opencode/protocol/groups/event"', - }, - }, - }), - fileURLToPath(new URL("../src/effect/api", import.meta.url)), - ), - ], - { concurrency: 3, discard: true }, - ).pipe(Effect.provide(NodeFileSystem.layer)), -) +process.chdir(fileURLToPath(new URL("..", import.meta.url))) -function namespaceTypes(namespace: string, module: string, values: object) { - return Object.entries(values).flatMap(([name, schema]) => - Schema.isSchema(schema) ? [typeReference(`${namespace}.${name}`, module, schema)] : [], - ) -} - -function typeReference(name: string, module: string, schema: Schema.Top) { - return { - schema, - name, - import: `import type { ${name.split(".")[0]} } from ${JSON.stringify(module)}`, - } -} +await $`rm -rf dist` +await $`bun tsc -p tsconfig.build.json` +const root = path.resolve("src") +const result = await Bun.build({ + entrypoints: await Array.fromAsync(new Bun.Glob("**/*.ts").scan({ cwd: root, absolute: true })).then((files) => + files.filter((file) => !file.endsWith(".d.ts")), + ), + root, + outdir: "dist", + target: "node", + format: "esm", + packages: "external", + splitting: true, + naming: { + entry: "[dir]/[name].[ext]", + chunk: "chunks/[name]-[hash].[ext]", + }, +}) +if (!result.success) throw new AggregateError(result.logs, "Failed to build Client") diff --git a/packages/client/script/generate.ts b/packages/client/script/generate.ts new file mode 100644 index 00000000000..5068e32f1fa --- /dev/null +++ b/packages/client/script/generate.ts @@ -0,0 +1,141 @@ +import { NodeFileSystem } from "@effect/platform-node" +import { compile, emitEffectImported, emitEffectShape, emitPromise, write } from "@opencode/httpapi-codegen" +import { ClientApi, effectOmitEndpoints, groupNames, promiseOmitEndpoints } from "@opencode/protocol/client" +import { Agent } from "@opencode/schema/agent" +import { Command } from "@opencode/schema/command" +import { Config } from "@opencode/schema/config" +import { Credential } from "@opencode/schema/credential" +import { Event } from "@opencode/schema/event" +import { EventLog } from "@opencode/schema/event-log" +import { FileDiff } from "@opencode/schema/file-diff" +import { FileSystem } from "@opencode/schema/filesystem" +import { Form } from "@opencode/schema/form" +import { Instruction } from "@opencode/schema/instruction" +import { InstructionEntry } from "@opencode/schema/instruction-entry" +import { Integration } from "@opencode/schema/integration" +import { Location } from "@opencode/schema/location" +import { Mcp } from "@opencode/schema/mcp" +import { Model } from "@opencode/schema/model" +import { Money } from "@opencode/schema/money" +import { Permission } from "@opencode/schema/permission" +import { PermissionSaved } from "@opencode/schema/permission-saved" +import { Plugin } from "@opencode/schema/plugin" +import { Project } from "@opencode/schema/project" +import { Worktree } from "@opencode/schema/worktree" +import { AgentAttachment, FileAttachment, Prompt, PromptMention } from "@opencode/schema/prompt" +import { PromptInput } from "@opencode/schema/prompt-input" +import { Provider } from "@opencode/schema/provider" +import { Pty } from "@opencode/schema/pty" +import { PtyTicket } from "@opencode/schema/pty-ticket" +import { Question } from "@opencode/schema/question" +import { Reference } from "@opencode/schema/reference" +import { AbsolutePath, RelativePath } from "@opencode/schema/schema" +import { Session } from "@opencode/schema/session" +import { SessionMessage } from "@opencode/schema/session-message" +import { SessionInbox } from "@opencode/schema/session-inbox" +import { Shell } from "@opencode/schema/shell" +import { Skill } from "@opencode/schema/skill" +import { Snapshot } from "@opencode/schema/snapshot" +import { UsageLimits } from "@opencode/schema/usage-limits" +import { Vcs } from "@opencode/schema/vcs" +import { WebSearch } from "@opencode/schema/websearch" +import { Workspace } from "@opencode/schema/workspace" +import { Effect, Schema } from "effect" +import { fileURLToPath } from "url" + +const promiseContract = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints }) +const effectContract = compile(ClientApi, { groupNames, omitEndpoints: effectOmitEndpoints }) +const effectTypeReferences = [ + ...namespaceTypes("Agent", "@opencode/schema/agent", Agent), + ...namespaceTypes("Command", "@opencode/schema/command", Command), + ...namespaceTypes("Config", "@opencode/schema/config", Config), + ...namespaceTypes("Credential", "@opencode/schema/credential", Credential), + ...namespaceTypes("Event", "@opencode/schema/event", Event), + ...namespaceTypes("EventLog", "@opencode/schema/event-log", EventLog), + ...namespaceTypes("FileDiff", "@opencode/schema/file-diff", FileDiff), + ...namespaceTypes("FileSystem", "@opencode/schema/filesystem", FileSystem), + ...namespaceTypes("Form", "@opencode/schema/form", Form), + ...namespaceTypes("Instruction", "@opencode/schema/instruction", Instruction), + ...namespaceTypes("InstructionEntry", "@opencode/schema/instruction-entry", InstructionEntry), + ...namespaceTypes("Integration", "@opencode/schema/integration", Integration), + typeReference("Location.PublicRef", "@opencode/schema/location", Location.PublicRef), + typeReference("Location.PublicInfo", "@opencode/schema/location", Location.PublicInfo), + ...namespaceTypes("Mcp", "@opencode/schema/mcp", Mcp), + ...namespaceTypes("Model", "@opencode/schema/model", Model), + ...namespaceTypes("Money", "@opencode/schema/money", Money), + ...namespaceTypes("Permission", "@opencode/schema/permission", Permission), + ...namespaceTypes("PermissionSaved", "@opencode/schema/permission-saved", PermissionSaved), + ...namespaceTypes("Plugin", "@opencode/schema/plugin", Plugin), + ...namespaceTypes("Project", "@opencode/schema/project", Project), + ...namespaceTypes("Worktree", "@opencode/schema/worktree", Worktree), + ...namespaceTypes("PromptInput", "@opencode/schema/prompt-input", PromptInput), + ...namespaceTypes("Provider", "@opencode/schema/provider", Provider), + ...namespaceTypes("Pty", "@opencode/schema/pty", Pty), + ...namespaceTypes("PtyTicket", "@opencode/schema/pty-ticket", PtyTicket), + ...namespaceTypes("Question", "@opencode/schema/question", Question), + ...namespaceTypes("Reference", "@opencode/schema/reference", Reference), + ...namespaceTypes("Session", "@opencode/schema/session", Session), + ...namespaceTypes("SessionMessage", "@opencode/schema/session-message", SessionMessage), + ...namespaceTypes("SessionInbox", "@opencode/schema/session-inbox", SessionInbox), + ...namespaceTypes("Shell", "@opencode/schema/shell", Shell), + ...namespaceTypes("Skill", "@opencode/schema/skill", Skill), + ...namespaceTypes("Snapshot", "@opencode/schema/snapshot", Snapshot), + ...namespaceTypes("UsageLimits", "@opencode/schema/usage-limits", UsageLimits), + ...namespaceTypes("Vcs", "@opencode/schema/vcs", Vcs), + ...namespaceTypes("WebSearch", "@opencode/schema/websearch", WebSearch), + ...namespaceTypes("Workspace", "@opencode/schema/workspace", Workspace), + typeReference("Prompt", "@opencode/schema/prompt", Prompt), + typeReference("PromptMention", "@opencode/schema/prompt", PromptMention), + typeReference("FileAttachment", "@opencode/schema/prompt", FileAttachment), + typeReference("AgentAttachment", "@opencode/schema/prompt", AgentAttachment), + typeReference("AbsolutePath", "@opencode/schema/schema", AbsolutePath), + typeReference("RelativePath", "@opencode/schema/schema", RelativePath), +] + +await Effect.runPromise( + Effect.all( + [ + write( + emitPromise(promiseContract, { + mutableOutputs: true, + }), + fileURLToPath(new URL("../src/promise/generated", import.meta.url)), + ), + write( + emitEffectImported(effectContract, { + module: "../../contract", + api: "ClientApi", + shapeModule: "../api/api.js", + }), + fileURLToPath(new URL("../src/effect/generated", import.meta.url)), + ), + write( + emitEffectShape(effectContract, { + typeReferences: effectTypeReferences, + outputTypes: { + "event.subscribe": { + name: "OpenCodeEvent", + import: 'import type { OpenCodeEvent } from "@opencode/protocol/groups/event"', + }, + }, + }), + fileURLToPath(new URL("../src/effect/api", import.meta.url)), + ), + ], + { concurrency: 3, discard: true }, + ).pipe(Effect.provide(NodeFileSystem.layer)), +) + +function namespaceTypes(namespace: string, module: string, values: object) { + return Object.entries(values).flatMap(([name, schema]) => + Schema.isSchema(schema) ? [typeReference(`${namespace}.${name}`, module, schema)] : [], + ) +} + +function typeReference(name: string, module: string, schema: Schema.Top) { + return { + schema, + name, + import: `import type { ${name.split(".")[0]} } from ${JSON.stringify(module)}`, + } +} diff --git a/packages/client/script/pack.ts b/packages/client/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/client/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/client/script/publish.ts b/packages/client/script/publish.ts deleted file mode 100644 index cea7358e4a6..00000000000 --- a/packages/client/script/publish.ts +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/codemode/package.json b/packages/codemode/package.json index c220aa042d2..d7de2c42977 100644 --- a/packages/codemode/package.json +++ b/packages/codemode/package.json @@ -21,6 +21,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit", "test": "bun test" diff --git a/packages/codemode/script/pack.ts b/packages/codemode/script/pack.ts new file mode 100644 index 00000000000..28c039c7157 --- /dev/null +++ b/packages/codemode/script/pack.ts @@ -0,0 +1,23 @@ +#!/usr/bin/env bun + +import { $ } from "bun" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" +import { pack } from "@opencode/script/pack" + +const tarball = await pack(path.resolve(import.meta.dir, "..")) + +// The package must import under Node and under Bun's workerd conditions once installed from the tarball. +const consumer = await mkdtemp(path.join(tmpdir(), "opencode-codemode-")) +try { + await Bun.write( + path.join(consumer, "package.json"), + JSON.stringify({ private: true, type: "module", dependencies: { "@opencode/codemode": `file:${tarball}` } }), + ) + await $`npm install --ignore-scripts --no-audit --no-fund`.cwd(consumer) + await $`node --input-type=module -e ${'await import("@opencode/codemode")'}`.cwd(consumer) + await $`bun --conditions=workerd -e ${'await import("@opencode/codemode")'}`.cwd(consumer) +} finally { + await rm(consumer, { recursive: true, force: true }) +} diff --git a/packages/codemode/script/publish.ts b/packages/codemode/script/publish.ts deleted file mode 100644 index b1039b4ed53..00000000000 --- a/packages/codemode/script/publish.ts +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { mkdtemp, rm } from "node:fs/promises" -import { tmpdir } from "node:os" -import { join } from "node:path" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const dryRun = Bun.argv.includes("--dry-run") -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record - imports?: Record> -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` -const output = (value: string, types = false) => - value.replace("./src/", "./dist/").replace(/\.ts$/, types ? ".d.ts" : ".js") - -if (!dryRun && (await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: output(value), - types: output(value, true), - }, - ] - }), - ) - if (pkg.imports) { - pkg.imports = Object.fromEntries( - Object.entries(pkg.imports).map(([key, conditions]) => [ - key, - Object.fromEntries(Object.entries(conditions).map(([condition, value]) => [condition, output(value)])), - ]), - ) - } - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - const consumer = await mkdtemp(join(tmpdir(), "opencode-codemode-")) - try { - await Bun.write( - join(consumer, "package.json"), - JSON.stringify({ - private: true, - type: "module", - dependencies: { [pkg.name]: `file:${join(process.cwd(), tarball)}` }, - }), - ) - await $`npm install --ignore-scripts --no-audit --no-fund`.cwd(consumer) - await $`node --input-type=module -e ${`await import(${JSON.stringify(pkg.name)})`}`.cwd(consumer) - await $`bun --conditions=workerd -e ${`await import(${JSON.stringify(pkg.name)})`}`.cwd(consumer) - } finally { - await rm(consumer, { recursive: true, force: true }) - } - if (!dryRun) await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/core/package.json b/packages/core/package.json index 20cf0992eca..bbae41e3804 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -22,6 +22,7 @@ "benchmark:location": "bun run script/benchmark-location.ts", "benchmark:location-memory": "bun run script/benchmark-location-memory.ts", "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "update-models-snapshot": "bun run script/update-models-snapshot.ts", "test": "bun run script/test.ts", "typecheck": "bun check --no-script -b -p tsconfig.tests.json", diff --git a/packages/core/script/pack.ts b/packages/core/script/pack.ts new file mode 100644 index 00000000000..43b22060ea9 --- /dev/null +++ b/packages/core/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, ".."), { types: "./dist/types/" }) diff --git a/packages/core/script/publish.ts b/packages/core/script/publish.ts deleted file mode 100644 index 3d234c650d8..00000000000 --- a/packages/core/script/publish.ts +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record - imports: Record> -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` -const output = (value: string, types = false) => - value.replace("./src/", types ? "./dist/types/" : "./dist/").replace(/\.ts$/, types ? ".d.ts" : ".js") - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [key, { import: output(value), types: output(value, true) }] - }), - ) - pkg.imports = Object.fromEntries( - Object.entries(pkg.imports).map(([key, conditions]) => [ - key, - Object.fromEntries( - Object.entries(conditions).map(([condition, value]) => [condition, output(value, condition === "types")]), - ), - ]), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/desktop/README.md b/packages/desktop/README.md index ec740d3378e..475e5e6873d 100644 --- a/packages/desktop/README.md +++ b/packages/desktop/README.md @@ -11,34 +11,28 @@ bun dev ## Build -Run the `build` script to build the app's JS assets, then `package` to -bundle the assets as an application. The resulting app will be in `dist/`. +`bun run build` prepares `resources/` (icons, metainfo and the bundled CLI) and builds the app into `out/`. +`bun run pack` then packages it, unsigned, into `dist/desktop/` at the repository root: a `.app` tarball on macOS, +the unpacked app on Windows, and AppImage/deb/rpm on Linux. The release workflow signs and notarizes afterwards. ```bash -bun run build && bun run package +bun run build && bun run pack ``` -Production builds require a prebuilt V2 CLI distribution. The release workflow supplies the artifact from the same run: +Both read the same environment as every other release package: -```bash -OPENCODE_CHANNEL=prod OPENCODE_CLI_DIST=/absolute/path/to/packages/cli/dist bun run build -OPENCODE_CHANNEL=prod bun run package -``` +| Variable | Meaning | +| ------------------ | --------------------------------------------------------------------------------------------------------------- | +| `OPENCODE_CHANNEL` | `dev` (default), `beta`, or `latest`/`prod`. Picks the app identity, icons and bundled CLI. | +| `OPENCODE_VERSION` | Version stamped into the app and its packages. | +| `OPENCODE_TARGET` | `darwin-arm64`, `darwin-x64`, `windows-arm64`, `windows-x64`, `linux-x64`, `linux-arm64`. Defaults to the host. | -Set `OPENCODE_CLI_TARGET` when packaging for a different architecture. The CLI is placed outside `app.asar` in the -application's resources directory, and packaging fails if it is missing. - -CLI preparation uses these channel rules: - -| Channel | Without `OPENCODE_CLI_DIST` | With `OPENCODE_CLI_DIST` | -| -------------------------------------- | ------------------------------ | --------------------------------------------- | -| `dev`, `local`, unset, or unrecognized | Download the dev CLI | Download the dev CLI; ignore the distribution | -| `beta` | Download the beta CLI | Copy the supplied CLI; fail if it is missing | -| `prod`, `latest` | Fail before changing resources | Copy the supplied CLI; fail if it is missing | +The CLI is placed outside `app.asar` in the application's resources directory, and packaging fails if it is missing. +`bun run build` uses `packages/cli/dist` when that holds the target's CLI. Otherwise `dev` (and `local`, unset or unrecognized) +downloads the published dev CLI, `beta` downloads the beta CLI, and `prod`/`latest` fail. `bun dev` is separate from packaging: it uses local renderer/server mode, the dev app identity, and the CLI source by -default. `bun dev --download-server ` instead downloads that CLI version for local development. Neither path -requires `OPENCODE_CLI_DIST` or runs the production prebuild. +default. `bun dev --download-server ` instead downloads that CLI version for local development. ## Beta channel @@ -48,7 +42,7 @@ from `dev`. Install it from `https://opencode.ai/download/beta/`, for `windows-x64-nsis`. Installed builds update in place on every platform. Each beta build compiles in its commit and the `feat`, `fix` and `perf` commits among its newest 200 -(`scripts/beta-notes.ts`, embedded by `electron.vite.config.ts`; run `bun scripts/beta-notes.ts` to preview them). After an +(`script/beta-notes.ts`, embedded by `electron.vite.config.ts`; run `bun script/beta-notes.ts` to preview them). After an update, the beta app lists the ones after the commit of the build the user saw last in a "What's new in beta" dialog, unless release notes are turned off in Settings. @@ -58,7 +52,7 @@ unless release notes are turned off in Settings. renderer going idle, so dev-server and bundling costs are not part of the numbers. ```bash -OPENCODE_CHANNEL=dev bun run build && bunx electron-builder --win --dir --config electron-builder.config.ts +OPENCODE_CHANNEL=dev bun run build && bun run pack bun run bench:startup -- --runs 5 # warm service (started once, reused by every launch) bun run bench:startup -- --runs 5 --compare dist/other/OpenCode\ Dev.exe # A/B: alternate launches of two builds bun run bench:startup -- --service cold # each launch spawns the service @@ -86,4 +80,4 @@ written to `dist/bench-startup`. A packaged beta or prod build registers itself as the `opencode://` handler when it starts, even from the bench; the installed app takes the registration back on its next launch. Those channels run with `HTTPS_PROXY` pointed at a -closed port (`--offline` forces it for dev) so the updater's first check fails fast instead of reaching GitHub. \ No newline at end of file +closed port (`--offline` forces it for dev) so the updater's first check fails fast instead of reaching GitHub. diff --git a/packages/desktop/electron-builder.config.test.ts b/packages/desktop/electron-builder.config.test.ts index 3b4f618fb12..b1b94f05421 100644 --- a/packages/desktop/electron-builder.config.test.ts +++ b/packages/desktop/electron-builder.config.test.ts @@ -7,7 +7,7 @@ import path from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import type { Configuration } from "electron-builder" import { getConfig } from "./electron-builder.config" -import { CLI_BINARIES, nodePtyPackage } from "./scripts/utils" +import { CLI_BINARIES, nodePtyPackage } from "./script/utils" // Use electron-builder's matcher so the tests also cover its glob and directory traversal semantics. const { FileMatcher } = createRequire(import.meta.resolve("electron-builder"))("app-builder-lib/out/fileMatcher") @@ -20,21 +20,21 @@ const channels = [ function load(channel: string, target?: string): Configuration { const previous = process.env.OPENCODE_CHANNEL - const previousTarget = process.env.OPENCODE_CLI_TARGET + const previousTarget = process.env.OPENCODE_TARGET process.env.OPENCODE_CHANNEL = channel - if (target !== undefined) process.env.OPENCODE_CLI_TARGET = target - else delete process.env.OPENCODE_CLI_TARGET + if (target !== undefined) process.env.OPENCODE_TARGET = target + else delete process.env.OPENCODE_TARGET try { return getConfig() } finally { delete process.env.OPENCODE_CHANNEL - delete process.env.OPENCODE_CLI_TARGET + delete process.env.OPENCODE_TARGET if (previous !== undefined) process.env.OPENCODE_CHANNEL = previous - if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget + if (previousTarget !== undefined) process.env.OPENCODE_TARGET = previousTarget } } @@ -84,7 +84,10 @@ test("legacy Linux launcher stays hidden", async () => { test("shared packaging defaults", async () => { const config = load("dev") - expect(config.mac?.sign).toBeFunction() + // Packaging runs in secretless build jobs; the release workflow signs and notarizes afterwards. + expect(config.mac?.sign).toBeUndefined() + expect(config.mac?.notarize).toBeUndefined() + expect(config.win?.signtoolOptions).toBeUndefined() expect(config.dmg?.sign).not.toBe(true) expect(config.mac?.extendInfo?.NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac).toBe(true) const include = path.join(import.meta.dirname, "resources/windows/installer.nsh") diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts index 5fcb7d0968d..0d489889710 100644 --- a/packages/desktop/electron-builder.config.ts +++ b/packages/desktop/electron-builder.config.ts @@ -1,23 +1,14 @@ -import { execFile } from "node:child_process" import { readdir, stat } from "node:fs/promises" import path from "node:path" import { fileURLToPath } from "node:url" -import { promisify } from "node:util" -import type { CustomMacSignOptions } from "app-builder-lib" import { Arch, type Configuration } from "electron-builder" import { NativeArch } from "../../script/native-arch" import { DESKTOP_NATIVE_ENGLISH } from "@opencode/app/i18n/desktop-native" -import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./scripts/utils" - -const execFileAsync = promisify(execFile) +import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./script/utils" const packageDir = path.dirname(fileURLToPath(import.meta.url)) -const rootDir = path.resolve(packageDir, "../..") - -const signScript = path.join(rootDir, "script", "sign-windows.ps1") - // The Electron 42 packaging update briefly installed Linux launchers/icons under // "opencode-desktop". Keep that hidden desktop entry around so existing GNOME/KDE // pins still resolve after the canonical app id changes back to ai.opencode.desktop. @@ -39,32 +30,6 @@ const metainfoFpm = (appId: string) => // compresses the payload about 3x faster than the deb default (-3) and 5x faster than the rpm default (-9). const betaCompressionFpm = (target: "deb" | "rpm") => [`--${target}-compression-level`, "1"] -async function signWindows(configuration: { path: string }) { - if (process.platform !== "win32") return - - if (process.env.GITHUB_ACTIONS !== "true") return - - await execFileAsync( - "pwsh", - ["-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", signScript, configuration.path], - { cwd: rootDir, windowsHide: true }, - ) -} - -function macSignOptions(options: CustomMacSignOptions): CustomMacSignOptions { - return { - ...options, - optionsForFile: (file) => { - const defaults = options.optionsForFile?.(file) - - if (file !== path.join(options.app, "Contents/Resources/opencode-cli")) return defaults ?? {} - - // The Bun CLI loads bun-pty's native library; Electron and its helpers do not need this exception. - return { ...defaults, entitlements: path.join(packageDir, "resources/entitlements.cli.plist") } - }, - } -} - function resolveChannel() { const raw = process.env.OPENCODE_CHANNEL @@ -96,6 +61,7 @@ function linuxExecutableName(appId: string): string { const getBase = (appId: string): Configuration => { const target = getCurrentCli() + const desktopName = `${appId}.desktop` return { artifactName: "opencode-desktop-${os}-${arch}.${ext}", @@ -108,9 +74,10 @@ const getBase = (appId: string): Configuration => { // "ai.opencode.desktop.desktop". // https://developer.gnome.org/documentation/guidelines/maintainer/integrating.html // https://www.electron.build/docs/linux/ - extraMetadata: { - desktopName: `${appId}.desktop`, - }, + // Release builds take their version from OPENCODE_VERSION instead of rewriting package.json. + extraMetadata: process.env.OPENCODE_VERSION + ? { desktopName, version: process.env.OPENCODE_VERSION } + : { desktopName }, files: [ "out/**/*", "resources/**/*", @@ -144,7 +111,7 @@ const getBase = (appId: string): Configuration => { afterPack: async (context) => { const arch = Arch[context.arch] - // The --arm64 flag picks Electron while OPENCODE_CLI_TARGET picks the CLI and node-pty, so they can disagree. + // The --arm64 flag picks Electron while OPENCODE_TARGET picks the CLI and node-pty, so they can disagree. if (arch !== "x64" && arch !== "arm64") throw new Error(`Unsupported desktop architecture: ${arch}`) if (arch !== target.cpu) throw new Error(`Packaging ${arch} Electron with the ${target.target} CLI`) @@ -191,15 +158,6 @@ const getBase = (appId: string): Configuration => { NSMicrophoneUsageDescription: DESKTOP_NATIVE_ENGLISH["desktop.microphoneUsage"], NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac: true, }, - hardenedRuntime: true, - gatekeeperAssess: false, - entitlements: "resources/entitlements.plist", - entitlementsInherit: "resources/entitlements.plist", - sign: async (options) => { - const { sign } = await import("app-builder-lib/out/codeSign/macCodeSign") - await sign(macSignOptions(options)) - }, - notarize: true, target: ["dmg", "zip"], }, protocols: { @@ -208,9 +166,6 @@ const getBase = (appId: string): Configuration => { }, win: { icon: `resources/icons/icon.ico`, - signtoolOptions: { - sign: signWindows, - }, target: ["nsis"], verifyUpdateCodeSignature: false, }, diff --git a/packages/desktop/electron.vite.config.test.ts b/packages/desktop/electron.vite.config.test.ts index bde20523324..b7bc28ece9d 100644 --- a/packages/desktop/electron.vite.config.test.ts +++ b/packages/desktop/electron.vite.config.test.ts @@ -5,7 +5,7 @@ import { MainConfigFactory } from "electron-vite" import { build } from "vite" import createConfig from "./electron.vite.config" import pkg from "./package.json" -import { CLI_BINARIES, nodePtyPackage } from "./scripts/utils" +import { CLI_BINARIES, nodePtyPackage } from "./script/utils" const load = async (command: "build" | "serve") => ({ config: await createConfig({ command, mode: command === "build" ? "production" : "development" }), @@ -16,7 +16,7 @@ const bundled = ["effect", "@effect/platform-node", "@effect/platform-node-share test("minifies only builds, previews onboarding only in development, and ships sourcemaps and public assets", async () => { const previous = process.env.OPENCODE_TEST_ONBOARDING - const previousTarget = process.env.OPENCODE_CLI_TARGET + const previousTarget = process.env.OPENCODE_TARGET try { process.env.OPENCODE_TEST_ONBOARDING = "1" @@ -36,7 +36,7 @@ test("minifies only builds, previews onboarding only in development, and ships s expect(serve.config.renderer?.define?.["import.meta.env.OPENCODE_TEST_ONBOARDING"]).toBe("false") for (const item of CLI_BINARIES) { - process.env.OPENCODE_CLI_TARGET = item.target + process.env.OPENCODE_TARGET = item.target const main = (await load("build")).config.main expect(main?.build?.externalizeDeps).toEqual({ exclude: bundled, @@ -45,11 +45,11 @@ test("minifies only builds, previews onboarding only in development, and ships s } } finally { delete process.env.OPENCODE_TEST_ONBOARDING - delete process.env.OPENCODE_CLI_TARGET + delete process.env.OPENCODE_TARGET if (previous !== undefined) process.env.OPENCODE_TEST_ONBOARDING = previous - if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget + if (previousTarget !== undefined) process.env.OPENCODE_TARGET = previousTarget } const renderer = (await load("build")).config.renderer @@ -77,13 +77,13 @@ test("bundles one Effect runtime and Drizzle while keeping native dependencies e "@lydell/node-pty-win32-x64", ]) - const previousTarget = process.env.OPENCODE_CLI_TARGET + const previousTarget = process.env.OPENCODE_TARGET // Build against the opposite architecture to prove cross-packaging resolves the target's native package, not the host's. - const crossTarget = process.arch === "arm64" ? "x86_64-pc-windows-msvc" : "aarch64-pc-windows-msvc" + const crossTarget = process.arch === "arm64" ? "windows-x64" : "windows-arm64" const crossNodePty = nodePtyPackage(crossTarget) try { - process.env.OPENCODE_CLI_TARGET = crossTarget + process.env.OPENCODE_TARGET = crossTarget const result = await load("build") if (!result.config.main) throw new Error("Missing main-process build configuration") @@ -124,8 +124,8 @@ test("bundles one Effect runtime and Drizzle while keeping native dependencies e expect(modules.some((id) => id.includes("/node_modules/msgpackr"))).toBe(false) expect(chunks.some((chunk) => chunk.code.includes("msgpackr"))).toBe(false) } finally { - delete process.env.OPENCODE_CLI_TARGET + delete process.env.OPENCODE_TARGET - if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget + if (previousTarget !== undefined) process.env.OPENCODE_TARGET = previousTarget } }, 30_000) diff --git a/packages/desktop/electron.vite.config.ts b/packages/desktop/electron.vite.config.ts index 479d5e2fd90..6cbba544cdc 100644 --- a/packages/desktop/electron.vite.config.ts +++ b/packages/desktop/electron.vite.config.ts @@ -1,8 +1,8 @@ import { defineConfig } from "electron-vite" import type { Plugin } from "vite" -import { BetaNotes } from "./scripts/beta-notes" -import { pickerPlugin } from "./scripts/picker" -import { nodePtyPackage } from "./scripts/utils" +import { BetaNotes } from "./script/beta-notes" +import { pickerPlugin } from "./script/picker" +import { nodePtyPackage } from "./script/utils" function resolveChannel() { const raw = process.env.OPENCODE_CHANNEL @@ -16,23 +16,6 @@ function resolveChannel() { const appPlugin = (await import("@opencode/app/vite")).default -const sentry = - process.env.SENTRY_AUTH_TOKEN && process.env.SENTRY_ORG && process.env.SENTRY_PROJECT - ? (await import("@sentry/vite-plugin")).sentryVitePlugin({ - authToken: process.env.SENTRY_AUTH_TOKEN, - org: process.env.SENTRY_ORG, - project: process.env.SENTRY_PROJECT, - telemetry: false, - release: { - name: process.env.SENTRY_RELEASE ?? process.env.VITE_SENTRY_RELEASE, - }, - sourcemaps: { - assets: "./out/renderer/**", - filesToDeleteAfterUpload: "./out/renderer/**/*.map", - }, - }) - : false - // Every module the entry reaches through static imports lands in one chunk. Automatic splitting // otherwise fragments the initial graph into ~50 files shared with lazy routes, and each file costs // the renderer a main-thread request round trip through the main process before first paint. @@ -139,7 +122,7 @@ const require = __cjs_mod__.createRequire(import.meta.url); command === "serve" && process.env.OPENCODE_TEST_ONBOARDING === "1", ), }, - plugins: [pickerPlugin(), appPlugin, initialChunk, sentry], + plugins: [pickerPlugin(), appPlugin, initialChunk], publicDir: "../../../app/public", root: "src/renderer", build: { diff --git a/packages/desktop/package.json b/packages/desktop/package.json index fe3a0ce0b01..a391ffbdb3c 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -13,16 +13,12 @@ "typecheck": "bun check --no-script -b", "typecheck:tsc": "tsc -b", "test": "bun test --timeout 30000", - "dev": "bun ./scripts/dev.ts", - "migration": "bun ./scripts/migration.ts", - "prebuild": "bun ./scripts/prebuild.ts", - "build": "electron-vite build", + "dev": "bun run script/dev.ts", + "migration": "bun run script/migration.ts", + "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "preview": "electron-vite preview", - "package": "electron-builder --config electron-builder.config.ts", - "package:mac": "electron-builder --mac --config electron-builder.config.ts", - "package:win": "electron-builder --win --config electron-builder.config.ts", - "package:linux": "electron-builder --linux --config electron-builder.config.ts", - "bench:startup": "bun ./scripts/bench-startup.ts" + "bench:startup": "bun run script/bench-startup.ts" }, "main": "./out/main/index.js", "dependencies": { @@ -42,7 +38,6 @@ "@opencode/schema": "workspace:*", "@opencode/ui": "workspace:*", "@sentry/solid": "catalog:", - "@sentry/vite-plugin": "catalog:", "@solidjs/router": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/packages/desktop/scripts/bench-startup.ts b/packages/desktop/script/bench-startup.ts similarity index 100% rename from packages/desktop/scripts/bench-startup.ts rename to packages/desktop/script/bench-startup.ts diff --git a/packages/desktop/scripts/bench-variant.ps1 b/packages/desktop/script/bench-variant.ps1 similarity index 57% rename from packages/desktop/scripts/bench-variant.ps1 rename to packages/desktop/script/bench-variant.ps1 index 5f9b869aca4..a9f6bd435f1 100644 --- a/packages/desktop/scripts/bench-variant.ps1 +++ b/packages/desktop/script/bench-variant.ps1 @@ -1,10 +1,10 @@ param([Parameter(Mandatory)][string]$Name, [int]$Runs = 5) $ErrorActionPreference = "Stop" Set-Location $PSScriptRoot\.. -# electron-vite directly: the package's prebuild hook re-downloads the CLI, which the bench keeps fixed. +# electron-vite directly: the build script re-downloads the CLI, which the bench keeps fixed. bunx electron-vite build 2>&1 | Select-String -Pattern "built in|error" | Select-Object -Last 3 if (-not (Test-Path out\main\index.js)) { throw "build failed" } bunx electron-builder --win --dir --config electron-builder.config.ts 2>&1 | Select-String -Pattern "error|signing with signtool.*OpenCode Dev" | Select-Object -Last 2 if (Test-Path "dist\$Name-unpacked") { Remove-Item "dist\$Name-unpacked" -Recurse -Force } Rename-Item -Path dist\win-unpacked -NewName "$Name-unpacked" -bun ./scripts/bench-startup.ts --exe "dist\base-unpacked\OpenCode Dev.exe" --compare "dist\$Name-unpacked\OpenCode Dev.exe" --runs $Runs --warmup 1 --window-at=-1700,20 --out "dist\bench-startup\$Name" 2>&1 | Select-String -Pattern "^warm service|^\s{2,}|^phases|^\S+\s+\d+\s+\(|^report|^warm-up|Error|error" | Select-Object -Last 45 +bun run script/bench-startup.ts --exe "dist\base-unpacked\OpenCode Dev.exe" --compare "dist\$Name-unpacked\OpenCode Dev.exe" --runs $Runs --warmup 1 --window-at=-1700,20 --out "dist\bench-startup\$Name" 2>&1 | Select-String -Pattern "^warm service|^\s{2,}|^phases|^\S+\s+\d+\s+\(|^report|^warm-up|Error|error" | Select-Object -Last 45 diff --git a/packages/desktop/scripts/beta-notes.test.ts b/packages/desktop/script/beta-notes.test.ts similarity index 100% rename from packages/desktop/scripts/beta-notes.test.ts rename to packages/desktop/script/beta-notes.test.ts diff --git a/packages/desktop/scripts/beta-notes.ts b/packages/desktop/script/beta-notes.ts similarity index 99% rename from packages/desktop/scripts/beta-notes.ts rename to packages/desktop/script/beta-notes.ts index 6225dc29802..50ee9200569 100644 --- a/packages/desktop/scripts/beta-notes.ts +++ b/packages/desktop/script/beta-notes.ts @@ -2,7 +2,7 @@ // feat, fix and perf commits among them, with who made each and what its pull request says it does when GitHub can be // asked. electron.vite.config.ts embeds them in the renderer as import.meta.env.OPENCODE_BETA_NOTES; the updater's // "What's new in beta" dialog lists the ones after the commit of the build the user saw last. -// Usage: GITHUB_TOKEN=... bun scripts/beta-notes.ts [head] +// Usage: GITHUB_TOKEN=... bun script/beta-notes.ts [head] export * as BetaNotes from "./beta-notes" import { execFileSync } from "node:child_process" diff --git a/packages/desktop/scripts/beta-visual.ts b/packages/desktop/script/beta-visual.ts similarity index 100% rename from packages/desktop/scripts/beta-visual.ts rename to packages/desktop/script/beta-visual.ts diff --git a/packages/desktop/script/build.ts b/packages/desktop/script/build.ts new file mode 100644 index 00000000000..e46e7580e10 --- /dev/null +++ b/packages/desktop/script/build.ts @@ -0,0 +1,31 @@ +#!/usr/bin/env bun +import { $ } from "bun" +import { exists } from "node:fs/promises" +import path from "node:path" +import { copyBuiltCliToResources, downloadCliToResources, getCurrentCli, resolveChannel } from "./utils" + +// Prepares resources/ (icons, metainfo, the bundled CLI) for OPENCODE_CHANNEL and builds the app into out/. +// The CLI comes from ../cli/dist when it holds the target; otherwise dev downloads the published dev CLI, +// beta the beta CLI, and prod fails. +const dir = path.resolve(import.meta.dir, "..") + +const cli = path.resolve(dir, "../cli/dist") + +const channel = resolveChannel() + +process.chdir(dir) + +await $`bun ./script/copy-icons.ts ${channel}` + +await $`bun ./script/copy-metainfo.ts ${channel}` + +const built = await exists(path.join(cli, getCurrentCli().package.replace("@opencode/", ""))) + +if (channel === "prod" && !built) + throw new Error(`Production desktop builds bundle the CLI from ${cli}; build it first`) + +if (built) await copyBuiltCliToResources(cli) + +if (!built) await downloadCliToResources(channel === "beta" ? "beta" : undefined) + +await $`bunx electron-vite build` diff --git a/packages/desktop/scripts/copy-icons.ts b/packages/desktop/script/copy-icons.ts similarity index 100% rename from packages/desktop/scripts/copy-icons.ts rename to packages/desktop/script/copy-icons.ts diff --git a/packages/desktop/scripts/copy-metainfo.ts b/packages/desktop/script/copy-metainfo.ts similarity index 100% rename from packages/desktop/scripts/copy-metainfo.ts rename to packages/desktop/script/copy-metainfo.ts diff --git a/packages/desktop/scripts/dev-electron.ts b/packages/desktop/script/dev-electron.ts similarity index 100% rename from packages/desktop/scripts/dev-electron.ts rename to packages/desktop/script/dev-electron.ts diff --git a/packages/desktop/scripts/dev.ts b/packages/desktop/script/dev.ts similarity index 97% rename from packages/desktop/scripts/dev.ts rename to packages/desktop/script/dev.ts index 69e640392a5..66bd2a975e1 100644 --- a/packages/desktop/scripts/dev.ts +++ b/packages/desktop/script/dev.ts @@ -25,7 +25,7 @@ async function main() { async function prepareDesktop() { await Promise.all([ $`bun run install-electron`, - $`bun ./scripts/copy-icons.ts ${process.env.OPENCODE_CHANNEL ?? "dev"}`, + $`bun ./script/copy-icons.ts ${process.env.OPENCODE_CHANNEL ?? "dev"}`, ]) if (process.platform === "darwin") process.env.ELECTRON_EXEC_PATH = await prepareDevElectron() diff --git a/packages/desktop/scripts/fixtures/picker/index.html b/packages/desktop/script/fixtures/picker/index.html similarity index 100% rename from packages/desktop/scripts/fixtures/picker/index.html rename to packages/desktop/script/fixtures/picker/index.html diff --git a/packages/desktop/scripts/fixtures/picker/main.ts b/packages/desktop/script/fixtures/picker/main.ts similarity index 100% rename from packages/desktop/scripts/fixtures/picker/main.ts rename to packages/desktop/script/fixtures/picker/main.ts diff --git a/packages/desktop/scripts/migration.ts b/packages/desktop/script/migration.ts similarity index 95% rename from packages/desktop/scripts/migration.ts rename to packages/desktop/script/migration.ts index 6d0feee8084..8e27748af75 100644 --- a/packages/desktop/scripts/migration.ts +++ b/packages/desktop/script/migration.ts @@ -54,7 +54,7 @@ async function render() { })), ) - const source = `// Generated by scripts/migration.ts from src/main/storage/migration. Do not edit. + const source = `// Generated by script/migration.ts from src/main/storage/migration. Do not edit. export const migrations = ${JSON.stringify(migrations, null, 2)} ` diff --git a/packages/desktop/script/pack.ts b/packages/desktop/script/pack.ts new file mode 100644 index 00000000000..ad4767c4def --- /dev/null +++ b/packages/desktop/script/pack.ts @@ -0,0 +1,61 @@ +#!/usr/bin/env bun +import { $ } from "bun" +import { cp, mkdir, readdir, rm } from "node:fs/promises" +import path from "node:path" +import { getCurrentCli, resolveChannel } from "./utils" + +// Packages the built app (out/) for OPENCODE_TARGET into dist/desktop at the repository root, unsigned: +// macOS: the .app as a tarball. Windows: the unpacked app in app/, or with OPENCODE_DESKTOP_APP, the NSIS +// installer around that (signed) app. Linux: AppImage, deb and rpm. The release workflow signs afterwards. +const dir = path.resolve(import.meta.dir, "..") + +const out = path.resolve(dir, "../../dist/desktop") + +const cli = getCurrentCli() + +const os = + new Map([ + ["darwin", "mac"], + ["win32", "win"], + ]).get(cli.os) ?? "linux" + +const app = process.env.OPENCODE_DESKTOP_APP + +const flags = [`--${os}`, `--${cli.cpu}`, "--publish", "never", "--config", "electron-builder.config.ts"] + +process.chdir(dir) + +await rm("dist", { recursive: true, force: true }) + +await rm(out, { recursive: true, force: true }) + +await mkdir(out, { recursive: true }) + +if (app) { + // The installer uses the channel's icons; the rest of the app is already built and signed. + await $`bun ./script/copy-icons.ts ${resolveChannel()}` + await $`bunx electron-builder ${flags} --prepackaged ${app}` + await cp(`dist/opencode-desktop-win-${cli.cpu}.exe`, path.join(out, `opencode-desktop-win-${cli.cpu}.exe`)) +} + +if (!app && os === "linux") { + await $`bunx electron-builder ${flags}` + const files = (await readdir("dist")).filter((file) => /\.(AppImage|deb|rpm)$/.test(file)) + await Promise.all(files.map((file) => cp(path.join("dist", file), path.join(out, file)))) +} + +if (!app && os === "mac") { + await $`bunx electron-builder ${flags} --dir -c.mac.identity=null` + const parent = path.join("dist", cli.cpu === "arm64" ? "mac-arm64" : "mac") + const bundles = (await readdir(parent)).filter((file) => file.endsWith(".app")) + + if (bundles.length !== 1) throw new Error(`Expected one .app bundle in ${parent}, found ${bundles.join(", ")}`) + await $`tar -cf ${path.join(out, `opencode-desktop-mac-${cli.cpu}.app.tar`)} -C ${parent} ${bundles[0]}` +} + +if (!app && os === "win") { + await $`bunx electron-builder ${flags} --dir` + await cp(path.join("dist", cli.cpu === "arm64" ? "win-arm64-unpacked" : "win-unpacked"), path.join(out, "app"), { + recursive: true, + }) +} diff --git a/packages/desktop/scripts/picker.test.ts b/packages/desktop/script/picker.test.ts similarity index 100% rename from packages/desktop/scripts/picker.test.ts rename to packages/desktop/script/picker.test.ts diff --git a/packages/desktop/scripts/picker.ts b/packages/desktop/script/picker.ts similarity index 100% rename from packages/desktop/scripts/picker.ts rename to packages/desktop/script/picker.ts diff --git a/packages/desktop/scripts/profile-by-source.ts b/packages/desktop/script/profile-by-source.ts similarity index 100% rename from packages/desktop/scripts/profile-by-source.ts rename to packages/desktop/script/profile-by-source.ts diff --git a/packages/desktop/scripts/utils.ts b/packages/desktop/script/utils.ts similarity index 78% rename from packages/desktop/scripts/utils.ts rename to packages/desktop/script/utils.ts index b1542d79dd0..c81406b42f2 100644 --- a/packages/desktop/scripts/utils.ts +++ b/packages/desktop/script/utils.ts @@ -21,57 +21,55 @@ export function resolveChannel(): Channel { export const CLI_BINARIES: Array<{ target: string; package: string; os: string; cpu: string }> = [ { - target: "aarch64-apple-darwin", + target: "darwin-arm64", package: "@opencode/cli-darwin-arm64", os: "darwin", cpu: "arm64", }, { - target: "x86_64-apple-darwin", + target: "darwin-x64", package: "@opencode/cli-darwin-x64-baseline", os: "darwin", cpu: "x64", }, { - target: "aarch64-pc-windows-msvc", + target: "windows-arm64", package: "@opencode/cli-windows-arm64", os: "win32", cpu: "arm64", }, { - target: "x86_64-pc-windows-msvc", + target: "windows-x64", package: "@opencode/cli-windows-x64-baseline", os: "win32", cpu: "x64", }, { - target: "x86_64-unknown-linux-gnu", + target: "linux-x64", package: "@opencode/cli-linux-x64-baseline", os: "linux", cpu: "x64", }, { - target: "aarch64-unknown-linux-gnu", + target: "linux-arm64", package: "@opencode/cli-linux-arm64", os: "linux", cpu: "arm64", }, ] -export const CLI_TARGET = process.env.OPENCODE_CLI_TARGET - function nativeTarget() { const { platform, arch } = process - if (platform === "darwin") return arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin" + if (platform === "darwin") return arch === "arm64" ? "darwin-arm64" : "darwin-x64" - if (platform === "win32") return arch === "arm64" ? "aarch64-pc-windows-msvc" : "x86_64-pc-windows-msvc" + if (platform === "win32") return arch === "arm64" ? "windows-arm64" : "windows-x64" - if (platform === "linux") return arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu" + if (platform === "linux") return arch === "arm64" ? "linux-arm64" : "linux-x64" throw new Error(`Unsupported platform: ${platform}/${arch}`) } -export function getCurrentCli(target = process.env.OPENCODE_CLI_TARGET ?? nativeTarget()) { +export function getCurrentCli(target = process.env.OPENCODE_TARGET ?? nativeTarget()) { const binaryConfig = CLI_BINARIES.find((item) => item.target === target) if (!binaryConfig) throw new Error(`CLI configuration not available for target '${target}'`) @@ -131,11 +129,6 @@ async function prepareCli(dest: string) { if (process.platform !== "win32") await chmod(dest, 0o755) - // electron-builder signs the bundled CLI again in Package, so beta signs it only there. - if (process.platform === "win32" && process.env.GITHUB_ACTIONS === "true" && resolveChannel() !== "beta") { - await $`pwsh -NoLogo -NoProfile -ExecutionPolicy Bypass -File ../../script/sign-windows.ps1 ${dest}` - } - if (process.platform === "darwin") await $`codesign --force --sign - ${dest}` } diff --git a/packages/desktop/scripts/windows-installer.test.ts b/packages/desktop/script/windows-installer.test.ts similarity index 100% rename from packages/desktop/scripts/windows-installer.test.ts rename to packages/desktop/script/windows-installer.test.ts diff --git a/packages/desktop/scripts/copy-bundles.ts b/packages/desktop/scripts/copy-bundles.ts deleted file mode 100644 index 48e22e9b9da..00000000000 --- a/packages/desktop/scripts/copy-bundles.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { $ } from "bun" -import * as path from "node:path" - -import { CLI_TARGET } from "./utils" - -if (!CLI_TARGET) throw new Error("OPENCODE_CLI_TARGET not defined") - -const BUNDLE_DIR = "dist" - -const BUNDLES_OUT_DIR = path.join(process.cwd(), "dist/bundles") - -await $`mkdir -p ${BUNDLES_OUT_DIR}` - -await $`cp -r ${BUNDLE_DIR}/* ${BUNDLES_OUT_DIR}` diff --git a/packages/desktop/scripts/prebuild.ts b/packages/desktop/scripts/prebuild.ts deleted file mode 100644 index ef9e517bfc9..00000000000 --- a/packages/desktop/scripts/prebuild.ts +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bun -import { $ } from "bun" - -import { copyBuiltCliToResources, downloadCliToResources, resolveChannel } from "./utils" - -const channel = resolveChannel() - -if (channel === "prod" && !Bun.env.OPENCODE_CLI_DIST) { - throw new Error("OPENCODE_CLI_DIST is required for production desktop builds") -} - -await $`bun ./scripts/copy-icons.ts ${channel}` - -await $`bun ./scripts/copy-metainfo.ts ${channel}` - -if (channel === "dev") await downloadCliToResources() - -if ((channel === "beta" || channel === "prod") && Bun.env.OPENCODE_CLI_DIST) { - await copyBuiltCliToResources(Bun.env.OPENCODE_CLI_DIST) -} - -if (channel === "beta" && !Bun.env.OPENCODE_CLI_DIST) await downloadCliToResources("beta") diff --git a/packages/desktop/scripts/prepare.ts b/packages/desktop/scripts/prepare.ts deleted file mode 100755 index 08c138429e2..00000000000 --- a/packages/desktop/scripts/prepare.ts +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bun -import { Script } from "@opencode/script" - -await import("./prebuild") - -const pkg = await Bun.file("./package.json").json() - -pkg.version = Script.version - -await Bun.write("./package.json", JSON.stringify(pkg, null, 2) + "\n") - -console.log(`Updated package.json version to ${Script.version}`) diff --git a/packages/desktop/scripts/publish.ts b/packages/desktop/scripts/publish.ts deleted file mode 100644 index 0c9916b79ae..00000000000 --- a/packages/desktop/scripts/publish.ts +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { Schema } from "effect" -import { UpdateArtifact } from "../../../script/update-artifact" - -const dryRun = process.argv.includes("--dry-run") - -if (!Script.release) { - console.log("skipped desktop publication without a release") - process.exit(0) -} - -const UploadedFiles = Schema.fromJsonString( - Schema.Record(Schema.String, Schema.Struct({ url: Schema.String, sha256: Schema.String, size: Schema.Number })), -) - -// Beta build jobs upload their own platform's files (scripts/upload.ts) and pass only the returned file lists here. -const uploadedDirectory = process.env.OPENCODE_DESKTOP_UPLOADED - -const uploaded = uploadedDirectory ? await uploadedByBuildJobs(uploadedDirectory) : await uploadFiles() - -const artifact = { - channel: Script.channel, - name: "desktop", - distribution: "opencode", - version: Script.version, - metadata: { files: uploaded, ...(await metadata(Script.version, uploaded)) }, -} - -if (dryRun) console.log(`dry-run artifact: ${JSON.stringify(artifact)}`) - -if (!dryRun) await UpdateArtifact.publish(artifact) - -async function uploadFiles() { - const directory = process.env.OPENCODE_DESKTOP_DIST - - if (!directory) throw new Error("OPENCODE_DESKTOP_DIST is required") - - const files = ( - await Array.fromAsync( - new Bun.Glob("*.{exe,blockmap,dmg,zip,AppImage,deb,rpm,app.tar.gz}").scan({ cwd: directory, absolute: true }), - ) - ).sort() - - if (!files.length) throw new Error("No desktop release files found") - - return UpdateArtifact.upload({ version: Script.version, files, dryRun }) -} - -async function uploadedByBuildJobs(directory: string) { - const lists = await Array.fromAsync(new Bun.Glob("*.json").scan({ cwd: directory, absolute: true })) - - if (!lists.length) throw new Error(`No uploaded desktop file lists found in ${directory}`) - - const entries = await Promise.all( - lists.map(async (file) => Object.entries(Schema.decodeUnknownSync(UploadedFiles)(await Bun.file(file).text()))), - ) - - return Object.fromEntries(entries.flat()) -} - -type DesktopFile = { - url: string - sha512: string - size: number - blockMapSize?: number -} - -async function metadata(version: string, files: Record) { - const directory = process.env.LATEST_YML_DIR - - if (!directory) throw new Error("LATEST_YML_DIR is required") - - const entries = await Promise.all( - [ - { - name: "desktop.yml", - sources: [ - ["latest-yml-aarch64-pc-windows-msvc", "latest.yml"], - ["latest-yml-x86_64-pc-windows-msvc", "latest.yml"], - ], - }, - { - name: "desktop-mac.yml", - sources: [ - ["latest-yml-aarch64-apple-darwin", "latest-mac.yml"], - ["latest-yml-x86_64-apple-darwin", "latest-mac.yml"], - ], - }, - { name: "desktop-linux.yml", sources: [["latest-yml-x86_64-unknown-linux-gnu", "latest-linux.yml"]] }, - { - name: "desktop-linux-arm64.yml", - sources: [["latest-yml-aarch64-unknown-linux-gnu", "latest-linux-arm64.yml"]], - }, - ].map(async (item) => { - const manifests = ( - await Promise.all( - item.sources.map(async ([subdirectory, source]) => { - const file = Bun.file(`${directory}/${subdirectory}/${source}`) - - if (!(await file.exists())) return undefined - - return parse(await file.text(), version, files) - }), - ) - ).filter((manifest) => manifest !== undefined) - - if (manifests.length !== item.sources.length) return undefined - - return [ - item.name, - { files: manifests.flatMap((manifest) => manifest.files), releaseDate: manifests[0]!.releaseDate }, - ] as const - }), - ) - - if (entries.some((entry) => entry === undefined)) throw new Error("Desktop update metadata is incomplete") - const manifests = Object.fromEntries(entries.filter((entry) => entry !== undefined)) - - return { manifests } -} - -function parse(content: string, version: string, uploaded: Record) { - const lines = content.split("\n") - - const found = lines - .find((line) => line.startsWith("version:")) - ?.slice("version:".length) - .trim() - - if (found !== version) throw new Error(`Desktop metadata version mismatch: expected ${version}, got ${found}`) - - const releaseDate = lines - .find((line) => line.startsWith("releaseDate:")) - ?.slice("releaseDate:".length) - .trim() - .replace(/^['"]|['"]$/g, "") - - if (!releaseDate) throw new Error("Desktop metadata did not include a release date") - const files: DesktopFile[] = [] - lines.forEach((line) => { - const value = line.trim() - - if (value.startsWith("- url:")) { - const name = value.slice("- url:".length).trim() - const filename = name.startsWith("http") ? decodeURIComponent(new URL(name).pathname.split("/").pop()!) : name - const url = uploaded[filename]?.url - - if (!url) throw new Error(`Desktop update file was not uploaded: ${filename}`) - files.push({ url, sha512: "", size: 0 }) - - return - } - - const current = files.at(-1) - - // electron-builder repeats the first file's sha512 as a top-level legacy field after the list. - if (!current || !line.startsWith(" ")) return - - if (value.startsWith("sha512:")) current.sha512 = value.slice("sha512:".length).trim() - - if (value.startsWith("size:")) current.size = Number(value.slice("size:".length).trim()) - - if (value.startsWith("blockMapSize:")) current.blockMapSize = Number(value.slice("blockMapSize:".length).trim()) - }) - - if (!files.length || files.some((file) => !file.sha512 || !file.size)) - throw new Error("Desktop metadata contained an incomplete file") - - return { files, releaseDate } -} diff --git a/packages/desktop/scripts/upload.ts b/packages/desktop/scripts/upload.ts deleted file mode 100644 index f3928f0c8f7..00000000000 --- a/packages/desktop/scripts/upload.ts +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bun - -// Uploads one platform's desktop release files to R2 from its build job and writes the returned file list, which -// publish.ts reads through OPENCODE_DESKTOP_UPLOADED instead of uploading every platform itself. -// Usage: bun scripts/upload.ts -import path from "node:path" -import { UpdateArtifact } from "../../../script/update-artifact" - -const [directory, output] = process.argv.slice(2) - -if (!directory || !output) throw new Error("Usage: bun scripts/upload.ts ") - -const version = process.env.OPENCODE_VERSION - -if (!version) throw new Error("OPENCODE_VERSION is required") - -const files = ( - await Array.fromAsync( - new Bun.Glob("*.{exe,blockmap,dmg,zip,AppImage,deb,rpm,app.tar.gz}").scan({ - cwd: path.resolve(directory), - absolute: true, - }), - ) -).sort() - -if (!files.length) throw new Error(`No desktop release files found in ${directory}`) - -await Bun.write(output, JSON.stringify(await UpdateArtifact.upload({ version, files }), null, 2)) diff --git a/packages/desktop/src/main/storage/migration.gen.ts b/packages/desktop/src/main/storage/migration.gen.ts index 54007cf8676..e71114e0efe 100644 --- a/packages/desktop/src/main/storage/migration.gen.ts +++ b/packages/desktop/src/main/storage/migration.gen.ts @@ -1,4 +1,4 @@ -// Generated by scripts/migration.ts from src/main/storage/migration. Do not edit. +// Generated by script/migration.ts from src/main/storage/migration. Do not edit. export const migrations = [ { diff --git a/packages/gui-extensions/src/env.d.ts b/packages/gui-extensions/src/env.d.ts index b77b3472ef9..0e58dcc1e70 100644 --- a/packages/gui-extensions/src/env.d.ts +++ b/packages/gui-extensions/src/env.d.ts @@ -1,6 +1,6 @@ interface ImportMetaEnv { /** The commit a beta desktop build was built from; undefined in every other build. */ readonly OPENCODE_COMMIT?: string - /** A beta desktop build's commit, recent history and notes as JSON (packages/desktop/scripts/beta-notes.ts). */ + /** A beta desktop build's commit, recent history and notes as JSON (packages/desktop/script/beta-notes.ts). */ readonly OPENCODE_BETA_NOTES?: string } diff --git a/packages/gui-extensions/src/updater/beta-notes.ts b/packages/gui-extensions/src/updater/beta-notes.ts index 8f66c0d5cfb..e49c92e9961 100644 --- a/packages/gui-extensions/src/updater/beta-notes.ts +++ b/packages/gui-extensions/src/updater/beta-notes.ts @@ -21,7 +21,7 @@ const Note = Schema.Struct({ visual: Schema.optional(Schema.Struct({ animated: Schema.String, still: Schema.String })), }) -/** What a beta build embeds (packages/desktop/scripts/beta-notes.ts), newest first. */ +/** What a beta build embeds (packages/desktop/script/beta-notes.ts), newest first. */ const Embedded = Schema.Struct({ /** The build's commit. */ sha: Schema.String, diff --git a/packages/gui-extensions/src/wsl/local.ts b/packages/gui-extensions/src/wsl/local.ts index 85b9fadb8fc..5d8ad0174a0 100644 --- a/packages/gui-extensions/src/wsl/local.ts +++ b/packages/gui-extensions/src/wsl/local.ts @@ -12,6 +12,7 @@ export async function buildLocalWslCli(input: { version: string; script: string; const root = join(dirname(input.script), "../../..") const build = async () => { + // SAFETY: the repository root package.json always pins packageManager. const packageManager = ( JSON.parse(await readFile(join(root, "package.json"), "utf8")) as { packageManager: string } ).packageManager @@ -24,15 +25,12 @@ export async function buildLocalWslCli(input: { version: string; script: string; }) await execFileAsync( "bunx", - [ - packageManager, - input.script, - `--target=opencode-${target}`, - "--skip-install", - "--skip-web-ui", - `--outdir=${directory}`, - ], - { cwd: root, env: { ...process.env, OPENCODE_VERSION: input.version }, windowsHide: true }, + [packageManager, input.script, "--skip-install", "--skip-web-ui", `--outdir=${directory}`], + { + cwd: root, + env: { ...process.env, OPENCODE_VERSION: input.version, OPENCODE_TARGET: target }, + windowsHide: true, + }, ) await copyFile(join(directory, `cli-${target}`, "bin", "opencode"), input.output) diff --git a/packages/plugin-browser/package.json b/packages/plugin-browser/package.json index 756cc89f495..a8e584ec5e0 100644 --- a/packages/plugin-browser/package.json +++ b/packages/plugin-browser/package.json @@ -23,6 +23,7 @@ }, "scripts": { "build": "tsc -p tsconfig.build.json", + "pack": "bun run script/pack.ts", "typecheck": "bun check --no-script -p tsconfig.test.json", "typecheck:tsc": "tsc --noEmit -p tsconfig.test.json", "test": "bun test" diff --git a/packages/plugin-browser/script/pack.ts b/packages/plugin-browser/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/plugin-browser/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/plugin-browser/script/publish.ts b/packages/plugin-browser/script/publish.ts deleted file mode 100644 index 52622765b52..00000000000 --- a/packages/plugin-browser/script/publish.ts +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" -import pkg from "../package.json" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -await $`bun run typecheck:tsc` -await $`bun run build` -const original = await Bun.file("package.json").text() -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` -try { - await Bun.write( - "package.json", - JSON.stringify( - { - ...pkg, - exports: Object.fromEntries( - Object.entries(pkg.exports).map(([name, value]) => [ - name, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ]), - ), - }, - null, - 2, - ) + "\n", - ) - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", original) - await rm(tarball, { force: true }) -} diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 571c508db2a..6562729f8ba 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -8,7 +8,8 @@ "test": "bun test --only-failures", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit", - "build": "tsc -p tsconfig.build.json" + "build": "tsc -p tsconfig.build.json", + "pack": "bun run script/pack.ts" }, "exports": { ".": "./src/promise/index.ts", diff --git a/packages/plugin/script/pack.ts b/packages/plugin/script/pack.ts new file mode 100755 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/plugin/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/plugin/script/publish.ts b/packages/plugin/script/publish.ts deleted file mode 100755 index 9613f179c77..00000000000 --- a/packages/plugin/script/publish.ts +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bun -import { Script } from "@opencode/script" -import { $ } from "bun" -import { fileURLToPath } from "url" - -const dir = fileURLToPath(new URL("..", import.meta.url)) -process.chdir(dir) - -async function published(name: string, version: string) { - return (await $`npm view ${name}@${version} version`.nothrow()).exitCode === 0 -} - -await $`bun run build` -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record - imports: Record> -} -if (await published(pkg.name, pkg.version)) { - console.log(`already published ${pkg.name}@${pkg.version}`) -} else { - for (const [key, value] of Object.entries(pkg.exports)) { - const file = value.replace("./src/", "./dist/").replace(".ts", "") - // @ts-ignore - pkg.exports[key] = { - import: file + ".js", - types: file + ".d.ts", - } - } - pkg.imports = Object.fromEntries( - Object.entries(pkg.imports).map(([key, conditions]) => [ - key, - Object.fromEntries( - Object.entries(conditions).map(([condition, value]) => [ - condition, - value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - ]), - ), - ]), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2)) - try { - await $`bun pm pack` - await $`npm publish *.tgz --tag ${Script.channel} --access public` - } finally { - await Bun.write("package.json", originalText) - } -} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index f0d4f73242c..efffa7c2262 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -21,6 +21,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "generate": "bun run script/generate-openapi.ts", "check:generated": "bun run script/generate-openapi.ts --check", "test": "bun test --only-failures", diff --git a/packages/protocol/script/pack.ts b/packages/protocol/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/protocol/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/protocol/script/publish.ts b/packages/protocol/script/publish.ts deleted file mode 100644 index cea7358e4a6..00000000000 --- a/packages/protocol/script/publish.ts +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/schema/package.json b/packages/schema/package.json index 7b20b6406c4..d26016890a6 100644 --- a/packages/schema/package.json +++ b/packages/schema/package.json @@ -21,6 +21,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --only-failures", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit" diff --git a/packages/schema/script/pack.ts b/packages/schema/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/schema/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/schema/script/publish.ts b/packages/schema/script/publish.ts deleted file mode 100644 index cea7358e4a6..00000000000 --- a/packages/schema/script/publish.ts +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/script/package.json b/packages/script/package.json index ec7a4553e62..3c89243fa66 100644 --- a/packages/script/package.json +++ b/packages/script/package.json @@ -15,6 +15,7 @@ }, "exports": { ".": "./src/index.ts", - "./highlights": "./src/highlights.ts" + "./highlights": "./src/highlights.ts", + "./pack": "./src/pack.ts" } } diff --git a/packages/script/src/index.ts b/packages/script/src/index.ts index 40dc28dca2b..6af860b9f0f 100644 --- a/packages/script/src/index.ts +++ b/packages/script/src/index.ts @@ -19,13 +19,10 @@ if (!semver.satisfies(process.versions.bun, expectedBunVersionRange)) { const env = { OPENCODE_CHANNEL: process.env["OPENCODE_CHANNEL"], - OPENCODE_BUMP: process.env["OPENCODE_BUMP"], OPENCODE_VERSION: process.env["OPENCODE_VERSION"], - OPENCODE_RELEASE: process.env["OPENCODE_RELEASE"], } const CHANNEL = await (async () => { if (env.OPENCODE_CHANNEL) return env.OPENCODE_CHANNEL - if (env.OPENCODE_BUMP) return "latest" if (env.OPENCODE_VERSION && !env.OPENCODE_VERSION.startsWith("0.0.0-")) return "latest" const branch = await $`git branch --show-current`.text().then((x) => x.trim()) if (!branch) return "detached" @@ -35,21 +32,11 @@ const CHANNEL = await (async () => { })() const IS_PREVIEW = CHANNEL !== "latest" -const VERSION = await (async () => { +// The release workflow's plan job owns release versions; builds only read them. +const VERSION = (() => { if (env.OPENCODE_VERSION) return env.OPENCODE_VERSION - if (IS_PREVIEW) return `0.0.0-${CHANNEL}-${previewBuildNumber()}` - const version = await fetch("https://registry.npmjs.org/@opencode%2fcli/latest") - .then((res) => { - if (!res.ok) throw new Error(res.statusText) - return res.json() - }) - .then((data: any) => data.version) - if (semver.lt(version, "2.0.0")) return "2.0.0" - const [major, minor, patch] = version.split(".").map((x: string) => Number(x) || 0) - const t = env.OPENCODE_BUMP?.toLowerCase() - if (t === "major") return `${major + 1}.0.0` - if (t === "minor") return `${major}.${minor + 1}.0` - return `${major}.${minor}.${patch + 1}` + if (!IS_PREVIEW) throw new Error("OPENCODE_VERSION is required for latest-channel builds") + return `0.0.0-${CHANNEL}-${previewBuildNumber()}` })() function previewBuildNumber() { @@ -80,9 +67,6 @@ export const Script = { get preview() { return IS_PREVIEW }, - get release(): boolean { - return !!env.OPENCODE_RELEASE - }, get team() { return team }, diff --git a/packages/script/src/pack.ts b/packages/script/src/pack.ts new file mode 100644 index 00000000000..ee0daa54bed --- /dev/null +++ b/packages/script/src/pack.ts @@ -0,0 +1,67 @@ +import { $ } from "bun" +import { mkdir, rm } from "node:fs/promises" +import path from "node:path" + +const root = path.resolve(import.meta.dir, "../../..") + +// Release outputs land at the repository root, where the release workflow uploads them. +export const npmDir = path.join(root, "dist", "npm") +export const archiveDir = path.join(root, "dist", "archives") + +type Manifest = { + name: string + version: string + exports: Record + imports?: Record> +} + +/** + * Builds the package in `directory`, points its TypeScript exports at the build output, and packs it + * into dist/npm. `types` is where the build writes declarations; `source` keeps `import` on the + * TypeScript sources for packages that ship them. + */ +export async function pack(directory: string, options: { types?: string; source?: boolean } = {}) { + const types = options.types ?? "./dist/" + const file = path.join(directory, "package.json") + const original = await Bun.file(file).text() + // SAFETY: release packages declare a name, a version, and string export targets. + const pkg = JSON.parse(original) as Manifest + const declaration = (value: string) => value.replace("./src/", types).replace(/\.tsx?$/, ".d.ts") + const output = (value: string) => value.replace("./src/", "./dist/").replace(/\.tsx?$/, ".js") + const tarball = path.join(npmDir, `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz`) + + await $`bun run build`.cwd(directory) + + const exports = Object.fromEntries( + Object.entries(pkg.exports).map(([key, value]) => { + if (!/\.tsx?$/.test(value)) return [key, value] + + return [key, { import: options.source ? value : output(value), types: declaration(value) }] + }), + ) + const imports = pkg.imports + ? Object.fromEntries( + Object.entries(pkg.imports).map(([key, conditions]) => [ + key, + Object.fromEntries( + Object.entries(conditions).map(([condition, value]) => [ + condition, + condition === "types" ? declaration(value) : output(value), + ]), + ), + ]), + ) + : undefined + + await mkdir(npmDir, { recursive: true }) + await rm(tarball, { force: true }) + await Bun.write(file, JSON.stringify({ ...pkg, exports, ...(imports ? { imports } : {}) }, null, 2) + "\n") + + try { + await $`bun pm pack --destination ${npmDir}`.cwd(directory) + } finally { + await Bun.write(file, original) + } + + return tarball +} diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 8db27b686a6..b927d12e5e4 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -23,6 +23,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --timeout 5000", "typecheck": "bun check --no-script -b", "typecheck:tsc": "tsc -b", diff --git a/packages/sdk/script/pack.ts b/packages/sdk/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/sdk/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/sdk/script/publish.ts b/packages/sdk/script/publish.ts deleted file mode 100644 index 7ff06121c0c..00000000000 --- a/packages/sdk/script/publish.ts +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const dryRun = Bun.argv.includes("--dry-run") -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` -const output = (value: string, types = false) => - value.replace("./src/", "./dist/").replace(/\.ts$/, types ? ".d.ts" : ".js") - -if (!dryRun && (await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [key, { import: output(value), types: output(value, true) }] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - if (!dryRun) await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/server/package.json b/packages/server/package.json index 7fb1f6b30b5..e3c1925026b 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -20,6 +20,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --only-failures", "typecheck": "bun check --no-script -b", "typecheck:tsc": "tsc -b", diff --git a/packages/server/script/pack.ts b/packages/server/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/server/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/server/script/publish.ts b/packages/server/script/publish.ts deleted file mode 100644 index ab9d8cdfe17..00000000000 --- a/packages/server/script/publish.ts +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const dryRun = Bun.argv.includes("--dry-run") -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if (!dryRun && (await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - if (!dryRun) await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/simulation/package.json b/packages/simulation/package.json index 59bae63b550..348770a7070 100644 --- a/packages/simulation/package.json +++ b/packages/simulation/package.json @@ -25,6 +25,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --timeout 30000 --only-failures", "typecheck": "bun check --no-script -b", "typecheck:tsc": "tsc -b" diff --git a/packages/simulation/script/pack.ts b/packages/simulation/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/simulation/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/simulation/script/publish.ts b/packages/simulation/script/publish.ts deleted file mode 100644 index ab9d8cdfe17..00000000000 --- a/packages/simulation/script/publish.ts +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const dryRun = Bun.argv.includes("--dry-run") -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if (!dryRun && (await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - if (!dryRun) await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/theme/package.json b/packages/theme/package.json index 89b1e71e5a9..7f33a4e6878 100644 --- a/packages/theme/package.json +++ b/packages/theme/package.json @@ -21,6 +21,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --timeout 30000", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit" diff --git a/packages/theme/script/pack.ts b/packages/theme/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/theme/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/theme/script/publish.ts b/packages/theme/script/publish.ts deleted file mode 100644 index cea7358e4a6..00000000000 --- a/packages/theme/script/publish.ts +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [ - key, - { - import: value.replace("./src/", "./dist/").replace(/\.ts$/, ".js"), - types: value.replace("./src/", "./dist/").replace(/\.ts$/, ".d.ts"), - }, - ] - }), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/packages/ui/package.json b/packages/ui/package.json index 0c920e00111..311fb7ee81f 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -100,6 +100,7 @@ }, "scripts": { "build": "rm -rf dist && tsc -p tsconfig.build.json", + "pack": "bun run script/pack.ts", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit", "test": "bun test src --only-failures", diff --git a/packages/ui/script/pack.ts b/packages/ui/script/pack.ts index 6e59744dca5..77701be0832 100644 --- a/packages/ui/script/pack.ts +++ b/packages/ui/script/pack.ts @@ -1,45 +1,5 @@ #!/usr/bin/env bun - -import { $ } from "bun" -import { rm } from "node:fs/promises" import path from "node:path" +import { pack } from "@opencode/script/pack" -export async function pack() { - const original = await Bun.file("package.json").text() - - const pkg = JSON.parse(original) as { - name: string - version: string - exports: Record - } - - const tarball = path.resolve(`${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz`) - - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string" || (!value.endsWith(".ts") && !value.endsWith(".tsx"))) return [key, value] - - return [ - key, - { - types: value.replace("./src/", "./dist/").replace(/\.tsx?$/, ".d.ts"), - import: value, - }, - ] - }), - ) - - await rm(tarball, { force: true }) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - - try { - await $`bun pm pack` - - return tarball - } finally { - await Bun.write("package.json", original) - } -} - -if (import.meta.main) console.log(await pack()) +await pack(path.resolve(import.meta.dir, ".."), { source: true }) diff --git a/packages/ui/script/publish.ts b/packages/ui/script/publish.ts deleted file mode 100644 index de25a0a5682..00000000000 --- a/packages/ui/script/publish.ts +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" -import { pack } from "./pack" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -// SAFETY: this package's own package.json always declares a string name and version. -const pkg = (await Bun.file("package.json").json()) as { name: string; version: string } - -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -try { - await $`bun run typecheck:tsc` - await $`bun run test` - await pack() - await $`npm publish ${tarball} --access public --tag ${Script.channel}` -} finally { - await rm(tarball, { force: true }) -} diff --git a/packages/util/package.json b/packages/util/package.json index a6798f315b9..7b211f3c1f5 100644 --- a/packages/util/package.json +++ b/packages/util/package.json @@ -33,6 +33,7 @@ }, "scripts": { "build": "bun run script/build.ts", + "pack": "bun run script/pack.ts", "test": "bun test --only-failures", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit", diff --git a/packages/util/script/pack.ts b/packages/util/script/pack.ts new file mode 100644 index 00000000000..5c2bafaed7a --- /dev/null +++ b/packages/util/script/pack.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env bun +import path from "node:path" +import { pack } from "@opencode/script/pack" + +await pack(path.resolve(import.meta.dir, "..")) diff --git a/packages/util/script/publish.ts b/packages/util/script/publish.ts deleted file mode 100644 index 87ff1f8bbe9..00000000000 --- a/packages/util/script/publish.ts +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { rm } from "node:fs/promises" -import { fileURLToPath } from "node:url" - -process.chdir(fileURLToPath(new URL("..", import.meta.url))) - -const originalText = await Bun.file("package.json").text() -const pkg = JSON.parse(originalText) as { - name: string - version: string - exports: Record - imports: Record> -} -const tarball = `${pkg.name.replace("@", "").replace("/", "-")}-${pkg.version}.tgz` - -if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode === 0) { - console.log(`already published ${pkg.name}@${pkg.version}`) - process.exit(0) -} - -const output = (value: string, extension: ".js" | ".d.ts") => - value.replace("./src/", "./dist/").replace(/\.ts$/, extension) - -try { - await $`bun run typecheck:tsc` - await $`bun run build` - pkg.exports = Object.fromEntries( - Object.entries(pkg.exports).map(([key, value]) => { - if (typeof value !== "string") return [key, value] - return [key, { import: output(value, ".js"), types: output(value, ".d.ts") }] - }), - ) - pkg.imports = Object.fromEntries( - Object.entries(pkg.imports).map(([key, conditions]) => [ - key, - Object.fromEntries(Object.entries(conditions).map(([condition, value]) => [condition, output(value, ".js")])), - ]), - ) - await Bun.write("package.json", JSON.stringify(pkg, null, 2) + "\n") - await rm(tarball, { force: true }) - await $`bun pm pack` - await $`npm publish ${tarball} --tag ${Script.channel} --access public` -} finally { - await Bun.write("package.json", originalText) - await rm(tarball, { force: true }) -} diff --git a/script/lint-changed.ts b/script/lint-changed.ts index ce0125445a0..5b721b21998 100644 --- a/script/lint-changed.ts +++ b/script/lint-changed.ts @@ -12,10 +12,17 @@ type Diagnostic = { } const base = await resolveBase(process.argv[2] ?? process.env.LINT_BASE) -const tracked = (await $`git diff --name-only --diff-filter=ACMR ${base}`.text()).split("\n") +// -M100% reports only exact moves as renames, so a moved file is linted only once its content changes. +const tracked = (await $`git diff --name-only -M100% --diff-filter=ACM ${base}`.text()).split("\n") const untracked = (await $`git ls-files --others --exclude-standard`.text()).split("\n") // The packages .oxlintrc.json applies the anti-slop rules to. -const packages = ["packages/app/", "packages/desktop/", "packages/gui-extensions/", "packages/ui/", "packages/session-ui/"] +const packages = [ + "packages/app/", + "packages/desktop/", + "packages/gui-extensions/", + "packages/ui/", + "packages/session-ui/", +] // oxlint skips declaration files and prints a non-JSON message when given only those. const files = [...new Set([...tracked, ...untracked])].filter( (file) => diff --git a/script/pack.ts b/script/pack.ts new file mode 100644 index 00000000000..ddf0a222bf0 --- /dev/null +++ b/script/pack.ts @@ -0,0 +1,45 @@ +#!/usr/bin/env bun + +import { Script } from "@opencode/script" +import { $ } from "bun" +import { rm } from "node:fs/promises" +import path from "node:path" + +// Runs `bun run pack` for every package published to npm, after moving every workspace to the build +// version so workspace dependencies pack at that version. Outputs land in dist/npm and dist/archives. +const root = path.resolve(import.meta.dir, "..") +process.chdir(root) +console.log(`=== packing ${Script.version} (${Script.channel}) ===\n`) + +await rm("dist/npm", { recursive: true, force: true }) +await rm("dist/archives", { recursive: true, force: true }) + +const pkgjsons = await Array.fromAsync(new Bun.Glob("**/package.json").scan({ absolute: true })).then((files) => + files.filter((file) => !file.includes("node_modules") && !file.includes("dist")), +) +for (const file of pkgjsons) { + const text = await Bun.file(file).text() + await Bun.write(file, text.replaceAll(/"version": "[^"]+"/g, `"version": "${Script.version}"`)) +} +await $`bun install` + +for (const name of [ + "schema", + "codemode", + "theme", + "ai", + "util", + "protocol", + "client", + "plugin", + "plugin-browser", + "core", + "simulation", + "server", + "sdk", + "ui", + "cli", +]) { + console.log(`\n=== ${name} ===\n`) + await $`bun run pack`.cwd(path.join("packages", name)) +} diff --git a/script/publish-winget.ts b/script/publish-winget.ts deleted file mode 100644 index 5b66026a7cb..00000000000 --- a/script/publish-winget.ts +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { mkdir, rm } from "node:fs/promises" -import path from "node:path" -import { fileURLToPath } from "node:url" - -if (Script.channel !== "latest" || !/^\d+\.\d+\.\d+$/.test(Script.version)) { - throw new Error("WinGet publishing requires a latest release version") -} - -const root = fileURLToPath(new URL("..", import.meta.url)) -const dryRun = process.argv.includes("--dry-run") -const token = process.env.WINGET_GITHUB_TOKEN -const cli = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(root, "packages", "cli", "dist")) -const desktop = process.env.OPENCODE_DESKTOP_DIST -if (!desktop) throw new Error("OPENCODE_DESKTOP_DIST is required") -const outdir = path.join(cli, "winget") -const manifestVersion = "1.12.0" - -const packages = [ - { - identifier: "Anomaly.OpenCode", - name: "OpenCode CLI", - moniker: "opencode", - description: "The open source AI coding agent for the terminal.", - installer: [ - "InstallerType: zip", - "NestedInstallerType: portable", - "NestedInstallerFiles:", - "- RelativeFilePath: opencode.exe", - " PortableCommandAlias: opencode", - "Commands:", - "- opencode", - ], - files: [ - { architecture: "x64", file: path.join(cli, "opencode-windows-x64-baseline.zip") }, - { architecture: "arm64", file: path.join(cli, "opencode-windows-arm64.zip") }, - ], - }, - { - identifier: "Anomaly.OpenCode.Desktop", - // Matches the display name the installer registers with Windows, without its version suffix. - name: "OpenCode", - moniker: "opencode-desktop", - description: "The open source AI coding agent as a desktop app.", - installer: [ - "InstallerType: nullsoft", - "Scope: user", - "UpgradeBehavior: install", - // electron-builder derives the NSIS uninstall key from the production app ID, ai.opencode.desktop. - "ProductCode: d074f30d-5f88-5885-b075-be1348cc7676", - "Protocols:", - "- opencode", - ], - files: [ - { architecture: "x64", file: path.join(desktop, "opencode-desktop-win-x64.exe") }, - { architecture: "arm64", file: path.join(desktop, "opencode-desktop-win-arm64.exe") }, - ], - }, -] - -await rm(outdir, { recursive: true, force: true }) -const prepared = await Promise.all(packages.map(prepare)) -prepared.forEach((item) => console.log(`Prepared ${item.identifier} ${Script.version} in ${item.directory}`)) -if (dryRun) process.exit(0) -if (!token) { - console.log("skipped WinGet submission: WINGET_GITHUB_TOKEN is not set") - process.exit(0) -} -for (const item of prepared) await submit(item) - -async function prepare(input: (typeof packages)[number]) { - const directory = path.join(outdir, input.identifier) - const header = (type: string) => [ - `# yaml-language-server: $schema=https://aka.ms/winget-manifest.${type}.${manifestVersion}.schema.json`, - "", - `PackageIdentifier: ${input.identifier}`, - `PackageVersion: ${Script.version}`, - ] - const footer = (type: string) => [`ManifestType: ${type}`, `ManifestVersion: ${manifestVersion}`, ""] - const installers = await Promise.all( - input.files.map(async (item) => { - const file = Bun.file(item.file) - if (!(await file.exists()) || !file.size) throw new Error(`Missing WinGet installer: ${item.file}`) - const sha256 = new Bun.CryptoHasher("sha256") - for await (const chunk of file.stream()) sha256.update(chunk) - return [ - `- Architecture: ${item.architecture}`, - ` InstallerUrl: https://opencode.ai/files/bin/${encodeURIComponent(Script.version)}/${path.basename(item.file)}`, - ` InstallerSha256: ${sha256.digest("hex").toUpperCase()}`, - ] - }), - ) - const manifests = { - [`${input.identifier}.yaml`]: [...header("version"), "DefaultLocale: en-US", ...footer("version")], - [`${input.identifier}.installer.yaml`]: [ - ...header("installer"), - ...input.installer, - `ReleaseDate: ${new Date().toISOString().slice(0, 10)}`, - "Installers:", - ...installers.flat(), - ...footer("installer"), - ], - [`${input.identifier}.locale.en-US.yaml`]: [ - ...header("defaultLocale"), - "PackageLocale: en-US", - // Matches the publisher the desktop installer registers with Windows. - "Publisher: OpenCode", - "PublisherUrl: https://anoma.ly/", - "PublisherSupportUrl: https://github.com/anomalyco/opencode/issues", - "PrivacyUrl: https://opencode.ai/legal/privacy-policy", - `PackageName: ${input.name}`, - "PackageUrl: https://opencode.ai/", - "License: MIT", - "LicenseUrl: https://github.com/anomalyco/opencode/blob/HEAD/LICENSE", - `ShortDescription: ${input.description}`, - `Moniker: ${input.moniker}`, - "Tags:", - "- ai", - "- coding-agent", - "- developer-tools", - "Documentations:", - "- DocumentLabel: Docs", - " DocumentUrl: https://opencode.ai/v2/docs", - ...footer("defaultLocale"), - ], - } - const files = Object.fromEntries(Object.entries(manifests).map(([name, lines]) => [name, lines.join("\n")])) - await mkdir(directory, { recursive: true }) - await Promise.all(Object.entries(files).map(([name, content]) => Bun.write(path.join(directory, name), content))) - return { identifier: input.identifier, directory, files } -} - -// Opens the pull request from the token owner's fork, the only way to contribute to microsoft/winget-pkgs. -async function submit(input: Awaited>) { - const upstream = "microsoft/winget-pkgs" - const folder = ["manifests", "a", ...input.identifier.split("."), Script.version].join("/") - const branch = `${input.identifier}-${Script.version}` - if ((await github(`/repos/${upstream}/contents/${folder}`)).status === 200) { - console.log(`${input.identifier} ${Script.version} is already in ${upstream}`) - return - } - const fork: { owner: { login: string }; full_name: string } = await json( - await github(`/repos/${upstream}/forks`, { method: "POST", body: { default_branch_only: true } }), - ) - const pulls: unknown[] = await json( - await github(`/repos/${upstream}/pulls?state=all&head=${encodeURIComponent(`${fork.owner.login}:${branch}`)}`), - ) - if (pulls.length) { - console.log(`${input.identifier} ${Script.version} already has a pull request`) - return - } - // Forks share objects with their upstream, so the branch can start from upstream master without syncing the fork. - const head: { object: { sha: string } } = await json(await github(`/repos/${upstream}/git/ref/heads/master`)) - const base: { tree: { sha: string } } = await json(await github(`/repos/${upstream}/git/commits/${head.object.sha}`)) - const tree: { sha: string } = await json( - await github(`/repos/${fork.full_name}/git/trees`, { - method: "POST", - body: { - base_tree: base.tree.sha, - tree: Object.entries(input.files).map(([name, content]) => ({ - path: `${folder}/${name}`, - mode: "100644", - type: "blob", - content, - })), - }, - }), - ) - const title = `New version: ${input.identifier} version ${Script.version}` - const commit: { sha: string } = await json( - await github(`/repos/${fork.full_name}/git/commits`, { - method: "POST", - body: { message: title, tree: tree.sha, parents: [head.object.sha] }, - }), - ) - const created = await github(`/repos/${fork.full_name}/git/refs`, { - method: "POST", - body: { ref: `refs/heads/${branch}`, sha: commit.sha }, - }) - // A retried release can find the branch from an attempt that failed before opening its pull request. - await json( - created.status === 422 - ? await github(`/repos/${fork.full_name}/git/refs/heads/${branch}`, { - method: "PATCH", - body: { sha: commit.sha, force: true }, - }) - : created, - ) - const run = process.env.GITHUB_RUN_ID - ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}` - : undefined - const pull: { html_url: string } = await json( - await github(`/repos/${upstream}/pulls`, { - method: "POST", - body: { - title, - head: `${fork.owner.login}:${branch}`, - base: "master", - body: `Published by the [OpenCode](https://github.com/anomalyco/opencode) release workflow${run ? ` in ${run}` : ""}.`, - }, - }), - ) - console.log(`Opened ${pull.html_url}`) -} - -function github(route: string, init?: { method?: string; body?: unknown }) { - return fetch(`https://api.github.com${route}`, { - method: init?.method ?? "GET", - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", - }, - body: init?.body === undefined ? undefined : JSON.stringify(init.body), - }) -} - -async function json(response: Response) { - if (!response.ok) throw new Error(`GitHub ${response.url} returned ${response.status}: ${await response.text()}`) - return response.json() -} diff --git a/script/publish.ts b/script/publish.ts deleted file mode 100755 index 9051e755113..00000000000 --- a/script/publish.ts +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" -import { $ } from "bun" -import { fileURLToPath } from "url" - -console.log("=== publishing ===\n") - -const dir = fileURLToPath(new URL("..", import.meta.url)) -process.chdir(dir) -const tag = `v${Script.version}` - -// Beta dogfoods the desktop app. The CLI and SDK packages ship from dev. -if (Script.channel === "beta") { - console.log("\n=== desktop ===\n") - await $`bun ./packages/desktop/scripts/publish.ts` - process.exit(0) -} - -const pkgjsons = await Array.fromAsync( - new Bun.Glob("**/package.json").scan({ - absolute: true, - }), -).then((arr) => arr.filter((x) => !x.includes("node_modules") && !x.includes("dist"))) - -async function prepareReleaseFiles() { - for (const file of pkgjsons) { - let pkg = await Bun.file(file).text() - pkg = pkg.replaceAll(/"version": "[^"]+"/g, `"version": "${Script.version}"`) - console.log("updated:", file) - await Bun.file(file).write(pkg) - } - - await $`bun install` -} - -async function writeChangelog() { - const notes = process.env["OPENCODE_RELEASE_NOTES"]?.trim() - if (!notes) return - const file = Bun.file("CHANGELOG.md") - const text = await file.text() - const lines = text.split("\n") - if (lines.some((line) => line === `## ${tag}` || line.startsWith(`## ${tag} `))) return - const index = lines.findIndex((line) => line.startsWith("## ")) - const head = (index === -1 ? lines : lines.slice(0, index)).join("\n").trimEnd() - const rest = index === -1 ? "" : lines.slice(index).join("\n") - const entry = `## ${tag} — ${new Date().toISOString().slice(0, 10)}\n\n${notes}\n` - await file.write(`${head}\n\n${entry}${rest ? `\n${rest}` : ""}`) -} - -if (Script.release && !Script.preview) { - await $`git fetch origin --tags` - await $`git switch --detach` -} - -await prepareReleaseFiles() - -if (Script.release) await $`bun ./packages/desktop/scripts/publish.ts --dry-run` - -console.log("\n=== schema ===\n") -await $`bun ./packages/schema/script/publish.ts` - -console.log("\n=== codemode ===\n") -await $`bun ./packages/codemode/script/publish.ts` - -console.log("\n=== theme ===\n") -await $`bun ./packages/theme/script/publish.ts` - -console.log("\n=== ai ===\n") -await $`bun ./packages/ai/script/publish.ts` - -console.log("\n=== util ===\n") -await $`bun ./packages/util/script/publish.ts` - -console.log("\n=== protocol ===\n") -await $`bun ./packages/protocol/script/publish.ts` - -console.log("\n=== client ===\n") -await $`bun ./packages/client/script/publish.ts` - -console.log("\n=== cli ===\n") -await $`bun ./packages/cli/script/publish.ts` - -console.log("\n=== plugin ===\n") -await $`bun ./packages/plugin/script/publish.ts` - -console.log("\n=== plugin-browser ===\n") -await $`bun ./packages/plugin-browser/script/publish.ts` - -console.log("\n=== core ===\n") -await $`bun ./packages/core/script/publish.ts` - -console.log("\n=== simulation ===\n") -await $`bun ./packages/simulation/script/publish.ts` - -console.log("\n=== server ===\n") -await $`bun ./packages/server/script/publish.ts` - -console.log("\n=== sdk ===\n") -await $`bun ./packages/sdk/script/publish.ts` - -console.log("\n=== ui ===\n") -await $`bun ./packages/ui/script/publish.ts` - -if (Script.release && !Script.preview) { - if ((await $`git diff --quiet`.nothrow()).exitCode !== 0) await $`git commit -am "release: ${tag}"` - await $`git tag -d ${tag}`.nothrow() - await $`git tag ${tag}` - await $`git push origin refs/tags/${tag} --force-with-lease --no-verify` - await new Promise((resolve) => setTimeout(resolve, 5_000)) - await $`git fetch origin` - await $`git checkout -B dev origin/dev` - await prepareReleaseFiles() - await writeChangelog() - if ((await $`git diff --quiet`.nothrow()).exitCode !== 0) { - // The release already published this code; a push-triggered dev publish of a version bump is wasted work. - await $`git commit -am ${`sync release versions for ${tag} [skip ci]`}` - await $`git push origin HEAD:dev --no-verify` - } -} - -if (Script.release) { - console.log("\n=== desktop ===\n") - await $`bun ./packages/desktop/scripts/publish.ts` -} - -// WinGet submission is paused until our packages are accepted into microsoft/winget-pkgs. -// if (Script.release && Script.channel === "latest") { -// console.log("\n=== winget ===\n") -// // Everything else is published by now, and WinGet validation can reject a submission for reasons unrelated to the release. -// if ((await $`bun ./script/publish-winget.ts`.nothrow()).exitCode !== 0) -// console.log("::warning::WinGet submission failed; see the winget step output above") -// } diff --git a/script/release.ts b/script/release.ts index e6e7d551a1e..92fdfeead37 100755 --- a/script/release.ts +++ b/script/release.ts @@ -102,7 +102,7 @@ if (answer?.trim().toLowerCase() !== "y" && answer?.trim().toLowerCase() !== "ye process.exit(0) } -await $`gh workflow run publish.yml --ref dev ${input} -f release_notes=${releaseNotes}` +await $`gh workflow run release.yml --ref dev ${input} -f release_notes=${releaseNotes}` console.log(`Triggered the ${version} release`) async function generateReview(base: string, head: string) { diff --git a/script/sign-windows.ps1 b/script/sign-windows.ps1 deleted file mode 100644 index ab0b617eb9c..00000000000 --- a/script/sign-windows.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -param( - [Parameter(ValueFromRemainingArguments = $true)] - [string[]] $Path -) - -$ErrorActionPreference = "Stop" - -if (-not $Path -or $Path.Count -eq 0) { - throw "At least one path is required" -} - -if ($env:GITHUB_ACTIONS -ne "true") { - Write-Host "Skipping Windows signing because this is not running on GitHub Actions" - exit 0 -} - -$vars = @{ - endpoint = $env:AZURE_TRUSTED_SIGNING_ENDPOINT - account = $env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME - profile = $env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE -} - -if ($vars.Values | Where-Object { -not $_ }) { - Write-Host "Skipping Windows signing because Azure Artifact Signing is not configured" - exit 0 -} - -$moduleVersion = "0.5.8" -$module = Get-Module -ListAvailable -Name TrustedSigning | Where-Object { $_.Version -eq [version] $moduleVersion } - -if (-not $module) { - try { - Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope CurrentUser | Out-Null - } - catch { - Write-Host "NuGet package provider install skipped: $($_.Exception.Message)" - } - - if (-not (Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue)) { - Register-PSRepository -Default - } - - Install-Module -Name TrustedSigning -RequiredVersion $moduleVersion -Force -Repository PSGallery -Scope CurrentUser -} - -Import-Module TrustedSigning -RequiredVersion $moduleVersion -Force - -$files = @($Path | ForEach-Object { Resolve-Path $_ -ErrorAction SilentlyContinue } | Select-Object -ExpandProperty Path -Unique) - -if (-not $files -or $files.Count -eq 0) { - throw "No files matched the requested paths" -} - -$params = @{ - Endpoint = $vars.endpoint - CodeSigningAccountName = $vars.account - CertificateProfileName = $vars.profile - Files = ($files -join ",") - FileDigest = "SHA256" - TimestampDigest = "SHA256" - TimestampRfc3161 = "http://timestamp.acs.microsoft.com" - ExcludeEnvironmentCredential = $true - ExcludeWorkloadIdentityCredential = $true - ExcludeManagedIdentityCredential = $true - ExcludeSharedTokenCacheCredential = $true - ExcludeVisualStudioCredential = $true - ExcludeVisualStudioCodeCredential = $true - ExcludeAzureCliCredential = $false - ExcludeAzurePowerShellCredential = $true - ExcludeAzureDeveloperCliCredential = $true - ExcludeInteractiveBrowserCredential = $true -} - -Invoke-TrustedSigning @params diff --git a/script/update-artifact.ts b/script/update-artifact.ts deleted file mode 100644 index 07f8b887a94..00000000000 --- a/script/update-artifact.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { createHash } from "node:crypto" -import { createReadStream } from "node:fs" -import path from "node:path" - -type Artifact = { - channel: string - name: string - distribution: string - version: string - metadata: Record -} - -export namespace UpdateArtifact { - export async function publish(artifact: Artifact) { - if (process.env.GITHUB_ACTIONS !== "true") { - console.log("skipped update artifact publication outside GitHub Actions") - return - } - const requestURL = process.env.ACTIONS_ID_TOKEN_REQUEST_URL - const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN - if (!requestURL || !requestToken) throw new Error("GitHub Actions OIDC is unavailable") - - const url = new URL(requestURL) - url.searchParams.set("audience", "https://update.opencode.ai") - const tokenResponse = await fetch(url, { headers: { Authorization: `Bearer ${requestToken}` } }) - if (!tokenResponse.ok) throw new Error(`Failed to request GitHub OIDC token: ${tokenResponse.status}`) - const token: unknown = await tokenResponse.json() - if (!isRecord(token) || typeof token.value !== "string") - throw new Error("GitHub OIDC response did not include a token") - - for (const attempt of [0, 1, 2]) { - const response = await fetch("https://opencode.ai/update/api/publish", { - method: "POST", - headers: { - Authorization: `Bearer ${token.value}`, - "Content-Type": "application/json", - }, - body: JSON.stringify(artifact), - }) - if (response.ok) return - // D1 can commit the upsert and still time out. Replaying the same artifact is safe. - if (response.status >= 500 && attempt < 2) { - await response.arrayBuffer() - console.warn(`Update artifact publication returned ${response.status}; retrying`) - await Bun.sleep((attempt + 1) * 1_000) - continue - } - throw new Error(`Failed to publish update artifact: ${response.status} ${await response.text()}`) - } - } - - export async function upload(input: { version: string; files: string[]; dryRun?: boolean }) { - const { PutObjectCommand, S3Client } = await import("@aws-sdk/client-s3") - const client = input.dryRun ? undefined : new S3Client(await credentials()) - const prefix = `bin/${input.version}/` - const base = `https://opencode.ai/files/bin/${encodeURIComponent(input.version)}/` - try { - return Object.fromEntries( - await Promise.all( - input.files.map(async (filepath) => { - const file = Bun.file(filepath) - const name = path.basename(filepath) - if (!file.size) throw new Error(`Empty release file: ${filepath}`) - const hash = createHash("sha256") - for await (const chunk of file.stream()) hash.update(chunk) - const metadata = { url: `${base}${encodeURIComponent(name)}`, sha256: hash.digest("hex"), size: file.size } - console.log(`${input.dryRun ? "dry-run upload" : "upload"}: ${prefix}${name}`) - if (client) { - await client.send( - new PutObjectCommand({ - Bucket: "opencode-production-files", - Key: `${prefix}${name}`, - Body: createReadStream(filepath), - ContentLength: file.size, - ContentType: name.endsWith(".tar.gz") ? "application/gzip" : file.type || "application/octet-stream", - ContentDisposition: `attachment; filename="${name}"`, - CacheControl: "public, max-age=31536000, immutable", - }), - ) - } - return [name, metadata] as const - }), - ), - ) - } finally { - client?.destroy() - } - } -} - -function isRecord(input: unknown): input is Record { - return typeof input === "object" && input !== null && !Array.isArray(input) -} - -async function credentials() { - const account = process.env.CLOUDFLARE_ACCOUNT_ID - const token = process.env.CLOUDFLARE_API_TOKEN - if (!account || !token) throw new Error("CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required") - // R2 uses the token ID as its access key and SHA-256(token) as its secret. - for (const scope of [`accounts/${account}`, "user"]) { - const response = await fetch(`https://api.cloudflare.com/client/v4/${scope}/tokens/verify`, { - headers: { Authorization: `Bearer ${token}` }, - }) - if (!response.ok) continue - const data: unknown = await response.json() - if (!isRecord(data) || data.success !== true || !isRecord(data.result) || typeof data.result.id !== "string") - continue - return { - region: "auto", - endpoint: `https://${account}.r2.cloudflarestorage.com`, - credentials: { - accessKeyId: data.result.id, - secretAccessKey: createHash("sha256").update(token).digest("hex"), - }, - } - } - throw new Error("Cloudflare token verification failed") -} diff --git a/script/version.ts b/script/version.ts deleted file mode 100755 index ef56553598d..00000000000 --- a/script/version.ts +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bun - -import { Script } from "@opencode/script" - -const output = [`version=${Script.version}`] - -if (!Script.preview || Script.channel === "beta") { - output.push("release=true") - output.push(`tag=v${Script.version}`) -} - -if (process.env.GITHUB_OUTPUT) { - await Bun.write(process.env.GITHUB_OUTPUT, output.join("\n")) -} - -process.exit(0) diff --git a/script/wait-for-artifact.ts b/script/wait-for-artifact.ts deleted file mode 100644 index 75f4d493163..00000000000 --- a/script/wait-for-artifact.ts +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bun - -// Waits until another job of this workflow run uploads an artifact, so a job can do its other work while that job -// runs. Fails as soon as the producing job ends without the artifact. -// Usage: bun script/wait-for-artifact.ts - -const [artifact, producer] = process.argv.slice(2) - -if (!artifact || !producer) throw new Error("Usage: bun script/wait-for-artifact.ts ") - -const token = process.env.GITHUB_TOKEN - -if (!token) throw new Error("GITHUB_TOKEN is required") - -const run = `https://api.github.com/repos/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}` -const started = Date.now() - -while (Date.now() - started < 30 * 60_000) { - if (await uploaded()) { - console.log(`${artifact} is ready after ${Math.round((Date.now() - started) / 1000)}s`) - process.exit(0) - } - - const conclusion = await producerConclusion() - - if (conclusion && conclusion !== "success") throw new Error(`${producer} finished with ${conclusion}`) - // A job can finish just before its artifact appears in the listing. - if (conclusion === "success" && (await uploaded())) process.exit(0) - if (conclusion === "success") throw new Error(`${producer} succeeded without uploading ${artifact}`) - - await Bun.sleep(5_000) -} - -throw new Error(`Timed out waiting for ${artifact}`) - -async function uploaded() { - const body = await get(`${run}/artifacts?name=${encodeURIComponent(artifact)}`) - - return isRecord(body) && typeof body.total_count === "number" && body.total_count > 0 -} - -async function producerConclusion() { - const body = await get(`${run}/attempts/${process.env.GITHUB_RUN_ATTEMPT ?? "1"}/jobs?per_page=100`) - const jobs = isRecord(body) && Array.isArray(body.jobs) ? body.jobs : [] - const job = jobs.find((item) => isRecord(item) && item.name === producer) - - if (!isRecord(job) || job.status !== "completed") return undefined - - return typeof job.conclusion === "string" ? job.conclusion : "unknown" -} - -async function get(url: string): Promise { - const response = await fetch(url, { - headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, - }) - - if (!response.ok) throw new Error(`GitHub API ${response.status} for ${url}`) - - return response.json() -} - -function isRecord(input: unknown): input is Record { - return typeof input === "object" && input !== null && !Array.isArray(input) -} diff --git a/services/README.md b/services/README.md index 8a8ea120735..ba868163d39 100644 --- a/services/README.md +++ b/services/README.md @@ -6,7 +6,7 @@ and clients live in `packages/`. | Service | Purpose | Deployment | | -------------------------- | -------------------------------------- | -------------------------------- | | [`www`](./www) | Website and V2 documentation | `deploy-www.yml`, Wrangler | -| [`updates`](./updates) | Release metadata and update selection | `publish.yml`, Wrangler | +| [`updates`](./updates) | Release metadata and update selection | `release.yml`, Wrangler | | [`files`](./files) | Public file distribution at `/files/*` | `deploy-files.yml`, Wrangler | | [`changelog`](./changelog) | Release notes at `/changelog` | `deploy-changelog.yml`, Wrangler | diff --git a/services/files/README.md b/services/files/README.md index 2a8962336f3..64ad379cd16 100644 --- a/services/files/README.md +++ b/services/files/README.md @@ -67,14 +67,11 @@ files to be consumed from other origins. ## Release Binaries -Each package owns its publishing destinations. `packages/cli/script/publish.ts` -publishes npm packages, Cloudflare archives, and AUR releases. -`packages/desktop/scripts/publish.ts` publishes GitHub release assets, finalizes -desktop manifests, uploads to Cloudflare, and registers its update artifacts. -The root release script invokes these package publishers. - -Both publishers upload signed/packaged outputs to the production bucket for -every release channel: +The `release` workflow (`.github/workflows/release.yml`) uploads release files. +Its `publish-cli` and `publish-desktop` jobs run in the `release` environment, +check out only `.github/release/`, and never execute repository code: +`publish-cli.sh` and `publish-desktop.sh` upload verified, signed build artifacts +to the production bucket for every release channel: ```text R2 key: bin/0.0.0-dev-123/opencode-linux-x64.tar.gz @@ -84,27 +81,18 @@ R2 key: bin/2.0.0/opencode-desktop-mac-arm64.dmg URL: https://opencode.ai/files/bin/2.0.0/opencode-desktop-mac-arm64.dmg ``` -CLI and Node CLI archives contain the standalone executable at their root, with -execute permissions restored after GitHub artifact downloads. Linux uses -`.tar.gz`; macOS and Windows use `.zip`. Desktop uploads retain their GitHub -release filenames, including blockmaps and `.app.tar.gz` bundles. +CLI and Node CLI archives contain the standalone executable at their root. +Linux uses `.tar.gz`; macOS and Windows use `.zip`. Desktop uploads keep their +electron-builder filenames and include `.app.tar.gz` bundles. -The package publishers use the shared `UpdateArtifact.upload` helper with the -existing GitHub `CLOUDFLARE_API_TOKEN` secret and R2 object write access. It derives -S3 credentials from the verified token, streams uploads, and sets the content -type, download filename, and immutable cache headers. +The jobs derive S3 credentials from the `CLOUDFLARE_API_TOKEN` secret and set +the content type, download filename, and immutable cache headers. -The publishers register `cli`, `cli-node` (when built), and `desktop` (when -released) with distribution `opencode`. Each record is published only after all -of its files have uploaded successfully. -Every `metadata.files` entry contains the direct CDN `url`, SHA-256 checksum, -and byte size. Desktop `metadata.manifests` also use those CDN URLs and retain -the original SHA-512 and blockmap metadata. - -For local verification, each package publisher accepts `--dry-run` with -`OPENCODE_VERSION` and `OPENCODE_CHANNEL` matching the build. CLI reads its own -`dist/` directory (or `OPENCODE_CLI_DIST`). Desktop reads `OPENCODE_DESKTOP_DIST`; -its dry run expects already-finalized manifests in `RUNNER_TEMP`. +They register `cli`, `cli-node` (dev builds), and `desktop` (beta and versioned +releases) with distribution `opencode`, each only after all of its files have +uploaded. Every `metadata.files` entry contains the direct CDN `url`, SHA-256 +checksum, and byte size. Desktop `metadata.manifests` use those CDN URLs with +SHA-512 checksums computed from the final signed files. ## Caching diff --git a/services/update/README.md b/services/update/README.md index b81affab8cc..4d1cf1c3520 100644 --- a/services/update/README.md +++ b/services/update/README.md @@ -108,7 +108,7 @@ has a single public deployment. ## Publishing -The publish workflow also registers direct binary downloads with distribution +The release workflow also registers direct binary downloads with distribution `opencode`, after uploading every file to the public files bucket: ```sh @@ -120,14 +120,16 @@ curl 'https://opencode.ai/update/api/latest/desktop/opencode' `metadata.files` maps each filename to its direct `https://opencode.ai/files/bin//` URL, SHA-256 checksum, and byte size. Desktop records additionally contain `metadata.manifests`, with -the CDN URLs and the original Electron update checksums. Existing `npm`, +the CDN URLs and SHA-512 checksums computed from the final signed files. Existing `npm`, `github`, and `aur` distributions are published independently. GitHub Actions publishes artifacts through `POST https://opencode.ai/update/api/publish` using a short-lived OIDC token with audience `https://update.opencode.ai`. The original hostname and token audience remain supported. The Worker accepts only tokens signed by -GitHub for repository ID `975734319`, owner ID `66570915`, and `.github/workflows/publish.yml` -on configured publishing refs. +GitHub for repository ID `975734319`, owner ID `66570915`, `.github/workflows/release.yml` +and environment `release`. Pushes to `dev` may publish only to `dev`; only a +`workflow_dispatch` on `dev` (a versioned release) may publish to `latest`, and `beta` +publishes only to `beta`. Apply migrations and deploy from this directory: diff --git a/services/update/src/index.ts b/services/update/src/index.ts index b8cb0dd0db3..465cf65b550 100644 --- a/services/update/src/index.ts +++ b/services/update/src/index.ts @@ -425,7 +425,7 @@ async function publishArtifact(request: Request, env: Env) { const input: unknown = await request.json().catch(() => undefined) const artifact = parseArtifact(isRecord(input) ? input : {}) if (artifact instanceof Response) return artifact - if (!channelsForRef(claims.ref).includes(artifact.channel)) return json({ error: "Channel is not allowed" }, 403) + if (!allowedChannels(claims).includes(artifact.channel)) return json({ error: "Channel is not allowed" }, 403) if (!isRecord(artifact.metadata)) return json({ error: "Metadata must be an object" }, 400) await activate(env.DB, [ { @@ -572,6 +572,8 @@ type GitHubClaims = JWTPayload & { repository_owner_id: string workflow_ref: string ref: string + event_name: string + environment: string sha: string run_id: string run_attempt: string @@ -583,14 +585,17 @@ export function validGitHubClaims(claims: JWTPayload): claims is GitHubClaims { if (claims.repository_id !== "975734319") return false if (claims.repository_owner_id !== "66570915") return false if (typeof claims.workflow_ref !== "string" || typeof claims.ref !== "string") return false - if (claims.workflow_ref !== `anomalyco/opencode/.github/workflows/publish.yml@${claims.ref}`) return false - if (!channelsForRef(claims.ref).length) return false + if (claims.workflow_ref !== `anomalyco/opencode/.github/workflows/release.yml@${claims.ref}`) return false + // Only publish jobs run in the release environment, and they never execute repository code. + if (claims.environment !== "release") return false + if (typeof claims.event_name !== "string") return false return [claims.sha, claims.run_id, claims.run_attempt, claims.actor].every((value) => typeof value === "string") } -export function channelsForRef(ref: string) { - if (ref === "refs/heads/dev") return ["dev", "latest"] - if (ref === "refs/heads/beta") return ["beta"] +// Pushes to dev ship dev builds. Only a manual dispatch of a versioned release may ship to latest. +export function allowedChannels(claims: Pick) { + if (claims.ref === "refs/heads/dev") return claims.event_name === "workflow_dispatch" ? ["dev", "latest"] : ["dev"] + if (claims.ref === "refs/heads/beta") return ["beta"] return [] } diff --git a/services/update/test/index.test.ts b/services/update/test/index.test.ts index 4681b026cf0..6abe3b091b3 100644 --- a/services/update/test/index.test.ts +++ b/services/update/test/index.test.ts @@ -2,7 +2,7 @@ import { Database } from "bun:sqlite" import { afterEach, expect, setSystemTime, test } from "bun:test" import { readdirSync, readFileSync } from "node:fs" import path from "node:path" -import worker, { channelsForRef, validGitHubClaims } from "../src/index" +import worker, { allowedChannels, validGitHubClaims } from "../src/index" type Env = Parameters[1] @@ -164,13 +164,15 @@ test("caches rollout fallback reads across caller IPs and overlapping releases", expect(db.queries).toHaveLength(3) }) -function publishClaims(ref: string) { +function publishClaims(ref: string, event_name = "push", environment = "release") { return { repository: "anomalyco/opencode", repository_id: "975734319", repository_owner_id: "66570915", - workflow_ref: `anomalyco/opencode/.github/workflows/publish.yml@${ref}`, + workflow_ref: `anomalyco/opencode/.github/workflows/release.yml@${ref}`, ref, + event_name, + environment, sha: "0".repeat(40), run_id: "1", run_attempt: "1", @@ -178,21 +180,26 @@ function publishClaims(ref: string) { } } -// dev publishes both kinds of build: pushes ship 0.0.0-dev-N to "dev", and dispatches with a bump or version ship -// releases to "latest". +// Pushes to dev ship 0.0.0-dev-N to "dev". Only a dispatch with a bump or version may ship a release to "latest". test.each([ - ["refs/heads/dev", ["dev", "latest"]], - ["refs/heads/beta", ["beta"]], -])("accepts publish tokens from %s", (ref, channels) => { - expect(channelsForRef(ref)).toEqual(channels) - expect(validGitHubClaims(publishClaims(ref))).toBe(true) + ["refs/heads/dev", "push", ["dev"]], + ["refs/heads/dev", "workflow_dispatch", ["dev", "latest"]], + ["refs/heads/beta", "push", ["beta"]], + ["refs/heads/beta", "workflow_dispatch", ["beta"]], + // These branches no longer publish (v2 was merged into dev). + ["refs/heads/v1", "push", []], + ["refs/heads/v2", "push", []], + ["refs/heads/ci", "push", []], + ["refs/heads/snapshot-otui", "workflow_dispatch", []], +] as const)("allows %s on %s to publish to %p", (ref, event, channels) => { + expect(allowedChannels({ ref, event_name: event })).toEqual([...channels]) }) -// These branches no longer publish (v2 was merged into dev), so their tokens must not be accepted. -test.each(["refs/heads/v2", "refs/heads/ci", "refs/heads/fix/npm-native-binary-install", "refs/heads/snapshot-otui"])( - "rejects publish tokens from %s", - (ref) => { - expect(channelsForRef(ref)).toEqual([]) - expect(validGitHubClaims(publishClaims(ref))).toBe(false) - }, -) +// Build jobs run repository code and hold no environment, so their tokens must never publish. +test.each([ + ["release", true], + ["", false], + ["production", false], +])("accepts publish tokens from environment %p: %p", (environment, valid) => { + expect(validGitHubClaims(publishClaims("refs/heads/dev", "push", environment))).toBe(valid) +})