From 6d5efdc2fafd98231fa7cae59b38cb3b04aef0cc Mon Sep 17 00:00:00 2001 From: 2noScript Date: Thu, 3 Dec 2026 18:49:03 +0700 Subject: [PATCH] Add a zero-cost agkit release pipeline --- .github/workflows/release.yml | 143 +++++++++++++++++++++++++ docs/release.md | 49 +++++++++ scripts/release.py | 189 ++++++++++++++++++++++++++++++++++ 3 files changed, 381 insertions(+) create mode 100644 .github/workflows/release.yml create mode 100644 docs/release.md create mode 100644 scripts/release.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c272cee --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,143 @@ +name: Build and release agkit + +on: + pull_request: + push: + branches: [main] + tags: ['v*'] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: agkit-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: Build ${{ matrix.target }} + if: github.event.repository.visibility == 'public' + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 + target: aarch64-apple-darwin + - runner: macos-15-intel + target: x86_64-apple-darwin + - runner: ubuntu-22.04 + target: x86_64-unknown-linux-gnu + - runner: ubuntu-22.04-arm + target: aarch64-unknown-linux-gnu + - runner: windows-2025 + target: x86_64-pc-windows-msvc + env: + AGKIT_TARGET: ${{ matrix.target }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + - name: Set up Rust + run: rustup toolchain install stable --profile minimal --target "$AGKIT_TARGET" + - name: Test + run: cargo +stable test --locked --target "$AGKIT_TARGET" + - name: Build + run: cargo +stable build --locked --release --bin agkit --target "$AGKIT_TARGET" + - name: Package and smoke test + run: | + binary="target/$AGKIT_TARGET/release/agkit" + if [[ "$RUNNER_OS" == Windows ]]; then + binary+=.exe + fi + python scripts/release.py pack --target "$AGKIT_TARGET" --binary "$binary" --output dist/assets + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: package-${{ matrix.target }} + path: dist/assets/ + if-no-files-found: error + overwrite: true + retention-days: 3 + + prepare: + name: Prepare checksums and package metadata + needs: build + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + pattern: package-* + path: dist/assets + merge-multiple: true + - name: Generate checksums, formula and WinGet manifests + shell: bash + run: | + args=(--repository "$GITHUB_REPOSITORY" --assets dist/assets --output dist/distribution) + if [[ "$GITHUB_REF_TYPE" == tag ]]; then + args+=(--tag "$GITHUB_REF_NAME") + fi + python scripts/release.py prepare "${args[@]}" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: agkit-release + path: dist/assets/ + if-no-files-found: error + overwrite: true + retention-days: 7 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: agkit-distribution + path: dist/distribution/ + if-no-files-found: error + overwrite: true + retention-days: 30 + + draft: + name: Attest and stage the GitHub Release + needs: prepare + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-24.04 + permissions: + contents: write + id-token: write + attestations: write + artifact-metadata: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: agkit-release + path: dist/assets + - name: Verify downloaded assets + working-directory: dist/assets + run: sha256sum --check SHA256SUMS + - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 + with: + subject-path: dist/assets/* + - name: Upload to a draft release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + shell: bash + run: | + if is_draft=$(gh release view "$GITHUB_REF_NAME" --json isDraft --jq .isDraft 2>/dev/null); then + if [[ "$is_draft" != true ]]; then + echo '::error::This release is already public. Publish changes under a new version.' + exit 1 + fi + gh release upload "$GITHUB_REF_NAME" dist/assets/* --clobber + else + gh release create "$GITHUB_REF_NAME" dist/assets/* --draft --verify-tag --generate-notes + fi diff --git a/docs/release.md b/docs/release.md new file mode 100644 index 0000000..f48a132 --- /dev/null +++ b/docs/release.md @@ -0,0 +1,49 @@ +# Phát hành agkit + +Bản phát hành dùng GitHub Releases làm nơi tải chung. GitHub Actions dùng runner tiêu chuẩn trên repo public. Workflow chỉ chạy trên repo public để tránh chi phí runner khi đổi sang repo private. [Giá runner GitHub-hosted](https://docs.github.com/en/actions/reference/runners/github-hosted-runners) + +## Tài khoản cần dùng + +| Kênh | Tài khoản và quyền | Chi phí | +| --- | --- | --- | +| GitHub Actions, Releases và bản Linux | Tài khoản GitHub có quyền push tag và phát hành trên `2noScript/agent-kit`. Actions dùng `GITHUB_TOKEN` để tạo bản nháp. | 0 đồng với repo public và runner tiêu chuẩn. | +| Homebrew tap | Cùng tài khoản GitHub có quyền tạo và cập nhật repo public `2noScript/homebrew-agent-kit`. | 0 đồng. | +| WinGet Community | Tài khoản GitHub để fork `microsoft/winget-pkgs` và gửi PR manifest. Kênh này dùng quy trình duyệt PR của WinGet. | 0 đồng. | + +Tham khảo [Homebrew tap](https://docs.brew.sh/How-to-Create-and-Maintain-a-Tap) và [quy trình nộp WinGet](https://learn.microsoft.com/en-us/windows/package-manager/package/repository). + +## Build và tạo bản nháp + +1. Merge thay đổi phát hành vào `main`. Workflow [Build and release agkit](../.github/workflows/release.yml) chạy trên PR, khi push `main` và khi chạy thủ công từ tab Actions. +2. Kiểm tra năm job build. macOS có Apple Silicon và Intel. Linux có x64 và ARM64, build và smoke test trên Ubuntu 22.04. Windows có x64. CI chạy `cargo test --locked`, build release rồi chạy `--version`, `--help`, `--json p l` và lệnh liệt kê phiên với kho SQLite tạm trên binary vừa giải nén. +3. Push tag khớp phiên bản trong `Cargo.toml`. Ví dụ với phiên bản `0.1.0` đã merge trên `main`: + + ```sh + git tag v0.1.0 + git push origin v0.1.0 + ``` + +4. Workflow từ tag tạo `SHA256SUMS`, GitHub Artifact Attestations và bản nháp GitHub Release. Bản nháp chứa `.tar.gz` cho macOS và Linux, `.zip` cho Windows và checksum chung. Mỗi gói kèm `LICENSE`. Kiểm tra bản nháp trước khi bấm **Publish release**. [GitHub Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository) + +## Đưa bản phát hành lên từng kênh + +Sau khi bản GitHub Release công khai, tải artifact `agkit-distribution` từ đúng lần chạy của tag. Artifact này chứa formula Homebrew và manifest WinGet được tạo từ URL theo phiên bản và SHA-256 của đúng file phát hành. + +- **Homebrew** — Đưa `Formula/agkit.rb` vào repo `2noScript/homebrew-agent-kit`. Kiểm tra `brew install 2noScript/agent-kit/agkit` và `brew test 2noScript/agent-kit/agkit`. Cú pháp đầy đủ cấp quyền tin cậy cho riêng formula đó. [Homebrew Tap Trust](https://docs.brew.sh/Tap-Trust) +- **WinGet** — Sao chép thư mục `manifests/2/2noScript/Agkit//` từ artifact vào fork `microsoft/winget-pkgs`. Chạy `winget validate --manifest ` trên Windows rồi mở PR. Khi PR đã merge và package có trong source, thử `winget install --id 2noScript.Agkit --exact --source winget` và `agkit --version`. [Nộp manifest WinGet](https://learn.microsoft.com/en-us/windows/package-manager/package/repository) +- **Linux** — Tải `.tar.gz` đúng kiến trúc cùng `SHA256SUMS`. Chạy `sha256sum --ignore-missing -c SHA256SUMS` trong thư mục tải về. Có thể xác minh nguồn gốc bằng `gh attestation verify -R 2noScript/agent-kit`. Sau đó giải nén và đưa `agkit` vào một thư mục trong `PATH`. [Xác minh artifact GitHub](https://docs.github.com/en/actions/how-tos/secure-your-work/use-artifact-attestations/use-artifact-attestations) + +## Xác thực và cảnh báo hệ điều hành + +Luồng 0 đồng xác minh toàn vẹn bằng SHA-256 và xác minh nguồn gốc build bằng GitHub Artifact Attestation. Homebrew và WinGet kiểm tra checksum của gói khi tải. + +- **macOS** — Gatekeeper có thể hỏi khi chạy bản tải trực tiếp. Developer ID và notarization là bước tùy chọn nếu sau này phát hành `.pkg` có danh tính nhà phát hành đã xác minh. Apple Developer Program thường có phí 99 USD/năm. [Apple Developer Program](https://developer.apple.com/programs/) +- **Windows** — SmartScreen có thể hỏi khi chạy binary mới tải. Có thể đăng ký SignPath để ký miễn phí nếu dự án được duyệt. [Microsoft SmartScreen](https://learn.microsoft.com/windows/apps/package-and-deploy/smartscreen-reputation), [SignPath Foundation](https://signpath.org/terms) + +## Checklist phát hành + +- [x] Tạo workflow build, test, đóng gói và tạo bản nháp cho năm target. +- [x] Tạo checksum, formula Homebrew và manifest WinGet từ cùng bộ asset. +- [ ] Xác nhận cả năm job trên GitHub Actions, nhất là bản Windows. Bộ fixture kiểm thử chat, tiếp tục và xóa phiên hiện chạy trên Unix. Smoke test Windows kiểm tra binary, JSON và mở kho SQLite. +- [ ] Tạo tag đầu tiên, tải thử bản từ Actions, sau đó duyệt và mở bản nháp GitHub Release. +- [ ] Cập nhật tap và kiểm tra Homebrew trên macOS sạch. Nộp PR WinGet và kiểm tra cài đặt trên Windows sạch sau khi PR được duyệt. diff --git a/scripts/release.py b/scripts/release.py new file mode 100644 index 0000000..0b62c19 --- /dev/null +++ b/scripts/release.py @@ -0,0 +1,189 @@ +"""Package a native agkit build and generate its distribution metadata.""" + +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +import tarfile +from tempfile import TemporaryDirectory +import tomllib +import zipfile + + +ROOT = Path(__file__).resolve().parents[1] +TARGETS = ( + "aarch64-apple-darwin", + "x86_64-apple-darwin", + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "x86_64-pc-windows-msvc", +) +WINDOWS = "x86_64-pc-windows-msvc" +WINGET_SCHEMA = "1.12.0" + + +def package_name(version, target): + extension = "zip" if target == WINDOWS else "tar.gz" + return f"agkit-{version}-{target}.{extension}" + + +def smoke_test(directory, executable, version): + binary = str(directory / executable) + + def run(*args): + return subprocess.check_output([binary, *args], text=True, timeout=30) + + if run("--version").strip() != f"agkit {version}": + raise ValueError("Packaged agkit version does not match Cargo.toml") + if "Usage: agkit" not in run("--help"): + raise ValueError("Packaged agkit did not display CLI help") + if not json.loads(run("--json", "p", "l"))["providers"]: + raise ValueError("Packaged agkit has an empty provider catalog") + if json.loads(run("--data-dir", str(directory / "data"), "--json", "s", "l"))["sessions"]: + raise ValueError("Packaged agkit did not initialize an empty session store") + + +def pack(version, target, binary, output): + output.mkdir(parents=True, exist_ok=True) + executable = "agkit.exe" if target == WINDOWS else "agkit" + files = {executable: binary, "LICENSE": ROOT / "LICENSE"} + + # Only export the package once the executable inside it passes the smoke checks. + with TemporaryDirectory(dir=output) as temporary: + directory = Path(temporary) + archive_path = directory / package_name(version, target) + if target == WINDOWS: + with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as archive: + for name, source in files.items(): + archive.write(source, name) + with zipfile.ZipFile(archive_path) as archive: + archive.extractall(directory) + else: + with tarfile.open(archive_path, "w:gz") as archive: + for name, source in files.items(): + archive.add(source, arcname=name) + with tarfile.open(archive_path) as archive: + archive.extractall(directory, filter="data") + smoke_test(directory, executable, version) + archive_path.replace(output / archive_path.name) + + +def write_distribution(version, repository, assets, output): + owner, _ = repository.split("/") + homepage = f"https://github.com/{repository}" + download = f"{homepage}/releases/download/v{version}" + checksums = {} + for target in TARGETS: + name = package_name(version, target) + with (assets / name).open("rb") as archive: + checksums[target] = hashlib.file_digest(archive, "sha256").hexdigest() + + formula_dir = output / "Formula" + formula_dir.mkdir(parents=True, exist_ok=True) + arm, intel = TARGETS[:2] + (formula_dir / "agkit.rb").write_text(f'''\ +class Agkit < Formula + desc "Run a shared chat across local agent CLIs" + homepage "{homepage}" + version "{version}" + license any_of: ["MIT", "Apache-2.0"] + depends_on :macos + + on_arm do + url "{download}/{package_name(version, arm)}" + sha256 "{checksums[arm]}" + end + + on_intel do + url "{download}/{package_name(version, intel)}" + sha256 "{checksums[intel]}" + end + + def install + bin.install "agkit" + prefix.install "LICENSE" + end + + test do + assert_match "agkit #{{version}}", shell_output("#{{bin}}/agkit --version") + end +end +''', encoding="utf-8") + + package_id = f"{owner}.Agkit" + manifests = output / "manifests" / owner[0].lower() / owner / "Agkit" / version + manifests.mkdir(parents=True, exist_ok=True) + common = f"PackageIdentifier: {package_id}\nPackageVersion: '{version}'\n" + manifest_data = { + "version": ("", "DefaultLocale: en-US\n"), + "defaultLocale": (".locale.en-US", f"""\ +PackageLocale: en-US +Publisher: {owner} +PublisherUrl: https://github.com/{owner} +PackageName: agkit +PackageUrl: {homepage} +License: MIT OR Apache-2.0 +LicenseUrl: {homepage}/blob/v{version}/LICENSE +ShortDescription: Run a shared chat across local agent CLIs +"""), + "installer": (".installer", f"""\ +InstallerType: zip +NestedInstallerType: portable +NestedInstallerFiles: +- RelativeFilePath: agkit.exe + PortableCommandAlias: agkit +Installers: +- Architecture: x64 + InstallerUrl: {download}/{package_name(version, WINDOWS)} + InstallerSha256: {checksums[WINDOWS].upper()} +"""), + } + for kind, (suffix, data) in manifest_data.items(): + schema = f"https://aka.ms/winget-manifest.{kind}.{WINGET_SCHEMA}.schema.json" + (manifests / f"{package_id}{suffix}.yaml").write_text( + f"# yaml-language-server: $schema={schema}\n\n" + f"{common}{data}ManifestType: {kind}\nManifestVersion: {WINGET_SCHEMA}\n", + encoding="utf-8", + ) + + (assets / "SHA256SUMS").write_text( + "".join(f"{digest} {package_name(version, target)}\n" + for target, digest in checksums.items()), + encoding="utf-8", + newline="\n", + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + package = commands.add_parser("pack") + package.add_argument("--target", choices=TARGETS, required=True) + package.add_argument("--binary", type=Path, required=True) + package.add_argument("--output", type=Path, required=True) + prepare = commands.add_parser("prepare") + prepare.add_argument("--repository", required=True) + prepare.add_argument("--assets", type=Path, required=True) + prepare.add_argument("--output", type=Path, required=True) + prepare.add_argument("--tag") + args = parser.parse_args() + + with (ROOT / "Cargo.toml").open("rb") as cargo: + version = tomllib.load(cargo)["package"]["version"] + if args.command == "pack": + pack(version, args.target, args.binary, args.output) + return + + if not re.fullmatch(r"\d+\.\d+\.\d+", version): + parser.error("Distribution supports stable versions in the form X.Y.Z") + if args.tag is not None and args.tag != f"v{version}": + parser.error(f"Tag {args.tag} must match Cargo.toml version v{version}") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9-]{0,31}/[A-Za-z0-9_.-]+", args.repository): + parser.error("Repository must be a GitHub owner/name") + write_distribution(version, args.repository, args.assets, args.output) + + +if __name__ == "__main__": + main()