Files
magpie/internal/plugin/bun.go
T
yetone 23c6e865a7 plugin: a musl Linux (Alpine) runs plugins on Bun's musl build, kept apart from the glibc one (#1877)
emptyteeth found it: bunTarget picked Bun's build from GOOS/GOARCH alone,
so Alpine got bun-linux-x64-baseline, a glibc build whose interpreter
(/lib64/ld-linux-x86-64.so.2) Alpine lacks. exec then said "fork/exec
…/bun/1.4.2/magpie-bun: no such file or directory", which reads as a
missing file, and no plugin could be added or run.

- bunTarget: a musl Linux gets bun-linux-x64-musl-baseline or
  bun-linux-aarch64-musl. The musl check moves out of internal/claudecode
  into internal/libc (libc.Musl, unchanged rule: Anthropic's installer's
  /lib/libc.musl-*.so.1), which claudecode, the plugin host and the CLI
  test that skipped on musl now share.
- bunSums: the two musl builds' checksums, checked against Bun v1.4.2's
  own SHASUMS256.txt (downloaded from the GitHub release; they match the
  issue's numbers).
- Cache: a musl Linux keeps its Buns and state.json under bun/musl, so a
  machine whose C library changed never runs the other build, nor takes
  its state, whose Bad may list versions only the glibc build failed
  (CheckBun on Alpine set aside every newer Bun). glibc, macOS and Windows
  stay in bun/<v>, so a Bun downloaded before is used as it is, with no
  new download.
- A bun on disk that exec can't start with ENOENT says it is a build for
  another C library and names MAGPIE_BUN (cantStart), for the host's start
  and for bun add/bun update. The same for a $MAGPIE_BUN.
- Bun's musl build needs libstdc++ and libgcc, which a bare Alpine lacks:
  the loader then prints "Error loading shared library libstdc++.so.6"
  above ~40 "Error relocating" lines, and bun add cut it off. bun add,
  bun update and a host that died starting now say which library is
  missing and `apk add libstdc++ libgcc` (missingLibs, whyDied).

Decided: a Bun that can't be started at all is not counted as crashed.
The fallback goes to the version before, which is the same build for
this system and fails the same way, and setting the current one aside
would mark a good version bad for good. The libc check happens before the
download instead (the target), so Alpine never fetches the glibc build.

Run:
- docker alpine:3.20 (arm64, and amd64 under emulation), sandbox HOME in
  the container, linux nogui builds. origin/main's binary reproduces the
  report: "bun add …: fork/exec /sbx/.cache/magpie/bun/1.4.2/magpie-bun:
  no such file or directory". This one on bare Alpine downloads
  bun/musl/1.4.2 and says "this system lacks libstdc++.so.6 … apk add
  libstdc++ libgcc"; after apk add, `magpie plugin add
  @magpie-community/opencode-cursor-auth` adds it and `plugin list` starts
  the host and lists cursor (arm64 and amd64), with the old glibc
  bun/1.4.2 left beside it unused. With libstdc++ removed again, plugin
  list says the library; MAGPIE_BUN pointed at the glibc build gives the
  C library message.
- New tests (bunmusl_test.go, libc_test.go), each broken by hand and seen
  red: no musl branch (TestBunTargetForMusl, TestMuslBunKeptApartFromGlibc),
  no bun/musl root (TestMuslBunKeptApartFromGlibc), cantStart returning
  the error as is (TestCantStartSaysCLibrary,
  TestHostOnUnstartableBunSaysCLibrary, which fails with the reporter's
  exact message), host.go without it, no musl sum (TestBunDefaultSums),
  no hint in bun add (TestMissingLibsNamesThem) or in the host's start
  (TestHostOnBunLackingLibsSaysWhich), muslAt always false (TestMuslAt).
  -race -count=20 on them: green.
- gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows;
  go build for darwin, linux nogui, windows; go test -tags nogui for
  internal/plugin, libc, claudecode, cli in a sandbox HOME, and
  go test -tags nogui ./... (all green). One earlier run of
  internal/plugin with the other three packages went red, and its output
  was lost to a tail; four reruns of it, alone and together, were green,
  and the new tests were green under -race -count=20, so which test it
  was isn't known.

Not tried: a glibc Linux end to end after the change (the unit test
covers that its Bun stays at bun/<v>); a musl Linux other than Alpine
(the detection is unchanged and looks for Alpine's libc.musl-*.so.1).
The old glibc bun/<v> on an Alpine machine stays on disk (~90 MB); it
isn't removed, as a volume shared with a glibc container could be using
it.
2026-10-13 07:25:22 +08:00

337 lines
10 KiB
Go

package plugin
import (
"archive/zip"
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/libc"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/source"
)
// BunVersion is the Bun magpie downloads to run plugins with the first
// time one is needed, and the oldest it runs them on: newer releases are
// taken as they come (see CheckBun). Update bunSums below, testenv.MinBun
// and test.yml's bun-version when it changes.
const BunVersion = "1.4.2"
// bunSums are the SHA-256s of BunVersion's builds, from Bun's own
// SHASUMS256.txt. They let the default Bun be downloaded through a mirror
// when Bun's GitHub release page can't be reached.
var bunSums = map[string]string{
"bun-darwin-aarch64.zip": "90987a3a16d7db556d886ac3d551e7b6d3edf0a1cf43acaed622e8676be1d12f",
"bun-darwin-x64.zip": "80520d7e17526308c9185d261679ac6d27798d3803a0e9f7ff9121ab8affb012",
"bun-linux-aarch64.zip": "54328bbc2d9c8e0c9f892c544d66c57a83b84139e34909e5ee81758f1ac8fda7",
"bun-linux-x64-baseline.zip": "c678040f14fe0440eb839d37cbd0ce4c051a32da72806ac97de6a6aab6bf728f",
"bun-linux-aarch64-musl.zip": "71760b6c8ea30623b81a4907cb815d48e2ea266f2e73e751534a44a0607950df",
"bun-linux-x64-musl-baseline.zip": "76e1db84e98f22f78de0a87e309bfbbf297732847f9720db36750646c85c8c18",
"bun-windows-x64-baseline.zip": "78c221c2376f79731ccf4e4af0b3bb46d81fefa3296c5abee09ad8a1b21e68c6",
"bun-linux-aarch64-android.zip": "a1c7e2983f1bb65146beb256a4d72449f23042412bc2cf278aa6397ba27e0274",
"bun-linux-x64-android-baseline.zip": "fe36d8d4795e0eadc22fb6696d44d168491c2e5b9b7cbb12b8c96b0c0c40a4f9",
}
func bunChecksum(version, target string) string {
if version != BunVersion {
return ""
}
return bunSums[target+".zip"]
}
// bunRelease is where Bun's releases are; a var for tests.
var bunRelease = "https://github.com/oven-sh/bun/releases/download"
var bunMu sync.Mutex
// bunPlatform is this machine as Bun's builds tell them apart: its OS, its
// architecture, and whether it is a Linux on musl (Alpine), where Bun's
// glibc builds can't start (#1877). A var for tests.
var bunPlatform = func() (goos, goarch string, musl bool) {
return runtime.GOOS, runtime.GOARCH, libc.Musl()
}
// bunTarget is the name of Bun's build for this machine: bun-darwin-aarch64
// and the like. x64 Linux and Windows get the baseline build, which runs
// on CPUs without AVX2 as well; a musl Linux gets the musl build.
func bunTarget() (string, error) {
return bunTargetFor(bunPlatform())
}
func bunTargetFor(goos, goarch string, musl bool) (string, error) {
arch := map[string]string{"arm64": "aarch64", "amd64": "x64"}[goarch]
if arch == "" {
return "", fmt.Errorf("Bun has no build for %s/%s", goos, goarch)
}
switch goos {
case "darwin":
case "linux":
if musl {
// arm64 has no baseline build, musl or not
t := "bun-linux-" + arch + "-musl"
if arch == "x64" {
t += "-baseline"
}
return t, nil
}
case "android":
t := "bun-linux-" + arch + "-android"
if arch == "x64" {
t += "-baseline"
}
return t, nil
case "windows":
if arch != "x64" {
return "", fmt.Errorf("Bun has no build for windows/%s", goarch)
}
default:
return "", fmt.Errorf("Bun has no build for %s", goos)
}
t := "bun-" + goos + "-" + arch
if arch == "x64" && goos != "darwin" {
t += "-baseline"
}
return t, nil
}
func bunExe() string {
if runtime.GOOS == "windows" {
return "bun.exe"
}
return "bun"
}
// missingLibRe finds what a musl Linux's loader says when a program needs
// a library the system lacks: "Error loading shared library
// libstdc++.so.6: No such file or directory (needed by …)".
var missingLibRe = regexp.MustCompile(`Error loading shared library ([^:\s]+)`)
// missingLibs says which libraries a bun that started couldn't be linked
// with lacks, from what it printed, "" when that isn't why it failed. Bun's
// musl build needs libstdc++ and libgcc, which a bare Alpine doesn't have
// (#1877); the loader's first line names them, under a screenful of
// "Error relocating" lines.
func missingLibs(out string) string {
var libs []string
for _, m := range missingLibRe.FindAllStringSubmatch(out, -1) {
if !slices.Contains(libs, m[1]) {
libs = append(libs, m[1])
}
}
if len(libs) == 0 {
return ""
}
return fmt.Sprintf("this system lacks %s, which Bun needs (on Alpine: apk add libstdc++ libgcc), or set MAGPIE_BUN to a bun that runs here", strings.Join(libs, ", "))
}
// whyDied adds to the error of a host that died starting what the bun it
// ran on says when asked its version, when that is a library it lacks.
func whyDied(ctx context.Context, bun string, err error) error {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
out, verr := command(ctx, bun, "--version").CombinedOutput()
if verr == nil {
return err
}
if hint := missingLibs(string(out)); hint != "" {
return fmt.Errorf("%s: %w", hint, err)
}
return err
}
// cantStart says what it means when a bun that is on disk can't be
// started with "no such file or directory": not that the file is missing,
// but that the interpreter it names is. A glibc build on a musl Linux
// (Alpine) names glibc's loader, which isn't there (#1877). Any other
// error is given back as it is.
func cantStart(bun string, err error) error {
if err == nil || !errors.Is(err, fs.ErrNotExist) {
return err
}
if fi, serr := os.Stat(bun); serr != nil || fi.IsDir() {
return err
}
if b := os.Getenv("MAGPIE_BUN"); b != "" && b == bun {
return fmt.Errorf("this system can't start $MAGPIE_BUN (%s), though it is there: it is likely a build for another C library than this system's (glibc or musl), whose loader isn't here: %w", bun, err)
}
target, _ := bunTarget()
return fmt.Errorf("this system can't start the Bun magpie downloaded (%s, %s), though it is there: the build doesn't match this system's C library (glibc or musl). Set MAGPIE_BUN to a bun built for this system to run plugins on it: %w", target, bun, err)
}
// Bun is the bun to run plugins with: $MAGPIE_BUN when set, else the one
// magpie downloaded and keeps up to date, downloading it now when there
// is none yet.
func Bun(ctx context.Context) (string, error) {
if b := os.Getenv("MAGPIE_BUN"); b != "" {
return b, nil
}
bunMu.Lock()
defer bunMu.Unlock()
v := inUseLocked()
exe := bunExeOf(v)
if haveBun(v) {
return exe, nil
}
if err := downloadBun(ctx, v, exe); err != nil {
return "", fmt.Errorf("downloading Bun %s to run plugins: %w", v, err)
}
return exe, nil
}
// HasBun is whether a Bun is at hand without a download.
func HasBun() bool {
if os.Getenv("MAGPIE_BUN") != "" {
return true
}
bunMu.Lock()
defer bunMu.Unlock()
return haveBun(inUseLocked())
}
func downloadBun(ctx context.Context, version, exe string) error {
target, err := bunTarget()
if err != nil {
return err
}
base := bunRelease + "/bun-v" + version + "/"
want := bunChecksum(version, target)
if want == "" {
sums, err := getURLOfficial(ctx, base+"SHASUMS256.txt", 1<<20)
if err != nil {
return err
}
sc := bufio.NewScanner(strings.NewReader(string(sums)))
for sc.Scan() {
f := strings.Fields(sc.Text())
if len(f) == 2 && f[1] == target+".zip" {
want = f[0]
}
}
if want == "" {
return fmt.Errorf("%s.zip isn't in the release's checksums", target)
}
}
z, err := getURL(ctx, base+target+".zip", 200<<20)
if err != nil {
return err
}
sum := sha256.Sum256(z)
if hex.EncodeToString(sum[:]) != want {
return errors.New("the download's checksum doesn't match the release's")
}
zr, err := zip.NewReader(bytes.NewReader(z), int64(len(z)))
if err != nil {
return err
}
for _, f := range zr.File {
if filepath.Base(f.Name) != bunExe() || f.FileInfo().IsDir() {
continue
}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
if err := os.MkdirAll(filepath.Dir(exe), 0o755); err != nil {
return err
}
tmp := exe + ".part"
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
if err != nil {
return err
}
if _, err := io.Copy(out, rc); err != nil {
out.Close()
os.Remove(tmp)
return err
}
if err := out.Close(); err != nil {
return err
}
return os.Rename(tmp, exe)
}
return fmt.Errorf("%s.zip has no %s", target, bunExe())
}
func getURL(ctx context.Context, url string, limit int64) ([]byte, error) {
return getURLFrom(ctx, url, limit, true)
}
func getURLOfficial(ctx context.Context, url string, limit int64) ([]byte, error) {
return getURLFrom(ctx, url, limit, false)
}
func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
var res *http.Response
if mirror {
res, err = source.Do(http.DefaultClient, req)
} else {
res, err = source.DoOfficial(http.DefaultClient, req)
}
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", url, res.Status)
}
b, err := io.ReadAll(io.LimitReader(res.Body, limit+1))
if err != nil {
return nil, err
}
if int64(len(b)) > limit {
return nil, fmt.Errorf("%s: too large", url)
}
return b, nil
}
// bunCommand runs bun with args in dir, the environment's proxy settings
// passed on (a SOCKS5 one bridged, as Bun can't use it: #1409), the roots
// the system trusts added to Bun's (caEnv), and npm's registry in China
// with the 「国内镜像」 switch on (its packages are npm's own, checked
// against the integrity npm gave).
var bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd {
cmd := command(ctx, bun, args...)
cmd.Dir = dir
cmd.Env = append(netproxy.EnvForBun(env()), "BUN_INSTALL_CACHE_DIR="+filepath.Join(filepath.Dir(catalog.CachePath()), "bun", "install-cache"))
cmd.Env = append(cmd.Env, caEnv(cmd.Env, dir)...)
cmd.Env = append(cmd.Env, registryEnv(cmd.Env)...)
return cmd
}
// registryEnv is what has bun install from npm's registry in China, with
// the switch on, unless the environment names a registry already.
func registryEnv(env []string) []string {
if !source.China() {
return nil
}
for _, kv := range env {
k, v, _ := strings.Cut(kv, "=")
if k = strings.ToUpper(k); (k == "BUN_CONFIG_REGISTRY" || k == "NPM_CONFIG_REGISTRY") && strings.TrimSpace(v) != "" {
return nil
}
}
return []string{"BUN_CONFIG_REGISTRY=" + source.NPMMirror + "/"}
}