magpie-pi 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,14 +8,14 @@ Derived from [yetone/magpie](https://github.com/yetone/magpie), with its OpenCod
8
8
 
9
9
  ## Installation
10
10
 
11
- Requires **Pi 1.6.0**, **Bun** to run community plugins, and **Node.js/npm** for plugin installation and management.
11
+ Requires **Pi 1.6.0**.
12
12
 
13
13
  ```sh
14
14
  pi install npm:magpie-pi
15
15
  pi
16
16
  ```
17
17
 
18
- The npm package includes prebuilt supervisor binaries: **no Go installation or build command is needed**. Bun is required to run configured community plugins (tested with 1.3.14), not to load the extension or open its plugin manager.
18
+ The package includes a prebuilt supervisor. The first plugin installation or startup downloads Bun once (~25–40 MB) and stores it under `bun/` in the state directory.
19
19
 
20
20
  ## Usage
21
21
 
package/README.zh-CN.md CHANGED
@@ -8,14 +8,14 @@
8
8
 
9
9
  ## 安装
10
10
 
11
- 需要 **Pi 1.6.0**、用于运行社区插件的 **Bun**,以及用于插件安装管理的 **Node.js/npm**。
11
+ 需要 **Pi 1.6.0**。
12
12
 
13
13
  ```sh
14
14
  pi install npm:magpie-pi
15
15
  pi
16
16
  ```
17
17
 
18
- npm 包包含预编译宿主程序,**无需安装 Go,也无需执行构建命令**。运行已配置的社区插件需要 Bun(测试版本为 1.3.14),加载扩展或打开插件管理器则不需要。
18
+ 包内已包含预编译宿主程序。首次安装或启动插件时会自动下载 Bun(一次性下载约 25–40 MB),保存在状态目录的 `bun/` 下。
19
19
 
20
20
  ## 使用
21
21
 
package/bin/magpie-pi CHANGED
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,143 @@
1
+ import {createHash, randomUUID} from "node:crypto";
2
+ import {chmod, lstat, mkdir, readdir, rename, rm, writeFile} from "node:fs/promises";
3
+ import path from "node:path";
4
+ import * as zlib from "node:zlib";
5
+
6
+ export const BUN_VERSION = "1.4.2";
7
+ const sumsByZip = Object.freeze({
8
+ "bun-darwin-aarch64.zip": "90987a3a16d7db556d886ac3d551e7b6d3edf0a1cf43acaed622e8676be1d12f",
9
+ "bun-darwin-x64.zip": "80520d7e17526308c9185d261679ac6d27798d3803a0e9f7ff9121ab8affb012",
10
+ "bun-linux-aarch64.zip": "54328bbc2d9c8e0c9f892c544d66c57a83b84139e34909e5ee81758f1ac8fda7",
11
+ "bun-linux-x64-baseline.zip": "c678040f14fe0440eb839d37cbd0ce4c051a32da72806ac97de6a6aab6bf728f",
12
+ "bun-linux-aarch64-musl.zip": "71760b6c8ea30623b81a4907cb815d48e2ea266f2e73e751534a44a0607950df",
13
+ "bun-linux-x64-musl-baseline.zip": "76e1db84e98f22f78de0a87e309bfbbf297732847f9720db36750646c85c8c18",
14
+ "bun-windows-x64-baseline.zip": "78c221c2376f79731ccf4e4af0b3bb46d81fefa3296c5abee09ad8a1b21e68c6",
15
+ "bun-windows-aarch64.zip": "a7a16b876a305fd1029c66dbd27007b4f6112ae896532f675878731a21e50cfd",
16
+ });
17
+ const pending = new Map();
18
+ const sizeLimit = 200 * 1024 * 1024;
19
+ const executable = process.platform === "win32" ? "bun.exe" : "bun";
20
+
21
+ export function bunTarget({platform, arch, musl}) {
22
+ if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch))
23
+ throw Error(`Bun has no build for ${platform}/${arch}`);
24
+ const cpu = arch === "arm64" ? "aarch64" : arch;
25
+ if (platform === "darwin") return "bun-darwin-" + cpu;
26
+ return "bun-" + (platform === "win32" ? "windows" : "linux") + "-" + cpu
27
+ + (platform === "linux" && musl ? "-musl" : "") + (arch === "x64" ? "-baseline" : "");
28
+ }
29
+
30
+ export function managedBunPath(state) {
31
+ return path.join(state, "bun", BUN_VERSION, executable);
32
+ }
33
+
34
+ async function regularFile(file) {
35
+ try { return (await lstat(file)).isFile(); }
36
+ catch (err) { if (err.code === "ENOENT") return false; throw err; }
37
+ }
38
+
39
+ async function download(url, fetcher) {
40
+ const res = await fetcher(url, {signal: AbortSignal.timeout(600000)});
41
+ if (!res.ok || Number(res.headers.get("content-length")) > sizeLimit) {
42
+ await res.body?.cancel();
43
+ throw Error(res.ok ? "download exceeds 200 MiB" : "HTTP " + res.status);
44
+ }
45
+ const chunks = [];
46
+ let bytes = 0;
47
+ for await (const chunk of res.body) {
48
+ bytes += chunk.length;
49
+ if (bytes > sizeLimit) throw Error("download exceeds 200 MiB");
50
+ chunks.push(chunk);
51
+ }
52
+ return Buffer.concat(chunks, bytes);
53
+ }
54
+
55
+ function zip32(value) {
56
+ if (value === 0xffffffff) throw Error("ZIP64 is unsupported");
57
+ return value;
58
+ }
59
+
60
+ function extract(zip) {
61
+ let end = zip.length - 22;
62
+ const limit = Math.max(0, zip.length - 65557);
63
+ while (end >= limit && (zip.readUInt32LE(end) !== 0x06054b50 ||
64
+ end + 22 + zip.readUInt16LE(end + 20) !== zip.length)) end--;
65
+ if (end < limit) throw Error("missing ZIP end record");
66
+ const count = zip.readUInt16LE(end + 10);
67
+ if (count === 0xffff) throw Error("ZIP64 is unsupported");
68
+ const size = zip32(zip.readUInt32LE(end + 12));
69
+ let entry = zip32(zip.readUInt32LE(end + 16));
70
+ if (entry + size !== end) throw Error("invalid ZIP directory size");
71
+ let result;
72
+ for (let i = 0; i < count; i++) {
73
+ if (entry + 46 > end || zip.readUInt32LE(entry) !== 0x02014b50) throw Error("invalid ZIP directory entry");
74
+ const compressed = zip32(zip.readUInt32LE(entry + 20));
75
+ const length = zip32(zip.readUInt32LE(entry + 24));
76
+ const local = zip32(zip.readUInt32LE(entry + 42));
77
+ const nameLength = zip.readUInt16LE(entry + 28);
78
+ const name = zip.toString("utf8", entry + 46, entry + 46 + nameLength);
79
+ const next = entry + 46 + nameLength + zip.readUInt16LE(entry + 30) + zip.readUInt16LE(entry + 32);
80
+ if (next > end) throw Error("truncated ZIP directory");
81
+ if (name.split("/").pop() === executable && !(zip.readUInt32LE(entry + 38) & 0x10)) {
82
+ if (result) throw Error("duplicate Bun executable");
83
+ if (zip.readUInt32LE(local) !== 0x04034b50) throw Error("invalid ZIP local header");
84
+ zip32(zip.readUInt32LE(local + 18));
85
+ zip32(zip.readUInt32LE(local + 22));
86
+ const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
87
+ if (start + compressed > end - size) throw Error("truncated ZIP data");
88
+ const data = zip.subarray(start, start + compressed);
89
+ switch (zip.readUInt16LE(entry + 10)) {
90
+ case 0: result = data; break;
91
+ case 8: result = zlib.inflateRawSync(data, {maxOutputLength: Math.max(1, length)}); break;
92
+ default: throw Error("unsupported ZIP compression");
93
+ }
94
+ if (result.length !== length || (zlib.crc32 && zlib.crc32(result) !== zip.readUInt32LE(entry + 16)))
95
+ throw Error("invalid Bun entry size or CRC-32");
96
+ }
97
+ entry = next;
98
+ }
99
+ if (!result || entry !== end) throw Error("invalid Bun archive");
100
+ return result;
101
+ }
102
+
103
+ async function install(exe, target, base, sums, fetcher) {
104
+ const archive = target + ".zip";
105
+ const zip = await download(`${base}/bun-v${BUN_VERSION}/${archive}`, fetcher);
106
+ if (createHash("sha256").update(zip).digest("hex") !== sums[archive]) throw Error("SHA-256 checksum mismatch");
107
+ const binary = extract(zip);
108
+ const dir = path.dirname(exe);
109
+ const root = path.dirname(dir);
110
+ for (const directory of [root, dir]) {
111
+ await mkdir(directory, {recursive: true, mode: 0o700});
112
+ if (!(await lstat(directory)).isDirectory()) throw Error("invalid Bun directory");
113
+ }
114
+ const part = exe + "." + process.pid + "." + randomUUID() + ".part";
115
+ try {
116
+ await writeFile(part, binary, {mode: 0o755, flag: "wx"});
117
+ await chmod(part, 0o755);
118
+ try { await rename(part, exe); }
119
+ catch (err) { if (!await regularFile(exe)) throw err; }
120
+ } finally { await rm(part, {force: true}); }
121
+ for (const other of await readdir(root, {withFileTypes: true}).catch(() => [])) {
122
+ if (other.isDirectory() && /^\d+\.\d+\.\d+$/.test(other.name) && other.name !== BUN_VERSION)
123
+ await rm(path.join(root, other.name), {recursive: true, force: true}).catch(() => {});
124
+ }
125
+ return exe;
126
+ }
127
+
128
+ export async function ensureBun(state, {fetcher = fetch, override = process.env.MAGPIE_PI_BUN,
129
+ base = "https://github.com/oven-sh/bun/releases/download", target, sums = sumsByZip} = {}) {
130
+ if (override) return override;
131
+ const exe = managedBunPath(state);
132
+ try {
133
+ if (await regularFile(exe)) return exe;
134
+ target ??= bunTarget({platform: process.platform, arch: process.arch,
135
+ musl: process.platform === "linux" && !process.report?.getReport?.()?.header?.glibcVersionRuntime});
136
+ if (!pending.has(exe)) {
137
+ pending.set(exe, install(exe, target, base, sums, fetcher).finally(() => pending.delete(exe)));
138
+ }
139
+ return await pending.get(exe);
140
+ } catch (err) {
141
+ throw Error(`magpie-pi: could not get Bun ${BUN_VERSION} (${target ?? process.platform + "/" + process.arch}): ${err.message ?? err}. Set MAGPIE_PI_BUN to a Bun executable to use one you have.`);
142
+ }
143
+ }
@@ -34,7 +34,7 @@ export interface MagpieSearchResult {
34
34
  }
