Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

plugins: a Bun Windows can't load (0xc0000139, before 10 1809 / Server 2019) says so and what to do (zgcwkj on Discord)

yetone5b32b7ea802e
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index e826f10bf..540c395a5 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -178,6 +178,8 @@ The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fet
magpie downloads the Bun build for this machine (`bunTarget` in [`bun.go`](../../internal/plugin/bun.go)): the baseline build on x64 Linux and Windows, the native `bun-windows-aarch64` on Windows on ARM (it was turned away as having no build until #2183), and on a musl Linux such as Alpine (`libc.Musl`, the check Claude Code's download uses too) the musl one, `bun-linux-x64-musl-baseline` or `bun-linux-aarch64-musl`. A glibc build names glibc's loader, which Alpine lacks, so it couldn't start there and exec said "no such file or directory" (#1877). A musl Linux keeps its Buns and their `state.json` under `bun/musl`, so a machine whose C library changed never runs the other one's build or takes its set-aside versions; everywhere else they stay in `bun`, where a Bun downloaded before is. A bun that is on disk but can't be started says it is a build for another C library and names `MAGPIE_BUN` (`cantStart`), and it isn't fallen back from or set aside: the version before is the same build. Bun's musl build needs libstdc++ and libgcc; on an Alpine without them, `bun add` and the host's start say which library is missing and `apk add libstdc++ libgcc` (`missingLibs`). `TestBunTargetForMusl`, `TestMuslBunKeptApartFromGlibc`, `TestCantStartSaysCLibrary`, `TestHostOnUnstartableBunSaysCLibrary`, `TestMissingLibsNamesThem` and `TestHostOnBunLackingLibsSaysWhich` in [`bunmusl_test.go`](../../internal/plugin/bunmusl_test.go) cover these.
+A bun this machine can't run at all says so instead of its exit status (`wontLoad`, a `*BunUnstartableError`). Windows refuses to load Bun 1.3.14 and later before Windows 10 1809 and Windows Server 2019: they import kernel32's `CreatePseudoConsole`, which older Windows lacks, so the process ends with 0xc0000139 (STATUS_ENTRYPOINT_NOT_FOUND) before it runs (zgcwkj on Discord, a Windows service). A processor without an instruction Bun's x64 build uses (it targets SSE4.2) ends it with 0xc000001d on Windows and SIGILL elsewhere. `bun add`, `bun update` and the host's start (`whyDied`, `cantStart`) each wrap the exit in it. The message says which of the two it is and names `MAGPIE_BUN`. An install doesn't try the community repo's dist branch after it, because that `bun add` can't start either. The GUI's `fail` answers it with code `bun_unstartable`, `bunWhy` (`windows` or `cpu`) and `said`, the i18n.js key for it (`bunSaid` in api.go, kept there so app.js holds one line under its budget), which `api()` in app.js puts through `t()` in place of the English. `TestBunSaidIsTranslated` fails when a language lacks it. There is no fallback to an older Bun: the last one Windows Server 2016 loads, 1.3.13, is below `BunVersion`, and Bun's baseline assets are now the same binary. `TestWontLoadSaysWindowsOrCPU`, `TestInstallOnUnstartableBunSaysWhyAndSkipsDist` and `TestHostOnUnstartableBunSaysWhy` in [`bunload_test.go`](../../internal/plugin/bunload_test.go), `TestFailSaysBunUnstartable` in internal/gui and `plugin-bun-unstartable.test.cjs` (both engines, every language) cover these.
+
Bun takes only http:// and https:// proxies. A SOCKS5 one, such as a Mac's system SOCKS proxy, is given to every bun magpie starts as a loopback HTTP proxy in front of it (`netproxy.Bridge`): to the host through `hostEnv`, and to `bun add`, `bun update` and `bun remove` through `bunCommand` (`netproxy.EnvForBun`). Before, an install with only a SOCKS system proxy failed as `UnsupportedProxyProtocol` (#1409). An agent CLI that bun installed is updated through the bridge too (`updateEnv` in `internal/agent/cliupdate.go`). Claude Code, built with Bun, gets it for the Claude subscription's runs and sign-ins (`netproxy.EnvForBunWith`, #2651; see [Claude subscription bridge](claude-subscription-bridge.md)).
The host reads its proxy once, when it starts. When the proxy magpie would give a new host differs from the one the running host got (the system proxy set after magpie started, as at login before Clash is up, or Settings changed), the next call to the host replaces it (`proxyMoved` in [`host.go`](../../internal/plugin/host.go), looked at no more than every 15s, or every 2s while the host has no proxy: `proxyLookNone`, #1518). A call made for a read nobody asked for, while allowances are read only when asked (`netproxy.Held`), never reaches the host. Before this, a host started without a proxy kept none, so the Grok plugin's `grok models` couldn't renew its token and the account read as signed out after each restart (#1363).
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 684102a2b..b29f80658 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -2520,6 +2520,13 @@ func fail(rw http.ResponseWriter, err error) {
out["reason"] = admin.Err.Error()
}
}
+ // a bun this Windows or processor can't run at all: said, with what
+ // to do, in the reader's language (zgcwkj on Discord)
+ var bun *plugin.BunUnstartableError
+ if errors.As(err, &bun) {
+ out["code"], out["bun"], out["bunWhy"] = "bun_unstartable", bun.Bun, bun.Why
+ out["said"] = bunSaid[bun.Why]
+ }
_ = json.NewEncoder(rw).Encode(out)
}
@@ -2594,3 +2601,11 @@ func countClient(m map[string]string, client, as string) (map[string]string, err
out[strings.ToLower(client)] = as
return out, nil
}
+
+// bunSaid is what the page says for a bun that can't start, by why: an
+// i18n.js key the page's api() puts through t(), kept here so app.js
+// carries one line for it, not both sentences
+var bunSaid = map[string]string{
+ "windows": "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.",
+ "cpu": "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.",
+}
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index bade2713b..217843abc 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -137,6 +137,7 @@ async function api(path, body, heads, signal) {
err.message = t("None of magpie's models is left in {agent}'s model list: pick one under Model list → Pick, then connect {agent}", { agent: data.agent });
}
if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language
+ if (data?.code === "bun_unstartable") err.message = t(data.said); // bunSaid in api.go: an i18n.js key
// an account the agent is signed in to, refused removal while it has
// another: said in the reader's language
if (data?.code === "signed_in") {
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index be209c088..55cdf041c 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -3587,6 +3587,8 @@ const I18N = {
"{name} is installed": "{name} 已安装",
"Getting Bun…": "正在下载 Bun…",
"Plugins run on Bun {v}, downloaded once": "插件运行在 Bun {v} 上,只需下载一次",
+ "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.": "运行插件的 Bun 无法在这个版本的 Windows 上启动:它需要 Windows 10 1809 或更新版本,或 Windows Server 2019 或更新版本。请升级 Windows 后再使用插件,或把 MAGPIE_BUN 设为能在这里运行的 bun。",
+ "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.": "运行插件的 Bun 无法在这台电脑的处理器上启动:它需要支持 SSE4.2 的 x64 处理器(2008 年以后的 Intel 或 AMD;虚拟机里请选能透传 SSE4.2 的 CPU 类型)。请在这样的处理器上运行 magpie 来使用插件,或把 MAGPIE_BUN 设为能在这里运行的 bun。",
"Coming soon": "即将上线",
"{n} stars on GitHub": "GitHub 上 {n} 个 Star",
"Unofficial, on GitHub": "非官方插件 · GitHub",
@@ -7511,6 +7513,8 @@ const I18N = {
"{name} is installed": "{name} 已安裝",
"Getting Bun…": "正在下載 Bun…",
"Plugins run on Bun {v}, downloaded once": "外掛執行在 Bun {v} 上,只需下載一次",
+ "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.": "執行外掛的 Bun 無法在這個版本的 Windows 上啟動:它需要 Windows 10 1809 或更新版本,或 Windows Server 2019 或更新版本。請更新 Windows 後再使用外掛,或將 MAGPIE_BUN 設為能在這裡執行的 bun。",
+ "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.": "執行外掛的 Bun 無法在這台電腦的處理器上啟動:它需要支援 SSE4.2 的 x64 處理器(2008 年以後的 Intel 或 AMD;虛擬機器中請選能傳遞 SSE4.2 的 CPU 類型)。請在這樣的處理器上執行 magpie 來使用外掛,或將 MAGPIE_BUN 設為能在這裡執行的 bun。",
"Coming soon": "即將上線",
"{n} stars on GitHub": "GitHub 上 {n} 個 Star",
"Unofficial, on GitHub": "非官方外掛 · GitHub",
@@ -11457,6 +11461,8 @@ const I18N = {
"{name} is installed": "{name} をインストールしました",
"Getting Bun…": "Bun を取得中…",
"Plugins run on Bun {v}, downloaded once": "プラグインは Bun {v} で動作します(ダウンロードは一度だけ)",
+ "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.": "プラグインを動かす Bun は、このバージョンの Windows では起動できません。Windows 10 バージョン 1809 以降、または Windows Server 2019 以降が必要です。プラグインを使うには Windows を更新するか、MAGPIE_BUN にここで動く bun を指定してください。",
+ "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.": "プラグインを動かす Bun は、このコンピューターのプロセッサでは起動できません。SSE4.2 に対応した x64 プロセッサ(2008 年以降の Intel または AMD。仮想マシンでは SSE4.2 を引き渡す CPU タイプ)が必要です。プラグインを使うにはそのようなプロセッサで magpie を実行するか、MAGPIE_BUN にここで動く bun を指定してください。",
"Coming soon": "近日公開",
"{n} stars on GitHub": "GitHub のスター {n}",
"Unofficial, on GitHub": "非公式 · GitHub",
@@ -15416,6 +15422,8 @@ const I18N = {
"{name} is installed": "{name} ist installiert",
"Getting Bun…": "Bun wird geladen…",
"Plugins run on Bun {v}, downloaded once": "Erweiterungen laufen auf Bun {v}, einmalig heruntergeladen",
+ "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.": "Bun, das die Erweiterungen ausführt, kann auf dieser Windows-Version nicht starten: Es braucht Windows 10 Version 1809 oder neuer oder Windows Server 2019 oder neuer. Aktualisieren Sie Windows, um Erweiterungen zu nutzen, oder setzen Sie MAGPIE_BUN auf ein bun, das hier läuft.",
+ "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.": "Bun, das die Erweiterungen ausführt, kann auf dem Prozessor dieses Computers nicht starten: Es braucht einen x64-Prozessor mit SSE4.2 (Intel oder AMD ab 2008; in einer virtuellen Maschine einen CPU-Typ, der es durchreicht). Führen Sie magpie auf einem solchen Prozessor aus, um Erweiterungen zu nutzen, oder setzen Sie MAGPIE_BUN auf ein bun, das hier läuft.",
"Coming soon": "Demnächst",
"{n} stars on GitHub": "{n} Sterne auf GitHub",
"Unofficial, on GitHub": "Inoffiziell, auf GitHub",
diff --git a/internal/gui/bun_unstartable_test.go b/internal/gui/bun_unstartable_test.go
new file mode 100644
index 000000000..8717857ed
--- /dev/null
+++ b/internal/gui/bun_unstartable_test.go
@@ -0,0 +1,50 @@
+package gui
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/plugin"
+)
+
+// A plugin install on a bun this Windows or processor can't run answers
+// with a code and the reason, which the page says in the reader's
+// language (zgcwkj on Discord), wrapped however deep the install put it.
+func TestFailSaysBunUnstartable(t *testing.T) {
+ bun := `C:\magpie\cache\bun\1.4.2\magpie-bun.exe`
+ ue := &plugin.BunUnstartableError{Bun: bun, Why: "windows", Err: fmt.Errorf("exit status 0xc0000139")}
+ rw := httptest.NewRecorder()
+ fail(rw, fmt.Errorf("bun add @magpie-community/opencode-raccoon-auth@latest: %w", ue))
+ var out map[string]string
+ if err := json.Unmarshal(rw.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ if rw.Code != 400 || out["code"] != "bun_unstartable" || out["bunWhy"] != "windows" || out["bun"] != bun || out["error"] == "" || out["said"] != bunSaid["windows"] {
+ t.Fatalf("fail answered %d %v", rw.Code, out)
+ }
+ rw = httptest.NewRecorder()
+ fail(rw, fmt.Errorf("bun add x: exit status 1"))
+ out = nil
+ if err := json.Unmarshal(rw.Body.Bytes(), &out); err != nil || out["code"] != "" || out["said"] != "" {
+ t.Fatalf("an ordinary failure answered %v (%v)", out, err)
+ }
+}
+
+// What the page says for it is a key i18n.js has in every language: a
+// t() of a word it lacks shows the English.
+func TestBunSaidIsTranslated(t *testing.T) {
+ words, err := os.ReadFile("assets/i18n.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for why, said := range bunSaid {
+ key, _ := json.Marshal(said)
+ if n := strings.Count(string(words), string(key)+":"); n != 4 {
+ t.Errorf("%s: i18n.js has %q in %d languages, want zh, zh-TW, ja and de", why, said, n)
+ }
+ }
+}
diff --git a/internal/gui/tests/plugin-bun-unstartable.test.cjs b/internal/gui/tests/plugin-bun-unstartable.test.cjs
new file mode 100644
index 000000000..9d705ea83
--- /dev/null
+++ b/internal/gui/tests/plugin-bun-unstartable.test.cjs
@@ -0,0 +1,100 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// A plugin's install on a machine whose Windows or processor can't start
+// Bun at all (zgcwkj on Discord: bun add … exit status 0xc0000139 on an
+// older Windows) says in the reader's language why, and what to do,
+// instead of bun's exit status: in the desktop window and in magpie web.
+// No backend: the API is faked here, and nothing is ever installed.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+
+const assets = path.resolve(__dirname, "../assets");
+const PKG = "@magpie-community/opencode-raccoon-auth";
+const listings = [{ package: PKG, name: "Raccoon", icon: "raccoon", providers: ["raccoon"], community: true,
+ summary: { en: "Your Raccoon plan." }, npm: { version: "0.1.3", weekly: 10, license: "MIT" } }];
+
+// what the server answers, its English message as plugin.BunUnstartableError says it
+const ANSWER = {
+ windows: { error: "bun add " + PKG + "@latest: Bun can't start on this version of Windows: … (C:\\magpie\\cache\\bun\\1.4.2\\magpie-bun.exe exited with 0xc0000139, entry point not found) …", code: "bun_unstartable", bun: "C:\\magpie\\cache\\bun\\1.4.2\\magpie-bun.exe", bunWhy: "windows", said: "" },
+ cpu: { error: "bun add " + PKG + "@latest: Bun can't start on this computer's processor: …", code: "bun_unstartable", bun: "/root/.cache/magpie/bun/1.4.2/magpie-bun", bunWhy: "cpu", said: "" },
+};
+
+// said is the i18n.js key the server chose (bunSaid in api.go)
+ANSWER.windows.said = "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.";
+ANSWER.cpu.said = "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.";
+
+function server(lang, web, why, asked) {
+ const state = { bun: true, bunVersion: "1.4.2", plugins: [] };
+ return async (route) => {
+ const req = route.request(), url = new URL(req.url());
+ const json = (data) => route.fulfill({ json: data });
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
+ if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
+ if (url.pathname === "/api/plugins/market") return json({ listings, state });
+ if (url.pathname === "/api/plugins") return json(state);
+ if (url.pathname === "/api/plugins/listings") return json({ listings });
+ if (url.pathname === "/api/plugins/add") {
+ asked.push(req.postDataJSON());
+ return route.fulfill({ status: 400, json: ANSWER[why] });
+ }
+ if (url.pathname.startsWith("/api/")) return json({});
+ if (!/^\/[\w./-]*$/.test(url.pathname) || url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
+ };
+}
+
+const SAID = {
+ en: {
+ install: "Install",
+ windows: "Bun, which runs plugins, can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later. Update Windows to use plugins, or set MAGPIE_BUN to a bun that runs here.",
+ cpu: "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.",
+ },
+ zh: { install: "安装", windows: /^运行插件的 Bun 无法在这个版本的 Windows 上启动:它需要 Windows 10 1809 或更新版本/, cpu: /^运行插件的 Bun 无法在这台电脑的处理器上启动:它需要支持 SSE4\.2 的 x64 处理器/ },
+ "zh-TW": { install: "安裝", windows: /^執行外掛的 Bun 無法在這個版本的 Windows 上啟動/, cpu: /^執行外掛的 Bun 無法在這台電腦的處理器上啟動/ },
+ ja: { install: "インストール", windows: /^プラグインを動かす Bun は、このバージョンの Windows では起動できません/, cpu: /^プラグインを動かす Bun は、このコンピューターのプロセッサでは起動できません/ },
+ de: { install: "Installieren", windows: /^Bun, das die Erweiterungen ausführt, kann auf dieser Windows-Version nicht starten/, cpu: /^Bun, das die Erweiterungen ausführt, kann auf dem Prozessor dieses Computers nicht starten/ },
+};
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": an install on a Bun this machine can't start says why", async (t) => {
+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ const errors = [];
+ t.after(async () => {
+ if (errors.length) console.log(errors);
+ await browser.close();
+ });
+ for (const [lang, want] of Object.entries(SAID)) {
+ for (const [why, web] of [["windows", false], ["cpu", true], ["windows", true]]) {
+ await t.test(`${lang} ${why} ${web ? "web" : "window"}`, async () => {
+ const asked = [];
+ const ctx = await browser.newContext({ viewport: { width: 980, height: 760 } });
+ const page = await ctx.newPage();
+ page.setDefaultTimeout(5000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server(lang, web, why, asked));
+ await page.goto("http://magpie.test/?view=plugins");
+ const act = page.locator(`#view-plugins .pm-card[data-pkg="${PKG}"] .pm-act`);
+ await act.filter({ hasText: want.install }).waitFor();
+ await act.click();
+ await page.waitForFunction(() => /Bun/.test(document.querySelector("#status")?.textContent || ""));
+ const said = (await page.locator("#status").textContent()).trim();
+ if (typeof want[why] === "string") assert.equal(said, want[why]);
+ else assert.match(said, want[why]);
+ // bun's exit status and the server's English aren't what's shown
+ assert.doesNotMatch(said, /0xc0000139|exit status|bun add/);
+ assert.deepEqual(asked, [{ spec: PKG }]);
+ await ctx.close();
+ });
+ }
+ }
+ assert.deepEqual(errors, []);
+ });
+}
diff --git a/internal/plugin/bun.go b/internal/plugin/bun.go
index f32e95389..ea7c23a74 100644
--- a/internal/plugin/bun.go
+++ b/internal/plugin/bun.go
@@ -20,6 +20,7 @@ import (
"slices"
"strings"
"sync"
+ "syscall"
"time"
"github.com/yetone/magpie/internal/ghtoken"
@@ -150,6 +151,9 @@ func whyDied(ctx context.Context, bun string, err error) error {
if verr == nil {
return err
}
+ if ue := wontLoad(bun, verr); ue != nil {
+ return fmt.Errorf("%w (%v)", ue, err)
+ }
if hint := missingLibs(string(out)); hint != "" {
return fmt.Errorf("%s: %w", hint, err)
}
@@ -159,9 +163,13 @@ func whyDied(ctx context.Context, bun string, err error) error {
// 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
+// (Alpine) names glibc's loader, which isn't there (#1877). A bun that
+// Windows or the processor won't load says so (wontLoad). Any other
// error is given back as it is.
func cantStart(bun string, err error) error {
+ if ue := wontLoad(bun, err); ue != nil {
+ return ue
+ }
if err == nil || !errors.Is(err, fs.ErrNotExist) {
return err
}
@@ -175,6 +183,62 @@ func cantStart(bun string, err error) error {
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)
}
+// The statuses Windows ends a program with when it can't load it.
+const (
+ // a DLL it imports lacks a function it names: Bun 1.3.14 and later
+ // import CreatePseudoConsole from kernel32, which Windows has only
+ // from Windows 10 1809 and Server 2019 on (zgcwkj on Discord)
+ statusEntrypointNotFound = 0xc0000139
+ // the processor lacks an instruction it uses
+ statusIllegalInstruction = 0xc000001d
+)
+
+// BunUnstartableError is a bun this machine can't run at all: Windows is
+// older than Bun needs, or the processor lacks an instruction Bun is
+// built for. No Bun magpie can download runs here, so an install isn't
+// tried again from elsewhere and the GUI says it in the reader's language.
+type BunUnstartableError struct {
+ Bun string
+ // Why is "windows" or "cpu".
+ Why string
+ Err error
+}
+
+func (e *BunUnstartableError) Error() string {
+ if e.Why == "windows" {
+ return fmt.Sprintf("Bun can't start on this version of Windows: it needs Windows 10 version 1809 or later, or Windows Server 2019 or later, and this one lacks a function it uses (%s exited with 0xc0000139, entry point not found). Update Windows to run plugins, or set MAGPIE_BUN to a bun that runs here: %v", e.Bun, e.Err)
+ }
+ return fmt.Sprintf("Bun can't start on this computer's processor: it lacks an instruction Bun uses (%s: %v). Bun's x64 build needs SSE4.2 (an Intel or AMD processor from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to run plugins, or set MAGPIE_BUN to a bun that runs here", e.Bun, e.Err)
+}
+
+func (e *BunUnstartableError) Unwrap() error { return e.Err }
+
+// wontLoad is a *BunUnstartableError when err is bun's exit with what
+// Windows or the processor says when it can't run it at all: STATUS_
+// ENTRYPOINT_NOT_FOUND, STATUS_ILLEGAL_INSTRUCTION, or SIGILL elsewhere.
+// Else nil.
+func wontLoad(bun string, err error) *BunUnstartableError {
+ if err == nil {
+ return nil
+ }
+ var ec interface{ ExitCode() int }
+ if errors.As(err, &ec) {
+ switch uint32(ec.ExitCode()) {
+ case statusEntrypointNotFound:
+ return &BunUnstartableError{Bun: bun, Why: "windows", Err: err}
+ case statusIllegalInstruction:
+ return &BunUnstartableError{Bun: bun, Why: "cpu", Err: err}
+ }
+ }
+ var ps interface{ Sys() any }
+ if errors.As(err, &ps) {
+ if ws, ok := ps.Sys().(syscall.WaitStatus); ok && ws.Signaled() && ws.Signal() == syscall.SIGILL {
+ return &BunUnstartableError{Bun: bun, Why: "cpu", Err: err}
+ }
+ }
+ return nil
+}
+
// 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.
diff --git a/internal/plugin/bunload_test.go b/internal/plugin/bunload_test.go
new file mode 100644
index 000000000..6971e3a37
--- /dev/null
+++ b/internal/plugin/bunload_test.go
@@ -0,0 +1,132 @@
+package plugin
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// exitedWith is a process's exit as Windows reports one: its NTSTATUS as
+// the exit code, which a fake bun on another system can't exit with.
+type exitedWith uint32
+
+func (e exitedWith) ExitCode() int { return int(uint32(e)) }
+func (e exitedWith) Error() string { return fmt.Sprintf("exit status %#x", uint32(e)) }
+
+// A bun that Windows won't load (STATUS_ENTRYPOINT_NOT_FOUND: Bun 1.3.14
+// and later import CreatePseudoConsole, which Windows has from 10 1809 on,
+// zgcwkj on Discord) or the processor won't run (STATUS_ILLEGAL_
+// INSTRUCTION, SIGILL) says which and what to do; any other exit is
+// given back as it was.
+func TestWontLoadSaysWindowsOrCPU(t *testing.T) {
+ bun := `C:\magpie\cache\bun\1.4.2\magpie-bun.exe`
+ for _, c := range []struct {
+ err error
+ why string
+ says []string
+ }{
+ {exitedWith(0xc0000139), "windows", []string{"Windows 10 version 1809", "Windows Server 2019", "0xc0000139", "MAGPIE_BUN", bun}},
+ {exitedWith(0xc000001d), "cpu", []string{"processor", "SSE4.2", "MAGPIE_BUN", bun}},
+ } {
+ wrapped := errors.Join(errors.New("starting"), c.err)
+ ue := wontLoad(bun, wrapped)
+ if ue == nil || ue.Why != c.why {
+ t.Fatalf("wontLoad(%v) = %#v, want %s", c.err, ue, c.why)
+ }
+ for _, s := range c.says {
+ if !strings.Contains(ue.Error(), s) {
+ t.Errorf("%s: %q doesn't say %q", c.why, ue.Error(), s)
+ }
+ }
+ if !errors.Is(ue, c.err) {
+ t.Errorf("%s: the exit isn't kept under it", c.why)
+ }
+ var got *BunUnstartableError
+ if err := cantStart(bun, c.err); !errors.As(err, &got) || got.Why != c.why {
+ t.Errorf("cantStart(%v) = %v", c.err, err)
+ }
+ }
+ for _, other := range []error{exitedWith(1), exitedWith(0xc0000005), errors.New("exit status 3"), nil} {
+ if ue := wontLoad(bun, other); ue != nil {
+ t.Errorf("wontLoad(%v) = %v, want nil", other, ue)
+ }
+ }
+ if runtime.GOOS != "windows" {
+ err := exec.Command("/bin/sh", "-c", "kill -ILL $$").Run()
+ if ue := wontLoad("bun", err); ue == nil || ue.Why != "cpu" {
+ t.Fatalf("wontLoad(%v) = %v, want cpu", err, ue)
+ }
+ err = exec.Command("/bin/sh", "-c", "kill -SEGV $$").Run()
+ if ue := wontLoad("bun", err); ue != nil {
+ t.Fatalf("wontLoad(%v) = %v, want nil", err, ue)
+ }
+ }
+}
+
+// stopsOnSIGILL is a bun as one the processor can't run is: the kernel
+// stops it on its first instruction the processor lacks.
+func stopsOnSIGILL(t *testing.T, path string) {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ t.Skip("the bun is a shell script")
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("#!/bin/sh\nkill -ILL $$\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// An install on a bun this machine can't run says so, as a
+// *BunUnstartableError the GUI translates, and isn't tried again from the
+// community repo's dist branch: that bun add can't start either, and its
+// error read as the dist branch's (bun add ./dist/…: exit status …).
+func TestInstallOnUnstartableBunSaysWhyAndSkipsDist(t *testing.T) {
+ bunHome(t, BunVersion, time.Now())
+ stopsOnSIGILL(t, bunExeOf(BunVersion))
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ http.NotFound(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ old := distBase
+ distBase = srv.URL
+ t.Cleanup(func() { distBase = old })
+
+ err := install(context.Background(), "@magpie-community/opencode-raccoon-auth@latest")
+ var ue *BunUnstartableError
+ if !errors.As(err, &ue) || ue.Why != "cpu" || ue.Bun != bunExeOf(BunVersion) {
+ t.Fatalf("install on a bun stopped by SIGILL: %v", err)
+ }
+ if strings.Contains(err.Error(), "dist branch") || hits.Load() != 0 {
+ t.Fatalf("the dist branch was tried (%d requests): %v", hits.Load(), err)
+ }
+}
+
+// The host on a bun this machine can't run says why.
+func TestHostOnUnstartableBunSaysWhy(t *testing.T) {
+ bunHome(t, BunVersion, time.Now())
+ t.Cleanup(Settle)
+ stopsOnSIGILL(t, bunExeOf(BunVersion))
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ abs, _ := filepath.Abs("testdata/fake/index.js")
+ _, _ = Add(ctx, abs)
+ _, err := Providers(ctx)
+ var ue *BunUnstartableError
+ if !errors.As(err, &ue) || ue.Why != "cpu" || !strings.Contains(err.Error(), "SSE4.2") {
+ t.Fatalf("Providers on a bun stopped by SIGILL: %v", err)
+ }
+}
diff --git a/internal/plugin/store.go b/internal/plugin/store.go
index 8c231c4fd..a96096c83 100644
--- a/internal/plugin/store.go
+++ b/internal/plugin/store.go
@@ -711,8 +711,10 @@ func install(ctx context.Context, spec string) error {
// a @magpie-community package or version npm doesn't have (a new
// one waits for an owner to publish it there) comes from the
// community repo's dist branch; one Bun's minimumReleaseAge holds
- // back stays held, as the user's bunfig asks
- if name, version, ok := distWanted(spec); ok && err != nil && !minAge.MatchString(err.Error()) {
+ // back stays held, as the user's bunfig asks, and a bun this machine
+ // can't run at all can't add it from there either
+ var ue *BunUnstartableError
+ if name, version, ok := distWanted(spec); ok && err != nil && !minAge.MatchString(err.Error()) && !errors.As(err, &ue) {
if derr := installDist(ctx, bun, name, version); derr != nil {
return fmt.Errorf("%w (and from the community repo's dist branch: %v)", err, derr)
}
@@ -733,6 +735,9 @@ func bunAdd(ctx context.Context, bun, spec string) error {
if hint := missingLibs(string(out)); hint != "" {
return fmt.Errorf("bun add %s: %s: %w", spec, hint, err)
}
+ if ue := wontLoad(bun, err); ue != nil {
+ return fmt.Errorf("bun add %s: %w", spec, ue)
+ }
return fmt.Errorf("bun add %s: %v: %s", spec, cantStart(bun, err), lastLines(string(out), 6))
}
return nil
@@ -902,6 +907,9 @@ func reinstall(ctx context.Context, spec string) error {
if hint := missingLibs(string(out)); hint != "" {
return fmt.Errorf("bun update %s: %s: %w", name, hint, err)
}
+ if ue := wontLoad(bun, err); ue != nil {
+ return fmt.Errorf("bun update %s: %w", name, ue)
+ }
return fmt.Errorf("bun update %s: %v: %s", name, cantStart(bun, err), lastLines(string(out), 6))
}
return nil