magpie-pi 0.0.0-stage → 0.1.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 +153 -2
- package/README.zh-CN.md +154 -0
- package/bin/magpie-pi +0 -0
- package/bin/magpie-pi-darwin-amd64 +0 -0
- package/bin/magpie-pi-darwin-arm64 +0 -0
- package/bin/magpie-pi-linux-amd64 +0 -0
- package/bin/magpie-pi-linux-arm64 +0 -0
- package/bin/magpie-pi-windows-amd64.exe +0 -0
- package/bin/magpie-pi-windows-arm64.exe +0 -0
- package/extension/bridge.mjs +64 -0
- package/extension/index.ts +103 -0
- package/extension/platform.mjs +10 -0
- package/extension/plugins.mjs +178 -0
- package/extraction.json +17 -0
- package/package.json +24 -4
- package/vendor/LICENSE +21 -0
- package/vendor/host.js +4002 -0
package/README.md
CHANGED
|
@@ -1,3 +1,154 @@
|
|
|
1
|
-
#
|
|
1
|
+
# magpie-pi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
English | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
A small Go stdio supervisor, a thin Pi extension, and the magpie OpenCode Bun host **extracted without modifications**.
|
|
6
|
+
No HTTP listener, full gateway, Go-to-TypeScript translation, or Pi core fork. Plugins handle accounts, refreshes, and requests; Pi's native SDK handles message, tool, and streaming-event conversion.
|
|
7
|
+
|
|
8
|
+
## Build and install
|
|
9
|
+
|
|
10
|
+
Requires Go 1.23+, Bun (locally tested with 1.3.14), Pi **1.6.0**, Node.js, and npm (for downloading and installing community plugins).
|
|
11
|
+
Run from this directory:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
node scripts/build.mjs
|
|
15
|
+
# Install the local extension explicitly; the build does not change global Pi settings.
|
|
16
|
+
pi install /absolute/path/magpie-pi
|
|
17
|
+
# Or load it for this session only.
|
|
18
|
+
pi -e /absolute/path/magpie-pi/extension/index.ts
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
For development dependencies, use the Pi installation's node_modules or install the exact peerDependencies versions in package.json. The local node_modules is a development symlink to an existing Pi installation, not part of the release.
|
|
22
|
+
|
|
23
|
+
Local-path installation references the project directory directly rather than copying source into Pi's plugin directory. Extension edits do not require reinstallation; after Go changes, rerun `node scripts/build.mjs`. Restart Pi after changes to the background host or configuration.
|
|
24
|
+
|
|
25
|
+
## Quick start: install from the menu → log in → select a model
|
|
26
|
+
|
|
27
|
+
After building, install persistently and start Pi:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pi install ~/Code/agent-playground/magpie-pi
|
|
31
|
+
pi
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Replace the path if your checkout is elsewhere. Alternatively, use the temporary `pi -e` command above; include `-e` again after each restart.
|
|
35
|
+
|
|
36
|
+
1. Enter `/magpie-plugins` in Pi to open the native TUI menu. Use **↑/↓** to select, **Enter** to confirm, and **Esc** to exit. UI text is in English.
|
|
37
|
+
2. Choose **Search and install**, enter `cursor` or `workbuddy`, then select a package and version. After you read the permissions notice and confirm, the extension downloads the plugin and saves its configuration automatically—no manual JSON editing needed.
|
|
38
|
+
3. Exit and restart Pi after installation. If multiple Pi instances share the state directory, exit all of them before restarting.
|
|
39
|
+
4. Enter `/login`, select the service, and follow the login prompts. Registered provider IDs have a `magpie-` prefix; menus may display the service name supplied by the plugin.
|
|
40
|
+
5. Enter `/model`, select a model from that service, and chat or use tools normally. Pi's built-in services remain available.
|
|
41
|
+
|
|
42
|
+
Other menu entries:
|
|
43
|
+
|
|
44
|
+
| Menu entry | Purpose |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| Installed plugins / details | View configured plugins and installation paths |
|
|
47
|
+
| Uninstall | Select and confirm removal of a managed plugin; old files are cleaned up after restart, preserving credentials |
|
|
48
|
+
| Install by package name | Enter an alias or full package name, optionally with `@exact-version` |
|
|
49
|
+
| Help | View text subcommands |
|
|
50
|
+
|
|
51
|
+
You can also enter `/magpie-plugins install cursor` or `/magpie-plugins install workbuddy`; interactive confirmation is still required. Reinstalling a managed plugin can replace its version; this is not an automatic background update.
|
|
52
|
+
|
|
53
|
+
**Current limitations:** Real Cursor/WorkBuddy accounts have not been verified. Successful search or installation does not establish model-call compatibility. If a service is missing from `/login`, confirm you restarted and check startup errors. If `/model` lists no models, the plugin may not expose a supported protocol; see “Supported scope” below. This extension does not yet integrate magpie's built-in Codex, Claude, Copilot, or Gemini account implementations.
|
|
54
|
+
|
|
55
|
+
## Configuration and credentials (manual configuration is optional)
|
|
56
|
+
|
|
57
|
+
On first load, the extension creates a separate state directory, `~/.local/share/magpie-pi` (0700), and an empty `config.json` (0600). With no plugins configured, it only displays a configuration hint: Go/Bun are not started, and Pi's existing services are unaffected. Existing configuration is not overwritten; invalid JSON produces an explicit error.
|
|
58
|
+
|
|
59
|
+
Use the menu to manage plugins. Manual editing of `config.json` is only needed for plugins you install yourself, for example:
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{
|
|
63
|
+
"plugins": [
|
|
64
|
+
{
|
|
65
|
+
"spec": "@magpie-community/opencode-cursor-auth",
|
|
66
|
+
"target": "/absolute/plugin-install/node_modules/@magpie-community/opencode-cursor-auth"
|
|
67
|
+
}
|
|
68
|
+
],
|
|
69
|
+
"accounts": {},
|
|
70
|
+
"opencode": {}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
For manual installation, use a separate directory of your choice, run `npm install --save-exact package-name@exact-version`, and retain `package-lock.json`. `target` must point to an installed package or entry file. This project does not automatically download third-party code at startup; configure it manually or explicitly confirm installation through the menu. WorkBuddy uses `@magpie-community/opencode-workbuddy-auth`, not the old built-in implementation.
|
|
75
|
+
Do not install the withdrawn Antigravity plugin for new users.
|
|
76
|
+
|
|
77
|
+
`MAGPIE_PI_STATE` selects an absolute state directory; `MAGPIE_PI_BUN` selects the Bun executable.
|
|
78
|
+
Use Pi's `/login` to select an extension-registered service (internal IDs start with `magpie-`). API keys, automatic/code-paste OAuth, and conditional host prompt/validate forms are supported; complex vendor forms have not been tested live.
|
|
79
|
+
The original host stores real tokens in a separate `plugin-auth.json` (0600); Pi stores only a `plugin-owned` marker.
|
|
80
|
+
For multiple accounts, the host's default account is used unless `config.accounts` pins an account key by plugin provider ID.
|
|
81
|
+
Pi's `/logout` clears the marker and disables the provider without deleting plugin credentials; use `/login` to enable it again. Resolution requires both Pi's saved marker and the host's login state, so cached credentials cannot bypass Pi logout. There is no plugin-credential deletion command yet.
|
|
82
|
+
|
|
83
|
+
## Supported scope
|
|
84
|
+
|
|
85
|
+
The full Go → Bun fixture plugin → Pi native OpenAI Chat SDK path has been tested for login, model discovery, text, tool calls, cancellation, and credential persistence across restarts.
|
|
86
|
+
Only Chat Completions models from `@ai-sdk/openai-compatible` and Messages models from `@ai-sdk/anthropic` are exposed.
|
|
87
|
+
The Anthropic path uses Pi's native implementation but has not had real-service or fixture verification. Responses/Gemini are unsupported. Because `@ai-sdk/openai` does not reliably distinguish Chat from Responses, all its models are hidden rather than silently treated as Chat.
|
|
88
|
+
Costs are currently marked as 0 to indicate missing pricing information, not free service.
|
|
89
|
+
Real Cursor/WorkBuddy accounts remain unverified; compatibility with all community plugins is not claimed.
|
|
90
|
+
Built-in Codex, Claude, Copilot, and Gemini account logic has not been extracted. There is no account rotation, quota routing, gateway conversion, GUI, migration tooling, or automatic plugin updating. For ordinary APIs, use Pi's `models.json` directly.
|
|
91
|
+
|
|
92
|
+
Plugins are trusted local code running with the current user's privileges, not a security sandbox. Windows file permissions depend on the user directory's ACL. Cross-platform compilation does not establish runtime support; only Linux has been tested at runtime.
|
|
93
|
+
|
|
94
|
+
## Protocol and lifecycle
|
|
95
|
+
|
|
96
|
+
Bridge protocol v1 uses the host JSON-lines contract pinned by `extraction.json`:
|
|
97
|
+
requests `{id,method,params}`; responses `{id,result}` / `{id,error}`.
|
|
98
|
+
Fetch sends a head, then base64 chunks, then a result. Credit returns the consumed byte count plus 2048 bytes of overhead per frame.
|
|
99
|
+
Each request starts with a 65536-byte window; credit is returned only on `ReadableStream` pull. Abort cancels the same ID.
|
|
100
|
+
Stdio provides backpressure; Go does not buffer complete responses. EOF closes Bun's stdin; direct children still running after two seconds are forcibly terminated.
|
|
101
|
+
Plugin-spawned grandchildren are not contained as a process tree. A host crash fails pending requests; generation is not retried automatically.
|
|
102
|
+
There is no local listening port. The Go supervisor manages only processes and state permissions; protocol adaptation stays in the thin extension.
|
|
103
|
+
|
|
104
|
+
## Testing and updates
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
node scripts/extraction.mjs
|
|
108
|
+
node scripts/build.mjs
|
|
109
|
+
node --test tests/*.test.mjs
|
|
110
|
+
bun test tests/provider.test.ts
|
|
111
|
+
go vet ./...
|
|
112
|
+
go test -race ./...
|
|
113
|
+
node scripts/build.mjs --all
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Tests use temporary state directories and local fixtures, requiring neither real tokens nor network access.
|
|
117
|
+
Go currently has no standalone unit tests; its main behavior is covered by integration tests using the compiled binary.
|
|
118
|
+
Cross-platform artifacts are in `bin/`. Keep their platform-specific names, such as `magpie-pi-linux-amd64` and `magpie-pi-windows-arm64.exe`; the extension selects the matching binary automatically. Retain `vendor/` and `extension/`. A local build also creates the legacy `magpie-pi` / `magpie-pi.exe` alias for integration tests.
|
|
119
|
+
|
|
120
|
+
### npm packaging preparation
|
|
121
|
+
|
|
122
|
+
The package whitelist includes `extension/`, `vendor/`, `bin/`, the extraction manifest, and both READMEs. Run `node scripts/build.mjs --all` before packaging to include all six platform binaries. Package users need Bun and compatible Pi, but not Go. Only Linux runtime behavior has been verified. These packaging changes do not mean the package has been published.
|
|
123
|
+
|
|
124
|
+
The project's own license is currently `UNLICENSED`; choose an explicit distribution license before public release. The extracted host retains its upstream MIT license in `vendor/LICENSE`.
|
|
125
|
+
|
|
126
|
+
`extraction.json` pins the source commit, per-file SHA-256 hashes, and an empty patch list. `vendor/LICENSE` contains the upstream MIT license.
|
|
127
|
+
Before updating, read the upstream design and review changes, then explicitly run:
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
node scripts/extraction.mjs extract /absolute/path/magpie
|
|
131
|
+
node scripts/extraction.mjs
|
|
132
|
+
# Rerun the tests above and review the new extraction.json before publishing.
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Extraction reads bytes from the git commit, not uncommitted working-tree changes. Verification checks local vendor hashes. Neither modifies magpie's source.
|
|
136
|
+
|
|
137
|
+
## Community plugin management
|
|
138
|
+
|
|
139
|
+
Native Pi 1.6.0 menus are implemented: enter `/magpie-plugins`, use arrow keys to select, Enter to confirm, and Esc to exit. Search by keyword, select a package, version, and description, then explicitly confirm installation of the exact selected version. You can also view installed-plugin details, uninstall managed plugins, or enter a package name directly. Manually configured plugins are read-only; cancellation triggers no subsequent actions. Noninteractive mode retains help and read-only subcommands but rejects mutations. Menu tests use mocked UI; neither real vendor services nor the live Pi TUI have been verified.
|
|
140
|
+
|
|
141
|
+
Text subcommands remain available, even with empty configuration:
|
|
142
|
+
- `/magpie-plugins help`
|
|
143
|
+
- `/magpie-plugins search cursor`
|
|
144
|
+
- `/magpie-plugins install cursor` (or a full package name with `@exact-version`)
|
|
145
|
+
- `/magpie-plugins list`
|
|
146
|
+
- `/magpie-plugins remove workbuddy`
|
|
147
|
+
|
|
148
|
+
Requires npm. Search queries npm metadata only and is restricted to community `opencode-*-auth` packages; compatibility with the current vendor host is not guaranteed. `cursor` and `workbuddy` are aliases. The withdrawn `antigravity-auth` cannot be installed; `agy-cli-auth` is unaffected.
|
|
149
|
+
|
|
150
|
+
Installation and removal require explicit UI confirmation; noninteractive mutations are rejected. npm runs through `execFile` with `--ignore-scripts` and `--save-exact`. Disabling install scripts is not a security sandbox: runtime plugins still have the current user's privileges. Downloads use separate `managed-plugins/pkg-*` directories; configuration is atomically replaced and the version pinned only on success. Failures preserve the original configuration. A cross-process lock rejects concurrent mutations. If a crash leaves `plugins.lock`, confirm no operation is running before manually deleting the lock.
|
|
151
|
+
|
|
152
|
+
Restart Pi after changes; running code is not unloaded. Removal and version replacement add old managed directories to an atomically saved deletion queue, processed at the next extension startup before the host starts. Exit all Pi instances sharing the state directory before restarting. Credentials and manually configured plugins are never deleted. Cleanup only removes `managed-plugins/pkg-*` directories with this manager's ownership marker. Legacy unmarked directories and directories that fail path validation are retained; cases whose safety cannot be established require manual handling. Unrelated configuration fields are preserved, and new files use mode 0600. Avoid simultaneous configuration writes from external editors that do not honor the management lock. Corrupt JSON requires manual repair; commands remain available for removal when a plugin fails to load.
|
|
153
|
+
|
|
154
|
+
Deterministic tests use temporary directories and mocked registry/npm operations, never installing real plugins into user state.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# magpie-pi
|
|
2
|
+
|
|
3
|
+
[English](README.md) | 简体中文
|
|
4
|
+
|
|
5
|
+
小型 Go stdio supervisor + 薄 Pi 扩展 + **原样抽取**的 magpie OpenCode Bun host。
|
|
6
|
+
没有 HTTP 监听、完整 gateway、Go→TS 翻译或 Pi core fork。插件负责账号、刷新和请求;Pi 原生 SDK 负责消息、工具和流式事件转换。
|
|
7
|
+
|
|
8
|
+
## 构建与安装
|
|
9
|
+
|
|
10
|
+
要求 Go 1.23+、Bun(本机测试 1.3.14)、Pi **1.6.0**、Node.js 和 npm(用于下载安装社区插件)。
|
|
11
|
+
从本目录执行:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
node scripts/build.mjs
|
|
15
|
+
# 安装本地扩展(由用户主动执行,不会由构建脚本修改全局 Pi 配置)
|
|
16
|
+
pi install /absolute/path/magpie-pi
|
|
17
|
+
# 或仅本次加载
|
|
18
|
+
pi -e /absolute/path/magpie-pi/extension/index.ts
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
开发依赖使用 Pi 安装目录的 node_modules 或安装 package.json 中精确版本的 peerDependencies。本机 node_modules 是指向已有 Pi 安装的开发用链接,不属于发布内容。
|
|
22
|
+
|
|
23
|
+
本地路径安装直接引用项目目录,不会复制源码到 Pi 的插件目录。修改扩展后无需重新安装;修改 Go 代码后先重新执行 `node scripts/build.mjs`。涉及后台宿主或配置的更改请重启 Pi。
|
|
24
|
+
|
|
25
|
+
## 快速使用:菜单安装 → 登录 → 选择模型
|
|
26
|
+
|
|
27
|
+
完成上述构建后,可以持久安装并启动:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pi install ~/Code/agent-playground/magpie-pi
|
|
31
|
+
pi
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
如果项目放在其他位置,请替换路径。也可以不安装,仅使用前面的 `pi -e` 临时加载;此时每次重启仍需带上 `-e`。
|
|
35
|
+
|
|
36
|
+
1. 在 Pi 输入 `/magpie-plugins`,打开原生 TUI 菜单。用 **↑/↓** 选择、**Enter** 确认、**Esc** 退出;界面文字使用 English。
|
|
37
|
+
2. 选择 **Search and install**,输入 `cursor` 或 `workbuddy`,从搜索结果中选择包和版本。阅读权限提示并确认后,扩展会下载插件并自动保存配置,无需手动编辑 JSON。
|
|
38
|
+
3. 安装成功后退出并重新启动 Pi。若多个 Pi 实例共享状态目录,先全部退出再启动。
|
|
39
|
+
4. 输入 `/login`,选择对应服务并按照提示完成登录。扩展注册的 provider ID 带 `magpie-` 前缀,菜单中可能显示插件提供的服务名称。
|
|
40
|
+
5. 输入 `/model`,选择该服务提供的模型,然后正常聊天或使用工具。Pi 原有服务仍然可用。
|
|
41
|
+
|
|
42
|
+
其他菜单项:
|
|
43
|
+
|
|
44
|
+
| 菜单项 | 用途 |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| Installed plugins / details | 查看已配置插件和安装路径 |
|
|
47
|
+
| Uninstall | 选择托管插件并确认卸载;重启后清理旧文件,保留凭据 |
|
|
48
|
+
| Install by package name | 输入别名或完整包名,可附 `@精确版本` |
|
|
49
|
+
| Help | 查看文本子命令 |
|
|
50
|
+
|
|
51
|
+
也可以直接输入 `/magpie-plugins install cursor` 或 `/magpie-plugins install workbuddy`,仍需交互确认。再次安装同一托管插件可替换版本;不是后台自动更新。
|
|
52
|
+
|
|
53
|
+
**当前限制:**真实 Cursor/WorkBuddy 账号尚未验证,搜索或安装成功不代表模型调用兼容。若 `/login` 没有出现服务,先确认已重启并查看启动错误;若 `/model` 没有模型,该插件可能未提供当前支持的协议,见下方“支持范围”。本扩展尚未接入 magpie 的内置 Codex、Claude、Copilot、Gemini 账号实现。
|
|
54
|
+
|
|
55
|
+
## 配置与凭据(手动配置可选)
|
|
56
|
+
|
|
57
|
+
首次加载会自动创建独立状态目录 ~/.local/share/magpie-pi(0700)和空的 config.json(0600)。未配置插件时仅显示配置提示,不启动 Go/Bun,也不影响 Pi 原有服务。已有配置不会被覆盖;无效 JSON 会明确报错。
|
|
58
|
+
|
|
59
|
+
推荐使用菜单管理插件。只有需要使用自行安装的插件时,才手动编辑其中的 config.json,例如:
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{
|
|
63
|
+
"plugins": [
|
|
64
|
+
{
|
|
65
|
+
"spec": "@magpie-community/opencode-cursor-auth",
|
|
66
|
+
"target": "/absolute/plugin-install/node_modules/@magpie-community/opencode-cursor-auth"
|
|
67
|
+
}
|
|
68
|
+
],
|
|
69
|
+
"accounts": {},
|
|
70
|
+
"opencode": {}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
插件安装在用户选定的独立目录,用 npm install --save-exact 包名@明确版本,并保留 package-lock.json。target 必须指向已安装包或入口文件;本项目不会在启动时自动下载安装第三方代码;可手动配置或通过下方菜单明确确认安装。WorkBuddy 使用 @magpie-community/opencode-workbuddy-auth,同样不是旧 builtin。
|
|
75
|
+
不要为新用户安装已撤回的 Antigravity 插件。
|
|
76
|
+
|
|
77
|
+
MAGPIE_PI_STATE 可指定绝对状态目录,MAGPIE_PI_BUN 可指定 Bun 可执行文件。
|
|
78
|
+
在 Pi /login 选择扩展注册的服务(内部 ID 以 magpie- 开头)。支持 API key、OAuth 自动/粘贴代码登录,以及 host prompt/validate 条件表单;复杂厂商表单尚未实测。
|
|
79
|
+
真实 token 由原 host 写入独立 plugin-auth.json(0600),Pi 中仅保存 plugin-owned 标记。
|
|
80
|
+
多账号默认使用 host 的默认账号;config.accounts 可按插件 provider ID 固定账号 key。
|
|
81
|
+
Pi /logout 清除标记并停用此 provider,不删除插件凭据;再次使用需 /login。resolve 同时要求 Pi 保存的标记与 host 登录状态,不会绕过 Pi logout。尚无插件凭据删除命令。
|
|
82
|
+
|
|
83
|
+
## 支持范围
|
|
84
|
+
|
|
85
|
+
已测试完整 Go → Bun fixture 插件 → Pi 原生 OpenAI Chat SDK:登录、模型发现、文本、工具调用、取消及重启后的凭据持久化。
|
|
86
|
+
仅暴露 @ai-sdk/openai-compatible 的 Chat Completions 模型和 @ai-sdk/anthropic 的 Messages 模型。
|
|
87
|
+
Anthropic 路径使用 Pi 原生实现,但未进行真实服务/fixture 验证。Responses/Gemini 不支持;@ai-sdk/openai 无法可靠区分 Chat 与 Responses,全部隐藏,不会静默按 Chat 处理。
|
|
88
|
+
成本目前以 0 标记,表示未接入价格信息,不代表服务免费。
|
|
89
|
+
Cursor/WorkBuddy 真账号尚未验证,不宣称兼容全部社区插件。
|
|
90
|
+
没有提取 builtin Codex、Claude、Copilot、Gemini 账号逻辑,没有账号轮转、配额路由、gateway 转换、GUI、迁移工具或插件自动更新。普通 API 请直接用 Pi models.json。
|
|
91
|
+
|
|
92
|
+
插件是受信任的本地代码,具有当前用户权限,不是安全沙箱。Windows 文件权限取决于用户目录 ACL;跨平台编译不等于平台运行验证。仅 Linux 实测。
|
|
93
|
+
|
|
94
|
+
## 协议与生命周期
|
|
95
|
+
|
|
96
|
+
桥接协议 v1 使用固定 extraction.json 所锁定的 host JSON-lines 合约:
|
|
97
|
+
请求 {id,method,params};响应 {id,result} / {id,error}。
|
|
98
|
+
fetch 先 head,再 base64 chunk,最后 result;credit 返回消费字节数加每帧 2048 的开销。
|
|
99
|
+
每请求初始窗口 65536,ReadableStream pull 才归还额度;abort 取消同一 id。
|
|
100
|
+
stdio 天然背压,Go 不缓冲完整响应。EOF 关闭 Bun stdin,2 秒后强制结束仍未退出的直接子进程。
|
|
101
|
+
插件自行派生的孙进程不提供进程树隔离。host 崩溃使 pending 请求失败,不自动重试生成。
|
|
102
|
+
没有本机监听端口。Go supervisor 只管理进程与状态权限,协议适配留在薄扩展中。
|
|
103
|
+
|
|
104
|
+
## 测试与更新
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
node scripts/extraction.mjs
|
|
108
|
+
node scripts/build.mjs
|
|
109
|
+
node --test tests/*.test.mjs
|
|
110
|
+
bun test tests/provider.test.ts
|
|
111
|
+
go vet ./...
|
|
112
|
+
go test -race ./...
|
|
113
|
+
node scripts/build.mjs --all
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
测试用临时状态目录和本地 fixture,不需要真实 token 或网络。
|
|
117
|
+
Go 当前没有单独单元测试;主要行为由实际编译二进制集成测试覆盖。
|
|
118
|
+
全平台产物在 bin/;部署时保留平台专用文件名,例如 magpie-pi-linux-amd64 和 magpie-pi-windows-arm64.exe,扩展会自动选择对应二进制。保留 vendor/ 和 extension/。本地构建还会生成旧的 magpie-pi / magpie-pi.exe 别名,供集成测试使用。
|
|
119
|
+
|
|
120
|
+
### npm 打包准备
|
|
121
|
+
|
|
122
|
+
发布文件白名单包含 extension/、vendor/、bin/、抽取清单和中英文 README。打包前执行 `node scripts/build.mjs --all`,以包含六个平台的二进制。包用户需要 Bun 和兼容版本的 Pi,无需 Go。目前仅验证了 Linux 运行行为;这些打包调整不代表已经发布 npm 包。
|
|
123
|
+
|
|
124
|
+
项目自身许可证暂标为 `UNLICENSED`,公开发布前应明确分发许可。抽取的 host 继续保留 vendor/LICENSE 中的上游 MIT 许可证。
|
|
125
|
+
|
|
126
|
+
extraction.json 锁定来源 commit、每个文件 SHA-256、空补丁列表。vendor/LICENSE 为上游 MIT 许可证。
|
|
127
|
+
升级时先阅读上游设计,审查差异,然后显式执行:
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
node scripts/extraction.mjs extract /absolute/path/magpie
|
|
131
|
+
node scripts/extraction.mjs
|
|
132
|
+
# 重跑上述测试;检查新 extraction.json 后再发布
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
extract 从 git commit 读取字节,不复制工作区未提交修改;verify 检查本地 vendor 哈希。不修改 magpie 源码。
|
|
136
|
+
|
|
137
|
+
## 社区插件管理
|
|
138
|
+
|
|
139
|
+
已实现 Pi 1.6.0 原生菜单:直接输入 `/magpie-plugins`,用方向键选择、Enter 确认、Esc 退出。搜索输入关键词后选择包名、版本和描述,明确确认后按所选精确版本安装。也可查看已安装插件详情、卸载托管插件或直接输入包名。手动配置只读;取消不触发后续操作。无交互模式保留帮助和只读子命令,拒绝修改。菜单测试使用模拟 UI,未验证真实厂商服务或真实 Pi TUI。
|
|
140
|
+
|
|
141
|
+
保留原有子命令,空配置也可用:
|
|
142
|
+
- `/magpie-plugins help`
|
|
143
|
+
- `/magpie-plugins search cursor`
|
|
144
|
+
- `/magpie-plugins install cursor`(或完整包名及 @精确版本)
|
|
145
|
+
- `/magpie-plugins list`
|
|
146
|
+
- `/magpie-plugins remove workbuddy`
|
|
147
|
+
|
|
148
|
+
需要 npm。搜索仅查询 npm 元数据,限定社区 opencode-*-auth 包,不保证所有插件与当前 vendor host 兼容。cursor/workbuddy 是快捷别名。撤回的 antigravity-auth 不允许安装,agy-cli-auth 不受影响。
|
|
149
|
+
|
|
150
|
+
安装及移除必须 UI 明确确认,无交互模式拒绝修改。npm 使用 execFile、--ignore-scripts、--save-exact;禁用安装脚本不代表安全沙箱,运行插件仍拥有当前用户权限。下载使用独立 managed-plugins/pkg-* 目录,成功才原子替换配置并固定版本;失败保留原配置。跨进程锁拒绝并发修改,异常退出遗留 plugins.lock 时,确认没有操作运行后手动删除锁。
|
|
151
|
+
|
|
152
|
+
更新后必须重启 Pi,不尝试卸载运行中的代码。移除和替换版本将旧托管目录加入原子保存的删除队列,下次扩展启动、host 启动前删除。共享状态目录的 Pi 实例应全部退出再重启。凭据及手动插件永不删除。仅清理带本管理器所有权标记的 managed-plugins/pkg-* 目录;历史无标记目录或路径验证失败的目录保留,不能确认安全时需人工处理。配置保留无关字段,新文件权限 0600。外部编辑器不遵守管理锁时仍应避免同时写配置。JSON 损坏需手动修复;插件加载失败时命令仍可用于移除。
|
|
153
|
+
|
|
154
|
+
确定性测试使用临时目录、模拟 registry 与 npm,不安装真实插件到用户状态。
|
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
|
+
}
|