From 96149cd045f89da0a1a8a78ca941d145ce51f968 Mon Sep 17 00:00:00 2001 From: unisong <30364110+unisong@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:47:35 +0800 Subject: [PATCH] pi-desktop 0.2.0: Pi-Desktop as a connect-only agent, through a plugin (#1206) Pi-Desktop (the desktop app) as a connect-only agent, id pi-desktop-app: magpie keeps a Pi-Desktop local-plugin folder whose manifest.json declares the gateway as a provider with magpie's models and their thinking levels, split into cards of at most 64 models. Pi-Desktop's database is never written. Ships scripts/doctor.mjs, a read-only check of both sides. By unisong (#1206). Run at 4ded8795d (macOS via mica-run, temp HOME): bun test in packages/pi-desktop 18 pass; bun scripts/check.mjs pi-desktop ok. The author ran it against Pi-Desktop 0.22.0 on Windows 11. Not tried here: a real Pi-Desktop. First npm publish waits for the owner; dist serves it meanwhile. --- README.md | 1 + packages/pi-desktop/README.md | 86 +++++++++++++++ packages/pi-desktop/package.json | 26 +++++ packages/pi-desktop/pi-desktop.agent.js | 132 +++++++++++++++++++++++ packages/pi-desktop/pi-desktop.test.mjs | 110 +++++++++++++++++++ packages/pi-desktop/pi-plugin.test.mjs | 95 +++++++++++++++++ packages/pi-desktop/scripts/doctor.mjs | 134 ++++++++++++++++++++++++ registry.json | 2 + 8 files changed, 586 insertions(+) create mode 100644 packages/pi-desktop/README.md create mode 100644 packages/pi-desktop/package.json create mode 100644 packages/pi-desktop/pi-desktop.agent.js create mode 100644 packages/pi-desktop/pi-desktop.test.mjs create mode 100644 packages/pi-desktop/pi-plugin.test.mjs create mode 100644 packages/pi-desktop/scripts/doctor.mjs diff --git a/README.md b/README.md index 348f2fa..7ca9ffc 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,7 @@ it off puts the config back. | [kilo](packages/kilo) | [Kilo Code](https://kilo.ai): `~/.config/kilo/kilo.jsonc`, through an OpenAI-compatible provider | | [junie](packages/junie) | [Junie CLI](https://junie.jetbrains.com/): an explicit `/v1/models` seed for its full picker and Magpie's selected model as the launch default; no LiteLLM | | [kimi-desktop](packages/kimi-desktop) | Ordinary [Kimi desktop](https://www.kimi.com/) Work, through its authenticated local runtime; not Kimi Code CLI | +| [pi-desktop](packages/pi-desktop) | Pi-Desktop (the desktop app, not the Pi CLI): magpie keeps a Pi-Desktop plugin folder, `~/.config/magpie-pi-desktop/plugin`, that adds it as a model provider with its current models and their thinking levels; load it once in Pi-Desktop, choose the model there | | [pig](packages/pig) | [PiG](https://github.com/MichaelKinsy/PiG): Magpie's endpoint and model catalog in `~/.pig/agent/models.json`, and the model PiG starts on (`defaultProvider`/`defaultModel` in `settings.json`) picked on the Agents page | | [type4me](packages/type4me) | [Type4Me](https://github.com/joewongjc/type4me), macOS voice input: `~/Library/Application Support/Type4Me/magpie-agent.json`, for its LLM post-processing | | [opencodereview](packages/opencodereview) | [Open Code Review](https://github.com/alibaba/open-code-review) (`ocr`): `~/.opencodereview/config.json` as a custom Anthropic provider, so `ocr review` / `ocr scan` run on magpie's models | diff --git a/packages/pi-desktop/README.md b/packages/pi-desktop/README.md new file mode 100644 index 0000000..36b39cb --- /dev/null +++ b/packages/pi-desktop/README.md @@ -0,0 +1,86 @@ +# Pi-Desktop for Magpie + +Pi-Desktop keeps its model providers in a database that only its own host process writes, so Magpie cannot wire it by editing a settings file the way it wires Codex or Pi. What Pi-Desktop does read from disk is a plugin folder: loaded as a local plugin, its `manifest.json` is read again every time Pi-Desktop starts. This package makes that file the one Magpie keeps. + +- **The Magpie agent `pi-desktop-app`** (connect-only; `pi-desktop` is the id of Magpie's own Sessions source, which Magpie refuses for a plugin). It gives Pi-Desktop a row on Magpie's Agents page, its own gateway key `magpie-pi-desktop-app` for Usage and routing rules, and model visibility (`magpie visible pi-desktop-app …`). +- **The plugin folder `~/.config/magpie-pi-desktop/plugin`**, which Magpie writes while the row is on. Its `manifest.json` is a Pi-Desktop plugin (`local.magpie-gateway`) that declares the provider *Magpie*, pointed at the gateway, with every model Magpie offers Pi-Desktop and each model's thinking levels. Magpie rewrites it when its models change. It holds no code, and its only permission is `provider.register`. Pi-Desktop stores the key you enter. + +Every model Magpie offers Pi-Desktop then shows up in Pi-Desktop's picker under *Magpie* (and *Magpie 2*, … past 64 models), including routing groups, so its multi-vendor routing and fallback apply to Pi-Desktop too. You still pick the model per chat in Pi-Desktop. + +## Set up + +1. In Magpie: `magpie plugin add `, or Plugins › Discover › *Have one in mind?*, pick this folder and Install (once published: `magpie plugin add @magpie-community/agent-pi-desktop`; the bare name `pi-desktop` is someone else's npm package). Under Plugins › Installed its row should read *Adds Pi-Desktop to Agents*, with no error. Then Connect Pi-Desktop in Agents (or `magpie pi-desktop-app provider magpie`). Pi-Desktop is detected by its data folder `~/.pi-desktop`. +2. In Pi-Desktop, once: Extensions › ⋯ (More actions) › Load local plugin, choose the folder `.config/magpie-pi-desktop/plugin` in your user folder, and confirm with Load plugin. *Magpie Gateway* appears with a *Local* tag, and its provider cards are there at once. +3. Settings › AI providers › Add provider › *Magpie*: enter the API key `magpie-pi-desktop-app` and save. Do the same for *Magpie 2* and any further card; Add provider lists the ones that have no key yet. +4. Pick a Magpie model in a chat. `node scripts/doctor.mjs` checks every step; it prints no secrets, only the public key name `magpie-pi-desktop-app`. + +Installed by its scoped name, the package lands under `~/.config/magpie/plugins/node_modules/@magpie-community/agent-pi-desktop`; run the script from there, or from a checkout. + +## When Magpie's models change + +Nothing to do in Magpie: while the row is connected it rewrites the manifest, for added and removed models, changed visibility and a changed port alike. Pi-Desktop reads the manifest's providers and models when it starts, so the change shows after Pi-Desktop is next opened. To apply it without a restart, turn *Magpie Gateway* off and on under Extensions (its row's ⋯ menu › Disable, then Enable). Saved keys stay. + +It is not instant: Pi-Desktop 0.22.0 reads a plugin's providers only when it starts, when the plugin is enabled and when a local plugin is loaded, and gives plugins no call to change them. While open, Pi-Desktop does notice the file change and says *Reloaded Magpie Gateway*; that reloads the plugin's code, not its provider list. *Reload plugin* in the row's menu does the same. + +## What Magpie writes + +Only `~/.config/magpie-pi-desktop/plugin/manifest.json`, a file of its own: + +```json +{ + "schemaVersion": 1, + "id": "local.magpie-gateway", + "name": "Magpie Gateway", + "version": "0.2.0", + "main": "manifest.json", + "contributes": { + "providers": [{ + "id": "magpie", "name": "Magpie", "baseUrl": "http://127.0.0.1:3425/v1", "apiStyle": "chat_completions", "authKind": "api_key", + "models": [{ "id": "deepseek/deepseek-chat", "name": "DeepSeek Chat", "contextWindow": 131072, "maxTokens": 8192, "thinkingLevels": ["low", "medium", "high"], "defaultThinkingLevel": "high" }] + }] + }, + "permissions": ["provider.register"], + "engines": { "piDesktop": ">=0.22.0" }, + "magpie": { "baseUrl": "http://127.0.0.1:3425/v1", "apiKey": "magpie-pi-desktop-app", "apiStyle": "chat_completions" } +} +``` + +`main` names the manifest itself: Pi-Desktop wants an entry file, and a JSON file loads as a module with no hooks. `magpie` is for Magpie and `doctor.mjs`; Pi-Desktop ignores it. Turning the row off takes every key out again. Pi-Desktop's own database and secrets are never written; `doctor.mjs` reads a temporary copy and deletes it. + +## Good to know + +- **Thinking levels.** Pi-Desktop (0.22.0) takes them only from models a plugin declares. A model it discovers from the gateway gets all seven levels and starts on `off`, which is why the manifest declares them. Each model starts on `high`, or the nearest level it has, as Magpie picks for Codex. A model Magpie gives no levels for keeps the generic settings. Magpie's `none` is Pi-Desktop's `off`; Magpie's `ultra` has no Pi-Desktop level and is left out. +- **64 models per card.** Pi-Desktop refuses a plugin provider with more, so the list is split into *Magpie*, *Magpie 2*, …, keeping one vendor's models together when they fit. Each card needs the key once, so a card that appears later (*Magpie 3*) asks for it then. When the list changes a model can move to another card, and a chat that used it needs its model picked again; `magpie visible pi-desktop-app …` can bring the list under 64. +- **Coming from 0.1.x** (the `.piplug` with a fixed model list): turn this Magpie plugin off and on, connect the row again, then do step 2. Loading the folder replaces the installed package and keeps the saved key. +- **Turning it off.** Disconnecting the row in Magpie empties the manifest; Pi-Desktop keeps the cards it last read. To remove them, uninstall *Magpie Gateway* in Pi-Desktop's Extensions. +- Turning this Magpie plugin off or removing it disconnects the agent first. +- **A wrong key still works.** The local gateway serves any key, so a mistyped key only shows up in Usage, under another name. Use `magpie-pi-desktop-app`. +- Tested with Magpie 0.1.4267 and Pi-Desktop 0.22.0 on Windows 11. + +## 中文说明 + +Pi-Desktop 的模型服务存放在只有它自己的宿主进程能写的数据库里,Magpie 没法像接 Codex、Pi 那样直接改配置文件。但 Pi-Desktop 会从磁盘读插件文件夹:作为"本地插件"加载的文件夹,它每次启动都重新读里面的 `manifest.json`。本包让 Magpie 来维护这个文件。 + +- **Magpie 代理 `pi-desktop-app`**(仅连接;`pi-desktop` 是 Magpie 自己会话功能的 id,插件不能用):Pi-Desktop 在 Agent 页有自己的一行,有独立的网关密钥 `magpie-pi-desktop-app`,用量和路由规则按它归属,可以用 `magpie visible pi-desktop-app …` 控制它看到的模型。 +- **插件文件夹 `~/.config/magpie-pi-desktop/plugin`**:这一行开着时由 Magpie 写。里面的 `manifest.json` 是一个 Pi-Desktop 插件(`local.magpie-gateway`),声明模型服务 *Magpie*,指向网关,带上 Magpie 给 Pi-Desktop 的全部模型和每个模型的推理等级。Magpie 的模型变了,它会重写这个文件。文件夹里没有代码,权限只有 `provider.register`。密钥由 Pi-Desktop 自己保存。 + +### 接入步骤 +1. Magpie:`magpie plugin add <本文件夹>`,或在 插件 › 发现 › 已有想装的? 选本文件夹后点"安装"(发布后用 `magpie plugin add @magpie-community/agent-pi-desktop`;不要用裸名 `pi-desktop`,那是 npm 上别人的包)。在 插件 › 已安装 里,它这一行下面应写着"把 Pi-Desktop 加到 Agent 页",没有红字。然后在 Agent 页接入 Pi-Desktop(或 `magpie pi-desktop-app provider magpie`)。 +2. Pi-Desktop(只做一次):扩展 › ⋯(更多操作)› 加载本地插件,选用户文件夹下的 `.config\magpie-pi-desktop\plugin`,在确认框里点"加载插件"。*Magpie Gateway* 出现并带"本地"标记,服务卡片马上就有。 +3. 设置 › AI 服务 › 添加服务 › *Magpie*:API 密钥填 `magpie-pi-desktop-app`,点"保存服务"。有 *Magpie 2* 等更多卡片时,每张都填一次;添加服务里只列出还没存密钥的。 +4. 在对话里选 Magpie 模型。用 `node scripts/doctor.mjs` 体检,它不输出任何秘密,只显示公开的密钥名 `magpie-pi-desktop-app`。 + +每一步的预期结果和排错表,见源码仓库的 `docs/04-详细接入教程.md`。 + +### Magpie 的模型变了之后 +Magpie 这边不用做任何事:这一行是已连接时,增删模型、改可见模型、换端口,它都会重写 manifest。Pi-Desktop 在启动时读 manifest 里的服务和模型,所以下次打开 Pi-Desktop 就是新清单。不想重启的话,在 扩展 里把 *Magpie Gateway* 禁用再启用(这一行的 ⋯ 菜单)。已存的密钥保留。 + +做不到即时生效:Pi-Desktop 0.22.0 只在启动、启用插件、加载本地插件时读插件的服务列表,也没有给插件修改服务列表的接口。Pi-Desktop 开着时会发现文件变了并提示 *Reloaded Magpie Gateway*,这只是重新加载插件代码,不更新模型清单;行菜单里的"重载插件"也一样。 + +### 注意 +- 推理等级:Pi-Desktop 0.22.0 只对插件声明的模型带推理等级,自己发现的模型七个档位全可选、默认 off,所以 manifest 要声明模型。每个模型默认 high 或它有的最接近的一档,和 Magpie 给 Codex 的选法一样。Magpie 没给推理等级的模型保持通用设置。Magpie 的 `ultra` 在 Pi-Desktop 里没有对应档位,不带过去。 +- 每张卡片最多 64 个模型,超过时分成 *Magpie*、*Magpie 2*…,同一供应商的模型尽量放一起,每张卡片各填一次密钥,以后新出现的卡片(*Magpie 3*)到时再填。清单变化后模型可能换卡片,用着它的对话要重新选模型;`magpie visible pi-desktop-app …` 可以把清单减到 64 个以内。 +- 从 0.1.x(模型清单固定的 `.piplug`)升级:在 Magpie 把本插件停用再启用,重新接入这一行,然后做第 2 步。加载文件夹会替换原来装的包,已存的密钥保留。 +- 在 Magpie 断开这一行会清空 manifest,Pi-Desktop 保留最后读到的卡片;要移除它们,请在 Pi-Desktop 扩展页卸载 *Magpie Gateway*。 +- 停用或移除本 Magpie 插件时,Magpie 会先自动断开这个代理。 +- 密钥填错不会报错:本机网关接受任何密钥,只是用量会记到别的名下。请填 `magpie-pi-desktop-app`。 diff --git a/packages/pi-desktop/package.json b/packages/pi-desktop/package.json new file mode 100644 index 0000000..fdadcca --- /dev/null +++ b/packages/pi-desktop/package.json @@ -0,0 +1,26 @@ +{ + "name": "@magpie-community/agent-pi-desktop", + "version": "0.2.0", + "description": "Pi-Desktop as a connect-only Magpie agent: Magpie keeps a Pi-Desktop plugin folder that declares it as a model provider, with its current models and their thinking levels", + "type": "module", + "files": [ + "pi-desktop.agent.js", + "scripts/doctor.mjs", + "README.md" + ], + "keywords": ["magpie", "magpie-agent", "pi-desktop", "pi", "llm-gateway"], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/pi-desktop" + }, + "scripts": { + "test": "bun test pi-desktop.test.mjs pi-plugin.test.mjs", + "doctor": "node scripts/doctor.mjs" + }, + "magpie": { + "agent": "./pi-desktop.agent.js", + "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMyYjNhNjciLz48cGF0aCBkPSJNMTQgMjBoMzZNMjUgMjB2MjZNMzkgMjB2MjBjMCA0IDIgNiA2IDYiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI2IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1IiBmaWxsPSIjZjVhNjIzIi8+PC9zdmc+" + } +} diff --git a/packages/pi-desktop/pi-desktop.agent.js b/packages/pi-desktop/pi-desktop.agent.js new file mode 100644 index 0000000..730e44e --- /dev/null +++ b/packages/pi-desktop/pi-desktop.agent.js @@ -0,0 +1,132 @@ +// Pi-Desktop keeps its providers in a database only its own host process writes, +// so Magpie cannot wire it by editing a settings file. What Pi-Desktop does read +// from disk is a plugin folder: loaded as a local plugin, its manifest.json is +// read again every time Pi-Desktop starts. So the file this row keeps current is +// such a manifest. It declares Magpie as a provider with the models Magpie offers +// Pi-Desktop and their thinking levels, and Magpie rewrites it when they change. +export const agent = { + // "pi-desktop" is taken: Magpie's own Sessions reader uses it, and own ids are refused. + id: "pi-desktop-app", + name: "Pi-Desktop", + icon: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMyYjNhNjciLz48cGF0aCBkPSJNMTQgMjBoMzZNMjUgMjB2MjZNMzkgMjB2MjBjMCA0IDIgNiA2IDYiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI2IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1IiBmaWxsPSIjZjVhNjIzIi8+PC9zdmc+", + dir: "~/.pi-desktop", + config: "~/.config/magpie-pi-desktop/plugin/manifest.json", + format: "json", + notice: "In Pi-Desktop: Extensions › More actions › Load local plugin, choose the folder .config/magpie-pi-desktop/plugin in your user folder, then Settings › AI providers › Add provider › Magpie with the key magpie-pi-desktop-app. Pi-Desktop picks up model changes when it starts. 在 Pi-Desktop 的 扩展 › 更多操作 › 加载本地插件 选用户文件夹下的 .config/magpie-pi-desktop/plugin,再到 设置 › AI 服务 › 添加服务 选 Magpie,填密钥 magpie-pi-desktop-app。模型有变化时,Pi-Desktop 重启后生效。", +} + +// Pi-Desktop's thinking levels; Magpie's "none" is Pi-Desktop's "off", and its +// "ultra" has no Pi-Desktop level. +export const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] +// Pi-Desktop's host refuses a plugin provider that declares more models than this. +export const MAX_MODELS = 64 + +// The level a chat starts on: `preferred` when the model has it, else the nearest +// level above, else the nearest below. Magpie picks Codex's default the same way. +export function defaultLevel(levels, preferred) { + const at = LEVELS.indexOf(preferred || "high") + for (let i = at; i < LEVELS.length; i++) if (levels.indexOf(LEVELS[i]) >= 0) return LEVELS[i] + for (let i = at - 1; i >= 0; i--) if (levels.indexOf(LEVELS[i]) >= 0) return LEVELS[i] + return undefined +} + +// One model as a Pi-Desktop manifest declares it. Pi-Desktop takes thinking levels +// only from declared models: one it discovers from the gateway gets every level +// and starts on "off", which is also what a model declared without levels gets. +function modelEntry(model, preferred) { + const entry = { id: model.id, name: model.name || model.id } + if (model.context > 0) entry.contextWindow = model.context + if (model.output > 0) entry.maxTokens = model.context > 0 ? Math.min(model.output, model.context) : model.output + if (model.images) entry.supportsImages = true + const efforts = model.efforts || [] + const levels = [] + for (let i = 0; i < LEVELS.length; i++) if (efforts.indexOf(LEVELS[i] === "off" ? "none" : LEVELS[i]) >= 0) levels.push(LEVELS[i]) + if (levels.length > 0) { + entry.thinkingLevels = levels + entry.defaultThinkingLevel = defaultLevel(levels, preferred) + } + return entry +} + +export function declaredModels(models, preferred) { + const seen = {}, out = [] + for (const model of models || []) { + if (!model || typeof model.id !== "string" || !model.id || seen[model.id]) continue + seen[model.id] = true + out.push(modelEntry(model, preferred)) + } + return out +} + +const vendorOf = (model) => model.id.split("/")[0] + +// Cuts the list into providers of at most `max` models, keeping one vendor's +// models (the id up to the first "/") together when they fit. +export function splitModels(models, max) { + const limit = max || MAX_MODELS + const chunks = [[]] + let i = 0 + while (i < models.length) { + let j = i + 1 + while (j < models.length && vendorOf(models[j]) === vendorOf(models[i])) j++ + let last = chunks[chunks.length - 1] + if (last.length > 0 && last.length + (j - i) > limit) { last = []; chunks.push(last) } + for (; i < j; i++) { + if (last.length === limit) { last = []; chunks.push(last) } + last.push(models[i]) + } + } + return chunks +} + +// The provider cards: "magpie" first, so the key Pi-Desktop already holds for it +// stays, then magpie-2, …. With no models there is one card without any, and +// Pi-Desktop lists the gateway's models itself. +export function providers(baseUrl, models) { + const chunks = splitModels(models || []) + const out = [] + for (let i = 0; i < chunks.length; i++) { + out.push({ + id: i ? "magpie-" + (i + 1) : "magpie", + name: i ? "Magpie " + (i + 1) : "Magpie", + category: { en: "Local gateway", "zh-CN": "本地网关" }, + description: { + en: "Models from the Magpie gateway on this computer. Enter the key magpie-pi-desktop-app.", + "zh-CN": "本机 Magpie 网关提供的模型。密钥填 magpie-pi-desktop-app。", + }, + baseUrl, + apiStyle: "chat_completions", + authKind: "api_key", + models: chunks[i], + }) + } + return out +} + +// The whole manifest. `main` names the manifest itself: Pi-Desktop wants an entry +// file, a JSON file loads as a module with no hooks, and so the folder Magpie +// keeps needs no second file and runs no code. +export function manifest(baseUrl, models) { + return { + schemaVersion: 1, + id: "local.magpie-gateway", + name: "Magpie Gateway", + version: "0.2.0", + description: "Adds the local Magpie gateway as a model provider: every model Magpie offers Pi-Desktop, with its multi-vendor routing, groups and fallback. 把本机 Magpie 网关加为模型服务。", + author: "magpie-community", + homepage: "https://github.com/magpie-community/plugins/tree/main/packages/pi-desktop", + main: "manifest.json", + contributes: { providers: providers(baseUrl, models) }, + permissions: ["provider.register"], + engines: { piDesktop: ">=0.22.0" }, + } +} + +// Every top-level key of the manifest, plus "magpie": the gateway and the key +// this row is known by (Pi-Desktop ignores keys it does not know). Switching the +// row off takes all of them out again. +export function connect({ gateway, models }) { + const out = manifest(gateway.v1, declaredModels(models)) + out.magpie = { baseUrl: gateway.v1, apiKey: gateway.key, apiStyle: "chat_completions" } + return out +} diff --git a/packages/pi-desktop/pi-desktop.test.mjs b/packages/pi-desktop/pi-desktop.test.mjs new file mode 100644 index 0000000..d783b94 --- /dev/null +++ b/packages/pi-desktop/pi-desktop.test.mjs @@ -0,0 +1,110 @@ +import { expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { agent, connect } from "./pi-desktop.agent.js" + +const gateway = { url: "http://127.0.0.1:3499", v1: "http://127.0.0.1:3499/v1", key: `magpie-${agent.id}` } +const model = { id: "relay/vendor/model:variant", name: "Example", context: 262144, output: 32768, images: true, efforts: ["none", "low", "high", "max", "ultra"] } +const output = (models = [model], gw = gateway) => connect({ gateway: gw, models, agent: { id: agent.id, config: "/synthetic/.config/magpie-pi-desktop/plugin/manifest.json" } }) +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// Magpie 0.1.2404's own agents, as `magpie ` lists them, plus "pi-desktop", +// which it refuses too ("agent id "pi-desktop" is magpie's own agent's"). +const magpieOwnIds = [ + "agy", "aionui", "air", "alma", "ante", "aside", "astrbot", "atomcode", "cindy", "claude", "claude-desktop", + "claude-science", "cline", "codebuddy", "codex", "commandcode", "copilot", "copilot-jetbrains", "crush", "cursor", + "cursor-local", "deveco", "devin", "droid", "dsh", "empryo", "fx", "gemini", "goose", "grok", "grok-app", "hanako", + "hermes", "jcode", "kimi", "kirocrew", "lody", "mimocode", "minimax-code", "morph", "mothx", "muse", "newmax", "omo", + "omp", "openchamber", "openclaw", "opencode", "openpencil", "pencil", "penguin", "pi", "pi-desktop", "prime-agent", + "qoder", "qoder-cn", "qwen", "raycast", "reasonix", "snow", "stepcode", "t3code", "vscode", "vscode-insiders", + "vscodium", "workbuddy", "workbuddy-ai", "zcode", "zed", "zoo-code", +] + +test("registers Pi-Desktop as a connect-only agent detected by its data folder", () => { + expect(agent).toMatchObject({ id: "pi-desktop-app", name: "Pi-Desktop", dir: "~/.pi-desktop", config: "~/.config/magpie-pi-desktop/plugin/manifest.json", format: "json" }) + expect(agent.model).toBeUndefined() + expect(agent.bin).toBeUndefined() + expect(agent.library).toBeUndefined() + expect(agent.notice).toContain(`magpie-${agent.id}`) + expect(agent.icon.startsWith("data:image/svg+xml;base64,")).toBe(true) +}) + +test("uses an id Magpie accepts for a plugin agent", () => { + expect(agent.id).toMatch(/^[a-z0-9._-]+$/) + expect(magpieOwnIds).not.toContain(agent.id) +}) + +test("declares the standard community Agent entry and no host plugin", () => { + expect(pkg.name).toBe("@magpie-community/agent-pi-desktop") + expect(pkg.type).toBe("module") + expect(pkg.magpie.agent).toBe("./pi-desktop.agent.js") + expect(pkg.magpie.icon).toBe(agent.icon) + expect(pkg.main).toBeUndefined() + expect(pkg.dependencies).toBeUndefined() + expect(pkg.scripts.preinstall).toBeUndefined() + expect(pkg.scripts.postinstall).toBeUndefined() + for (const file of pkg.files) expect(() => readFileSync(new URL(`./${file}`, import.meta.url))).not.toThrow() +}) + +test("stays import-free for Magpie's descriptor runtime", () => { + const source = readFileSync(new URL("./pi-desktop.agent.js", import.meta.url), "utf8") + expect(source).not.toMatch(/^\s*import\s/m) + expect(source).not.toMatch(/\brequire\(/) +}) + +test("writes a whole Pi-Desktop manifest, with the gateway and key beside it", () => { + const out = output() + expect(Object.keys(out)).toEqual(["schemaVersion", "id", "name", "version", "description", "author", "homepage", "main", "contributes", "permissions", "engines", "magpie"]) + // No key is a dotted path: Magpie sets each as one top-level key of the file. + for (const key of Object.keys(out)) expect(key).not.toContain(".") + expect(out.magpie).toEqual({ baseUrl: gateway.v1, apiKey: "magpie-pi-desktop-app", apiStyle: "chat_completions" }) + expect(out.version).toBe(pkg.version) + expect(agent.config.endsWith("/manifest.json")).toBe(true) +}) + +test("declares the catalog as Pi-Desktop models, keeping gateway ids", () => { + expect(output().contributes.providers[0].models).toEqual([{ + id: "relay/vendor/model:variant", name: "Example", contextWindow: 262144, maxTokens: 32768, supportsImages: true, + thinkingLevels: ["off", "low", "high", "max"], defaultThinkingLevel: "high", + }]) +}) + +test("drops limits it does not know and caps output at the context window", () => { + const [bare, capped] = output([ + { id: "a/b", context: 0, output: -1, efforts: [] }, + { id: "c/d", name: "D", context: 8192, output: 65536 }, + ]).contributes.providers[0].models + // No levels known: Pi-Desktop keeps its generic settings for the model. + expect(bare).toEqual({ id: "a/b", name: "a/b" }) + expect(capped).toEqual({ id: "c/d", name: "D", contextWindow: 8192, maxTokens: 8192 }) +}) + +test("gives a model that always reasons no off level, and leaves ultra out", () => { + const [entry, top] = output([{ ...model, efforts: ["low", "medium", "high"] }, { ...model, id: "x/top", efforts: ["xhigh", "max", "ultra"] }]).contributes.providers[0].models + expect(entry.thinkingLevels).toEqual(["low", "medium", "high"]) + expect(top.thinkingLevels).toEqual(["xhigh", "max"]) + expect(top.defaultThinkingLevel).toBe("xhigh") +}) + +test("keeps one provider without models for an empty or missing catalog", () => { + for (const out of [output([]), connect({ gateway })]) { + expect(out.contributes.providers).toHaveLength(1) + expect(out.contributes.providers[0]).toMatchObject({ id: "magpie", baseUrl: gateway.v1, models: [] }) + } +}) + +test("skips entries without an id and repeated ids", () => { + const models = output([model, null, { name: "no id" }, { ...model, name: "again" }]).contributes.providers[0].models + expect(models.map((m) => m.name)).toEqual(["Example"]) +}) + +test("reads the gateway on every call and leaves its inputs alone", () => { + const models = [structuredClone(model)] + const before = structuredClone(models) + output(models) + expect(models).toEqual(before) + const other = { url: "http://127.0.0.1:4000", v1: "http://127.0.0.1:4000/v1", key: "magpie-other" } + const out = output([model], other) + expect(out.magpie).toMatchObject({ baseUrl: other.v1, apiKey: other.key }) + expect(out.contributes.providers[0].baseUrl).toBe(other.v1) + expect(JSON.stringify(output())).toBe(JSON.stringify(output())) +}) diff --git a/packages/pi-desktop/pi-plugin.test.mjs b/packages/pi-desktop/pi-plugin.test.mjs new file mode 100644 index 0000000..01b9319 --- /dev/null +++ b/packages/pi-desktop/pi-plugin.test.mjs @@ -0,0 +1,95 @@ +import { expect, test } from "bun:test" +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { createRequire } from "node:module" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { LEVELS, MAX_MODELS, agent, connect, declaredModels, defaultLevel, manifest, providers, splitModels } from "./pi-desktop.agent.js" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) +const gateway = { url: "http://127.0.0.1:3425", v1: "http://127.0.0.1:3425/v1", key: `magpie-${agent.id}` } +const catalog = (count, vendor = (i) => `v${i}`) => Array.from({ length: count }, (_, i) => ({ id: `${vendor(i)}/m${i}`, name: `M${i}`, efforts: ["low", "high"] })) +const built = connect({ gateway, models: catalog(97) }) + +// The rules Pi-Desktop 0.22's validateManifest and its host apply to the fields this manifest uses. +const API_STYLES = ["chat_completions", "opencode_go", "responses", "anthropic_messages", "google_generative_ai", "openai_codex_responses", "pi_messages"] +const localized = (value, max) => typeof value === "string" + ? !!value.trim() && value.length <= max + : ["en", "zh-CN"].every((locale) => typeof value?.[locale] === "string" && !!value[locale].trim() && value[locale].length <= max) + +test("passes Pi-Desktop's manifest rules", () => { + expect(built.schemaVersion).toBe(1) + expect(built.id).toMatch(/^[a-z0-9]+(\.[a-z0-9_-]+)+$/) + expect(built.name.trim()).not.toBe("") + expect(built.version).toMatch(/^\d+\.\d+\.\d+$/) + expect(built.version).toBe(pkg.version) + for (const p of built.contributes.providers) { + expect(p.id).toMatch(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/) + expect(p.name.trim()).not.toBe("") + expect(localized(p.category, 128)).toBe(true) + expect(localized(p.description, 280)).toBe(true) + expect(p.description.en).toContain(gateway.key) + expect(p.description["zh-CN"]).toContain(gateway.key) + expect(p.baseUrl).toBe(gateway.v1) + expect(API_STYLES).toContain(p.apiStyle) + expect(p.authKind).toBe("api_key") + expect(p.models.length).toBeLessThanOrEqual(MAX_MODELS) + for (const m of p.models) { + for (const level of m.thinkingLevels) expect(LEVELS).toContain(level) + expect(m.thinkingLevels).toContain(m.defaultThinkingLevel) + } + } + expect(agent.notice).toContain("Magpie") +}) + +test("asks for provider.register only", () => { + expect(built.permissions).toEqual(["provider.register"]) + expect(built.contributes.agentExtensions).toBeUndefined() + expect(built.fs).toBeUndefined() + expect(built.net).toBeUndefined() + expect(built.ui).toBeUndefined() +}) + +test("needs no file but the manifest, which loads as a module without hooks", () => { + expect(built.main).toBe("manifest.json") + const dir = mkdtempSync(join(tmpdir(), "magpie-pi-manifest-")) + writeFileSync(join(dir, "manifest.json"), JSON.stringify(built, null, 2)) + // What Pi-Desktop's plugin host does with the entry file. + const mod = createRequire(import.meta.url)(join(dir, built.main)) + expect(mod.onLoad).toBeUndefined() + expect(mod.onUnload).toBeUndefined() + expect(mod.onProviderOAuth).toBeUndefined() +}) + +test("starts a chat on high, else the nearest level above, else below", () => { + expect(defaultLevel(["low", "medium", "high", "xhigh", "max"])).toBe("high") + expect(defaultLevel(["xhigh", "max"])).toBe("xhigh") + expect(defaultLevel(["off", "low", "medium"])).toBe("medium") + expect(defaultLevel(["off"])).toBe("off") + expect(defaultLevel([])).toBeUndefined() + expect(defaultLevel(["low", "medium", "high"], "medium")).toBe("medium") + expect(defaultLevel(["low", "high"], "medium")).toBe("high") +}) + +test("splits past Pi-Desktop's 64 models per provider, keeping a vendor together", () => { + const split = (models) => splitModels(declaredModels(models)).map((c) => c.length) + expect(split(catalog(MAX_MODELS))).toEqual([MAX_MODELS]) + // 60 single-model vendors, then a vendor of 10 that would straddle the limit. + expect(split(catalog(70, (i) => (i < 60 ? `v${i}` : "big")))).toEqual([60, 10]) + // One vendor larger than a provider has to be cut. + expect(split(catalog(150, () => "one"))).toEqual([64, 64, 22]) + expect(splitModels([])).toEqual([[]]) +}) + +test("names the cards Magpie, Magpie 2, … and keeps the first one's id", () => { + const cards = built.contributes.providers + // "magpie" is the id whose key Pi-Desktop already holds. + expect(cards.map((p) => [p.id, p.name, p.models.length])).toEqual([["magpie", "Magpie", 64], ["magpie-2", "Magpie 2", 33]]) + expect(cards.flatMap((p) => p.models)).toEqual(declaredModels(catalog(97))) + expect(new Set(cards.flatMap((p) => p.models.map((m) => m.id))).size).toBe(97) + expect(providers(gateway.v1, []).map((p) => p.id)).toEqual(["magpie"]) + expect(manifest(gateway.v1, []).contributes.providers[0].models).toEqual([]) +}) + +test("ships every file it needs", () => { + for (const file of ["pi-desktop.agent.js", "scripts/doctor.mjs", "README.md"]) expect(pkg.files).toContain(file) +}) diff --git a/packages/pi-desktop/scripts/doctor.mjs b/packages/pi-desktop/scripts/doctor.mjs new file mode 100644 index 0000000..80c0324 --- /dev/null +++ b/packages/pi-desktop/scripts/doctor.mjs @@ -0,0 +1,134 @@ +#!/usr/bin/env node +// Read-only check of the Magpie → Pi-Desktop connection. Prints no secrets; reads +// Pi-Desktop's database from a temporary copy that it deletes afterwards. +// node --no-warnings scripts/doctor.mjs (Node 22.5+ for the database check) +import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmdirSync, unlinkSync } from "node:fs" +import { homedir, tmpdir } from "node:os" +import { dirname, join, resolve } from "node:path" +import { LEVELS, MAX_MODELS, agent } from "../pi-desktop.agent.js" + +const KEY = `magpie-${agent.id}` +const PLUGIN_ID = "local.magpie-gateway" +// The manifest Magpie keeps, and the folder Pi-Desktop loads as a local plugin. +const manifestPath = process.env.MAGPIE_PI_DESKTOP_MANIFEST || join(homedir(), agent.config.replace(/^~[\\/]/, "")) +const pluginDir = dirname(manifestPath) +const dataDir = process.env.PI_DESKTOP_DATA_DIR || join(homedir(), ".pi-desktop") +const LOAD = `in Pi-Desktop, Extensions › More actions › Load local plugin, and choose ${pluginDir}` +const RESTART = "quit Pi-Desktop from its tray icon and open it again (or turn Magpie Gateway off and on under Extensions)" +let failed = 0 +const ok = (msg) => console.log(`ok ${msg}`) +const info = (msg) => console.log(`info ${msg}`) +const fail = (msg) => { failed++; console.log(`FAIL ${msg}`) } +// Only this agent's own gateway key name is printed; it is public (the manifest says it too). +const keyLabel = (key) => (key === KEY ? key : key ? "(another key, not shown)" : "(none)") +const samePath = (a, b) => resolve(a).toLowerCase() === resolve(b).toLowerCase() + +// 1. Magpie's side: the manifest connect() writes while Pi-Desktop's row is on. +let manifest = null +try { manifest = JSON.parse(readFileSync(manifestPath, "utf8")) } catch {} +const bridge = manifest?.magpie +const providers = Array.isArray(manifest?.contributes?.providers) ? manifest.contributes.providers.map((p) => ({ ...p, models: p.models || [] })) : [] +const declared = providers.flatMap((p) => p.models) +if (!bridge?.baseUrl) { + manifest = null + fail(`Magpie is not keeping ${manifestPath}: turn Pi-Desktop on in Magpie's Agents page, or run: magpie ${agent.id} provider magpie`) +} else { + ok(`Magpie keeps ${manifestPath}: ${bridge.baseUrl}, key ${keyLabel(bridge.apiKey)}, ${declared.length} models in ${providers.map((p) => `${p.name} (${p.models.length})`).join(", ")}`) + const problems = manifestProblems() + if (problems.length) fail(`Pi-Desktop will not accept the manifest: ${problems.slice(0, 3).join("; ")}`) + else ok(`manifest is one Pi-Desktop accepts; ${declared.filter((m) => m.defaultThinkingLevel).length} models start on a thinking level of their own, ${declared.filter((m) => !m.thinkingLevels).length} have none from Magpie and start on off`) +} + +// The rules Pi-Desktop 0.22's host applies to what this manifest uses. +function manifestProblems() { + const out = [] + if (manifest.id !== PLUGIN_ID) out.push(`id is ${manifest.id}`) + if (typeof manifest.main !== "string" || !existsSync(join(pluginDir, manifest.main))) out.push(`main entry ${manifest.main} is missing`) + if (!manifest.permissions?.includes("provider.register")) out.push("provider.register is not requested") + if (providers.length === 0) out.push("no provider") + const seen = new Set() + for (const p of providers) { + if (p.models.length > MAX_MODELS) out.push(`${p.name} declares ${p.models.length} models, more than ${MAX_MODELS}`) + if (p.baseUrl !== bridge.baseUrl) out.push(`${p.name} points at ${p.baseUrl}`) + for (const m of p.models) { + if (seen.has(m.id)) out.push(`${m.id} is declared twice`) + seen.add(m.id) + if (m.thinkingLevels?.some((level) => !LEVELS.includes(level))) out.push(`${m.id} has a level Pi-Desktop does not know`) + if (m.defaultThinkingLevel && !m.thinkingLevels?.includes(m.defaultThinkingLevel)) out.push(`${m.id} starts on a level it does not have`) + } + } + return out +} + +// 2. The gateway serves Pi-Desktop the models the manifest declares. +if (manifest) { + try { + const res = await fetch(`${bridge.baseUrl}/models`, { headers: { authorization: `Bearer ${bridge.apiKey}` }, signal: AbortSignal.timeout(8000) }) + const body = await res.json().catch(() => null) + const list = Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : [] + const served = new Set(list.map((m) => m?.id ?? m?.slug).filter((id) => typeof id === "string" && id)) + if (!res.ok) fail(`gateway ${bridge.baseUrl}/models answered HTTP ${res.status}`) + else if (served.size === 0) fail(`gateway lists no models for Pi-Desktop: check magpie visible ${agent.id}`) + else { + const ids = new Set(declared.map((m) => m.id)) + const added = [...served].filter((id) => !ids.has(id)), gone = [...ids].filter((id) => !served.has(id)) + if (added.length + gone.length === 0) ok(`gateway serves the same ${served.size} models to Pi-Desktop`) + else info(`gateway serves ${served.size} models, ${added.length} not in the manifest yet and ${gone.length} no longer served${added.length ? ` (e.g. ${added.slice(0, 3).join(", ")})` : ""}; Magpie rewrites the manifest when its models change, so check again in a moment`) + } + } catch (e) { fail(`gateway ${bridge.baseUrl} not reachable: ${e.name}`) } +} + +// 3. Pi-Desktop's side: it has to load the folder Magpie keeps, not a copy of it. +let live = false +if (!existsSync(dataDir)) fail(`no Pi-Desktop data folder at ${dataDir} (set PI_DESKTOP_DATA_DIR if it moved)`) +else { + let entry + try { + const registry = JSON.parse(readFileSync(join(dataDir, "plugins", "registry.json"), "utf8")) + entry = (Array.isArray(registry) ? registry : registry.plugins || []).find((p) => p?.id === PLUGIN_ID) + } catch {} + if (!entry) fail(`Pi-Desktop has no ${PLUGIN_ID} plugin: ${LOAD}`) + else if (entry.source !== "dev" || !entry.path || !samePath(entry.path, pluginDir)) { + fail(`Pi-Desktop uses its own copy of the plugin (${entry.version}, at ${entry.path}), so it does not follow Magpie's models: ${LOAD}. The saved key stays.`) + } else if (!entry.enabled) fail("the Magpie Gateway plugin is off: turn it on in Pi-Desktop's Extensions") + else { live = true; ok(`Pi-Desktop loads Magpie Gateway from ${entry.path} and reads it again each time it starts`) } +} + +if (manifest) await checkProviderRows() +console.log(failed ? `\n${failed} problem(s)` : "\nall checks passed") +process.exitCode = failed ? 1 : 0 + +// 4. The provider rows Pi-Desktop's host made from the manifest. +async function checkProviderRows() { + const db = join(dataDir, "pi.sqlite") + if (!existsSync(db)) return info("no pi.sqlite yet; open Pi-Desktop once") + let DatabaseSync + try { ({ DatabaseSync } = await import("node:sqlite")) } catch { return info("provider rows not checked: needs Node 22.5+ (node:sqlite)") } + const dir = mkdtempSync(join(tmpdir(), "magpie-pi-doctor-")) + const copy = join(dir, "pi.sqlite") + let conn + try { + for (const suffix of ["", "-wal", "-shm"]) if (existsSync(db + suffix)) copyFileSync(db + suffix, copy + suffix) + conn = new DatabaseSync(copy, { readOnly: true }) + const find = conn.prepare("SELECT enabled, base_url, secret_ref, config_json FROM providers WHERE id = ?") + const hasSecret = conn.prepare("SELECT 1 FROM secrets_meta WHERE secret_ref = ?") + for (const p of providers) { + const row = find.get(`plugin:${PLUGIN_ID}:${p.id}`) + if (!row) { fail(`Pi-Desktop has no ${p.name} provider yet: ${live ? RESTART : LOAD}`); continue } + let models = [] + try { models = JSON.parse(row.config_json).models || [] } catch {} + const same = models.length === p.models.length && p.models.every((m, i) => models[i].id === m.id && (models[i].defaultThinkingLevel ?? undefined) === m.defaultThinkingLevel) + if (!row.enabled) fail(`the ${p.name} provider is disabled: turn the Magpie Gateway plugin on in Pi-Desktop's Extensions`) + else if (!same) fail(`Pi-Desktop's ${p.name} has an older model list (${models.length} models, Magpie now offers ${p.models.length} there): ${live ? RESTART : LOAD}`) + else if (!(row.secret_ref && hasSecret.get(row.secret_ref))) fail(`no key saved for ${p.name}: Settings › AI providers › Add provider › ${p.name}, enter ${KEY} and save`) + else ok(`${p.name} ready at ${row.base_url}: ${models.length} models, as Magpie offers them`) + } + const known = new Set(providers.map((p) => `plugin:${PLUGIN_ID}:${p.id}`)) + const extra = conn.prepare("SELECT id FROM providers WHERE id LIKE ?").all(`plugin:${PLUGIN_ID}:%`).filter((row) => !known.has(row.id)) + if (extra.length) info(`Pi-Desktop still has ${extra.map((row) => row.id.split(":").pop()).join(", ")} from an older model list; it goes when Pi-Desktop starts again`) + } finally { + try { conn?.close() } catch {} + for (const suffix of ["-shm", "-wal", ""]) { try { unlinkSync(copy + suffix) } catch {} } + try { rmdirSync(dir) } catch {} + } +} diff --git a/registry.json b/registry.json index 088b2bf..7ad47f4 100644 --- a/registry.json +++ b/registry.json @@ -133,6 +133,8 @@ "summary": { "en": "Tuanjie Cowork (codely) on magpie's Agents page: pick one of magpie's models and Cowork chats with it, on the subscriptions magpie already holds.", "zh": "把团结 Cowork(codely)加到 magpie 的 Agent 页:给它选一个 magpie 的模型,它聊天就走那个模型,用的是 magpie 里已登录的那些订阅的额度。" } }, { "package": "@magpie-community/agent-opencodereview", "name": "Open Code Review", "kind": "agent", "community": true, "summary": { "en": "Open Code Review (Alibaba's ocr CLI) on magpie's Agents page: pick one of magpie's models and ocr review / ocr scan use it, read from the config on the next run.", "zh": "把 Open Code Review(阿里巴巴的 ocr CLI)加到 magpie 的 Agent 页:给它选 magpie 的模型,下一次 ocr review / ocr scan 即从配置中读到并生效。" } }, + { "package": "@magpie-community/agent-pi-desktop", "name": "Pi-Desktop", "kind": "agent", "community": true, + "summary": { "en": "Pi-Desktop on magpie's Agents page: magpie keeps a Pi-Desktop plugin folder that adds it as a model provider, with its current models and their thinking levels. Pi-Desktop picks up model changes when it starts.", "zh": "把 Pi-Desktop 加到 magpie 的 Agent 页:magpie 维护一个 Pi-Desktop 插件文件夹,把自己加为模型服务,带上当前模型和推理等级;模型有变化时,Pi-Desktop 重启后生效。" } }, { "package": "@magpie-community/agent-junie", "name": "Junie CLI", "kind": "agent", "community": true, "icon": "https://junie.jetbrains.com/favicons/favicon.svg", "summary": { "en": "An explicit seed copies Magpie's full model catalog into Junie CLI and uses Magpie's selected model as the launch default, without LiteLLM. Native ECO is unavailable for custom profiles in Junie 3893.6.", "zh": "手动 seed 向 Junie CLI 同步全部模型,并将 Magpie 所选模型设为启动默认模型,无需 LiteLLM。Junie 3893.6 的自定义 profile 不支持原生 ECO。" } },