35
35
 
36
36
  export class PluginManager {
37
- constructor(state: string, options?: { fetcher?: typeof fetch; runner?: unknown });
37
+ constructor(state: string, options?: { bun?: string; fetcher?: typeof fetch; runner?: unknown });
38
38
  cleanup(): Promise<void>;
39
39
  search(query: string): Promise<MagpieSearchResult[]>;
40
40
  list(): Promise<MagpiePluginEntry[]>;
@@ -20,7 +20,7 @@ export {defaultState} from "./providers.mjs";
20
20
  * Pi provider definitions. Never throws for configuration or plugin problems: they are returned in
21
21
  * `errors` (with no providers) so the embedder keeps working; `close()` is always safe to call.
22
22
  *
23
- * @param {{state?: string, bun?: string}} [options]
23
+ * @param {{state?: string, bun?: string}} [options] The bun option overrides the downloaded Bun executable.
24
24
  * @returns {Promise<{state: string, configPath: string, providers: any[], errors: string[], close: () => Promise<void>}>}
25
25
  */
26
26
  export async function startMagpie(options={}){
@@ -35,7 +35,7 @@ export async function startMagpie(options={}){
35
35
  const {config,configPath}=loaded;
36
36
  if(config.plugins.length===0)return {state,configPath,providers:[],errors:[],close:none};
37
37
  let bridge;
38
- try {bridge=startBridge(state,options.bun);}
38
+ try {bridge=await startBridge(state,options.bun);}
39
39
  catch(e){return {state,configPath,providers:[],errors:[String(e)],close:none};}
40
40
  const close=()=>bridge.close().then(()=>undefined);
41
41
  try {
@@ -17,8 +17,8 @@ export default async function(pi:ExtensionAPI){
17
17
  });
18
18
  return;
19
19
  }
20
- let bridge:ReturnType<typeof startBridge>;
21
- try {bridge=startBridge(state);}catch(e){
20
+ let bridge:Awaited<ReturnType<typeof startBridge>>;
21
+ try {bridge=await startBridge(state);}catch(e){
22
22
  pi.on("session_start",async(_event,ctx)=>{if(ctx.hasUI)ctx.ui.notify(String(e),"error")});
23
23
  return;
24
24
  }
@@ -2,6 +2,7 @@ import {readFile,writeFile,mkdir,rename,rm,mkdtemp,lstat,realpath} from "node:fs
2
2
  import path from "node:path";
3
3
  import {execFile} from "node:child_process";
4
4
  import {promisify} from "node:util";
5
+ import {ensureBun} from "./bun.mjs";
5
6
  const scope="@magpie-community/opencode-";
6
7
  const withdrawn=scope+"antigravity-auth";
7
8
  export function parse(input){
@@ -12,8 +13,8 @@ export function parse(input){
12
13
  return {name:m[1],version:m[2]};
13
14
  }
14
15
  export class PluginManager{
15
- constructor(state,{fetcher=fetch,runner=promisify(execFile)}={}){
16
- this.state=state;this.file=path.join(state,"config.json");this.fetcher=fetcher;this.runner=runner;
16
+ constructor(state,{bun,fetcher=fetch,runner=promisify(execFile)}={}){
17
+ this.bun=bun;this.state=state;this.file=path.join(state,"config.json");this.fetcher=fetcher;this.runner=runner;
17
18
  }
18
19
  // Queue entries are identifiers, never filesystem paths. Only our marked stages qualify.
19
20
  stageEntry(p){
@@ -30,7 +31,9 @@ export class PluginManager{
30
31
  const lock=path.join(this.state,"plugins.lock");
31
32
  try{await mkdir(lock,{mode:0o700})}catch(e){if(e.code==="ENOENT"||e.code==="EEXIST")return;throw e}
32
33
  try{
33
- const before=await readFile(this.file,"utf8"),c=JSON.parse(before);
34
+ let before;
35
+ try{before=await readFile(this.file,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}
36
+ const c=JSON.parse(before);
34
37
  if(!Array.isArray(c.pendingPluginDeletes)||!Array.isArray(c.plugins))return;
35
38
  const root=path.join(path.resolve(this.state),"managed-plugins");
36
39
  const remaining=[];
@@ -94,9 +97,10 @@ export class PluginManager{
94
97
  const root=path.join(this.state,"managed-plugins");
95
98
  await mkdir(root,{recursive:true,mode:0o700});
96
99
  if((await lstat(root)).isSymbolicLink()||await realpath(root)!==path.join(await realpath(this.state),"managed-plugins"))throw Error("managed-plugins must not be a symlink");
100
+ const bun=this.bun ?? await ensureBun(this.state,{fetcher:this.fetcher});
97
101
  stage=await mkdtemp(path.join(root,"pkg-"));
98
102
  await writeFile(path.join(stage,"package.json"),'{"private":true}',{mode:0o600});
99
- await this.runner("npm",["install","--ignore-scripts","--save-exact","--no-audit","--no-fund","--registry=https://registry.npmjs.org",name+"@"+resolved],{cwd:stage,timeout:120000,maxBuffer:1024*1024});
103
+ await this.runner(bun,["add","--exact","--ignore-scripts","--linker=hoisted","--no-progress","--registry=https://registry.npmjs.org",name+"@"+resolved],{cwd:stage,timeout:120000,maxBuffer:1024*1024,windowsHide:true});
100
104
  const target=path.join(stage,"node_modules",name);
101
105
  const installed=JSON.parse(await readFile(path.join(target,"package.json"),"utf8"));
102
106
  if(installed.name!==name||installed.version!==resolved)throw Error("Installed package metadata does not match");
@@ -116,7 +120,7 @@ export class PluginManager{
116
120
  const help="/magpie-plugins search QUERY | install PACKAGE[@EXACT_VERSION] | list | remove PACKAGE. Aliases: cursor/workbuddy. Searches community auth packages only; compatibility is not guaranteed.";
117
121
  async function change(manager,ctx,action,input){
118
122
  return manager.mutate(action,input,async()=>{
119
- const ok=await ctx.ui.confirm(action+" "+input,"Third-party plugins run with your user permissions. Disabling npm install scripts does not sandbox runtime code. Removal preserves credentials; old managed directories are deleted on next startup (including versions replaced by updates). Continue?");
123
+ const ok=await ctx.ui.confirm(action+" "+input,"Third-party plugins run with your user permissions. Disabling install scripts does not sandbox runtime code. Removal preserves credentials; old managed directories are deleted on next startup (including versions replaced by updates). Continue?");
120
124
  if(ok)ctx.ui.notify((action==="install"?"Installing":"Removing")+"…","info");
121
125
  return ok;
122
126
  });
@@ -170,7 +174,7 @@ export function registerPlugins(pi,state,dependencies={}){
170
174
  else if(action==="list")result=JSON.stringify(await manager.list(),null,2);
171
175
  else if(["install","remove"].includes(action)){
172
176
  if(!ctx.hasUI)throw Error("Changes refused: explicit confirmation in an interactive UI is required");
173
- result=await manager.mutate(action,input,name=>ctx.ui.confirm(action+" "+name,"Third-party plugins run with your user permissions. Disabling npm install scripts does not sandbox runtime code. Removal preserves credentials; old managed directories are deleted on next startup (including versions replaced by updates). Continue?"));
177
+ result=await manager.mutate(action,input,name=>ctx.ui.confirm(action+" "+name,"Third-party plugins run with your user permissions. Disabling install scripts does not sandbox runtime code. Removal preserves credentials; old managed directories are deleted on next startup (including versions replaced by updates). Continue?"));
174
178
  }else result="/magpie-plugins search QUERY | install PACKAGE[@EXACT_VERSION] | list | remove PACKAGE. Aliases: cursor/workbuddy. Searches community auth packages only; compatibility is not guaranteed.";
175
179
  ctx.ui.notify(result,"info");
176
180
  }catch(e){ctx.ui.notify(String(e),"error")}
@@ -7,6 +7,7 @@ import os from "node:os";
7
7
  // The Pi extension loader exposes the compat entry, not the per-API subpaths.
8
8
  import {openAICompletionsApi,anthropicMessagesApi} from "@earendil-works/pi-ai/compat";
9
9
  import {Bridge} from "./bridge.mjs";
10
+ import {ensureBun} from "./bun.mjs";
10
11
  import {supervisorPath} from "./platform.mjs";
11
12
 
12
13
  export const packageRoot=fileURLToPath(new URL("..",import.meta.url));
@@ -33,7 +34,8 @@ export async function loadConfig(state){
33
34
  }
34
35
 
35
36
  /** Start the plugin host for a non-empty config. Throws if the supervisor is unavailable. */
36
- export function startBridge(state,bun=process.env.MAGPIE_PI_BUN){
37
+ export async function startBridge(state,bun=undefined){
38
+ bun ??= await ensureBun(state);
37
39
  return new Bridge(supervisorPath(packageRoot),path.join(packageRoot,"vendor","host.js"),state,bun);
38
40
  }
39
41
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie-pi",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Magpie community plugin integration for Pi",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [