magpie-pi 0.0.0-stage → 0.1.1

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
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # magpie-pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](README.zh-CN.md)
4
+
5
+ Bring magpie's community plugin integrations to Pi through a lightweight extension and a local host. Uses Pi's native SDK over stdio, without an HTTP gateway or Pi core changes.
6
+
7
+ Derived from [yetone/magpie](https://github.com/yetone/magpie), with its OpenCode host extracted without modifications. Thanks to the original author and maintainers.
8
+
9
+ ## Installation
10
+
11
+ Requires **Pi 1.6.0**, **Bun** to run community plugins, and **Node.js/npm** for plugin installation and management.
12
+
13
+ ```sh
14
+ pi install npm:magpie-pi
15
+ pi
16
+ ```
17
+
18
+ The npm package includes prebuilt supervisor binaries: **no Go installation or build command is needed**. Bun is still required at runtime (locally tested with 1.3.14).
19
+
20
+ ## Usage
21
+
22
+ 1. Enter `/magpie-plugins` in Pi.
23
+ 2. Choose **Search and install**, search for `cursor` or `workbuddy`, select a package and version, then confirm.
24
+ 3. Exit and restart Pi. If multiple instances share the state directory, exit all of them before restarting.
25
+ 4. Enter `/login` and select the service.
26
+ 5. Enter `/model` to select a model and start chatting.
27
+
28
+ Use ↑/↓ to navigate, Enter to confirm, and Esc to cancel. The menu also supports viewing installed plugins, installing by package name, and uninstalling. Pi's built-in providers remain available.
29
+
30
+ Third-party plugins run with your user privileges; install only plugins you trust. Real Cursor/WorkBuddy accounts remain unverified.
31
+
32
+ ## State and credentials
33
+
34
+ Configuration is created automatically in `~/.local/share/magpie-pi`; manual JSON editing is not needed for menu-managed plugins.
35
+
36
+ - `MAGPIE_PI_STATE`: override the state directory with an absolute path.
37
+ - `MAGPIE_PI_BUN`: override the Bun executable.
38
+ - `/logout`: disables the provider without deleting plugin credentials; use `/login` to enable it again.
39
+
40
+ ## License
41
+
42
+ The project's own license is currently `UNLICENSED`. The extracted host retains its upstream MIT license in [vendor/LICENSE](vendor/LICENSE).
@@ -0,0 +1,42 @@
1
+ # magpie-pi
2
+
3
+ [English](README.md) | 简体中文
4
+
5
+ 通过轻量 Pi 扩展和本地宿主,将 magpie 的社区插件集成带入 Pi。使用 stdio 对接 Pi 原生 SDK,无需 HTTP 网关或修改 Pi 核心。
6
+
7
+ 本项目源自 [yetone/magpie](https://github.com/yetone/magpie),原样抽取其 OpenCode 宿主。感谢原作者和维护者的付出。
8
+
9
+ ## 安装
10
+
11
+ 需要 **Pi 1.6.0**、用于运行社区插件的 **Bun**,以及用于插件安装管理的 **Node.js/npm**。
12
+
13
+ ```sh
14
+ pi install npm:magpie-pi
15
+ pi
16
+ ```
17
+
18
+ npm 包包含预编译宿主程序,**无需安装 Go,也无需执行构建命令**。Bun 是运行依赖,仍需安装(本机测试版本为 1.3.14)。
19
+
20
+ ## 使用
21
+
22
+ 1. 在 Pi 输入 `/magpie-plugins`。
23
+ 2. 选择 **Search and install**,搜索 `cursor` 或 `workbuddy`,选择包和版本后确认安装。
24
+ 3. 退出并重新启动 Pi。若多个实例共享状态目录,先全部退出再启动。
25
+ 4. 输入 `/login`,选择对应服务并登录。
26
+ 5. 输入 `/model`,选择模型后开始使用。
27
+
28
+ 菜单用 ↑/↓ 选择、Enter 确认、Esc 取消,也支持查看已安装插件、按包名安装和卸载。Pi 原有服务不受影响。
29
+
30
+ 第三方插件拥有当前用户权限,请仅安装可信插件。真实 Cursor/WorkBuddy 账号尚未验证。
31
+
32
+ ## 配置与凭据
33
+
34
+ 配置自动保存在 `~/.local/share/magpie-pi`,使用菜单管理插件无需手动编辑 JSON。
35
+
36
+ - `MAGPIE_PI_STATE`:指定其他状态目录,需使用绝对路径。
37
+ - `MAGPIE_PI_BUN`:指定 Bun 可执行文件。
38
+ - `/logout`:停用服务但不删除插件凭据;再次使用时执行 `/login`。
39
+
40
+ ## 许可证
41
+
42
+ 项目自身暂标为 `UNLICENSED`。抽取的宿主保留 [vendor/LICENSE](vendor/LICENSE) 中的上游 MIT 许可证。
package/bin/magpie-pi ADDED
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,64 @@
1
+ import {spawn} from "node:child_process";
2
+ import {createInterface} from "node:readline";
3
+ export class Bridge {
4
+ constructor(binary,host,state,bun="bun") {
5
+ this.next=0; this.pending=new Map();
6
+ this.child=spawn(binary,["--host",host,"--state",state,"--bun",bun],{stdio:["pipe","pipe","inherit"]});
7
+ this.closed=new Promise(resolve=>this.child.once("close",resolve));
8
+ this.child.on("error",e=>this.fail(e));
9
+ this.child.stdin.on("error",e=>this.fail(e));
10
+ this.child.on("exit",()=>this.fail(new Error("plugin supervisor exited")));
11
+ createInterface({input:this.child.stdout}).on("line",line=>{
12
+ try {const m=JSON.parse(line); this.pending.get(m.id)?.(m);} catch(e){this.fail(e);}
13
+ });
14
+ }
15
+ fail(e){this.terminalError ||= e;for(const f of this.pending.values())f({error:{message:e.message}});this.pending.clear();}
16
+ send(m){if(this.terminalError)return;try{this.child.stdin.write(JSON.stringify(m)+"\n");}catch(e){this.fail(e)}}
17
+ call(method,params={},signal){
18
+ if(this.terminalError)return Promise.reject(this.terminalError);
19
+ return new Promise((resolve,reject)=>{
20
+ const id=++this.next;
21
+ const finish=(e,value)=>{this.pending.delete(id);signal?.removeEventListener("abort",abort);e?reject(e):resolve(value)};
22
+ const abort=()=>{this.send({method:"abort",params:{id}});finish(new Error("aborted"))};
23
+ if(signal?.aborted)return reject(new Error("aborted"));
24
+ this.pending.set(id,m=>m.error?finish(new Error(m.error.message)):finish(null,m.result));
25
+ signal?.addEventListener("abort",abort,{once:true});
26
+ this.send({id,method,params});
27
+ });
28
+ }
29
+ fetch(provider,account,npm,model){
30
+ return async (url,init={})=>{
31
+ if(this.terminalError)throw this.terminalError;
32
+ const request=new Request(url,init);
33
+ const body=Buffer.from(await request.arrayBuffer()).toString("base64");
34
+ for(const key of ["authorization","x-api-key"]) if(request.headers.get(key)?.includes("plugin-owned"))request.headers.delete(key);
35
+ if(this.terminalError)throw this.terminalError;
36
+ return new Promise((resolve,reject)=>{
37
+ const id=++this.next; let controller,ended=false,owed=0;
38
+ const abort=()=>{this.send({method:"abort",params:{id}});finish(new Error("aborted"))};
39
+ const finish=(e,cancelled=false)=>{
40
+ if(ended)return;ended=true;this.pending.delete(id);request.signal.removeEventListener("abort",abort);
41
+ if(!cancelled){if(e)controller?.error(e);else controller?.close();}
42
+ if(e)reject(e);
43
+ };
44
+ if(request.signal.aborted)return reject(new Error("aborted"));
45
+ request.signal.addEventListener("abort",abort,{once:true});
46
+ this.pending.set(id,m=>{
47
+ if(m.error)return finish(new Error(m.error.message));
48
+ if(m.event==="head"){
49
+ const stream=new ReadableStream({start(c){controller=c},pull:()=>{
50
+ if(owed){this.send({method:"credit",params:{id,n:owed}});owed=0}
51
+ },cancel:()=>{this.send({method:"abort",params:{id}});finish(undefined,true)}},{highWaterMark:0});
52
+ resolve(new Response(stream,{status:m.status,headers:m.headers}));
53
+ }else if(m.event==="chunk"){
54
+ const bytes=Buffer.from(m.data,"base64");
55
+ owed+=bytes.length+2048;
56
+ controller.enqueue(bytes);
57
+ }else if("result" in m)finish();
58
+ });
59
+ this.send({id,method:"fetch",params:{provider,account,npm,model,url:request.url,method:request.method,headers:Object.fromEntries(request.headers),body,window:65536}});
60
+ });
61
+ };
62
+ }
63
+ close(){this.fail(new Error("plugin bridge closed"));this.child.stdin.end();return this.closed;}
64
+ }
@@ -0,0 +1,103 @@
1
+ import {readFile,mkdir,writeFile} from "node:fs/promises";
2
+ import {fileURLToPath} from "node:url";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import type {ExtensionAPI} from "@earendil-works/pi-coding-agent";
6
+ import * as completions from "@earendil-works/pi-ai/api/openai-completions";
7
+ import * as anthropic from "@earendil-works/pi-ai/api/anthropic-messages";
8
+ import {Bridge} from "./bridge.mjs";
9
+ import {supervisorPath} from "./platform.mjs";
10
+ import {registerPlugins,PluginManager} from "./plugins.mjs";
11
+
12
+ export default async function(pi:ExtensionAPI){
13
+ const root=fileURLToPath(new URL("..",import.meta.url));
14
+ const state=process.env.MAGPIE_PI_STATE || path.join(os.homedir(),".local","share","magpie-pi");
15
+ registerPlugins(pi,state);
16
+ await new PluginManager(state).cleanup();
17
+ const configPath=path.join(state,"config.json");
18
+ let source:string;
19
+ try {source=await readFile(configPath,"utf8");}
20
+ catch(error){
21
+ if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;
22
+ await mkdir(state,{recursive:true,mode:0o700});
23
+ try {await writeFile(configPath,JSON.stringify({plugins:[],accounts:{},opencode:{}},null,2)+"\n",{flag:"wx",mode:0o600});}
24
+ catch(error){if((error as NodeJS.ErrnoException).code!=="EEXIST")throw error;}
25
+ source=await readFile(configPath,"utf8");
26
+ }
27
+ const config=JSON.parse(source);
28
+ if(!config||!Array.isArray(config.plugins))throw new Error(`magpie-pi: ${configPath} must contain a plugins array`);
29
+ if(config.plugins.length===0){
30
+ pi.on("session_start",async(_event,ctx)=>{
31
+ if(ctx.hasUI)ctx.ui.notify(`No magpie-pi providers configured. Use /magpie-plugins to search and install plugins, or edit ${configPath}; restart Pi after configuration. See ${path.join(root,"README.md")}`,"info");
32
+ });
33
+ return;
34
+ }
35
+ let executable:string;
36
+ try {executable=supervisorPath(root);}catch(e){
37
+ pi.on("session_start",async(_event,ctx)=>{if(ctx.hasUI)ctx.ui.notify(String(e),"error")});
38
+ return;
39
+ }
40
+ const bridge=new Bridge(executable,path.join(root,"vendor","host.js"),state,process.env.MAGPIE_PI_BUN);
41
+ pi.on("session_shutdown",async()=>{await bridge.close();});
42
+ try {
43
+ const initialized=await bridge.call("init",{plugins:config.plugins,config:config.opencode || {},authPath:path.join(state,"plugin-auth.json"),directory:state});
44
+ for(const p of initialized.plugins)if(p.error)throw new Error(p.error);
45
+ const rows=await bridge.call("providers");
46
+ for(const initial of rows){
47
+ let row=initial;
48
+ const id="magpie-"+row.id;
49
+ const models=()=>row.models.filter((m:any)=>["@ai-sdk/openai-compatible","@ai-sdk/anthropic"].includes(m.npm)).map((m:any)=>({
50
+ type:"chat",id:m.id,name:m.name||m.id,provider:id,
51
+ api:m.npm==="@ai-sdk/anthropic"?"anthropic-messages":"openai-completions",
52
+ baseUrl:m.url||row.api,reasoning:m.reasoning,input:m.image?["text","image"]:["text"],
53
+ cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:m.context||128000,maxTokens:m.output||8192
54
+ }));
55
+ const stream=(simple:boolean)=>(model:any,context:any,options:any={})=>{
56
+ const m=row.models.find((m:any)=>m.id===model.id);
57
+ const api=model.api==="anthropic-messages"?anthropic:completions;
58
+ return api[simple?"streamSimple":"stream"]({...model,id:m.apiId||model.id},context,{...options,apiKey:"plugin-owned",fetch:bridge.fetch(row.id,config.accounts?.[row.id],m.npm,m.id)});
59
+ };
60
+ pi.registerProvider({
61
+ id,name:row.name||row.id,
62
+ auth:{apiKey:{name:"Plugin-managed account",
63
+ resolve:async({credential})=>credential?.key==="plugin-owned"&&row.signedIn?{auth:{apiKey:"plugin-owned"}}:undefined,
64
+ login:async interaction=>{
65
+ const method=Number(await interaction.prompt({type:"select",message:"Sign-in method",options:row.methods.map((m:any,i:number)=>({id:String(i),label:m.label}))}));
66
+ const m=row.methods[method];let result;
67
+ const inputs:Record<string,string>={};
68
+ while(true){
69
+ const {prompt}=await bridge.call("prompt",{provider:row.id,method,inputs},interaction.signal);
70
+ if(!prompt)break;
71
+ const value=await interaction.prompt(prompt.type==="select"?{
72
+ type:"select",message:prompt.message,options:prompt.options.map((o:any)=>({id:o.value,label:o.label,description:o.hint}))
73
+ }:{type:"secret",message:prompt.message,placeholder:prompt.placeholder});
74
+ const {error}=await bridge.call("validate",{provider:row.id,method,key:prompt.key,value},interaction.signal);
75
+ if(error){interaction.notify({type:"info",message:error});continue;}
76
+ inputs[prompt.key]=value;
77
+ }
78
+ if(m.type==="api"){
79
+ const key=m.keyless||m.keyAsked?"":await interaction.prompt({type:"secret",message:"API key"});
80
+ result=await bridge.call("apiKey",{provider:row.id,method,key,inputs},interaction.signal);
81
+ }else{
82
+ const a=await bridge.call("authorize",{provider:row.id,method,inputs},interaction.signal);
83
+ if(!a.ok)throw new Error(a.error||"Sign-in failed");
84
+ if(a.url)interaction.notify({type:"auth_url",url:a.url,instructions:a.instructions});
85
+ const code=a.method==="code"?await interaction.prompt({type:"manual_code",message:a.instructions||"Authorization code"}):undefined;
86
+ result=await bridge.call("callback",{session:a.session,code},interaction.signal);
87
+ }
88
+ if(!result.ok)throw new Error(result.error||"Sign-in failed");
89
+ row=(await bridge.call("providers")).find((r:any)=>r.id===row.id);
90
+ return {type:"api_key",key:"plugin-owned"};
91
+ }}},
92
+ getModels:models,
93
+ refreshModels:async context=>{
94
+ if(!context.allowNetwork)return;
95
+ const next=(await bridge.call("providers",{},context.signal)).find((r:any)=>r.id===row.id);
96
+ if(!next||next.fellBack)throw new Error(next?.listError||"Model discovery failed");
97
+ await context.publish({update:()=>{row=next}});
98
+ },
99
+ stream:stream(false),streamSimple:stream(true)
100
+ });
101
+ }
102
+ }catch(e){await bridge.close();pi.on("session_start",async(_event,ctx)=>{if(ctx.hasUI)ctx.ui.notify(String(e)+"; use /magpie-plugins to fix the configuration","error")});}
103
+ }
@@ -0,0 +1,10 @@
1
+ import path from "node:path";
2
+
3
+ export function supervisorPath(root, platform = process.platform, arch = process.arch) {
4
+ const os = {linux:"linux", darwin:"darwin", win32:"windows"}[platform];
5
+ const cpu = {x64:"amd64", arm64:"arm64"}[arch];
6
+ if (!os || !cpu || !["linux", "darwin", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) {
7
+ throw new Error(`magpie-pi: unsupported platform ${platform}/${arch}; supported: Linux, macOS, Windows on x64 or arm64`);
8
+ }
9
+ return path.join(root, "bin", `magpie-pi-${os}-${cpu}${platform === "win32" ? ".exe" : ""}`);
10
+ }
@@ -0,0 +1,178 @@
1
+ import {readFile,writeFile,mkdir,rename,rm,mkdtemp,lstat,realpath} from "node:fs/promises";
2
+ import path from "node:path";
3
+ import {execFile} from "node:child_process";
4
+ import {promisify} from "node:util";
5
+ const scope="@magpie-community/opencode-";
6
+ const withdrawn=scope+"antigravity-auth";
7
+ export function parse(input){
8
+ const alias=/^(cursor|workbuddy)(@.*)?$/.exec(input);
9
+ const value=alias?scope+alias[1]+"-auth"+(alias[2]||""):input;
10
+ const m=/^(@magpie-community\/opencode-[a-z0-9-]+-auth)(?:@([0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?))?$/.exec(value);
11
+ if(!m)throw Error("Only community auth package names and exact versions are accepted");
12
+ return {name:m[1],version:m[2]};
13
+ }
14
+ 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;
17
+ }
18
+ // Queue entries are identifiers, never filesystem paths. Only our marked stages qualify.
19
+ stageEntry(p){
20
+ if(!p.magpieManaged)return;
21
+ const {name,version}=parse(p.spec);
22
+ if(!version)return;
23
+ const root=path.join(path.resolve(this.state),"managed-plugins");
24
+ const relative=path.relative(root,p.target||"");
25
+ const id=relative.split(path.sep)[0];
26
+ if(!/^pkg-[a-zA-Z0-9]+$/.test(id)||p.target!==path.join(root,id,"node_modules",name))return;
27
+ return {id,spec:p.spec};
28
+ }
29
+ async cleanup(){
30
+ const lock=path.join(this.state,"plugins.lock");
31
+ try{await mkdir(lock,{mode:0o700})}catch(e){if(e.code==="ENOENT"||e.code==="EEXIST")return;throw e}
32
+ try{
33
+ const before=await readFile(this.file,"utf8"),c=JSON.parse(before);
34
+ if(!Array.isArray(c.pendingPluginDeletes)||!Array.isArray(c.plugins))return;
35
+ const root=path.join(path.resolve(this.state),"managed-plugins");
36
+ const remaining=[];
37
+ for(const entry of c.pendingPluginDeletes){
38
+ try{
39
+ if(!entry||!/^pkg-[a-zA-Z0-9]+$/.test(entry.id))throw Error("invalid stage");
40
+ const {name,version}=parse(entry.spec);
41
+ if(!version)throw Error("missing version");
42
+ const dir=path.join(root,entry.id);
43
+ if(c.plugins.some(p=>typeof p.target==="string"&&(path.resolve(p.target)===dir||path.resolve(p.target).startsWith(dir+path.sep))))throw Error("still referenced");
44
+ if((await lstat(root)).isSymbolicLink()||await realpath(root)!==path.join(await realpath(this.state),"managed-plugins"))throw Error("unsafe root");
45
+ let stat;
46
+ try{stat=await lstat(dir)}catch(e){if(e.code==="ENOENT")continue;throw e}
47
+ if(!stat.isDirectory()||stat.isSymbolicLink()||await realpath(dir)!==dir)throw Error("unsafe stage");
48
+ const marker=path.join(dir,".magpie-owned.json");
49
+ if(!(await lstat(marker)).isFile()||(await lstat(marker)).isSymbolicLink())throw Error("unsafe marker");
50
+ if(await readFile(marker,"utf8")!==JSON.stringify({id:entry.id,spec:name+"@"+version}))throw Error("not owned");
51
+ // rm does not follow nested symlinks.
52
+ await rm(dir,{recursive:true,force:true});
53
+ }catch{remaining.push(entry)}
54
+ }
55
+ if(await readFile(this.file,"utf8")!==before)return;
56
+ c.pendingPluginDeletes=remaining;
57
+ const tmp=path.join(lock,"config.json");
58
+ await writeFile(tmp,JSON.stringify(c,null,2)+"\n",{mode:0o600,flag:"wx"});
59
+ await rename(tmp,this.file);
60
+ }finally{await rm(lock,{recursive:true,force:true})}
61
+ }
62
+ async json(url){
63
+ const r=await this.fetcher(url,{signal:AbortSignal.timeout(15000)});
64
+ if(!r.ok)throw Error("Registry HTTP "+r.status);
65
+ return r.json();
66
+ }
67
+ async config(){const c=JSON.parse(await readFile(this.file,"utf8"));if(!Array.isArray(c.plugins))throw Error("plugins must be an array");return c;}
68
+ async search(query){
69
+ const data=await this.json("https://registry.npmjs.org/-/v1/search?size=100&text="+encodeURIComponent("@magpie-community/opencode- "+query));
70
+ return (data.objects||[]).map(x=>x.package).filter(p=>{try{return parse(p.name).name!==withdrawn}catch{return false}}).map(p=>({name:p.name,version:p.version,description:p.description}));
71
+ }
72
+ async list(){return (await this.config()).plugins;}
73
+ async mutate(action,input,confirm){
74
+ if(!["install","remove"].includes(action))throw Error("Unknown operation");
75
+ const {name,version}=parse(input);
76
+ if(action==="install"&&name===withdrawn)throw Error("The Antigravity plugin has been withdrawn and cannot be installed; agy-cli is unaffected");
77
+ if(!await confirm(name))return "Cancelled";
78
+ const lock=path.join(this.state,"plugins.lock");
79
+ try{await mkdir(lock,{mode:0o700})}catch(e){if(e.code==="EEXIST")throw Error("Another plugin operation is running. If that process has exited, manually remove plugins.lock");throw e}
80
+ let stage;
81
+ try{
82
+ const before=await readFile(this.file,"utf8"),c=JSON.parse(before);
83
+ if(!Array.isArray(c.plugins))throw Error("plugins must be an array");
84
+ const matches=c.plugins.filter(p=>p.spec===name||p.spec?.startsWith(name+"@"));
85
+ const managedRoot=path.join(path.resolve(this.state),"managed-plugins");
86
+ if(matches.some(p=>!p.magpieManaged||typeof p.target!=="string"||!path.resolve(p.target).startsWith(managedRoot+path.sep)))throw Error("Refusing to overwrite manual configuration");
87
+ if(action==="remove"){
88
+ c.plugins=c.plugins.filter(p=>!matches.includes(p));
89
+ }else{
90
+ const metadata=await this.json("https://registry.npmjs.org/"+encodeURIComponent(name));
91
+ const resolved=version||metadata["dist-tags"]?.latest;
92
+ parse(name+"@"+resolved);
93
+ if(!metadata.versions?.[resolved])throw Error("Version not found");
94
+ const root=path.join(this.state,"managed-plugins");
95
+ await mkdir(root,{recursive:true,mode:0o700});
96
+ 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");
97
+ stage=await mkdtemp(path.join(root,"pkg-"));
98
+ 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});
100
+ const target=path.join(stage,"node_modules",name);
101
+ const installed=JSON.parse(await readFile(path.join(target,"package.json"),"utf8"));
102
+ if(installed.name!==name||installed.version!==resolved)throw Error("Installed package metadata does not match");
103
+ c.plugins=c.plugins.filter(p=>!matches.includes(p));
104
+ await writeFile(path.join(stage,".magpie-owned.json"),JSON.stringify({id:path.basename(stage),spec:name+"@"+resolved}),{mode:0o600,flag:"wx"});
105
+ c.plugins.push({spec:name+"@"+resolved,target,magpieManaged:true});
106
+ }
107
+ c.pendingPluginDeletes=[...(Array.isArray(c.pendingPluginDeletes)?c.pendingPluginDeletes:[]),...matches.map(p=>this.stageEntry(p)).filter(Boolean)];
108
+ if(await readFile(this.file,"utf8")!==before)throw Error("Configuration changed during the operation; please retry");
109
+ const tmp=path.join(lock,"config.json");
110
+ await writeFile(tmp,JSON.stringify(c,null,2)+"\n",{mode:0o600,flag:"wx"});
111
+ await rename(tmp,this.file);stage=undefined;
112
+ return "Configuration updated. Restart Pi to apply changes. Installation does not guarantee compatibility. Credentials are preserved; old managed installations will be cleaned up before the host starts next time. Currently running plugins are unaffected.";
113
+ }finally{if(stage)await rm(stage,{recursive:true,force:true});await rm(lock,{recursive:true,force:true})}
114
+ }
115
+ }
116
+ 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
+ async function change(manager,ctx,action,input){
118
+ 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?");
120
+ if(ok)ctx.ui.notify((action==="install"?"Installing":"Removing")+"…","info");
121
+ return ok;
122
+ });
123
+ }
124
+ // One selection path per invocation: Escape always exits, never reopens a prompt.
125
+ export async function pluginMenu(manager,ctx){
126
+ const choice=await ctx.ui.select("Magpie Community Plugins",["Search and install","Installed plugins / details","Uninstall","Install by package name","Help"]);
127
+ if(!choice)return;
128
+ if(choice==="Help"){ctx.ui.notify(help,"info");return}
129
+ if(choice==="Install by package name"){
130
+ const input=await ctx.ui.input("Package name[@EXACT_VERSION]","cursor / workbuddy");
131
+ if(input?.trim())ctx.ui.notify(await change(manager,ctx,"install",input.trim()),"info");
132
+ return;
133
+ }
134
+ if(choice==="Search and install"){
135
+ const query=await ctx.ui.input("Search community plugins","cursor / workbuddy");
136
+ if(!query?.trim())return;
137
+ ctx.ui.notify("Searching npm…","info");
138
+ const results=await manager.search(query.trim());
139
+ if(!results.length){ctx.ui.notify("No results found","info");return}
140
+ const labels=results.map((p,i)=>`${i+1}. ${p.name}@${p.version} — ${p.description||"No description"}`);
141
+ const selected=await ctx.ui.select("Select a plugin to install (compatibility not guaranteed)",labels);
142
+ const p=results[labels.indexOf(selected)];
143
+ if(!p)return;
144
+ const spec=p.name+"@"+p.version;
145
+ if(!parse(spec).version)throw Error("Search result is missing an exact version");
146
+ ctx.ui.notify(await change(manager,ctx,"install",spec),"info");
147
+ return;
148
+ }
149
+ const all=await manager.list();
150
+ const owned=p=>!!manager.stageEntry(p);
151
+ const entries=choice==="Uninstall"?all.filter(owned):all;
152
+ if(!entries.length){ctx.ui.notify((choice==="Uninstall"?"No managed plugins to uninstall":"No installed plugins"),"info");return}
153
+ const labels=entries.map((p,i)=>`${i+1}. ${p.spec||p.target} [${owned(p)?"Managed":"Manual / read-only"}]`);
154
+ const selected=await ctx.ui.select(choice,labels);
155
+ const p=entries[labels.indexOf(selected)];
156
+ if(!p)return;
157
+ ctx.ui.notify(`${p.spec||"Manual plugin"}\nPath: ${p.target}\n${owned(p)?"Managed; removal preserves credentials and cleans up files on next startup":"Read-only: cannot be modified through this menu"}`,"info");
158
+ if(!owned(p))return;
159
+ if(choice!=="Uninstall"&&await ctx.ui.select("Plugin actions",["Uninstall","Close"])!=="Uninstall")return;
160
+ ctx.ui.notify(await change(manager,ctx,"remove",p.spec),"info");
161
+ }
162
+ export function registerPlugins(pi,state,dependencies={}){
163
+ const manager=new PluginManager(state,dependencies);
164
+ pi.registerCommand("magpie-plugins",{description:"Community plugin menu and help/search/install/list/remove",handler:async(args,ctx)=>{
165
+ try{
166
+ if(!args.trim()&&ctx.hasUI)return await pluginMenu(manager,ctx);
167
+ const [action="help",...rest]=args.trim().split(/\s+/),input=rest.join(" ");
168
+ let result;
169
+ if(action==="search")result=JSON.stringify(await manager.search(input),null,2);
170
+ else if(action==="list")result=JSON.stringify(await manager.list(),null,2);
171
+ else if(["install","remove"].includes(action)){
172
+ 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?"));
174
+ }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
+ ctx.ui.notify(result,"info");
176
+ }catch(e){ctx.ui.notify(String(e),"error")}
177
+ }});
178
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "repository": "https://github.com/yetone/magpie",
3
+ "commit": "e6f4af3f9a25d0b18d36d8224fb861c8ab254ea8",
4
+ "patches": [],
5
+ "files": [
6
+ {
7
+ "source": "internal/plugin/host.js",
8
+ "path": "vendor/host.js",
9
+ "sha256": "962fccd89469eaf5749e5e1b742ee81a03ded84820c055ffcf3b5747abe7fac9"
10
+ },
11
+ {
12
+ "source": "LICENSE",
13
+ "path": "vendor/LICENSE",
14
+ "sha256": "79d2c8444715d4bc453ec4f8a0aaf2051a4c1ee5ac08f5bd2e5848aef87c7572"
15
+ }
16
+ ]
17
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "magpie-pi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Magpie community plugin integration for Pi",
5
+ "license": "UNLICENSED",
6
+ "keywords": ["pi-package"],
7
+ "files": ["extension/", "vendor/", "bin/", "extraction.json", "README.md", "README.zh-CN.md"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/arklee/magpie-pi.git"
11
+ },
12
+ "type": "module",
13
+ "pi": {
14
+ "extensions": [
15
+ "./extension/index.ts"
16
+ ]
17
+ },
18
+ "peerDependencies": {
19
+ "@earendil-works/pi-ai": "1.6.0",
20
+ "@earendil-works/pi-coding-agent": "1.6.0"
21
+ },
22
+ "scripts": {
23
+ "test": "node --test tests/*.test.mjs",
24
+ "typecheck": "npm exec --yes --package typescript@7.0.2 -- tsc --noEmit --allowJs --skipLibCheck --module nodenext --moduleResolution nodenext --target es2022 extension/index.ts"
25
+ }
26
+ }
package/vendor/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yetone
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.