opencode-magpie-plugin 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yee94
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,233 @@
1
- # Temporary Holding Version
1
+ # opencode-magpie-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/opencode-magpie-plugin)](https://www.npmjs.com/package/opencode-magpie-plugin)
4
+ [![CI](https://github.com/yee94/opencode-magpie-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/yee94/opencode-magpie-plugin/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
7
+ **在 OpenCode V2 中动态使用 Magpie 的 Cursor、WorkBuddy 等服务,无需手写模型配置。**
8
+
9
+ An OpenCode V2 plugin for the local [Magpie](https://usemagpie.ai/) gateway. It discovers providers and models, supplies built-in token pricing, and starts an installed gateway when needed. Zero runtime npm dependencies; no private registry or company-scoped packages required.
10
+
11
+ ## 它解决什么问题
12
+
13
+ Magpie 管理多个服务的账号、模型、协议转换和路由;这个插件负责把这些能力接入 OpenCode。
14
+
15
+ ```text
16
+ OpenCode V2
17
+ ├─ /models:Cursor、WorkBuddy、独立 routing group
18
+ ├─ 模型能力、上下文限制、reasoning 档位和价格
19
+ └─ 原生 Chat / Responses / Anthropic 请求
20
+ ↓
21
+ 本机 Magpie 网关
22
+ ↓
23
+ Cursor / WorkBuddy / 其他已配置服务
24
+ ```
25
+
26
+ - `opencode.jsonc` 只加载插件,不维护 `providers.models`。
27
+ - 启动时发现目录,每 30 秒刷新;服务新增、模型下线都能反映到 OpenCode。
28
+ - Provider 显示 Magpie 中的分组名称,而不是统一挤在一个 “Magpie” 下。
29
+ - 内置独立价格表和模型名归一化逻辑,支持输入、输出、缓存读取与写入价格。
30
+ - Magpie 已安装但未运行时自动执行 `magpie serve`;未安装时给出安装链接。
31
+ - 登录和服务凭据由 Magpie 管理,插件不需要复制上游 token。
32
+
33
+ 这不是一个绕过 Magpie 的社区插件宿主:**推理请求仍经过本机 Magpie 网关**。
34
+
35
+ ## 前置条件
36
+
37
+ 1. 使用支持 `setup()`、`provider.transform` 和原生 provider runtime 的 **OpenCode V2**。不支持 V1。
38
+ 2. 从 [Magpie 官网](https://usemagpie.ai/zh/) 安装 Magpie,并在其中登录需要的服务、启用模型。
39
+ 3. 网关对本机可访问,默认地址 `http://127.0.0.1:3425`。
40
+
41
+ 包的 Node.js 要求为 **22 或更高**。macOS 上已验证插件加载与 Cursor / WorkBuddy 目录注册;Windows 和 Linux 的实际网关联调尚未验证。
42
+
43
+ ## 安装
44
+
45
+ 在全局 `~/.config/opencode/opencode.jsonc` 中加入插件;如果已有 `plugins` 数组,追加即可:
46
+
47
+ ```jsonc
48
+ {
49
+ "$schema": "https://opencode.ai/config.json",
50
+ "plugins": ["opencode-magpie-plugin"]
51
+ }
52
+ ```
53
+
54
+ 也可以固定版本:
55
+
56
+ ```jsonc
57
+ {
58
+ "plugins": ["opencode-magpie-plugin@0.1.0"]
59
+ }
60
+ ```
61
+
62
+ OpenCode 会从公网 npm 安装插件,不需要先全局安装 npm 包。不要同时加载本插件的 npm 版和本地 file 版。
63
+
64
+ 重启 OpenCode 服务,使全局配置生效:
65
+
66
+ ```sh
67
+ opencode service restart
68
+ ```
69
+
70
+ 打开 `/plugins`,应看到 `magpie.providers`;打开 `/models`,选择 Cursor、WorkBuddy 等分组下的模型。
71
+
72
+ ### Provider 名称与模型 ID
73
+
74
+ 显示名与 Magpie 保持一致,内部 ID 则使用命名空间,避免覆盖另一个 Cursor / WorkBuddy 插件:
75
+
76
+ | OpenCode 中的显示名 | 内部 provider ID | 示例模型引用 | 发给 Magpie 的 model |
77
+ | --- | --- | --- | --- |
78
+ | Cursor | `magpie-cursor` | `magpie-cursor/gpt-5.5` | `cursor/gpt-5.5` |
79
+ | WorkBuddy | `magpie-workbuddy` | `magpie-workbuddy/claude-opus-4-6` | `workbuddy/claude-opus-4-6` |
80
+
81
+ 示例模型仅说明格式,实际列表取决于 Magpie 当前账号与配置。Magpie 自定义 provider ID 会原样映射为带 `magpie-` 前缀的 ID。
82
+
83
+ Magpie 的 routing group(例如 `group/fast`)单独成为一个分组,内部 provider ID 为 `magpie-group%2Ffast`,发送时仍保留 `group/fast`,不会误归到第一个候选服务。
84
+
85
+ ## 自动发现与请求行为
86
+
87
+ 插件先检查网关根路径的 `name: "magpie"`,再请求 `/v1/models`。请求携带 `X-Magpie-Prices: 1` 读取可用的网关价格扩展。
88
+
89
+ 目录映射保留模型的上下文窗口、最大输出、输入输出模态和 reasoning 档位。仅发现聊天目录;重复的无 provider 前缀别名、图片生成或其他非聊天专用模型不会注册为聊天模型。
90
+
91
+ 根据 `native_endpoints` 选择 OpenCode 内置 runtime:
92
+
93
+ | Magpie 元数据 | OpenCode runtime |
94
+ | --- | --- |
95
+ | 包含 `/v1/messages` | `anthropic-compatible` |
96
+ | 否则包含 `/v1/responses` | `openai-compatible/responses` |
97
+ | 其他情况 | `openai-compatible`(Chat Completions) |
98
+
99
+ 消息、工具调用和工具结果由 OpenCode 原生 runtime 编码,再由 Magpie 转接。插件传递 `X-Magpie-Session` 保持会话标识,并指定 HTTP 传输。模型上游支持的完整能力仍取决于 Magpie 和相应服务。
100
+
101
+ 刷新成功时替换完整目录;刷新失败保留最近一次成功的目录。首次发现失败会报告初始化错误,不生成虚假的可用模型。
102
+
103
+ ## 网关地址与启动
104
+
105
+ 地址优先级:
106
+
107
+ 1. OpenCode 服务进程中的 `MAGPIE_ADDR`。
108
+ 2. `$XDG_CONFIG_HOME/magpie/settings.json` 的 `port`。
109
+ 3. 未指定 XDG 路径时,使用 `~/.config/magpie/settings.json` 的 `port`。
110
+ 4. 默认端口 `3425`。
111
+
112
+ `MAGPIE_ADDR` 使用 Magpie 自身的监听地址格式,例如:
113
+
114
+ ```sh
115
+ MAGPIE_ADDR=127.0.0.1:3426 opencode --standalone
116
+ ```
117
+
118
+ `0.0.0.0`、`::` 监听地址会转换为本机访问地址。本版本面向本机网关,不支持远程服务器地址。共享服务模式下,在终端临时设置变量不一定会改变已经启动的 OpenCode 服务环境。
119
+
120
+ 网关不在线时,插件在 PATH、`~/.local/bin`、常见 Homebrew 路径以及 macOS 的 `Magpie.app` 中寻找可执行文件,并后台启动 `magpie serve`。Windows 通过 PATH / `~/.local/bin` 寻找 `magpie.exe`。如果无法找到,请安装 Magpie 或把它加入 OpenCode 服务的 PATH。
121
+
122
+ 启动后会等待网关就绪;请求前和目录刷新时也会检查网关。插件卸载不会关闭已启动的共享网关。若端口被其他服务占用,会报错而不是向其发送模型请求。
123
+
124
+ 便携版使用自定义端口时,请显式设置 `MAGPIE_ADDR`;插件不自动推断便携版的 data 目录。
125
+
126
+ ## 价格与费用统计
127
+
128
+ ### 价格从哪里来
129
+
130
+ 价格表完整内置于 [`src/model-pricing.ts`](src/model-pricing.ts),包含模型别名、渠道后缀处理、版本回退与 provider 专属覆盖。它从原有共享价格模块迁移而来,之后随本项目版本独立维护;运行时不请求私有包、私有 registry 或其他仓库。
131
+
132
+ 普通模型使用以下顺序:
133
+
134
+ 1. 内置价格表,优先应用已识别 provider 的专属覆盖。
135
+ 2. 内置表未覆盖时,使用 Magpie 返回的 `magpie_price`。
136
+ 3. 两边均没有价格时,不启用该模型,避免把未知价格显示为免费。
137
+
138
+ Cursor 使用 `cursor` 覆盖,WorkBuddy 使用 `codebuddy` 覆盖;其他已识别服务按表中对应 provider 处理。Routing group 使用 Magpie 提供的价格,不按首个成员猜测。明确记录的零价格仍视为有效价格。
139
+
140
+ 所有价格单位都是 **美元 / 百万 token**。OpenCode 用这些单价计算请求费用。普通计费的概念公式为:
141
+
142
+ ```text
143
+ 费用 = (非缓存输入 × input + 输出 × output
144
+ + 缓存读取 × cache.read + 缓存写入 × cache.write) / 1,000,000
145
+ ```
146
+
147
+ 缓存部分不能再次算入非缓存输入。不同协议的 token 字段由宿主 runtime 归一化;插件不重写 token 来凑费用。继承的价格记录缺少缓存单价时,当前映射将该项设为 0。
148
+
149
+ ### 准确性边界
150
+
151
+ - 表中同时存在官方参考价、服务专属估算价和版本回退,**不是所有模型的实时账单价**。
152
+ - Magpie 用户自定义价格不会覆盖已命中的内置价格表。
153
+ - Routing group 可能动态切换成员,目录价格不保证等于实际被选成员的价格。
154
+ - Cursor 等服务的 `usage.magpie_deferred` 是迟到用量,Magpie 会补记到账本;OpenCode 原生 runtime 不会因此修改历史费用。
155
+ - 当前价格映射不支持 Magpie 的上下文阶梯价和独立的一小时缓存写入价。
156
+
157
+ 因此,OpenCode 费用适合观察 token 成本,**不能承诺与 Magpie 或订阅服务最终账单完全一致**。
158
+
159
+ ### 查看或复用价格表
160
+
161
+ 包提供公开的 `pricing` 子路径:
162
+
163
+ ```js
164
+ import { getModelPricing, resolveModelPricingKey } from 'opencode-magpie-plugin/pricing';
165
+
166
+ console.log(resolveModelPricingKey('claude-opus-4-6'));
167
+ console.log(getModelPricing('claude-opus-4-6', 'cursor'));
168
+ ```
169
+
170
+ `getModelPricing()` 对未知模型返回 `undefined`,不会自动填零;调用方获得的是副本,不会修改全局价格表。
171
+
172
+ ## 本地开发 / file 模式
173
+
174
+ ```sh
175
+ git clone https://github.com/yee94/opencode-magpie-plugin.git
176
+ cd opencode-magpie-plugin
177
+ corepack enable
178
+ pnpm install
179
+ pnpm check
180
+ ```
181
+
182
+ 把配置中的 npm 包替换为构建目录的 URL:
183
+
184
+ ```jsonc
185
+ {
186
+ "plugins": ["file:///absolute/path/opencode-magpie-plugin/dist"]
187
+ }
188
+ ```
189
+
190
+ **必须指向 `dist` 目录,不是 `dist/index.mjs` 文件,也不是仓库根目录。** V2 本地目录加载器寻找目录内的 `server` / `index` 入口;直接填写文件路径会被忽略并记录 `configured plugin path must be a directory`。
191
+
192
+ 修改源码后重新执行 `pnpm build`,再重新加载 OpenCode 服务。
193
+
194
+ ## 排查
195
+
196
+ | 现象 | 检查项 |
197
+ | --- | --- |
198
+ | `/plugins` 没有 `magpie.providers` | 全局配置是否被当前服务读取;file 模式是否填写 `dist` 目录并已构建;查看 OpenCode 日志 |
199
+ | 提示未安装 Magpie | 安装 [Magpie](https://usemagpie.ai/zh/),确认服务进程 PATH 可以找到它 |
200
+ | 启动超时 | 手动执行 `magpie serve` 查看错误,检查监听端口 |
201
+ | 插件已加载但没有模型 | 在 Magpie 登录并启用服务,检查 `/v1/models` 是否有模型及有效价格 |
202
+ | 添加模型后没出现 | 等待下一个 30 秒刷新周期;初次初始化失败则重载 OpenCode |
203
+ | 原有 Cursor 与新 Cursor 同时出现 | 两个插件可同时存在;Magpie 的内部 ID 是 `magpie-cursor` |
204
+ | 费用和实际账单不同 | 查看上面的价格优先级、迟到用量和阶梯价格边界 |
205
+
206
+ 本机目录检查(不会调用模型):
207
+
208
+ ```sh
209
+ curl http://127.0.0.1:3425/
210
+ curl -H 'Authorization: Bearer magpie' -H 'X-Magpie-Prices: 1' \
211
+ http://127.0.0.1:3425/v1/models
212
+ ```
213
+
214
+ 这里的 `magpie` 是本机网关占位 key,不是上游账号 token。
215
+
216
+ ## 测试与发布
217
+
218
+ ```sh
219
+ pnpm check
220
+ pnpm pack
221
+ pnpm publish --access public --registry=https://registry.npmjs.org/
222
+ ```
223
+
224
+ 测试覆盖目录分组与替换、wire model ID、协议元数据、价格归一化与覆盖、未知价格、会话头、网关身份检查、自动启动与并发去重、未安装提示、刷新失败和清理。测试不消耗真实服务额度。
225
+
226
+ 只发布 `dist`、README 和许可证,**没有 runtime dependencies**。价格表变更时应更新相应测试,并在 release 说明价格来源与变化。
227
+
228
+ ## 相关项目与许可证
229
+
230
+ - [Magpie](https://usemagpie.ai/):账号、网关、路由和上游转接。
231
+ - [OpenCode V2 plugins](https://opencode.ai/v2/docs/build/plugins):插件生命周期与动态 provider API。
232
+
233
+ 这是独立集成项目,不是 Magpie 或 OpenCode 官方插件。插件代码采用 [MIT](LICENSE);Magpie 与各上游服务遵循各自的许可证和服务条款。
@@ -0,0 +1,74 @@
1
+ //#region src/opencode.d.ts
2
+ /** Structural subset of the OpenCode V2 plugin API; the host supplies the runtime. */
3
+ type Registration = {
4
+ dispose: () => Promise<void>;
5
+ };
6
+ type ProviderInfo = {
7
+ id: string;
8
+ name: string;
9
+ activation: 'enabled';
10
+ package: string;
11
+ settings?: Record<string, unknown>;
12
+ headers?: Record<string, string>;
13
+ };
14
+ type ModelInfo2 = {
15
+ id: string;
16
+ modelID: string;
17
+ providerID: string;
18
+ name: string;
19
+ capabilities: {
20
+ tools: boolean;
21
+ input: readonly string[];
22
+ output: readonly string[];
23
+ };
24
+ limit: {
25
+ context: number;
26
+ output: number;
27
+ };
28
+ variants: readonly {
29
+ id: string;
30
+ settings?: Record<string, unknown>;
31
+ }[];
32
+ status: 'active';
33
+ enabled: boolean;
34
+ time: {
35
+ released: number;
36
+ };
37
+ cost: readonly {
38
+ input: number;
39
+ output: number;
40
+ cache: {
41
+ read: number;
42
+ write: number;
43
+ };
44
+ }[];
45
+ package?: string;
46
+ settings?: Record<string, unknown>;
47
+ };
48
+ type ProviderEditor = {
49
+ add: (entry: {
50
+ info: ProviderInfo;
51
+ models: ModelInfo2[];
52
+ }) => void;
53
+ };
54
+ type PluginContext = {
55
+ provider?: {
56
+ transform: (callback: (editor: ProviderEditor) => void) => Promise<Registration>;
57
+ reload: () => Promise<void>;
58
+ };
59
+ session: {
60
+ hook: (name: 'http.request', callback: (event: {
61
+ sessionID: string;
62
+ request: Request;
63
+ }) => Promise<void>) => Promise<Registration>;
64
+ };
65
+ };
66
+ type Plugin2 = {
67
+ id: string;
68
+ setup: (ctx: PluginContext) => Promise<(() => Promise<void>) | void>;
69
+ };
70
+ //#endregion
71
+ //#region src/index.d.ts
72
+ declare const plugin: Plugin2;
73
+ //#endregion
74
+ export { plugin as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,301 @@
1
+ import { n as getModelPricing } from "./model-pricing--x7wwPba.mjs";
2
+ import { spawn } from "node:child_process";
3
+ import { constants } from "node:fs";
4
+ import { access, readFile } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { delimiter, join } from "node:path";
7
+ import { setTimeout } from "node:timers/promises";
8
+
9
+ //#region src/opencode.ts
10
+ const createTrackedSetup = () => {
11
+ const registrations = [];
12
+ return {
13
+ track: async (registration) => {
14
+ registrations.push(await registration);
15
+ },
16
+ cleanup: async () => {
17
+ await registrations.splice(0).reverse().reduce(async (previous, registration) => {
18
+ await previous;
19
+ await registration.dispose().catch(() => {});
20
+ }, Promise.resolve());
21
+ }
22
+ };
23
+ };
24
+ const reloadProviderCatalog = async (ctx) => {
25
+ await ctx.provider?.reload();
26
+ };
27
+ /** USD per million tokens. Missing cache rates retain the original registry's zero fallback. */
28
+ const normalizeModelCosts = (cost) => {
29
+ if (!cost || typeof cost !== "object") return [];
30
+ const value = cost;
31
+ if (typeof value.input !== "number" || !Number.isFinite(value.input) || typeof value.output !== "number" || !Number.isFinite(value.output)) return [];
32
+ return [{
33
+ input: value.input,
34
+ output: value.output,
35
+ cache: {
36
+ read: value.cache?.read ?? value.cache_read ?? 0,
37
+ write: value.cache?.write ?? value.cache_write ?? 0
38
+ }
39
+ }];
40
+ };
41
+ const toClassicModelInfo = (providerID, catalogID, entry) => ({
42
+ id: catalogID,
43
+ modelID: entry.id,
44
+ providerID,
45
+ name: entry.name,
46
+ capabilities: {
47
+ tools: entry.tool_call !== false,
48
+ input: entry.modalities?.input?.length ? entry.modalities.input : ["text"],
49
+ output: entry.modalities?.output?.length ? entry.modalities.output : ["text"]
50
+ },
51
+ limit: { ...entry.limit },
52
+ variants: [],
53
+ status: "active",
54
+ enabled: true,
55
+ time: { released: 0 },
56
+ cost: normalizeModelCosts(entry.cost)
57
+ });
58
+
59
+ //#endregion
60
+ //#region src/catalog.ts
61
+ const pricingProvider = (owner) => {
62
+ const id = owner.toLowerCase();
63
+ if (id === "workbuddy") return "codebuddy";
64
+ return [
65
+ "astra",
66
+ "boxai",
67
+ "codebuddy",
68
+ "cursor",
69
+ "imate",
70
+ "kalm"
71
+ ].find((provider) => provider === id);
72
+ };
73
+ const providerName = (model) => {
74
+ const label = model.magpie_label?.split(" · ").slice(1).join(" · ");
75
+ if (label) return label;
76
+ return {
77
+ cursor: "Cursor",
78
+ workbuddy: "WorkBuddy"
79
+ }[model.owned_by] ?? model.owned_by;
80
+ };
81
+ const buildInventory = (rows, baseURL) => {
82
+ const providers = /* @__PURE__ */ new Map();
83
+ rows.filter((row) => !row.kind && row.id.includes("/")).forEach((row) => {
84
+ const group = row.id.startsWith("group/");
85
+ const owner = group ? row.id : row.owned_by;
86
+ const providerID = `magpie-${encodeURIComponent(owner)}`;
87
+ const modelID = row.id.slice(row.id.indexOf("/") + 1);
88
+ const cost = (!group ? getModelPricing(modelID, pricingProvider(owner)) : void 0) ?? row.magpie_price;
89
+ const model = toClassicModelInfo(providerID, modelID, {
90
+ id: row.id,
91
+ name: row.display_name ?? modelID,
92
+ cost,
93
+ limit: {
94
+ context: row.context_window || 128e3,
95
+ output: row.max_output_tokens || 32e3
96
+ },
97
+ modalities: row.modalities,
98
+ tool_call: true
99
+ });
100
+ model.enabled = !!cost;
101
+ if (!cost) model.name += " (价格未知)";
102
+ const anthropic = row.native_endpoints?.includes("/v1/messages");
103
+ const responses = !anthropic && row.native_endpoints?.includes("/v1/responses");
104
+ model.package = anthropic ? "@opencode/ai/providers/anthropic-compatible" : responses ? "@opencode/ai/providers/openai-compatible/responses" : "@opencode/ai/providers/openai-compatible";
105
+ model.settings = {
106
+ baseURL: `${baseURL}/v1`,
107
+ apiKey: "magpie",
108
+ transport: "http"
109
+ };
110
+ model.variants = (row.reasoning_levels ?? []).map((effort) => ({
111
+ id: effort,
112
+ settings: { reasoningEffort: effort }
113
+ }));
114
+ const entry = providers.get(providerID) ?? {
115
+ info: {
116
+ id: providerID,
117
+ name: group ? row.display_name ?? modelID : providerName(row),
118
+ activation: "enabled",
119
+ package: "@opencode/ai/providers/openai-compatible",
120
+ settings: {
121
+ baseURL: `${baseURL}/v1`,
122
+ apiKey: "magpie",
123
+ transport: "http"
124
+ },
125
+ headers: {
126
+ Authorization: "Bearer magpie",
127
+ "X-Magpie-Agent": "opencode"
128
+ }
129
+ },
130
+ models: []
131
+ };
132
+ if (!entry.models.some((existing) => existing.id === model.id)) entry.models.push(model);
133
+ providers.set(providerID, entry);
134
+ });
135
+ return [...providers.values()];
136
+ };
137
+
138
+ //#endregion
139
+ //#region src/gateway.ts
140
+ const INSTALL_MESSAGE = "未安装 Magpie,请先从 https://usemagpie.ai/zh/ 安装并登录所需服务,再使用此插件。";
141
+ const resolveBaseURL = async () => {
142
+ if (process.env.MAGPIE_ADDR) {
143
+ const addr = process.env.MAGPIE_ADDR.replace(/^:/, "127.0.0.1:");
144
+ const url = new URL(addr.includes("://") ? addr : `http://${addr}`);
145
+ if (url.hostname === "0.0.0.0" || url.hostname === "[::]") url.hostname = "127.0.0.1";
146
+ if (![
147
+ "127.0.0.1",
148
+ "localhost",
149
+ "[::1]"
150
+ ].includes(url.hostname)) throw new Error("Magpie 自动启动仅支持本机 MAGPIE_ADDR。");
151
+ return url.origin;
152
+ }
153
+ const port = (await readFile(join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "magpie", "settings.json"), "utf8").then((text) => JSON.parse(text)).catch((error) => {
154
+ if (error.code === "ENOENT") return {};
155
+ throw error;
156
+ })).port || 3425;
157
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("Magpie settings.json 中的 port 无效。");
158
+ return `http://127.0.0.1:${port}`;
159
+ };
160
+ const findExecutable = async () => {
161
+ const binary = process.platform === "win32" ? "magpie.exe" : "magpie";
162
+ const candidates = [
163
+ ...(process.env.PATH ?? "").split(delimiter).filter(Boolean).map((path) => join(path, binary)),
164
+ join(homedir(), ".local", "bin", binary),
165
+ "/opt/homebrew/bin/magpie",
166
+ "/usr/local/bin/magpie",
167
+ "/Applications/Magpie.app/Contents/MacOS/magpie",
168
+ join(homedir(), "Applications/Magpie.app/Contents/MacOS/magpie")
169
+ ];
170
+ return (await Promise.all(candidates.map(async (path) => await access(path, constants.X_OK).then(() => path, () => void 0)))).find(Boolean);
171
+ };
172
+ const probeGateway = async (baseURL) => {
173
+ let response;
174
+ try {
175
+ response = await fetch(baseURL, { signal: AbortSignal.timeout(1500) });
176
+ } catch {
177
+ return false;
178
+ }
179
+ const info = await response.json().catch(() => void 0);
180
+ if (!response.ok || info?.name !== "magpie") throw new Error(`${baseURL} 已被非 Magpie 服务占用。`);
181
+ return true;
182
+ };
183
+ const startGateway = async (executable) => {
184
+ await new Promise((resolve, reject) => {
185
+ const child = spawn(executable, ["serve"], {
186
+ detached: true,
187
+ stdio: "ignore",
188
+ windowsHide: true
189
+ });
190
+ child.once("error", reject);
191
+ child.once("spawn", () => {
192
+ child.unref();
193
+ resolve();
194
+ });
195
+ });
196
+ };
197
+ const starting = /* @__PURE__ */ new Map();
198
+ const ensureGateway = async (baseURL) => {
199
+ if (await probeGateway(baseURL)) return;
200
+ const pending = starting.get(baseURL);
201
+ if (pending) return pending;
202
+ const task = (async () => {
203
+ const executable = await findExecutable();
204
+ if (!executable) throw new Error(INSTALL_MESSAGE);
205
+ await startGateway(executable);
206
+ const wait = async (remaining) => {
207
+ if (await probeGateway(baseURL)) return;
208
+ if (remaining === 0) throw new Error("Magpie 网关启动超时,请运行 magpie serve 查看错误。");
209
+ await setTimeout(500);
210
+ return wait(remaining - 1);
211
+ };
212
+ await wait(30);
213
+ })();
214
+ starting.set(baseURL, task);
215
+ try {
216
+ await task;
217
+ } finally {
218
+ starting.delete(baseURL);
219
+ }
220
+ };
221
+ const fetchModels = async (baseURL) => {
222
+ const response = await fetch(`${baseURL}/v1/models`, {
223
+ headers: {
224
+ Authorization: "Bearer magpie",
225
+ "X-Magpie-Prices": "1"
226
+ },
227
+ signal: AbortSignal.timeout(15e3)
228
+ });
229
+ if (!response.ok) throw new Error(`Magpie 模型发现失败:HTTP ${response.status}`);
230
+ const body = await response.json();
231
+ if (!Array.isArray(body.data) || body.data.some((model) => typeof model.id !== "string" || typeof model.owned_by !== "string")) throw new Error("Magpie /v1/models 返回了无效的模型目录。");
232
+ return body.data;
233
+ };
234
+
235
+ //#endregion
236
+ //#region src/index.ts
237
+ const plugin = {
238
+ id: "magpie.providers",
239
+ setup: async (ctx) => {
240
+ if (!ctx.provider) throw new Error("Magpie 插件需要 OpenCode V2 provider.transform。");
241
+ const baseURL = await resolveBaseURL();
242
+ await ensureGateway(baseURL);
243
+ let inventory = buildInventory(await fetchModels(baseURL), baseURL);
244
+ const { track, cleanup } = createTrackedSetup();
245
+ let disposed = false;
246
+ let refreshing = false;
247
+ try {
248
+ await track(ctx.provider.transform((editor) => {
249
+ inventory.forEach((entry) => {
250
+ editor.add(entry);
251
+ });
252
+ }));
253
+ await track(ctx.session.hook("http.request", async (event) => {
254
+ const url = new URL(event.request.url);
255
+ if (url.origin !== baseURL || !url.pathname.startsWith("/v1/")) return;
256
+ await ensureGateway(baseURL);
257
+ event.request.headers.set("X-Magpie-Session", event.sessionID);
258
+ event.request.headers.set("X-Magpie-Agent", "opencode");
259
+ }));
260
+ await reloadProviderCatalog(ctx);
261
+ } catch (error) {
262
+ await cleanup();
263
+ throw error;
264
+ }
265
+ const refresh = async () => {
266
+ if (disposed || refreshing) return;
267
+ refreshing = true;
268
+ try {
269
+ await ensureGateway(baseURL);
270
+ const next = buildInventory(await fetchModels(baseURL), baseURL);
271
+ if (!disposed && JSON.stringify(next) !== JSON.stringify(inventory)) {
272
+ const previous = inventory;
273
+ inventory = next;
274
+ try {
275
+ await reloadProviderCatalog(ctx);
276
+ } catch (error) {
277
+ inventory = previous;
278
+ throw error;
279
+ }
280
+ }
281
+ } catch (error) {
282
+ console.warn("[magpie] 模型刷新失败,保留上次目录:", error instanceof Error ? error.message : String(error));
283
+ } finally {
284
+ refreshing = false;
285
+ }
286
+ };
287
+ const timer = setInterval(() => {
288
+ refresh();
289
+ }, 3e4);
290
+ timer.unref();
291
+ return async () => {
292
+ disposed = true;
293
+ clearInterval(timer);
294
+ await cleanup();
295
+ };
296
+ }
297
+ };
298
+ var src_default = plugin;
299
+
300
+ //#endregion
301
+ export { src_default as default };