chat: Magic_zero's magpie-chat page, as published at Magiczerowxy/magpie-chat 15de02d

The files its package.json ships, unchanged, from
https://github.com/Magiczerowxy/magpie-chat at 15de02d (0.1.18). The
vendored KaTeX is katex@0.16.11's dist, byte for byte (checked against
npm's tarball). Not published from this commit: the next ones close the
local service to other pages and fit it to the repo.

Co-authored-by: Magiczerowxy <magiczerowxy@users.noreply.github.com>
This commit is contained in:
yetone
2026-10-29 09:01:47 +08:00
co-authored by Magiczerowxy
parent f968917875
commit 4193f7410c
42 changed files with 5686 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Magiczerowxy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+167
View File
@@ -0,0 +1,167 @@
# magpie-chat
**在 magpie 窗口里加一个「对话」页面。** 用 magpie 已经接好的模型、指令、技能和 MCP 服务器聊天,不用再开一个 Agent。
**A chat page inside magpie's window.** Talk with magpie's own models, instructions, skills and MCP servers — no second agent needed.
[![版本](https://img.shields.io/badge/version-0.1.6-blue)](https://github.com/Magiczerowxy/magpie-chat)
[![许可](https://img.shields.io/badge/license-MIT-green)](LICENSE)
---
## 中文
### 功能
- **一个页面**。装好后侧栏「插件」分组里出现「对话」。
- **用 magpie 的模型**。模型列表来自网关 `/v1/models`,切换即时生效;有推理档位的模型会给出对应的思考强度选项。
- **用 magpie 的配置**。右侧栏里勾选 `~/.config/magpie/library/` 的指令与技能(拼进 system prompt)、勾选 MCP 服务器(工具以 `tool_calls` 真正执行)。
- **多模态**。左下角「+」选图片或文件,也可以直接把文件拖进页面,或粘贴剪贴板里的图片。图片以 `image_url` 交给模型,气泡里显示缩略图、点开看大图。
- **流式输出**。思考过程边收边展开,输出结束后自动收起;正文逐字出现。
- **公式**。`$…$`、`$$…$$`、`\(…\)`、`\[…\]` 由本地 KaTeX 渲染,随包打包,不连 CDN。
- **对话留存**。存在 magpie 配置目录的 `magpie-chat/conversations/`;每条可以置顶或删除。
- **和 magpie 同一个样子**。配色与字体取自 magpie 自己的设计令牌,切换主题时对话页跟着变。
- **可调布局**。右侧栏「布局」里两个滑条:会话区宽度(100% 即铺满,最窄 560px)、输入框宽度;左右两侧栏都能拖拽调宽、也都能收起。
- **代码折叠**。一条消息里有多段代码时只展开最后一段,其余收起。
### 截图
在 magpie 窗口里的一次真实对话:公式由本地 KaTeX 渲染,表格正常排版,右侧设置栏可以调会话区与输入框宽度。
![在 magpie 窗口里的对话](screenshots/23-math-and-layout.png)
### 安装
```powershell
magpie plugin add Magiczerowxy/magpie-chat
```
或者在应用里:**插件 → 发现 → 非官方插件 · GitHub**,搜索 `magpie-chat` 后点「安装」。
装好后侧栏「插件」里点「对话」即可。
### 没有登录,也没有账号
这个插件**不注册供应商、不需要登录、不保存任何凭据**。它复用 magpie 自己已经配好的模型和额度,请求全部由 magpie 的网关发出,所以用量统计与故障切换和 Agent 一致。
它只保存你自己的东西,都在 magpie 配置目录下:
```
~/.config/magpie/magpie-chat/
├── settings.json 模型、思考强度、系统提示词、勾选的指令/技能/MCP、窗口布局
└── conversations/ 每个对话一个 JSON
```
### 它怎么工作
magpie 的插件页面跑在 `sandbox="allow-scripts"` 的框架里:没有网络权限、不能内嵌框架、不能用存储,唯一允许的联网动作是把自身导航到别处。所以这个插件是两层的:
1. `page/index.html` 是 magpie 托管的「带路页」,读窗口主题后 `location.replace` 到本地服务。
2. `index.mjs` 作为 OpenCode v1 插件被 magpie 的 Bun 宿主加载,加载时启动那个本地服务(`127.0.0.1:3477`)。
3. `lib/server.mjs` 提供 `/api/*` 并把聊天请求转发给 magpie 网关;`chat/` 是真正的界面。
服务只监听回环地址,并拒绝非同源请求(只接受 opaque 的 `Origin: null` 与自身 origin),任意网页都无法借它消耗额度。
### 打不开怎么办
正常情况下装好、重启 magpie,打开「对话」就能用(干净环境实测 397ms 服务就绪)。
如果看到这个页面卡住或「127.0.0.1 拒绝连接」:
1. 先看 `magpie plugin` 的输出,有没有插件在反复报登录失败 / 401。
宿主加载插件是排队走的,前面卡住会拖到后面的页面插件。
2. 把一直报错的插件停掉:`magpie plugin off <那个插件>`
3. 还不行就用独立启动兜底:双击插件目录里的 `start-server.cmd`
(或 `start-server.vbs` 静默启动),再用 `install-autostart.cmd` 设成开机自启。
细节见 [SERVE.md](SERVE.md)。
### 已知限制
- MCP 实现了 Streamable HTTP 与 stdio,不含旧版 GET SSE 长连接与断线重连。
- 图片以 base64 内联发送,单图上限 24MB;对话很长时请求体也会变大。
- 供应商图标:magpie 的内置图标编在它自己的二进制里,取不到时服务端会画一个首字母 SVG。
- 工具调用最多 8 轮。
---
## English
### What it does
- **One page.** Once installed, a **Chat** page appears under Plugins in the sidebar.
- **Uses magpie's own models.** The model list comes from the gateway's `/v1/models`; switching takes effect immediately, and models with reasoning levels get a thinking-effort picker.
- **Uses magpie's own library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt) and MCP servers (their tools run as real `tool_calls`).
- **Multimodal.** Pick images or files with the "+" button, drop files anywhere on the page, or paste an image. Images go to the model as `image_url`; thumbnails appear in the bubble and open full size.
- **Streaming.** Reasoning unfolds while it arrives and collapses automatically when the answer is done; the reply streams in.
- **Math.** `$…$`, `$$…$$`, `\(…\)` and `\[…\]` render through a bundled KaTeX — no CDN.
- **Conversations persist.** Stored under `magpie-chat/conversations/` in magpie's config directory; each can be pinned or deleted.
- **Looks like magpie.** Colors and fonts come from magpie's own design tokens, so the page follows the window theme.
- **Adjustable layout.** Two sliders under Layout: conversation width (100% fills the pane, never narrower than 560px) and composer width. Both sidebars can be dragged and collapsed.
- **Collapsible code.** When a reply has several code blocks, only the last one is expanded.
### Screenshot
A real conversation inside magpie's window: math rendered by the bundled KaTeX, tables laid out normally, and the settings sidebar on the right for adjusting conversation and composer width.
![Chat inside magpie's window](screenshots/23-math-and-layout.png)
### Install
```powershell
magpie plugin add Magiczerowxy/magpie-chat
```
Or in the app: **Plugins → Discover → Unofficial · GitHub**, search `magpie-chat`, click Install.
Then open **Chat** under Plugins in the sidebar.
### No sign-in, no account
This plugin **registers no provider, asks for no login, and stores no credentials**. It reuses whatever magpie itself is already signed in to; every request goes out through magpie's gateway, so usage and failover match the agent exactly.
What it does store is only yours, all under magpie's config directory:
```
~/.config/magpie/magpie-chat/
├── settings.json model, effort, system prompt, ticked instructions/skills/MCP, layout
└── conversations/ one JSON per conversation
```
### How it works
magpie's plugin pages run in a `sandbox="allow-scripts"` frame: no network, no nested frames, no storage. The only way out is to navigate itself somewhere else. So this plugin is two layers:
1. `page/index.html` is a small launcher hosted by magpie; it reads the window theme and `location.replace`s to the local service.
2. `index.mjs` is loaded as an OpenCode v1 plugin by magpie's Bun host, and starts that local service (`127.0.0.1:3477`).
3. `lib/server.mjs` serves `/api/*` and forwards chat requests to magpie's gateway; `chat/` is the real UI.
The service binds loopback only and refuses any request whose Origin is neither opaque `null` (the sandboxed frame) nor its own, so no web page can borrow it to spend your quota.
### Known limits
- MCP covers Streamable HTTP and stdio; no legacy GET SSE stream or reconnect.
- Images are sent inline as base64, 24MB per image; long conversations make bigger requests.
- Provider icons live inside magpie's own binary; when one can't be read the server draws a letter badge.
- At most 8 tool-call rounds.
---
## 目录 / Layout
```
index.mjs 插件入口(启动本地服务) / plugin entry, starts the local service
page/ 带路页,magpie 托管 / launcher page, hosted by magpie
chat/ 对话界面 / the chat UI (index.html, app.js, style.css, vendor/katex)
lib/server.mjs HTTP 路由、SSE、设置与对话持久化 / routes, SSE, settings, persistence
lib/gateway.mjs magpie 网关客户端 / gateway client
lib/library.mjs 读取指令、技能、MCP 与供应商图标 / reads instructions, skills, MCP, icons
lib/mcp.mjs MCP 客户端(Streamable HTTP + stdio)/ MCP client
assets/icon.svg 插件图标 / plugin icon
```
无需构建,仓库里的文件就是 magpie 加载的文件。
No build step: the files in this repo are exactly what magpie loads.
## 许可 / License
MIT
+45
View File
@@ -0,0 +1,45 @@
## 独立启动(不依赖 magpie 宿主)
这个插件的对话界面需要一个本地服务转发请求。默认由 magpie 的插件宿主在加载
`index.mjs` 时启动它。但插件宿主会被其他插件拖慢、可能起不来,
这时候可以用独立进程兜底。
### 三种启动方式
| 方式 | 做法 | 适用 |
|---|---|---|
| 自动 | 什么都不做,magpie 加载插件时自己起 | 正常情况 |
| 双击 | 运行 `start-server.cmd` | 插件没被加载时 |
| 静默 | 运行 `start-server.vbs` | 不想看黑窗口 |
服务只会在 3477/3478/3479/3480 里挑一个空闲端口;如果已经有一个在跑,
再启动会直接提示并退出,不会产生两个实例抢同一份设置。
### 开机自启
双击 `install-autostart.cmd`,它会在「启动」文件夹放一个快捷方式,
以后开机自动在后台起服务。
手动办法:按 `Win+R` 输入 `shell:startup`,把 `start-server.vbs` 的快捷方式拖进去。
### 为什么带路页是"直接跳"而不是"先探测"
页面的 CSP 是 `connect-src 'none'` —— fetch、XHR、WebSocket 全被禁止,
连 `mode: "no-cors"` 的请求都会被直接拒绝。所以「先探一下服务在不在再决定跳不跳」
这条路根本走不通:探测永远失败,页面会永远停在等待状态(这个坑我踩过)。
唯一可行的是直接 `location.replace` 跳过去。
### 已知问题:宿主被其他插件堵住
如果一个 magpie 里装了十几个插件,其中几个登录失败会反复超时重试
(比如账号已经登出的 OAuth 插件、返回 401 的供应商),插件宿主会被拖住,
排在后面的页面插件迟迟加载不上,服务也就起不来,页面就会显示
「127.0.0.1 拒绝连接」。
干净环境下实测:装好后启动 magpie,**397ms** 服务就绪,页面正常打开。
所以遇到这个问题,先看 `magpie plugin` 的输出,把一直报错的插件停掉或移除。
### 为什么不能做成纯静态页面
magpie 的插件页面跑在 `connect-src 'none'` 的沙盒里 —— 页面发不出任何网络请求,
只有 `magpie.read()` 能读少量数据(用量、供应商列表)。
聊天要调模型、要 MCP 工具、要流式输出,这些都必须在页面之外的进程里做。
所以页面只能把自己导航到本地服务,服务必须有人启动。
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="28" fill="#4f46e5"/>
<path d="M30 38h68a8 8 0 0 1 8 8v34a8 8 0 0 1-8 8H60l-16 14v-14h-14a8 8 0 0 1-8-8V46a8 8 0 0 1 8-8z" fill="#fff"/>
<g fill="#4f46e5">
<circle cx="46" cy="58" r="5"/>
<circle cx="64" cy="58" r="5"/>
<circle cx="82" cy="58" r="5"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 406 B

File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>magpie chat</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="vendor/katex/katex.min.css">
<!-- 用户在 magpie 设置里选的字体,由服务端读 settings.json 生成,放在最后好覆盖上面的兜底 -->
<link rel="stylesheet" href="/api/fonts.css">
</head>
<body>
<div class="app" id="app">
<!-- 左侧:会话列表,可拖拽调宽 -->
<aside class="sessions" id="sessions" aria-label="对话列表">
<div class="sessions-head">
<span class="sessions-title">对话</span>
<button class="pill icon" id="newSession" type="button" title="新建对话" aria-label="新建对话">
<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M8 3.6v8.8M3.6 8h8.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
</button>
<button class="pill icon" id="sideToggle" type="button" title="收起侧栏" aria-label="收起侧栏">
<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><rect x="2" y="3" width="12" height="10" rx="2" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M8.4 3v10" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M6.2 6.6L4.6 8l1.6 1.4" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
</div>
<div class="sessions-list" id="sessionList"></div>
<div class="sessions-foot"><span class="hint" id="version"></span></div>
<div class="resizer" id="leftResizer" role="separator" aria-label="调整侧栏宽度" tabindex="0"></div>
</aside>
<!-- 收起后唯一留下的东西:浮在左上角,不占布局 -->
<button class="pill icon dock-toggle" id="dockToggle" type="button" title="展开侧栏" aria-label="展开侧栏">
<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><rect x="2" y="3" width="12" height="10" rx="2" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M8.4 3v10" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M6.6 6.6L8.2 8l-1.6 1.4" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<main class="main">
<!-- 会话区:滚动容器 + 浮层滚动条(和 magpie 自己的做法一致) -->
<div class="stream-wrap" id="streamWrap">
<div class="stream" id="stream"></div>
<div class="scroll-bar" id="scrollBar" hidden aria-hidden="true"><i></i></div>
</div>
<div class="composer" id="composer">
<div class="field" id="dropZone">
<div class="drop-hint" id="dropHint" hidden>松手就把文件放进对话框</div>
<div class="attach-list" id="attachList" hidden></div>
<textarea id="input" rows="1" placeholder="给模型说点什么…(可拖入图片或文件、粘贴图片)" aria-label="输入消息"></textarea>
<div class="field-foot">
<button class="pill icon" id="attachBtn" type="button" title="添加图片或文件" aria-label="添加图片或文件">
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M8 3.4v9.2M3.4 8h9.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
</button>
<input type="file" id="fileInput" multiple hidden>
<span class="spacer"></span>
<button class="pill" id="modelBtn" type="button" aria-haspopup="true" aria-expanded="false" title="选择模型">
<span class="pill-k">模型</span>
<span class="pill-v" id="modelValue">载入中…</span>
<span class="chev"><svg viewBox="0 0 16 16" width="10" height="10" aria-hidden="true"><path d="M4.2 6.4L8 9.8l3.8-3.4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
</button>
<button class="pill" id="effortBtn" type="button" aria-haspopup="true" aria-expanded="false" title="思考强度">
<span class="pill-k">思考</span>
<span class="pill-v" id="effortValue">默认</span>
<span class="chev"><svg viewBox="0 0 16 16" width="10" height="10" aria-hidden="true"><path d="M4.2 6.4L8 9.8l3.8-3.4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
</button>
<button class="send" id="send" type="button" disabled aria-label="发送">
<span class="send-label">发送</span>
<span class="send-stop" aria-hidden="true">&#9632;</span>
</button>
</div>
</div>
<div class="pop" id="modelPop" role="menu" aria-label="模型" hidden></div>
<div class="pop" id="effortPop" role="menu" aria-label="思考强度" hidden></div>
</div>
</main>
<!-- 右侧:设置边栏 -->
<aside class="settings-panel" id="settingsPanel" aria-label="设置" hidden>
<div class="resizer left" id="rightResizer" role="separator" aria-label="调整设置栏宽度" tabindex="0"></div>
<div class="settings-head">
<span class="settings-title">设置</span>
</div>
<div class="settings-body">
<div class="set-sec">
<div class="set-title">系统提示词</div>
<textarea id="systemInput" class="ta" rows="3" placeholder="拼在指令和技能之前,可留空" aria-label="系统提示词"></textarea>
</div>
<div class="set-sec">
<div class="set-title">指令</div>
<div class="set-list" id="instructionList"></div>
</div>
<div class="set-sec">
<div class="set-title">技能</div>
<div class="set-list" id="skillList"></div>
</div>
<div class="set-sec">
<div class="set-title">MCP 服务器</div>
<div class="set-list" id="mcpList"></div>
<div class="set-tools">
<button class="text" id="checkTools" type="button">检查连接</button>
<span class="set-tools-status" id="toolsStatus"></span>
</div>
</div>
<div class="set-sec">
<div class="set-title">布局</div>
<div class="set-row">
<span class="set-label">会话区宽度</span>
<input class="range" id="convWidth" type="range" min="35" max="100" step="1" value="72"
aria-label="会话区宽度" title="拖动调整;最右是铺满">
<output class="set-val" id="convWidthValue">72%</output>
</div>
<div class="set-row">
<span class="set-label">输入框宽度</span>
<input class="range" id="composerWidth" type="range" min="40" max="100" step="1" value="70"
aria-label="输入框宽度" title="拖动调整输入框相对会话区的宽度">
<output class="set-val" id="composerWidthValue">70%</output>
</div>
</div>
<div class="set-sec">
<div class="set-title">生成</div>
<div class="set-row">
<span class="set-label">温度</span>
<input class="range" id="temperature" type="range" min="0" max="2" step="0.05" value="0.7" aria-label="温度">
<output class="set-val" id="tempValue">0.70</output>
</div>
<div class="set-row">
<span class="set-label">最大 token</span>
<input class="num" id="maxTokens" type="number" min="0" step="256" value="0" aria-label="最大 token" title="0 表示不限">
</div>
<div class="set-row">
<span class="set-label">显示思考过程</span>
<button class="switch" id="showReasoning" type="button" role="switch" aria-checked="true" aria-label="显示思考过程"><span class="switch-thumb"></span></button>
</div>
</div>
</div>
</aside>
<!-- 右侧栏的开关:页面右上角那个矩形折叠图标,点它开、也点它关 -->
<button class="pill icon settings-toggle" id="settingsToggle" type="button" title="展开设置栏" aria-label="展开设置栏" aria-expanded="false">
<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><rect x="2" y="3" width="12" height="10" rx="2" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M7.6 3v10" fill="none" stroke="currentColor" stroke-width="1.3"/><path class="ico-in" d="M10.2 6.6L8.6 8l1.6 1.4" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/><path class="ico-out" d="M9.4 6.6L11 8l-1.6 1.4" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<div class="toast" id="toast" role="status" aria-live="polite" hidden><span id="toastText"></span></div>
</div>
<script src="vendor/katex/katex.min.js" defer></script>
<script src="app.js" defer></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
// @magpie-community/page-chat:在 magpie 窗口里加一个「对话」页面。
//
// 两件事:
// 1. 作为 OpenCode v1 插件被 magpie 的 Bun 宿主加载(不注册任何供应商,只借宿主的进程起服务)。
// 2. 在加载时起一个本地 HTTP 服务,窗口里的页面把自己导航过去,界面与 magpie 网关同源直连。
//
// magpie 的插件页面跑在 sandbox="allow-scripts" 的框架里,没有网络权限、不能内嵌框架、
// 不能用存储,唯一能做的联网动作是把自身导航到别处(文档已明说)。所以这里只是一个
// 「带路页」,真正的界面由本插件的服务提供。
import { startServer } from "./lib/server.mjs";
const started = startServer({ configDir: process.env.MAGPIE_CHAT_CONFIG || "", options: {} })
.then((info) => {
console.log(`[page-chat] listening on http://127.0.0.1:${info.port}`);
return info;
})
.catch((err) => {
console.error("[page-chat] could not start:", err?.message || err);
return null;
});
// magpie 会把每个导出的函数当成一个插件调用;用 OpenCode v1 的形式只导出服务器。
export default {
id: "magpie-chat",
server: async (input, options) => {
// 插件被重新启用时,宿主是新的进程;这里无事可做,服务已在加载时起来。
if (options && typeof options === "object") {
await started.catch(() => null);
}
return {};
},
};
+11
View File
@@ -0,0 +1,11 @@
@echo off
chcp 65001 >nul
title 安装 magpie-chat 开机自启
cd /d "%~dp0"
echo.
echo 在「启动」文件夹里放一个快捷方式,
echo 以后开机会自动在后台起对话服务(不弹窗口)。
echo.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install-autostart.ps1"
echo.
pause >nul
+20
View File
@@ -0,0 +1,20 @@
# 在「启动」文件夹里放一个指向 start-server.vbs 的快捷方式
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$vbs = Join-Path $root 'start-server.vbs'
if (-not (Test-Path $vbs)) { Write-Host '找不到 start-server.vbs'; exit 1 }
$startup = [Environment]::GetFolderPath('Startup')
$lnk = Join-Path $startup 'magpie-chat 对话服务.lnk'
$sh = New-Object -ComObject WScript.Shell
$s = $sh.CreateShortcut($lnk)
$s.TargetPath = $vbs
$s.WorkingDirectory = $root
$s.Description = 'magpie 对话页面的本地服务'
$s.Save()
if (Test-Path $lnk) {
Write-Host ''
Write-Host ' 已安装开机自启:' -ForegroundColor Green
Write-Host " $lnk"
Write-Host ' 下次开机会自动在后台启动。想立刻测试就双击 start-server.vbs。'
} else {
Write-Host ' 安装失败,请手动把 start-server.vbs 的快捷方式放进 shell:startup' -ForegroundColor Yellow
}
+148
View File
@@ -0,0 +1,148 @@
// 和 magpie 自己的网关说话:列模型、发 chat completions(流式),带工具循环。
// 网关是 OpenAI 兼容的,所以这里就是标准的 chat completions 客户端。
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
const DEFAULT_GATEWAY = "http://127.0.0.1:3425";
// 候选地址:显式指定的 → 本次 magpie 的 MAGPIE_ADDR → magpie 的老端口
function candidates(opts = {}) {
const out = [];
const push = (u) => {
if (!u) return;
const s = String(u).trim().replace(/\/+$/, "");
if (!/^https?:\/\//.test(s) || out.includes(s)) return;
out.push(s);
};
push(opts.gateway || process.env.MAGPIE_CHAT_GATEWAY);
const addr = process.env.MAGPIE_ADDR;
if (addr && /^[\w.-]+:\d+$/.test(addr)) push("http://" + addr);
push(DEFAULT_GATEWAY);
return out;
}
// 第一个真的答得上 /v1/models 的地址;都没答上就用默认的,让错误原样露出来
let picked = { at: 0, url: "" };
export async function resolveGateway(opts = {}) {
if (picked.url && Date.now() - picked.at < 60e3) return picked.url;
for (const url of candidates(opts)) {
try {
const res = await fetch(url + "/v1/models", {
headers: headers(),
signal: AbortSignal.timeout(2500),
});
if (res.ok) {
picked = { at: Date.now(), url };
return url;
}
} catch {
/* 换下一个 */
}
}
return candidates(opts)[0] || DEFAULT_GATEWAY;
}
export function gatewayURL(opts = {}) {
return picked.url || candidates(opts)[0] || DEFAULT_GATEWAY;
}
// 显式给的 key;没有就问 magpie 自己的 caller-keys.json 要一把
// (magpie web 的网关要 key,桌面版的不要,带着也无害)
let keyCache;
function callerKey() {
if (keyCache !== undefined) return keyCache;
keyCache = process.env.MAGPIE_API_KEY || process.env.MAGPIE_GATEWAY_KEY || "";
if (keyCache) return keyCache;
try {
const dir = process.env.XDG_CONFIG_HOME
? join(process.env.XDG_CONFIG_HOME, "magpie")
: join(homedir(), ".config", "magpie");
const list = JSON.parse(readFileSync(join(dir, "caller-keys.json"), "utf8"));
const hit = Array.isArray(list) ? (list.find((k) => k?.secret && k.name) || list.find((k) => k?.secret)) : null;
if (hit?.secret) keyCache = String(hit.secret);
} catch {
/* 没有这把 key 就算了 */
}
return keyCache;
}
function headers(extra = {}) {
const h = { "content-type": "application/json", ...extra };
const key = callerKey();
if (key) h.authorization = "Bearer " + key;
return h;
}
// 归一化成界面要用的形状:名字、思考档位、上下文、能不能看图
export function normalizeModel(m) {
const id = String(m.id || "");
const efforts = Array.isArray(m.reasoning_levels) && m.reasoning_levels.length
? m.reasoning_levels
: (m.supported_reasoning_levels || []).map((x) => x.effort).filter(Boolean);
const input = m.modalities?.input || m.input_modalities || [];
return {
id,
name: String(m.display_name || m.magpie_label || m.name || id),
provider: id.includes("/") ? id.slice(0, id.indexOf("/")) : "",
// 真正接住请求的供应商:路由组模型的 provider 是 "group",看 owned_by 才对
owner: String(m.owned_by || m.provider_source_id || ""),
reasoning: Boolean(m.reasoning) && efforts.length > 0,
efforts,
context: Number(m.max_input_tokens || m.context_length || m.context_window || 0) || 0,
output: Number(m.max_output_tokens || 0) || 0,
images: Array.isArray(input) ? input.includes("image") : false,
};
}
export async function listModels(opts = {}) {
const url = await resolveGateway(opts) + "/v1/models";
const res = await fetch(url, { headers: headers() });
if (!res.ok) throw new Error(`magpie ${res.status} · ${(await res.text()).slice(0, 300)}`);
const body = await res.json();
const list = Array.isArray(body?.data) ? body.data : Array.isArray(body) ? body : [];
return list.map(normalizeModel).filter((m) => m.id);
}
// 发一次 chat completions(stream 时返回原始 Response,由调用方读 SSE)
export async function chatCompletions(body, { signal, stream = true } = {}, opts = {}) {
const base = await resolveGateway(opts);
return fetch(base + "/v1/chat/completions", {
method: "POST",
headers: headers(),
body: JSON.stringify({ ...body, stream }),
signal,
});
}
// 解析 SSE:逐行 data:,回调每个 JSON
export async function* sseChunks(res) {
if (!res.body) return;
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let i;
while ((i = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, i).replace(/\r$/, "");
buffer = buffer.slice(i + 1);
if (!line || line.startsWith(":")) continue; // 心跳
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (!data || data === "[DONE]") continue;
try {
yield JSON.parse(data);
} catch {
/* 半行,丢掉 */
}
}
}
} finally {
try { reader.releaseLock(); } catch { /* 已关闭 */ }
}
}
+204
View File
@@ -0,0 +1,204 @@
// 读 magpie 自己的资源库:指令、技能、MCP 服务器。
// 这些是用户在 magpie 里配好的东西,插件只是照着用,不改它们。
import { readFile, readdir, stat } from "node:fs/promises";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export function configDir() {
const xdg = process.env.XDG_CONFIG_HOME;
if (xdg) return join(xdg, "magpie");
return join(homedir(), ".config", "magpie");
}
export function libraryDir(dir = configDir()) {
return join(dir, "library");
}
async function readJson(path, fallback) {
try {
return JSON.parse(await readFile(path, "utf8"));
} catch {
return fallback;
}
}
// SKILL.md 的 frontmatter:name 与 description,够用即可
function frontmatter(text) {
const out = { name: "", description: "" };
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
if (!m) return out;
for (const line of m[1].split(/\r?\n/)) {
const i = line.indexOf(":");
if (i < 0) continue;
const k = line.slice(0, i).trim();
const v = line.slice(i + 1).trim().replace(/^["']|["']$/g, "");
if (k === "name") out.name = v;
else if (k === "description") out.description = v;
}
return out;
}
export async function readInstructions(dir = configDir()) {
const root = join(libraryDir(dir), "instructions");
if (!existsSync(root)) return [];
const names = await readdir(root).catch(() => []);
const out = [];
for (const file of names) {
if (!/\.(md|markdown|txt)$/i.test(file)) continue;
const path = join(root, file);
const st = await stat(path).catch(() => null);
if (!st?.isFile()) continue;
out.push({ id: file.replace(/\.(md|markdown|txt)$/i, ""), name: file, size: st.size, path });
}
return out.sort((a, b) => a.name.localeCompare(b.name));
}
export async function readSkills(dir = configDir()) {
const root = join(libraryDir(dir), "skills");
if (!existsSync(root)) return [];
const names = await readdir(root).catch(() => []);
const out = [];
for (const name of names) {
const path = join(root, name, "SKILL.md");
if (!existsSync(path)) continue;
const text = await readFile(path, "utf8").catch(() => "");
const fm = frontmatter(text);
out.push({
name: fm.name || name,
description: fm.description,
path,
body: text.replace(/^---[\s\S]*?---\r?\n/, "").trim(),
});
}
return out.sort((a, b) => a.name.localeCompare(b.name));
}
export async function readMcp(dir = configDir()) {
// magpie 的 MCP 列表在配置目录的 library.json(library/ 里放的是指令和技能的正文)
const lib = await readJson(join(dir, "library.json"), {});
const list = Array.isArray(lib.mcp) ? lib.mcp : [];
return list.map((m) => ({
name: m.name || m.url || m.command || "mcp",
transport: m.transport === "stdio" ? "stdio" : "http",
url: m.url,
headers: m.headers && typeof m.headers === "object" ? m.headers : undefined,
command: m.command,
args: Array.isArray(m.args) ? m.args : undefined,
env: m.env && typeof m.env === "object" ? m.env : undefined,
detail: m.url || [m.command, ...(m.args || [])].join(" "),
}));
}
// 给前端的精简视图(不带正文,免得 bootstrap 太重)
export async function libraryView(dir = configDir()) {
const [instructions, skills, mcp] = await Promise.all([readInstructions(dir), readSkills(dir), readMcp(dir)]);
return {
instructions: instructions.map(({ id, name, size }) => ({ id, name, size })),
skills: skills.map(({ name, description }) => ({ name, description })),
mcp: mcp.map(({ name, transport, detail }) => ({ name, transport, detail })),
};
}
// 组装 system prompt:用户自己写的 + 勾选的指令 + 勾选的技能
export async function composeSystem(settings, dir = configDir()) {
const parts = [];
const mine = String(settings.system || "").trim();
if (mine) parts.push(mine);
const [instructions, skills] = await Promise.all([readInstructions(dir), readSkills(dir)]);
for (const id of settings.instructions || []) {
const hit = instructions.find((x) => x.id === id || x.name === id);
if (!hit) continue;
const text = await readFile(hit.path, "utf8").catch(() => "");
if (text.trim()) parts.push(`# ${hit.id}\n\n${text.trim()}`);
}
for (const name of settings.skills || []) {
const hit = skills.find((x) => x.name === name);
if (!hit) continue;
parts.push(`# Skill: ${hit.name}\n\n${hit.description ? hit.description + "\n\n" : ""}${hit.body}`);
}
return parts.join("\n\n---\n\n");
}
// 供应商图标:magpie 的 providers.json 里每个供应商有 icon,
// 可能是内置图标名(deepseek-color)、file: 本地文件,或 http 地址。
// 这里统一变成服务端能直接给的 URL(/api/icon/<provider>),取不到就不给。
export async function providerIcons(dir = configDir()) {
const out = new Map();
const providers = await readJson(join(dir, "providers.json"), null);
const list = Array.isArray(providers) ? providers : Array.isArray(providers?.providers) ? providers.providers : [];
for (const p of list) {
if (!p || typeof p !== "object") continue;
const id = p.id || p.name;
const icon = p.icon || p.logo || "";
if (!id || typeof icon !== "string" || !icon) continue;
out.set(String(id), "/api/icon/" + encodeURIComponent(String(id)));
}
return out;
}
// 路由组(group/<id>)本身没有图标:用组里第一个成员模型的供应商图标顶上。
export async function groupIcons(dir = configDir()) {
const out = new Map();
const groups = await readJson(join(dir, "providers.json"), null).catch(() => null);
const routing = await readJson(join(dir, "routing.json"), null).catch(() => null);
const list = Array.isArray(routing) ? routing : Array.isArray(routing?.groups) ? routing.groups : [];
for (const g of list) {
if (!g || typeof g !== "object") continue;
const id = g.id || g.name;
const members = Array.isArray(g.models) ? g.models : Array.isArray(g.members) ? g.members : [];
const first = members.find((m) => typeof m === "string" && m.includes("/"));
if (id && first) out.set(String(id), first.slice(0, first.indexOf("/")));
}
void groups;
return out;
}
// 真去磁盘/网络拿那个图标,回给页面
export async function readProviderIcon(providerId, dir = configDir()) {
const providers = await readJson(join(dir, "providers.json"), null);
const list = Array.isArray(providers) ? providers : Array.isArray(providers?.providers) ? providers.providers : [];
const p = list.find((x) => x && String(x.id || x.name) === String(providerId));
const icon = p && (p.icon || p.logo);
if (!icon || typeof icon !== "string") return null;
// 1) file:xxx → 配置目录 icons/ 下的文件
if (icon.startsWith("file:")) {
const name = icon.slice(5).replace(/[^\w.-]/g, "");
if (!name) return null;
for (const base of [join(dir, "icons"), dir]) {
const data = await readFile(join(base, name)).catch(() => null);
if (data) return { data, type: mimeOf(name) };
}
return null;
}
// 2) 内置图标名(deepseek-color 之类):magpie 把它们编在自己身上,
// 只在可执行文件旁边有解包目录时才找得到;找不到就当没有图标。
if (!/^(https?:|data:)/.test(icon)) {
const name = icon.replace(/[^\w.-]/g, "");
const roots = [
join(dir, "icons"),
join(dir, "..", "assets", "icons"),
join(dir, "..", "..", "assets", "icons"),
];
for (const root of roots) {
for (const ext of [".svg", ".png", ".webp", ".ico"]) {
const data = await readFile(join(root, name + ext)).catch(() => null);
if (data) return { data, type: mimeOf(name + ext) };
}
}
return null;
}
// 3) http(s) 图标:不代拉(页面本身没有网络),直接用远程地址
return { url: icon };
}
function mimeOf(name) {
const ext = String(name).toLowerCase().split(".").pop();
return { svg: "image/svg+xml", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", ico: "image/x-icon" }[ext] || "application/octet-stream";
}
export { readJson };
+469
View File
@@ -0,0 +1,469 @@
// magpie MCP 客户端:Streamable HTTP + stdio。只依赖 Node/Bun 内置模块与全局 fetch。
// 契约见 CONTRACT.md「lib/mcp.mjs 必需导出」。
import { readFileSync } from "node:fs";
import { spawn } from "node:child_process";
import { homedir } from "node:os";
import path from "node:path";
const PROTOCOL_VERSION = "2024-11-05";
const CLIENT_INFO = { name: "magpie", version: "0.1.0" };
const TIMEOUT_MS = 60_000;
const httpSessions = new Map(); // key -> { id, ready }
const stdioSessions = new Map(); // key -> { proc, buf, err, pending, seq, closed, ready }
let seq = 0;
/* ---------------- 配置 ---------------- */
// 与 lib/library.mjs 的 configDir 保持一致:支持 XDG_CONFIG_HOME 覆盖
function configDir() {
const xdg = process.env.XDG_CONFIG_HOME;
return xdg ? path.join(xdg, "magpie") : path.join(homedir(), ".config", "magpie");
}
export function loadServers() {
const file =
process.env.MAGPIE_LIBRARY || path.join(configDir(), "library.json");
let raw;
try {
raw = readFileSync(file, "utf8");
} catch (e) {
if (e.code === "ENOENT") return []; // 没装过 magpie 配置就当没有服务器
throw new Error(`读取 magpie 配置失败:${file}(${e.message})`);
}
let data;
try {
data = JSON.parse(raw);
} catch (e) {
throw new Error(`magpie 配置不是合法 JSON:${file}(${e.message})`);
}
const list = Array.isArray(data?.mcp) ? data.mcp : [];
const out = [];
for (const item of list) {
if (!item || typeof item !== "object" || !item.name) continue;
const transport =
item.transport === "stdio" || item.transport === "http"
? item.transport
: item.command
? "stdio"
: "http";
const server = { name: String(item.name), transport };
// library.mjs 会带 detail 字段,这里也保留,方便前端展示
if (typeof item.detail === "string") server.detail = item.detail;
if (item.env && typeof item.env === "object") server.env = { ...item.env };
if (transport === "http") {
server.url = typeof item.url === "string" ? item.url : "";
if (item.headers && typeof item.headers === "object") server.headers = { ...item.headers };
} else {
server.command = typeof item.command === "string" ? item.command : "";
server.args = Array.isArray(item.args) ? item.args.map(String) : [];
}
out.push(server);
}
return out;
}
/* ---------------- 对外 API ---------------- */
export async function listTools(server) {
const target = targetOf(server);
const result = await rpc(target, "tools/list", {});
const tools = Array.isArray(result?.tools) ? result.tools : [];
return tools.map((t) => ({
name: String(t?.name ?? ""),
description: typeof t?.description === "string" ? t.description : "",
inputSchema: t?.inputSchema ?? { type: "object", properties: {} },
server: target.name,
}));
}
export async function callTool(server, name, args) {
if (!name) throw new Error("调用 MCP 工具时缺少工具名");
const target = targetOf(server);
const result = await rpc(target, "tools/call", {
name: String(name),
arguments: args && typeof args === "object" ? args : {},
});
const parts = [];
for (const c of Array.isArray(result?.content) ? result.content : []) {
if (c?.type === "text") parts.push(String(c.text ?? ""));
else if (c?.type === "image") parts.push(`[图片 ${c.mimeType ?? "unknown"},已省略]`);
else if (c?.type === "resource") parts.push(String(c.resource?.text ?? `[资源 ${c.resource?.uri ?? ""}]`));
else if (c?.type === "audio") parts.push(`[音频 ${c.mimeType ?? "unknown"},已省略]`);
else parts.push(JSON.stringify(c));
}
let text = parts.join("\n").trim();
if (!text && result?.structuredContent) text = JSON.stringify(result.structuredContent, null, 2);
if (!text && result != null) text = JSON.stringify(result);
return { text, isError: Boolean(result?.isError) };
}
export async function closeAll() {
for (const session of stdioSessions.values()) killStdio(session);
stdioSessions.clear();
httpSessions.clear();
}
/* ---------------- 公共 ---------------- */
function targetOf(server) {
if (typeof server === "string") {
const found = loadServers().find((s) => s.name === server);
if (!found) throw new Error(`未在 magpie 配置里找到 MCP 服务器「${server}」`);
server = found;
}
if (!server || typeof server !== "object" || !server.name) {
throw new Error("MCP 服务器配置无效:缺少 name");
}
const transport = server.transport === "stdio" ? "stdio" : "http";
const target = { name: String(server.name), transport };
if (transport === "http") {
if (!server.url) throw new Error(`MCP 服务器「${target.name}」缺少 url,无法连接`);
target.url = server.url;
target.headers =
server.headers && typeof server.headers === "object" ? { ...server.headers } : {};
} else {
if (!server.command) throw new Error(`MCP 服务器「${target.name}」缺少 command,无法启动`);
target.command = server.command;
target.args = Array.isArray(server.args) ? server.args.map(String) : [];
target.env = server.env && typeof server.env === "object" ? { ...server.env } : null;
}
target.key = `${target.name}\u0000${transport === "http" ? target.url : target.command}`;
return target;
}
function rpc(target, method, params) {
return target.transport === "http"
? httpRpc(target, method, params)
: stdioRpc(target, method, params);
}
/* ---------------- HTTP (Streamable MCP) ---------------- */
async function ensureHttp(target) {
let session = httpSessions.get(target.key);
if (session) {
await session.ready;
return session;
}
session = { id: null, ready: null };
session.ready = (async () => {
const id = ++seq;
const res = await httpPost(
target,
{
jsonrpc: "2.0",
id,
method: "initialize",
params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO },
},
session,
);
session.id = res.headers.get("mcp-session-id") || null;
const msg = await readRpc(target, res, id);
if (!msg) throw new Error(`MCP 服务器「${target.name}」的 initialize 没有返回结果`);
if (msg.error) {
throw new Error(
`MCP 服务器「${target.name}」拒绝初始化:${msg.error.message || JSON.stringify(msg.error)}`,
);
}
// initialized 通知:部分实现不回 202,出错也不阻断后续调用
try {
const note = await httpPost(target, { jsonrpc: "2.0", method: "notifications/initialized" }, session);
const sid = note.headers.get("mcp-session-id");
if (sid) session.id = sid;
await note.text().catch(() => "");
} catch {
/* ignore */
}
})().catch((e) => {
httpSessions.delete(target.key);
throw e;
});
session.ready.catch(() => {});
httpSessions.set(target.key, session);
await session.ready;
return session;
}
async function httpRpc(target, method, params) {
let session = await ensureHttp(target);
const attempt = async () => {
const id = ++seq;
const res = await httpPost(target, { jsonrpc: "2.0", id, method, params }, session);
const sid = res.headers.get("mcp-session-id");
if (sid) session.id = sid;
if (res.status === 404 && session.id) {
await res.text().catch(() => "");
const err = new Error("MCP 会话已过期");
err.expired = true;
throw err;
}
const msg = await readRpc(target, res, id);
if (!msg) throw new Error(`MCP 服务器「${target.name}」没有返回 ${method} 的结果`);
if (msg.error) {
throw new Error(
`MCP 服务器「${target.name}」执行 ${method} 出错:${msg.error.message || JSON.stringify(msg.error)}`,
);
}
return msg.result;
};
try {
return await attempt();
} catch (e) {
if (!e.expired) throw e;
httpSessions.delete(target.key);
session = await ensureHttp(target);
return await attempt();
}
}
async function httpPost(target, body, session) {
const headers = {
"content-type": "application/json",
accept: "application/json, text/event-stream",
...target.headers,
};
if (session?.id) headers["mcp-session-id"] = session.id;
try {
return await fetch(target.url, {
method: "POST",
headers,
body: JSON.stringify(body),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (e) {
const reason =
e?.name === "TimeoutError"
? `超过 ${TIMEOUT_MS / 1000}s 未响应`
: e?.cause?.message || e?.message || String(e);
throw new Error(`连接 MCP 服务器「${target.name}」失败(${target.url}):${reason}`);
}
}
async function readRpc(target, res, id) {
if (!res.ok) {
const body = await res.text().catch(() => "");
const hint =
res.status === 401 || res.status === 403
? ",请检查 headers 里的 Authorization"
: res.status === 404
? ",地址或会话不存在"
: "";
throw new Error(
`MCP 服务器「${target.name}」返回 HTTP ${res.status}${hint}${body ? `:${body.slice(0, 300)}` : ""}`,
);
}
if (res.status === 202 || res.status === 204) return null;
const ct = (res.headers.get("content-type") || "").toLowerCase();
const text = await res.text();
if (!text.trim()) return null;
const messages = ct.includes("text/event-stream") || text.startsWith("data:")
? parseSse(text)
: parseJson(text);
return pick(messages, id);
}
function parseJson(text) {
try {
const data = JSON.parse(text);
return Array.isArray(data) ? data : [data];
} catch {
throw new Error(`MCP 服务器返回了无法解析的响应:${text.slice(0, 200)}`);
}
}
function parseSse(text) {
const out = [];
for (const block of text.split(/\r?\n\r?\n/)) {
const data = block
.split(/\r?\n/)
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).replace(/^ /, ""))
.join("\n")
.trim();
if (!data) continue;
try {
const msg = JSON.parse(data);
if (Array.isArray(msg)) out.push(...msg);
else out.push(msg);
} catch {
/* 心跳或非 JSON 事件,忽略 */
}
}
return out;
}
function pick(messages, id) {
if (!messages.length) return null;
const same = (m) => m && String(m.id) === String(id);
return messages.find(same) || messages.find((m) => m && m.id !== undefined && m.id !== null) || null;
}
/* ---------------- stdio ---------------- */
function ensureStdio(target) {
const existing = stdioSessions.get(target.key);
if (existing) return existing;
const session = { proc: null, buf: "", err: "", pending: new Map(), seq: 0, closed: false };
session.ready = (async () => {
const proc = spawn(target.command, target.args, {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
env: target.env ? { ...process.env, ...target.env } : process.env,
});
session.proc = proc;
proc.stdin.on("error", () => {});
proc.stdout.setEncoding("utf8");
proc.stdout.on("data", (chunk) => onStdout(session, target, chunk));
proc.stderr.setEncoding("utf8");
proc.stderr.on("data", (chunk) => {
session.err = (session.err + chunk).slice(-4000);
});
proc.on("error", (e) => {
const hint = e?.code === "ENOENT" ? "(命令不存在,检查是否已安装或不在 PATH)" : "";
fail(session, `无法启动 MCP 服务器「${target.name}」:${target.command}${hint}(${e.message})`);
});
proc.on("exit", (code, signal) => {
if (session.closed) return;
const tail = session.err.trim().slice(-600);
fail(
session,
`MCP 服务器「${target.name}」(${target.command})已退出(code=${code}${signal ? `, signal=${signal}` : ""})${tail ? `:${tail}` : ""}`,
);
stdioSessions.delete(target.key);
});
await stdioCall(session, target, "initialize", {
protocolVersion: PROTOCOL_VERSION,
capabilities: {},
clientInfo: CLIENT_INFO,
});
send(session, { jsonrpc: "2.0", method: "notifications/initialized" });
})().catch((e) => {
killStdio(session);
stdioSessions.delete(target.key);
throw e;
});
session.ready.catch(() => {});
stdioSessions.set(target.key, session);
return session;
}
async function stdioRpc(target, method, params) {
const session = ensureStdio(target);
await session.ready;
return stdioCall(session, target, method, params);
}
function stdioCall(session, target, method, params) {
if (session.closed) return Promise.reject(new Error(`MCP 服务器「${target.name}」已停止`));
const id = ++session.seq;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
session.pending.delete(id);
const tail = session.err.trim().slice(-400);
reject(
new Error(
`MCP 服务器「${target.name}」在 ${TIMEOUT_MS / 1000}s 内没有响应 ${method}${tail ? `:${tail}` : ""}`,
),
);
}, TIMEOUT_MS);
timer.unref?.();
session.pending.set(id, { resolve, reject, timer, method });
if (!send(session, { jsonrpc: "2.0", id, method, params })) {
session.pending.delete(id);
clearTimeout(timer);
const tail = session.err.trim().slice(-400);
reject(
new Error(
`无法向 MCP 服务器「${target.name}」写入请求,进程可能已退出${tail ? `:${tail}` : ""}`,
),
);
}
});
}
function send(session, msg) {
const proc = session.proc;
if (!proc || proc.exitCode !== null || !proc.stdin.writable) return false;
try {
proc.stdin.write(JSON.stringify(msg) + "\n");
return true;
} catch {
return false;
}
}
function onStdout(session, target, chunk) {
session.buf += chunk;
let idx;
while ((idx = session.buf.indexOf("\n")) >= 0) {
const line = session.buf.slice(0, idx).trim();
session.buf = session.buf.slice(idx + 1);
if (!line) continue;
let msg;
try {
msg = JSON.parse(line);
} catch {
continue; // 非 JSON 行(启动日志等)直接跳过
}
for (const m of Array.isArray(msg) ? msg : [msg]) handleStdioMessage(session, target, m);
}
}
function handleStdioMessage(session, target, msg) {
if (!msg || typeof msg !== "object") return;
const pending = msg.id !== undefined && msg.id !== null ? session.pending.get(msg.id) : undefined;
if (pending) {
session.pending.delete(msg.id);
clearTimeout(pending.timer);
if (msg.error) {
pending.reject(
new Error(
`MCP 服务器「${target.name}」执行 ${pending.method} 出错:${msg.error.message || JSON.stringify(msg.error)}`,
),
);
} else {
pending.resolve(msg.result);
}
return;
}
// 服务器反向请求(ping / roots 等):回空结果,避免对方等待
if (msg.id !== undefined && msg.id !== null && msg.method) {
send(
session,
msg.method === "ping"
? { jsonrpc: "2.0", id: msg.id, result: {} }
: { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "method not supported" } },
);
}
}
function fail(session, message) {
session.closed = true;
for (const p of session.pending.values()) {
clearTimeout(p.timer);
p.reject(new Error(message));
}
session.pending.clear();
}
function killStdio(session) {
session.closed = true;
fail(session, "MCP 客户端已关闭");
const proc = session.proc;
if (!proc || proc.exitCode !== null) return;
try {
proc.kill();
} catch {
/* ignore */
}
const timer = setTimeout(() => {
try {
proc.kill("SIGKILL");
} catch {
/* ignore */
}
}, 2000);
timer.unref?.();
}
+740
View File
@@ -0,0 +1,740 @@
// magpie-chat 的服务:给窗口里的对话页提供 /api/*,并把聊天请求转给 magpie 网关。
// 只用内置模块,不装依赖。
import { createServer } from "node:http";
import { readFile, writeFile } from "node:fs/promises";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, extname, normalize } from "node:path";
import { fileURLToPath } from "node:url";
import { composeSystem, configDir, groupIcons, libraryView, providerIcons, readJson, readMcp, readProviderIcon } from "./library.mjs";
import { chatCompletions, gatewayURL, listModels, resolveGateway, sseChunks } from "./gateway.mjs";
import { callTool, closeAll, listTools } from "./mcp.mjs";
const here = fileURLToPath(new URL(".", import.meta.url));
const UI_ROOT = join(here, "..", "chat");
const MAX_TOOL_ROUNDS = 8;
// 插件版本,从包里的 package.json 读(别在两处写死同一个数字)
const VERSION = (() => {
try {
return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")).version || "";
} catch {
return "";
}
})();
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".json": "application/json; charset=utf-8",
".woff2": "font/woff2",
};
// ---- 设置与对话:存在 magpie 配置目录下,跟插件自己的数据放一起 ----
function dataDir(configDirPath) {
const dir = join(configDirPath || configDir(), "magpie-chat");
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
return dir;
}
// 从 magpie 的 settings.json 读用户设的字体,拼成覆盖 :root 的 CSS。
// 没设就返回空串,页面用自己的兜底字体栈。
async function fontCss() {
const UI_FALLBACK = '-apple-system, BlinkMacSystemFont, "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif';
const CODE_FALLBACK = 'ui-monospace, "SF Mono", Menlo, Consolas, monospace';
const quote = (s) => '"' + String(s).replace(/["\\\x00-\x1f]/g, "") + '"';
const parts = [];
try {
const s = JSON.parse(await readFile(join(configDir(), "settings.json"), "utf8"));
const has = (f) => f && typeof f.family === "string" && f.family.trim();
if (has(s.uiFont)) {
const f = s.uiFont;
// 字体名后面接 magpie 自己的基础栈:找不到那个字体时逐级回落
parts.push(`--font: ${quote(f.family)}, ${UI_FALLBACK};`);
if (Number.isFinite(f.weight) && f.weight >= 1 && f.weight <= 1000) parts.push(`--font-weight: ${f.weight};`);
if (["normal", "italic", "oblique"].includes(f.style)) parts.push(`--font-style: ${f.style};`);
if (Number.isFinite(f.stretch) && f.stretch > 0) parts.push(`--font-stretch: ${f.stretch}%;`);
}
if (has(s.codeFont)) {
const c = s.codeFont;
parts.push(`--code: ${quote(c.family)}, ${CODE_FALLBACK};`);
if (Number.isFinite(c.weight) && c.weight >= 1 && c.weight <= 1000) parts.push(`--code-weight: ${c.weight};`);
}
} catch {
return ""; // 读不到设置就用页面自己的兜底
}
return parts.length ? `:root { ${parts.join(" ")} }` : "";
}
const DEFAULTS = {
model: "", effort: "", system: "", instructions: [], skills: [], mcp: [],
temperature: 0.7, maxTokens: 0, showReasoning: true,
pinned: [], // 置顶的对话 id,按置顶顺序排在列表最前
sidebar: true, // 左侧栏是否展开
settingsOpen: false, // 右侧设置栏是否打开
leftWidth: 0, // 左侧栏宽度(0 = 用默认值)
rightWidth: 0, // 设置栏宽度(0 = 用默认值)
convWidth: 72, // 会话内容列宽度(%),100 = 铺满
composerWidth: 70, // 输入框宽度(%)
};
function cleanSettings(raw) {
const s = { ...DEFAULTS, ...(raw && typeof raw === "object" ? raw : {}) };
return {
model: String(s.model || ""),
effort: String(s.effort || ""),
system: String(s.system || ""),
instructions: Array.isArray(s.instructions) ? s.instructions.map(String) : [],
skills: Array.isArray(s.skills) ? s.skills.map(String) : [],
mcp: Array.isArray(s.mcp) ? s.mcp.map(String) : [],
temperature: Number.isFinite(Number(s.temperature)) ? Number(s.temperature) : 0.7,
maxTokens: Number.isFinite(Number(s.maxTokens)) ? Number(s.maxTokens) : 0,
showReasoning: s.showReasoning !== false,
pinned: Array.isArray(s.pinned) ? s.pinned.map(String).filter(Boolean).slice(0, 200) : [],
sidebar: s.sidebar !== false,
settingsOpen: s.settingsOpen === true,
leftWidth: Number.isFinite(Number(s.leftWidth)) ? Math.max(0, Math.min(420, Number(s.leftWidth))) : 0,
rightWidth: Number.isFinite(Number(s.rightWidth)) ? Math.max(0, Math.min(560, Number(s.rightWidth))) : 0,
convWidth: Number.isFinite(Number(s.convWidth)) ? Math.max(0, Math.min(100, Number(s.convWidth))) : 72,
composerWidth: Number.isFinite(Number(s.composerWidth)) ? Math.max(40, Math.min(100, Number(s.composerWidth))) : 70,
};
}
export function createStore(configDirPath) {
const dir = dataDir(configDirPath);
const settingsPath = join(dir, "settings.json");
const convDir = join(dir, "conversations");
if (!existsSync(convDir)) mkdirSync(convDir, { recursive: true });
const store = {
dir,
async settings() {
return cleanSettings(await readJson(settingsPath, {}));
},
async saveSettings(patch) {
const next = cleanSettings({ ...(await store.settings()), ...(patch || {}) });
await writeFile(settingsPath, JSON.stringify(next, null, 2));
return next;
},
convPath(id) {
const safe = String(id || "").replace(/[^\w-]/g, "").slice(0, 64);
return safe ? join(convDir, safe + ".json") : "";
},
async getConversation(id) {
const p = store.convPath(id);
if (!p) return null;
return readJson(p, null);
},
async saveConversation(conv) {
const id = conv.id || "c_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
const messages = Array.isArray(conv.messages) ? conv.messages.slice(-400) : [];
const title = String(conv.title || firstLine(messages) || "新对话").slice(0, 90);
const out = { id, title, updated: Date.now(), messages };
const p = store.convPath(id);
if (!p) throw new Error("bad conversation id");
await writeFile(p, JSON.stringify(out));
return out;
},
async listConversations() {
const { readdir } = await import("node:fs/promises");
const names = await readdir(convDir).catch(() => []);
const items = [];
for (const n of names) {
if (!n.endsWith(".json")) continue;
const c = await readJson(join(convDir, n), null);
if (!c?.id) continue;
const last = [...(c.messages || [])].reverse().find((m) => m.role === "user");
items.push({ id: c.id, title: c.title, updated: c.updated || 0, preview: String(last?.content || "").slice(0, 120) });
}
// 置顶的排在前面(按置顶顺序),其余按最近更新
const pinned = (await store.settings()).pinned || [];
const rank = new Map(pinned.map((id, i) => [id, i]));
return items.sort((a, b) => {
const ra = rank.has(a.id) ? rank.get(a.id) : -1;
const rb = rank.has(b.id) ? rank.get(b.id) : -1;
if (ra >= 0 && rb >= 0) return ra - rb;
if (ra >= 0) return -1;
if (rb >= 0) return 1;
return b.updated - a.updated;
}).map((item) => ({ ...item, pinned: rank.has(item.id) }));
},
async removeConversation(id) {
const { rm } = await import("node:fs/promises");
const p = store.convPath(id);
if (p) await rm(p, { force: true });
},
};
return store;
}
// 没有图标文件时生成的首字母徽章:颜色按名字散列,同一供应商总是同一色
function letterIcon(name) {
const s = String(name || "?");
let hue = 0;
for (let i = 0; i < s.length; i++) hue = (hue * 31 + s.charCodeAt(i)) % 360;
const ch = s.slice(0, 1).toUpperCase().replace(/[<&>"]/g, "");
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
<rect width="32" height="32" rx="7" fill="hsl(${hue}, 52%, 88%)"/>
<text x="16" y="16" text-anchor="middle" dominant-baseline="central"
font-family="-apple-system, Segoe UI, sans-serif" font-size="16" font-weight="600"
fill="hsl(${hue}, 52%, 30%)">${ch}</text></svg>`;
}
function firstLine(messages) {
const u = (messages || []).find((m) => m.role === "user");
const text = String(u?.content || "").trim().replace(/\s+/g, " ");
return text.slice(0, 60);
}
// ---- HTTP ----
// magpie 的插件页面跑在 sandbox="allow-scripts" 的框架里,origin 是 opaque,
// 浏览器发来的 Origin 就是字面量 "null"。直接在地址栏打开同一个服务时,Origin 是本服务自己。
// 其他来源一律拒绝:这个服务能替用户烧额度,不能给任意网页用。
let OWN = new Set();
function originAllowed(req) {
const o = req.headers.origin;
return o === undefined || o === "null" || OWN.has(o);
}
function corsHeaders(req) {
const o = req.headers?.origin;
const allow = o === "null" ? "null" : o && OWN.has(o) ? o : "null";
return {
"access-control-allow-origin": allow,
"access-control-allow-headers": "content-type",
"access-control-allow-methods": "GET,POST,DELETE,OPTIONS",
vary: "Origin",
};
}
function send(res, status, body, type = "application/json; charset=utf-8") {
const data = typeof body === "string" || body instanceof Uint8Array ? body : JSON.stringify(body);
res.writeHead(status, {
"content-type": type,
"cache-control": "no-store",
...corsHeaders(res.req),
"x-content-type-options": "nosniff",
});
res.end(data);
}
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const c of req) {
size += c.length;
if (size > 24 * 1024 * 1024) throw new Error("请求太大");
chunks.push(c);
}
if (!chunks.length) return {};
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
throw new Error("请求不是合法的 JSON");
}
}
function sseHead(res) {
res.writeHead(200, {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-store",
connection: "keep-alive",
...corsHeaders(res.req),
"x-accel-buffering": "no",
});
res.flushHeaders?.();
}
function sse(res, type, data) {
if (res.writableEnded) return;
res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);
}
// system prompt 之外,把 MCP 工具的用途也告诉模型(工具本身用 function calling 给)
// 工具清单写在 system 里会和 function 定义重复一遍,所以只给一句交代。
function toolsHint(tools) {
if (!tools.length) return "";
return `# 工具\n\n你可以调用用户配置的 MCP 工具(共 ${tools.length} 个)。需要时直接调用,不要臆造结果;用不上就直接回答。`;
}
// 工具的 schema 是提示词里最大的一块:GitHub 那 46 个工具光描述和参数就有上千万字符。
// 只留名字、第一行说明,参数表裁到前 8 个字段、每个字段只留类型和一句说明。
const MAX_PROPS = 8;
function slimSchema(schema) {
if (!schema || typeof schema !== "object") return { type: "object", properties: {} };
const out = { type: "object", properties: {} };
const props = schema.properties && typeof schema.properties === "object" ? schema.properties : {};
for (const [key, val] of Object.entries(props).slice(0, MAX_PROPS)) {
if (!val || typeof val !== "object") { out.properties[key] = { type: "string" }; continue; }
const slim = { type: val.type || "string" };
if (val.description) slim.description = String(val.description).split("\n")[0].slice(0, 120);
if (Array.isArray(val.enum)) slim.enum = val.enum.slice(0, 20);
if (val.type === "array" && val.items?.type) slim.items = { type: val.items.type };
out.properties[key] = slim;
}
if (Array.isArray(schema.required) && schema.required.length) out.required = schema.required.slice(0, MAX_PROPS);
return out;
}
function toFunctionTools(tools) {
return tools.map((t) => ({
type: "function",
function: {
name: t.name,
description: (t.description || "").split("\n")[0].slice(0, 200) || t.name,
parameters: slimSchema(t.inputSchema),
},
}));
}
// 一条消息转成网关认的 content:
// 没有图片就是字符串;有图片就变成 [{type:"text"},{type:"image_url",image_url:{url}}]
// (image_url 收 data: URL,magpie 网关会原样转给上游)。
function toGatewayContent(m) {
const text = String(m.content ?? "");
const files = Array.isArray(m.files) ? m.files : [];
const images = files.filter((f) => f && f.kind === "image" && f.data);
if (!images.length) return text;
const parts = [];
if (text.trim()) parts.push({ type: "text", text });
for (const img of images) {
parts.push({ type: "image_url", image_url: { url: String(img.data) } });
}
// 非图片附件以文字交代给模型,避免它不知道用户放了文件
const others = files.filter((f) => f && f.kind !== "image");
if (others.length) {
parts.push({ type: "text", text: others.map((f) => `[附件] ${f.name || "文件"}(${f.size || 0} 字节)`).join("\n") });
}
return parts;
}
// 一轮对话:可多次工具调用;把每条增量转成 SSE 发回浏览器
async function runChat({ res, body, settings, store }, controllers) {
const clientId = String(body.clientId || "");
const abort = new AbortController();
if (clientId) controllers.set(clientId, abort);
res.on("close", () => { if (!res.writableEnded) abort.abort(); });
const started = Date.now();
const model = String(body.model || settings.model || "");
const effort = String(body.effort ?? settings.effort ?? "");
const temperature = Number.isFinite(Number(body.temperature)) ? Number(body.temperature) : settings.temperature;
const maxTokens = Number.isFinite(Number(body.maxTokens)) ? Number(body.maxTokens) : settings.maxTokens;
const wantTools = body.useTools !== false && (settings.mcp || []).length > 0;
const history = Array.isArray(body.messages) ? body.messages.filter((m) => m && (m.role === "user" || m.role === "assistant")) : [];
// 只挂了图片/文件、没写文字的消息也算有内容
const hasContent = history.some((m) => String(m.content ?? "").trim() || (Array.isArray(m.files) && m.files.length));
if (!model) { sse(res, "error", { message: "没有选模型:在右下角挑一个 magpie 的模型" }); res.end(); return; }
if (!history.length || !hasContent) { sse(res, "error", { message: "没有内容可发送" }); res.end(); return; }
// 工具:只把跟这轮问题相关的交出去。
// GitHub 一个服务器就有 46 个工具,全塞给模型时提示词会涨到上千万 token:
// 又慢又贵,模型还会被工具说明淹掉、几乎不产出正文。所以按问题里的词筛,
// 没筛出相关的就只留最通用的几个,宁可少给也不要全给。
let tools = [];
let toolNote = "";
if (wantTools) {
const servers = await readMcp();
const picked = servers.filter((s) => (settings.mcp || []).includes(s.name));
const all = [];
for (const s of picked) {
try {
const list = await listTools(s);
for (const t of list) all.push({ ...t, server: s.name, name: s.name + "_" + t.name.replace(/[^\w-]/g, "_"), rawName: t.name });
} catch (err) {
sse(res, "tool", { phase: "error", name: s.name, result: "无法连接 " + s.name + ":" + (err?.message || err) });
}
}
const q = String(history[history.length - 1]?.content || "").toLowerCase();
const words = q.split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length >= 3);
const scored = all.map((t) => {
const hay = (t.name + " " + (t.description || "")).toLowerCase();
let score = 0;
for (const w of words) if (hay.includes(w)) score += w.length > 4 ? 2 : 1;
return { t, score };
}).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
const MAX_TOOLS = 12;
tools = scored.slice(0, MAX_TOOLS).map((x) => x.t);
if (tools.length < 3) {
// 问得太笼统时给一组最通用的,但仍然封顶
const common = /^(get|list|search|read|fetch|query)_|(_search|_list|_get)$/;
const extra = all.filter((t) => common.test(t.rawName) && !tools.includes(t)).slice(0, 8);
tools = tools.concat(extra).slice(0, MAX_TOOLS);
}
if (all.length > tools.length) {
toolNote = `(这次提供了 ${tools.length}/${all.length} 个工具:按你的问题挑的)`;
}
}
const system = [await composeSystem(settings), toolsHint(tools)].filter(Boolean).join("\n\n");
if (toolNote) sse(res, "tool", { phase: "note", name: "tools", result: toolNote });
const messages = [];
if (system) messages.push({ role: "system", content: system });
for (const m of history) {
const calls = m.role === "assistant" && Array.isArray(m.toolCalls) ? m.toolCalls.filter((c) => c && c.name) : [];
if (!calls.length) {
messages.push({ role: m.role, content: toGatewayContent(m) });
continue;
}
// 一轮工具调用的完整重放:assistant.tool_calls 后面必须跟每个调用的 tool 结果,
// 少一条网关就拒收,所以没有结果的调用不放进历史。
const done = calls.filter((c) => String(c.result ?? "") !== "" || c.isError);
if (!done.length) {
if (m.content) messages.push({ role: "assistant", content: String(m.content) });
continue;
}
messages.push({
role: "assistant",
content: m.content || "",
tool_calls: done.map((c, i) => ({
id: String(c.id || `history_${i}`),
type: "function",
function: { name: String(c.name), arguments: typeof c.args === "string" ? c.args : JSON.stringify(c.args || {}) },
})),
});
for (const [i, c] of done.entries()) {
messages.push({
role: "tool",
tool_call_id: String(c.id || `history_${i}`),
content: String(c.result ?? "").slice(0, 20000) || (c.isError ? "error" : "ok"),
});
}
}
sse(res, "start", { model, tools: tools.map((t) => t.name), gateway: await resolveGateway().catch(() => gatewayURL()) });
let usageTotal = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
try {
for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
const payload = { model, messages, stream: true };
if (effort) payload.reasoning_effort = effort;
if (Number.isFinite(temperature)) payload.temperature = temperature;
if (maxTokens > 0) payload.max_tokens = maxTokens;
if (tools.length) {
payload.tools = toFunctionTools(tools);
payload.tool_choice = "auto";
}
const upstream = await chatCompletions(payload, { signal: abort.signal });
if (!upstream.ok || !upstream.body) {
const text = upstream.body ? (await upstream.text()).slice(0, 600) : "";
sse(res, "error", { message: `magpie ${upstream.status}${text ? " · " + text : ""}` });
res.end();
return;
}
let content = "";
let reasoning = "";
const calls = new Map(); // index -> { id, name, args }
let finish = "";
for await (const chunk of sseChunks(upstream)) {
const choice = chunk?.choices?.[0];
if (chunk?.usage) {
usageTotal = {
prompt_tokens: usageTotal.prompt_tokens + (chunk.usage.prompt_tokens || 0),
completion_tokens: usageTotal.completion_tokens + (chunk.usage.completion_tokens || 0),
total_tokens: usageTotal.total_tokens + (chunk.usage.total_tokens || 0),
};
}
if (!choice) continue;
const d = choice.delta || {};
if (d.reasoning_content) { reasoning += d.reasoning_content; sse(res, "reasoning", { text: d.reasoning_content }); }
if (d.content) { content += d.content; sse(res, "delta", { text: d.content }); }
for (const tc of d.tool_calls || []) {
const i = tc.index ?? 0;
const cur = calls.get(i) || { id: "", name: "", args: "" };
if (tc.id) cur.id = tc.id;
if (tc.function?.name) cur.name += tc.function.name;
if (tc.function?.arguments) cur.args += tc.function.arguments;
calls.set(i, cur);
}
if (choice.finish_reason) finish = choice.finish_reason;
}
if (calls.size && (finish === "tool_calls" || finish === "stop")) {
const made = [...calls.values()].filter((c) => c.name);
if (!made.length) { sse(res, "done", { ms: Date.now() - started, usage: usageTotal }); res.end(); return; }
messages.push({
role: "assistant",
content: content || "",
tool_calls: made.map((c, i) => ({ id: c.id || `call_${round}_${i}`, type: "function", function: { name: c.name, arguments: c.args || "{}" } })),
});
if (content) sse(res, "delta", { text: "" });
for (const c of made) {
const id = c.id || `call_${round}`;
let args = {};
try { args = JSON.parse(c.args || "{}"); } catch { args = {}; }
const tool = tools.find((t) => t.name === c.name) || tools.find((t) => t.rawName === c.name);
sse(res, "tool", { phase: "call", id, name: c.name, args });
let result = "", isError = false;
if (!tool) {
result = "没有这个工具:" + c.name; isError = true;
} else {
const server = (await readMcp()).find((s) => s.name === tool.server);
try {
const out = await callTool(server, tool.rawName, args);
result = out.text; isError = Boolean(out.isError);
} catch (err) {
result = String(err?.message || err); isError = true;
}
}
sse(res, "tool", { phase: "result", id, name: c.name, args, result: String(result).slice(0, 20000), isError });
messages.push({ role: "tool", tool_call_id: id, content: String(result).slice(0, 60000) || (isError ? "error" : "ok") });
}
continue; // 让模型基于工具结果继续
}
sse(res, "usage", usageTotal);
sse(res, "done", { ms: Date.now() - started });
res.end();
return;
}
sse(res, "error", { message: `工具调用超过 ${MAX_TOOL_ROUNDS} 轮,已停下` });
res.end();
} catch (err) {
if (abort.signal.aborted) { sse(res, "done", { ms: Date.now() - started, stopped: true }); }
else sse(res, "error", { message: String(err?.message || err) });
res.end();
} finally {
if (clientId) controllers.delete(clientId);
}
}
export async function startServer({ configDir: dir, options = {} } = {}) {
const store = createStore(dir || configDir());
const controllers = new Map();
const port = Number(options.port || process.env.MAGPIE_CHAT_PORT || 3477);
OWN = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]);
// 模型列表缓存几十秒,够界面用,又不用每次开页都等网关
let cache = { at: 0, models: [] };
async function models(opts = {}) {
if (Date.now() - cache.at < 30e3 && cache.models.length) return cache.models;
const list = await listModels(opts);
cache = { at: Date.now(), models: list };
return list;
}
const server = createServer(async (req, res) => {
const url = new URL(req.url || "/", "http://127.0.0.1:" + port);
const path = url.pathname;
if (!originAllowed(req)) return send(res, 403, { error: "只服务于 magpie 窗口里的对话页" });
if (req.method === "OPTIONS") {
res.writeHead(204, corsHeaders(req));
return res.end();
}
try {
if (path.startsWith("/api/")) {
if (req.method === "GET" && path === "/api/bootstrap") {
const settings = await store.settings();
let list = [];
let gatewayError = "";
await resolveGateway(options).catch(() => "");
try { list = await models(options); } catch (err) { gatewayError = String(err?.message || err); }
// 模型图标:magpie 的 providers.json 里有各供应商的 logo,能对上就带上
try {
const icons = await providerIcons(dir);
// group/<id> 这种路由组没有自己的图标,借组里第一个供应商的
const groups = await groupIcons(dir).catch(() => new Map());
list = list.map((m) => {
// 路由组(group/*)的 provider 是 "group",实际供应商在 owner 里
const icon = icons.get(m.owner) || icons.get(m.provider)
|| (m.provider === "group" ? icons.get(groups.get(m.id.replace(/^group\//, "")) || "") : "");
return { ...m, icon: icon || "" };
});
} catch { /* 没有图标就只显示名字 */ }
if (!settings.model && list.length) settings.model = list[0].id;
const effortOK = list.find((m) => m.id === settings.model)?.efforts?.includes(settings.effort);
if (!effortOK) settings.effort = "";
return send(res, 200, {
port,
version: "0.1.0",
gateway: gatewayURL(options),
settings,
models: list,
library: await libraryView(dir),
error: gatewayError,
});
}
// 供应商图标:模型名字前面那个小图标
const iconHit = /^\/api\/icon\/([^/]+)$/.exec(path);
if (iconHit && req.method === "GET") {
const pid = decodeURIComponent(iconHit[1]);
const icon = await readProviderIcon(pid, dir).catch(() => null);
if (icon && icon.url) return send(res, 302, "", "text/plain");
// 没有图片文件就画一个首字母徽章(magpie 的内置图标编在二进制里,取不到)
const body = icon ? icon.data : letterIcon(pid);
res.writeHead(200, {
"content-type": icon ? icon.type || "application/octet-stream" : "image/svg+xml",
"cache-control": "public, max-age=86400",
"access-control-allow-origin": "*",
});
return res.end(body);
}
// 探活:带路页在跳转前先打这个,确认服务已经起来,
// 免得页面直接撞上"127.0.0.1 拒绝连接"。
if (path === "/api/ping" && req.method === "GET") {
// 版本号从 package.json 读,别再写死(写死会跟实际版本对不上)
// 报实际端口(可能不是 3477,被占时会退到 3478…)
return send(res, 200, { ok: true, port: actualPort, version: VERSION });
}
// 字体:直接读 magpie 设置里的 uiFont / codeFont,生成一份 CSS 给页面用。
//
// 为什么从服务端读,而不是让带路页在 magpie 页面里读 CSS 变量:
// 带路页能读,但读的时机靠不住 —— magpie 是在设置加载完之后才把
// --ui-font 写到 :root 上的,带路页 await 完 magpie.ready 立刻读,
// 经常读到空值;页面 CSP 是 connect-src 'none',读不到也没法重试。
// 服务是普通 node 进程,直接读 settings.json,什么时候读都准。
if (path === "/api/fonts.css" && req.method === "GET") {
const css = await fontCss();
res.writeHead(200, {
"content-type": "text/css; charset=utf-8",
"cache-control": "no-store",
"access-control-allow-origin": "*",
});
return res.end(css);
}
if (path === "/api/upload" && req.method === "POST") {
const body = await readBody(req);
const name = String(body.name || "file").slice(0, 200);
const type = String(body.type || "");
const data = String(body.data || "");
if (!data) return send(res, 400, { error: "没有内容" });
// 图片保留 data URL 直接给模型;文本文件转成文本附件
const isImage = /^image\//.test(type);
if (isImage && data.length > 24 * 1024 * 1024) return send(res, 413, { error: "图片太大(上限约 24MB)" });
if (!isImage && data.length > 8 * 1024 * 1024) return send(res, 413, { error: "文件太大(上限约 8MB)" });
return send(res, 200, { name, type, kind: isImage ? "image" : "file", size: data.length, data });
}
if (path === "/api/settings" && req.method === "GET") return send(res, 200, await store.settings());
if (path === "/api/settings" && req.method === "POST") {
const patch = await readBody(req);
return send(res, 200, await store.saveSettings(patch));
}
if (path === "/api/library" && req.method === "GET") return send(res, 200, await libraryView(dir));
if (path === "/api/mcp/tools" && req.method === "GET") {
const settings = await store.settings();
const servers = (await readMcp(dir)).filter((s) => settings.mcp.includes(s.name));
const out = [];
for (const s of servers) {
try {
const tools = await listTools(s);
out.push({ name: s.name, ok: true, tools: tools.map((t) => ({ name: t.name, description: t.description, server: s.name })) });
} catch (err) {
out.push({ name: s.name, ok: false, error: String(err?.message || err), tools: [] });
}
}
return send(res, 200, { servers: out });
}
if (path === "/api/models" && req.method === "GET") {
try { return send(res, 200, { models: await models(options) }); }
catch (err) { return send(res, 502, { error: String(err?.message || err), models: [] }); }
}
if (path === "/api/conversations" && req.method === "GET") return send(res, 200, { items: await store.listConversations() });
if (path === "/api/conversations" && req.method === "POST") {
const body = await readBody(req);
return send(res, 200, await store.saveConversation(body || {}));
}
const conv = /^\/api\/conversations\/([\w-]+)$/.exec(path);
if (conv && req.method === "GET") {
const c = await store.getConversation(conv[1]);
return c ? send(res, 200, c) : send(res, 404, { error: "没有这个对话" });
}
if (conv && req.method === "DELETE") {
await store.removeConversation(conv[1]);
return send(res, 200, { ok: true });
}
if (path === "/api/chat" && req.method === "POST") {
const body = await readBody(req);
const settings = await store.settings();
sseHead(res);
await runChat({ res, body, settings, store }, controllers);
return;
}
if (path === "/api/chat/stop" && req.method === "POST") {
const body = await readBody(req).catch(() => ({}));
const c = controllers.get(String(body.clientId || ""));
if (c) c.abort();
return send(res, 200, { ok: Boolean(c) });
}
return send(res, 404, { error: "没有这个接口:" + path });
}
// 静态:对话页自己的文件
const rel = normalize(decodeURIComponent(path)).replace(/^([/\\.]+)/, "");
const file = join(UI_ROOT, rel === "" ? "index.html" : rel);
if (!file.startsWith(UI_ROOT)) return send(res, 403, { error: "forbidden" });
const data = await readFile(file).catch(() => null);
if (!data) return send(res, 404, "没有这个文件", "text/plain; charset=utf-8");
return send(res, 200, data, MIME[extname(file).toLowerCase()] || "application/octet-stream");
} catch (err) {
if (res.headersSent) { try { res.end(); } catch { /* 已结束 */ } return; }
return send(res, 500, { error: String(err?.message || err) });
}
});
// 端口策略:先试指定的(默认 3477),被占就立刻换一个空闲端口 ——
// 不再傻等 6 秒。窗口里常常同时有命令行 magpie 和桌面 magpie 两个宿主,
// 抢同一个端口是常态;谁抢到谁服务,后来者换一个端口照样能用。
const bindOn = (p) => new Promise((resolve, reject) => {
const onError = (err) => { server.removeListener("listening", onListening); reject(err); };
const onListening = () => { server.removeListener("error", onError); resolve(); };
server.once("error", onError);
server.once("listening", onListening);
server.listen(p, "127.0.0.1");
});
// 从 0 让内核分配一个空闲端口,拿它的实际值
const bindEphemeral = () => new Promise((resolve, reject) => {
const onError = (err) => { server.removeListener("listening", onListening); reject(err); };
const onListening = () => {
server.removeListener("error", onError);
resolve(server.address().port);
};
server.once("error", onError);
server.once("listening", onListening);
server.listen(0, "127.0.0.1");
});
const actualPort = port;
// 端口固定用 3477 —— 带路页写死了跳这个端口(页面 CSP 是 connect-src 'none',
// 没法先探测再决定跳哪,只能盲跳)。所以这里也必须是 3477,换端口页面就连不上了。
// 被上一次的宿主占着就等它松手,最多等 6 秒。
let bound = false;
for (let i = 0; i < 12 && !bound; i++) {
try {
await bindOn(port);
bound = true;
} catch (err) {
if (err?.code !== "EADDRINUSE") throw err;
if (i === 0) console.log(`[page-chat] ${port} 被上一次的宿主占着,等一下再绑`);
await new Promise((r) => setTimeout(r, 500));
}
}
if (!bound) throw new Error(`${port} 一直被占用,服务起不来`);
// 把实际端口写到配置目录,带路页(page/boot.js)会来读 ——
// 端口可能是换过的,页面不能假设永远是 3477。
try {
// dir 可能是空字符串(没传 configDir),交给 dataDir 落到默认配置目录
const cfgRoot = dataDir(dir);
writeFileSync(join(cfgRoot, "port.json"), JSON.stringify({ port: actualPort, at: Date.now() }));
} catch (err) {
console.warn("[page-chat] 端口文件写失败:", err?.message || err);
}
return { port: actualPort, server, store, close: async () => { await closeAll(); server.close(); } };
}
+59
View File
@@ -0,0 +1,59 @@
{
"name": "@magpie-community/page-chat",
"version": "0.1.18",
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
"files": [
"index.mjs",
"lib",
"chat",
"page",
"assets",
"serve.mjs",
"start-server.cmd",
"start-server.vbs",
"install-autostart.cmd",
"install-autostart.ps1",
"README.md",
"SERVE.md",
"LICENSE"
],
"keywords": [
"magpie",
"magpie-page",
"magpie-plugin",
"opencode",
"opencode-plugin",
"chat",
"llm"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/Magiczerowxy/magpie-chat.git"
},
"bugs": {
"url": "https://github.com/Magiczerowxy/magpie-chat/issues"
},
"homepage": "https://github.com/Magiczerowxy/magpie-chat#readme",
"engines": {
"magpie": ">=0.1.1340"
},
"magpie": {
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHJlY3Qgd2lkdGg9IjEyOCIgaGVpZ2h0PSIxMjgiIHJ4PSIyOCIgZmlsbD0iIzRmNDZlNSIvPgogIDxwYXRoIGQ9Ik0zMCAzOGg2OGE4IDggMCAwIDEgOCA4djM0YTggOCAwIDAgMS04IDhINjBsLTE2IDE0di0xNGgtMTRhOCA4IDAgMCAxLTgtOFY0NmE4IDggMCAwIDEgOC04eiIgZmlsbD0iI2ZmZiIvPgogIDxnIGZpbGw9IiM0ZjQ2ZTUiPgogICAgPGNpcmNsZSBjeD0iNDYiIGN5PSI1OCIgcj0iNSIvPgogICAgPGNpcmNsZSBjeD0iNjQiIGN5PSI1OCIgcj0iNSIvPgogICAgPGNpcmNsZSBjeD0iODIiIGN5PSI1OCIgcj0iNSIvPgogIDwvZz4KPC9zdmc+Cg==",
"page": {
"title": "Chat",
"titles": {
"zh": "对话",
"zh-TW": "對話",
"ja": "チャット"
},
"file": "page/index.html",
"icon": "assets/icon.svg"
}
},
"scripts": {
"start": "node -e \"import('./index.mjs')\""
},
"main": "./index.mjs",
"type": "module"
}
+56
View File
@@ -0,0 +1,56 @@
// 带路页:把它自己(也就是 magpie 页面那个框架)导航到插件的服务。
//
// 这里必须"直接跳",不能先探测:
// 页面的 CSP 是 connect-src 'none',fetch/XHR/WebSocket 全被禁止 ——
// 连 no-cors 的请求都会被直接拒绝。所以「先探一下服务在不在」这条路走不通,
// alive() 永远返回 false,页面会永远停在等待页。
// magpie 文档也明说了:这个页面唯一能做的联网动作就是把自己跳转到别处。
//
// 端口用固定的 3477。多个 magpie 实例同时在跑时,后来者会退到 3478…,
// 但页面一律跳 3477 —— 指向先起来的那个,行为反而更一致。
//
// 顺手把窗口的主题和设计令牌一起带上(magpie 的 bridge 已经把它们算好了),
// 这样对话页的配色和字体跟窗口完全一致,连用户的自定义主题也算在内。
(async () => {
const DEFAULT_PORT = 3477;
let port = DEFAULT_PORT;
let theme = "";
let tokens = null;
try {
const t = await window.magpie?.ready; // { dark, lang, tokens }
if (t) {
if (typeof t.dark === "boolean") theme = t.dark ? "dark" : "light";
if (t.tokens && typeof t.tokens === "object") tokens = t.tokens;
}
} catch { /* 没有 bridge 就退回默认主题 */ }
try {
const o = await window.magpie?.options?.get?.();
if (o && Number.isFinite(Number(o.port)) && Number(o.port) > 0) port = Number(o.port);
} catch { /* 没有 options 就用默认端口 */ }
// 字体不在这里传。
//
// 试过从 magpie 页面的 CSS 变量里读 --ui-font 再带过去,但时机靠不住:
// magpie 是设置加载完之后才把 --ui-font 写到 :root 上的,这里 await 完
// magpie.ready 立刻读,经常读到空。而且页面 CSP 是 connect-src 'none',
// 读不到也没法重试。现在改成服务端直接读 magpie 的 settings.json,
// 由 /api/fonts.css 提供给对话页 —— 那边什么时候读都准。
const q = new URLSearchParams();
if (theme) q.set("theme", theme);
if (true) {
// 只留非空的令牌,压成一个短串;令牌本身就是 magpie 自己的 CSS 变量值。
const slim = {};
for (const [k, v] of Object.entries(tokens || {})) {
const s = String(v ?? "").trim();
if (s) slim[k] = s;
}
if (Object.keys(slim).length) {
try { q.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); } catch { /* 编码不了就只带主题 */ }
}
}
location.replace("http://127.0.0.1:" + port + "/?" + q.toString());
})();
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>对话</title>
<style>
:root { color-scheme: light dark; }
html, body { margin: 0; height: 100%; }
body {
display: grid; place-items: center;
font: 13px/1.5 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif);
background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText);
}
.box { text-align: center; color: var(--magpie-muted, GrayText); }
.box b { display: block; color: var(--magpie-fg, CanvasText); font-size: 14px; margin-bottom: 4px; }
</style>
</head>
<body>
<div class="box"><b>对话</b><span id="said">正在连接到本地对话服务…</span></div>
<script src="_magpie/bridge.js"></script>
<script src="boot.js"></script>
</body>
</html>
+48
View File
@@ -0,0 +1,48 @@
// 独立启动对话服务,不依赖 magpie 的插件宿主。
// 用法:node serve.mjs (或双击 start-server.cmd)
//
// 如果 magpie 已经通过插件把服务起起来了,这里就什么都不做直接退出,
// 避免两个实例抢同一份设置和对话文件。
import { startServer } from "./lib/server.mjs";
const CANDIDATES = [3477, 3478, 3479, 3480];
async function alreadyRunning() {
for (const p of CANDIDATES) {
try {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 800);
const res = await fetch("http://127.0.0.1:" + p + "/api/ping", { signal: ctl.signal });
clearTimeout(timer);
if (res.ok) {
const j = await res.json().catch(() => null);
if (j && j.ok) return { port: p, version: j.version };
}
} catch { /* 这个端口没有 */ }
}
return null;
}
const alive = await alreadyRunning();
if (alive) {
console.log("");
console.log(" 对话服务已经在运行了");
console.log(" 地址: http://127.0.0.1:" + alive.port + " (版本 " + (alive.version || "?") + ")");
console.log(" 不需要再起一个,直接去 magpie 里打开「对话」即可。");
console.log("");
process.exit(0);
}
const info = await startServer({ configDir: process.env.MAGPIE_CHAT_CONFIG || "", options: {} })
.catch((err) => {
console.error("启动失败:", err?.message || err);
process.exit(1);
});
console.log("");
console.log(" 对话服务已就绪");
console.log(" 地址: http://127.0.0.1:" + info.port);
console.log(" 这个窗口最小化即可,关掉服务就停了");
console.log("");
process.on("SIGINT", async () => { await info.close(); process.exit(0); });
+11
View File
@@ -0,0 +1,11 @@
@echo off
chcp 65001 >nul
title magpie-chat 对话服务
cd /d "%~dp0"
echo.
echo 正在启动 magpie 对话服务...
echo.
node serve.mjs
echo.
echo 服务已停止。按任意键关闭。
pause >nul
+7
View File
@@ -0,0 +1,7 @@
' 静默启动 magpie 对话服务(不弹命令行窗口)
' 双击即可;把它放进「启动」文件夹就能开机自启
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
here = fso.GetParentFolderName(WScript.ScriptFullName)
sh.CurrentDirectory = here
sh.Run "node serve.mjs", 0, False