opencode-magpie-plugin 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,7 +27,7 @@ OpenCode V2
27
27
  - 启动时发现目录,每 30 秒刷新;服务新增、模型下线都能反映到 OpenCode。
28
28
  - Provider 显示 Magpie 中的分组名称,而不是统一挤在一个 “Magpie” 下;路由分组统一归入 Magpie。
29
29
  - 内置独立价格表和模型名归一化逻辑,支持输入、输出、缓存读取与写入价格。
30
- - Magpie 已安装但未运行时自动执行 `magpie serve`;未安装时给出安装链接。
30
+ - Magpie 已安装但未运行时自动启动;macOS 上找到 app 内的可执行文件时优先启动 app,保留路由页;未安装时给出安装链接。
31
31
  - 登录和服务凭据由 Magpie 管理,插件不需要复制上游 token。
32
32
 
33
33
  这不是一个绕过 Magpie 的社区插件宿主:**推理请求仍经过本机 Magpie 网关**。
@@ -55,7 +55,7 @@ OpenCode V2
55
55
 
56
56
  ```jsonc
57
57
  {
58
- "plugins": ["opencode-magpie-plugin@0.1.4"]
58
+ "plugins": ["opencode-magpie-plugin@0.1.6"]
59
59
  }
60
60
  ```
61
61
 
@@ -122,9 +122,9 @@ MAGPIE_ADDR=127.0.0.1:3426 opencode --standalone
122
122
 
123
123
  `0.0.0.0`、`::` 监听地址会转换为本机访问地址。本版本面向本机网关,不支持远程服务器地址。共享服务模式下,在终端临时设置变量不一定会改变已经启动的 OpenCode 服务环境。
124
124
 
125
- 网关不在线时,插件在 PATH、`~/.local/bin`、常见 Homebrew 路径以及 macOS 的 `Magpie.app` 中寻找可执行文件,并后台启动 `magpie serve`。Windows 通过 PATH / `~/.local/bin` 寻找 `magpie.exe`。如果无法找到,请安装 Magpie 或把它加入 OpenCode 服务的 PATH。
125
+ 网关不在线时,插件在 PATH、`~/.local/bin`、常见 Homebrew 路径以及 macOS 的 `Magpie.app` 中寻找可执行文件并把它拉起来。找到的是 `Magpie.app` 里的可执行文件时(安装器的软链会解析到真实路径),macOS 上优先启动 `magpie tray`——它同样提供网关,而且带窗口,路由页可以查看。app 非零退出或被信号终止后,才退回无窗口的 `magpie serve`。其他情况直接用 `serve`。Windows 通过 PATH / `~/.local/bin` 寻找 `magpie.exe`。如果无法找到,请安装 Magpie 或把它加入 OpenCode 服务的 PATH。
126
126
 
127
- 启动后会等待网关就绪;请求前和目录刷新时也会检查网关。插件卸载不会关闭已启动的共享网关。若端口被其他服务占用,会报错而不是向其发送模型请求。
127
+ 启动后会等待网关就绪;app 明确异常退出时才降级到 `serve`。app 仍在启动或正常退出(可能已交给现有 app)时,超时会提示检查 app,不会另起 `serve` 抢占端口。请求前和目录刷新时也会检查网关。插件卸载不会关闭已启动的共享网关。若端口被其他服务占用,会报错而不是向其发送模型请求。
128
128
 
129
129
  便携版使用自定义端口时,请显式设置 `MAGPIE_ADDR`;插件不自动推断便携版的 data 目录。
130
130
 
@@ -138,7 +138,20 @@ MAGPIE_ADDR=127.0.0.1:3426 opencode --standalone
138
138
 
139
139
  1. 内置价格表,优先应用已识别 provider 的专属覆盖。
140
140
  2. 内置表未覆盖时,使用 Magpie 返回的 `magpie_price`。
141
- 3. 两边均没有价格时,不启用该模型,避免把未知价格显示为免费。
141
+ 3. 普通模型仍缺价时,查询 models.dev 本地缓存:优先同 provider 的精确 ID,再查已识别厂商(OpenAI、Anthropic、DeepSeek、Google、xAI)的精确 ID 或 `canonical_model_id`。不跨版本猜价、不采用其他转售商报价、不使用订阅 plan 目录的零价。
142
+ 4. 所有来源均没有价格时,不启用该模型,避免把未知价格显示为免费。**路由组例外**:Magpie 只在组内全部成员同价时才给组报价,而路由组每一轮的成员由路由决定,成本本来就是一个区间而不是单一数字。这类组保持可选用、保留自己的名字,只是费用读数不精确。路由分组仍只用 Magpie 报价,不根据 `auto-*` 名称推断成员价格。
143
+
144
+ models.dev 缓存写入 `$XDG_CACHE_HOME/opencode-magpie-plugin/models.json`(默认 `~/.cache/opencode-magpie-plugin/models.json`)。首次可只读复用 Magpie、OpenCode 的 `models.json`;下载只写插件自己的目录。每次模型刷新检查缓存,超过 24 小时后台更新,缺价时可提前到 6 小时;同进程下载去重且失败后至少间隔 6 小时重试。首次下载和更新不阻塞模型发现,成功后下一次 30 秒刷新采用新目录;离线保留旧缓存。下载源为 `https://models.dev/api.json`,仍然零运行时依赖,目前只采用基础价,未接入阶梯价。
145
+
146
+ ### 0.1.6
147
+
148
+ - 无报价路由组保持可选并保留原名;OpenCode 对这些请求的费用估算仍为 0,不代表实际免费,实际费用请查看 Magpie 或服务账单。
149
+ - macOS 找到 Magpie app 时优先启动带窗口的网关,解析安装器软链;仅在 app 异常退出时降级到 `serve`,避免慢启动或交接现有 app 时被无窗口进程抢占端口。
150
+ - 内置费率不变,尚未接入按请求实际路由成员计费。
151
+
152
+ ### 0.1.5
153
+
154
+ 新增 models.dev 缓存作为缺价兜底,不改动内置费率和 provider 覆盖。补充的价格来自 models.dev,对应目录更新后可能变化;以实际服务账单为准。
142
155
 
143
156
  Cursor 使用 `cursor` 覆盖,WorkBuddy 使用 `codebuddy` 覆盖;其他已识别服务按表中对应 provider 处理。Routing group 只用 Magpie 提供的价格,不按成员猜测。明确记录的零价格仍视为有效价格。
144
157
 
package/dist/index.d.mts CHANGED
@@ -70,5 +70,6 @@ type Plugin2 = {
70
70
  //#endregion
71
71
  //#region src/index.d.ts
72
72
  declare const plugin: Plugin2;
73
+ declare const setupPlugin: Plugin2['setup'];
73
74
  //#endregion
74
- export { plugin as default };
75
+ export { plugin as default, setupPlugin };
package/dist/index.mjs CHANGED
@@ -1,11 +1,183 @@
1
1
  import { n as getModelPricing } from "./model-pricing--x7wwPba.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { access, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { delimiter, dirname, join } from "node:path";
2
6
  import { spawn } from "node:child_process";
3
7
  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
8
  import { setTimeout } from "node:timers/promises";
8
9
 
10
+ //#region src/catalog-cache.ts
11
+ /**
12
+ * models.dev catalog, read the way Magpie reads it.
13
+ *
14
+ * Magpie fetches `models.dev/api.json`, keeps it in `~/.cache/magpie/models.json`,
15
+ * uses OpenCode's `~/.cache/opencode/models.json` when its own is absent, treats it
16
+ * as stale after a day, and looks again sooner when a model it cannot price appears.
17
+ * This module mirrors that, so a model Magpie knows comes with a price here too.
18
+ */
19
+ const MODELS_DEV_URL = "https://models.dev/api.json";
20
+ const DAY = 1440 * 60 * 1e3;
21
+ const MISSING_RETRY = 360 * 60 * 1e3;
22
+ /** Own writable cache, followed by read-only Magpie and OpenCode seed catalogs. */
23
+ const cachePaths = () => {
24
+ const cache = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
25
+ return [
26
+ join(cache, "opencode-magpie-plugin", "models.json"),
27
+ join(cache, "magpie", "models.json"),
28
+ join(cache, "opencode", "models.json")
29
+ ];
30
+ };
31
+ const parse = (text) => {
32
+ try {
33
+ const data = JSON.parse(text);
34
+ if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
35
+ const providers = Object.values(data);
36
+ return providers.length && providers.every((p) => p && typeof p === "object" && p.models && typeof p.models === "object" && !Array.isArray(p.models) && Object.values(p.models).every((m) => m && typeof m === "object")) ? data : void 0;
37
+ } catch {
38
+ return;
39
+ }
40
+ };
41
+ /** First readable, valid catalog and its age; a corrupt file does not hide the seeds. */
42
+ const catalogSource = async () => {
43
+ for (const path of cachePaths()) {
44
+ let age;
45
+ try {
46
+ const stats = await stat(path);
47
+ if (!stats.isFile()) continue;
48
+ if (!parse(await readFile(path, "utf8"))) continue;
49
+ age = Date.now() - stats.mtimeMs;
50
+ } catch {
51
+ continue;
52
+ }
53
+ return {
54
+ path,
55
+ age
56
+ };
57
+ }
58
+ };
59
+ const readCatalogCache = async () => {
60
+ const [first] = cachePaths();
61
+ const source = await catalogSource();
62
+ if (!source) return {
63
+ data: void 0,
64
+ path: first,
65
+ stale: true
66
+ };
67
+ const data = parse(await readFile(source.path, "utf8").catch(() => ""));
68
+ if (!data) return {
69
+ data: void 0,
70
+ path: source.path,
71
+ stale: true
72
+ };
73
+ return {
74
+ data,
75
+ path: source.path,
76
+ stale: source.age > DAY
77
+ };
78
+ };
79
+ /** Download the catalog and write it atomically, leaving the previous file intact on failure. */
80
+ const fetchCatalogCache = async (url = MODELS_DEV_URL, timeout = 3e4) => {
81
+ const path = cachePaths()[0];
82
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeout) });
83
+ if (!response.ok) throw new Error(`models.dev 返回 HTTP ${response.status}`);
84
+ const text = await response.text();
85
+ const data = parse(text);
86
+ if (!data || Object.keys(data).length === 0) throw new Error("models.dev 返回了无效的模型目录");
87
+ await mkdir(dirname(path), { recursive: true });
88
+ const temporary = `${path}.${randomUUID()}.tmp`;
89
+ try {
90
+ await writeFile(temporary, text);
91
+ await rename(temporary, path);
92
+ } finally {
93
+ await rm(temporary, { force: true });
94
+ }
95
+ return {
96
+ data,
97
+ path,
98
+ stale: false
99
+ };
100
+ };
101
+ /** Read the cache and refresh it in the background when stale; discovery never waits on the network. */
102
+ const attempts = /* @__PURE__ */ new Map();
103
+ const pending = /* @__PURE__ */ new Map();
104
+ const loadCatalogCache = async (missing = false) => {
105
+ const cache = await readCatalogCache().catch(() => ({
106
+ data: void 0,
107
+ path: cachePaths()[0],
108
+ stale: true
109
+ }));
110
+ const path = cachePaths()[0];
111
+ if ((cache.stale || missing && missingPriceStale(await catalogSource())) && !pending.has(path) && Date.now() - (attempts.get(path) ?? -Infinity) >= MISSING_RETRY) {
112
+ attempts.set(path, Date.now());
113
+ const task = fetchCatalogCache().then(() => {}).catch((error) => {
114
+ console.warn("[magpie] models.dev 价格目录刷新失败,继续使用本地缓存:", error instanceof Error ? error.message : String(error));
115
+ }).finally(() => {
116
+ pending.delete(path);
117
+ });
118
+ pending.set(path, task);
119
+ }
120
+ return cache;
121
+ };
122
+ /** A model Magpie gave no price for: refetch sooner than a day, as Magpie does. */
123
+ const missingPriceStale = (source) => (source?.age ?? Infinity) > MISSING_RETRY;
124
+ const bareID = (id) => {
125
+ const slash = id.indexOf("/");
126
+ return slash < 0 ? id : id.slice(slash + 1);
127
+ };
128
+ const catalogPrice = (cost) => {
129
+ if (!cost || typeof cost.input !== "number" || typeof cost.output !== "number") return void 0;
130
+ if ([
131
+ cost.input,
132
+ cost.output,
133
+ cost.cache_read ?? 0,
134
+ cost.cache_write ?? 0
135
+ ].some((n) => typeof n !== "number" || !Number.isFinite(n) || n < 0)) return void 0;
136
+ return {
137
+ input: cost.input,
138
+ output: cost.output,
139
+ cache: {
140
+ read: cost.cache_read ?? 0,
141
+ write: cost.cache_write ?? 0
142
+ }
143
+ };
144
+ };
145
+ /**
146
+ * The price models.dev lists for a model, under the maker that sells it.
147
+ *
148
+ * The maker's own catalog is the only one read, so a reseller's tariff never
149
+ * passes for the maker's. Matching follows models.dev's own links rather than
150
+ * guessing by name:
151
+ * 1. the maker's entry of that id;
152
+ * 2. the maker's entry whose `canonical_model_id` is it, e.g. DeepSeek's
153
+ * `deepseek-flash` standing for `deepseek/deepseek-v4.1-flash`;
154
+ * Known model prefixes may fall back to the maker's catalog. Conflicting
155
+ * canonical entries and subscription-plan catalogs are not used for prices.
156
+ */
157
+ const lookupCatalogPrice = (catalog, maker, modelID) => {
158
+ if (/(?:^|-)plan(?:-|$)/i.test(maker)) return void 0;
159
+ const id = modelID.replace(/@\d+(?:k|m)$/i, "").toLowerCase();
160
+ const own = priceInProvider(catalog, maker, id);
161
+ if (own) return own;
162
+ const vendor = /^(?:gpt-|o[134](?:-|$))/.test(id) ? "openai" : id.startsWith("claude-") ? "anthropic" : id.startsWith("deepseek-") ? "deepseek" : id.startsWith("gemini-") ? "google" : id.startsWith("grok-") ? "xai" : void 0;
163
+ return vendor && vendor !== maker ? priceInProvider(catalog, vendor, id) : void 0;
164
+ };
165
+ const priceInProvider = (catalog, maker, id) => {
166
+ const models = catalog?.[maker.toLowerCase()]?.models;
167
+ if (!models) return void 0;
168
+ const bare = bareID(id).toLowerCase();
169
+ const canonical = `${maker.toLowerCase()}/${bare}`;
170
+ const entries = Object.entries(models).map(([key, model]) => ({
171
+ ...model,
172
+ id: model.id ?? key
173
+ }));
174
+ const price = catalogPrice(entries.find((model) => model.id.toLowerCase() === id)?.cost);
175
+ if (price) return price;
176
+ const prices = entries.filter((model) => model.canonical_model_id?.toLowerCase() === canonical).map((model) => catalogPrice(model.cost)).filter((price$1) => price$1 !== void 0);
177
+ return prices.length && prices.every((price$1) => JSON.stringify(price$1) === JSON.stringify(prices[0])) ? prices[0] : void 0;
178
+ };
179
+
180
+ //#endregion
9
181
  //#region src/opencode.ts
10
182
  const createTrackedSetup = () => {
11
183
  const registrations = [];
@@ -58,6 +230,8 @@ const toClassicModelInfo = (providerID, catalogID, entry) => ({
58
230
 
59
231
  //#endregion
60
232
  //#region src/catalog.ts
233
+ /** Whether any model Magpie lists has no price in any source, which asks for a fresher catalog. */
234
+ const hasUnpricedModel = (inventory) => inventory.some((entry) => entry.models.some((model) => model.cost.length === 0));
61
235
  /** Routing groups route across providers, so they belong to Magpie itself rather than to a vendor. */
62
236
  const ROUTING_GROUP = "magpie";
63
237
  const reasoningVariants = (row, anthropic) => {
@@ -91,15 +265,35 @@ const providerName = (model) => {
91
265
  workbuddy: "WorkBuddy"
92
266
  }[model.owned_by] ?? model.owned_by;
93
267
  };
94
- const buildInventory = (rows, baseURL) => {
268
+ const modelCost = (row, group, catalog) => {
269
+ const pricingID = row.id.slice(row.id.indexOf("/") + 1).replace(/@\d+(?:k|m)$/i, "");
270
+ const builtin = group ? void 0 : getModelPricing(pricingID, pricingProvider(row.owned_by));
271
+ if (builtin) return {
272
+ cost: builtin,
273
+ source: "builtin"
274
+ };
275
+ if (row.magpie_price) return {
276
+ cost: row.magpie_price,
277
+ source: "magpie"
278
+ };
279
+ const listed = group ? void 0 : lookupCatalogPrice(catalog, row.owned_by, pricingID);
280
+ if (listed) return {
281
+ cost: listed,
282
+ source: "models.dev"
283
+ };
284
+ return {
285
+ cost: void 0,
286
+ source: "none"
287
+ };
288
+ };
289
+ const buildInventory = (rows, baseURL, options = {}) => {
95
290
  const providers = /* @__PURE__ */ new Map();
96
291
  rows.filter((row) => !row.kind && row.id.includes("/")).forEach((row) => {
97
292
  const group = row.id.startsWith("group/");
98
293
  const owner = group ? ROUTING_GROUP : row.owned_by;
99
294
  const providerID = `magpie-${encodeURIComponent(owner)}`;
100
295
  const modelID = row.id.slice(row.id.indexOf("/") + 1);
101
- const pricingID = modelID.replace(/@\d+(?:k|m)$/i, "");
102
- const cost = (!group ? getModelPricing(pricingID, pricingProvider(owner)) : void 0) ?? row.magpie_price;
296
+ const { cost } = modelCost(row, group, options.catalog);
103
297
  const model = toClassicModelInfo(providerID, modelID, {
104
298
  id: row.id,
105
299
  name: row.display_name ?? modelID,
@@ -111,8 +305,8 @@ const buildInventory = (rows, baseURL) => {
111
305
  modalities: row.modalities,
112
306
  tool_call: true
113
307
  });
114
- model.enabled = !!cost;
115
- if (!cost) model.name += " (价格未知)";
308
+ if (!cost && !group) model.name += " (价格未知)";
309
+ model.enabled = !!cost || group;
116
310
  const anthropic = row.native_endpoints?.includes("/v1/messages");
117
311
  const responses = !anthropic && row.native_endpoints?.includes("/v1/responses");
118
312
  model.package = anthropic ? "@opencode/ai/providers/anthropic-compatible" : responses ? "@opencode/ai/providers/openai-compatible/responses" : "@opencode/ai/providers/openai-compatible";
@@ -178,7 +372,9 @@ const findExecutable = async () => {
178
372
  "/Applications/Magpie.app/Contents/MacOS/magpie",
179
373
  join(homedir(), "Applications/Magpie.app/Contents/MacOS/magpie")
180
374
  ];
181
- return (await Promise.all(candidates.map(async (path) => await access(path, constants.X_OK).then(() => path, () => void 0)))).find(Boolean);
375
+ const executable = (await Promise.all(candidates.map(async (path) => await access(path, constants.X_OK).then(() => path, () => void 0)))).find(Boolean);
376
+ if (!executable) return void 0;
377
+ return await realpath(executable).catch(() => executable);
182
378
  };
183
379
  const probeGateway = async (baseURL) => {
184
380
  let response;
@@ -191,36 +387,78 @@ const probeGateway = async (baseURL) => {
191
387
  if (!response.ok || info?.name !== "magpie") throw new Error(`${baseURL} 已被非 Magpie 服务占用。`);
192
388
  return true;
193
389
  };
194
- const startGateway = async (executable) => {
390
+ /**
391
+ * How to bring the gateway up when nothing is listening.
392
+ *
393
+ * `magpie serve` runs the gateway with no window, and only a window can show Magpie's Routing
394
+ * view. A windowless gateway that wins the port keeps Magpie's own app from starting one — the
395
+ * app does not take the port back, it just reports that routing cannot be watched there. On
396
+ * macOS the bundled executable is the app, which serves the gateway as well and keeps the
397
+ * Routing view available.
398
+ *
399
+ * `--web` is not an option here: it opens a second listener on a fixed port, and when that port
400
+ * is taken the whole gateway exits instead of just the page.
401
+ */
402
+ const gatewayArgs = (executable) => {
403
+ const app = /[\\/]magpie\.app[\\/]/i.test(executable);
404
+ return process.platform === "darwin" && app ? ["tray"] : ["serve"];
405
+ };
406
+ /**
407
+ * The commands to try, in order, when nothing is listening.
408
+ *
409
+ * The app is preferred on macOS because only it has a window, and a window is what shows the
410
+ * Routing view. It needs a GUI session, though: a Mac reached over SSH, or one where OpenCode
411
+ * runs as a daemon, has none, and `magpie tray` then exits without serving. The windowless
412
+ * gateway has no such requirement, which is why it stays as the fallback rather than being
413
+ * replaced.
414
+ */
415
+ const startAttempts = (executable) => {
416
+ const preferred = gatewayArgs(executable);
417
+ return preferred[0] === "tray" ? [preferred, ["serve"]] : [preferred];
418
+ };
419
+ const startGateway = async (executable, args) => {
420
+ const state = { failed: false };
195
421
  await new Promise((resolve, reject) => {
196
- const child = spawn(executable, ["serve"], {
422
+ const child = spawn(executable, args, {
197
423
  detached: true,
198
424
  stdio: "ignore",
199
425
  windowsHide: true
200
426
  });
201
427
  child.once("error", reject);
428
+ child.once("exit", (code, signal) => {
429
+ state.failed = code !== null && code !== 0 || signal != null;
430
+ });
202
431
  child.once("spawn", () => {
203
432
  child.unref();
204
433
  resolve();
205
434
  });
206
435
  });
436
+ return state;
437
+ };
438
+ /** Polls until the gateway answers, or gives up after `tries` half-second waits. */
439
+ const waitForGateway = async (baseURL, tries, state) => {
440
+ for (let remaining = tries; remaining >= 0; remaining -= 1) {
441
+ if (await probeGateway(baseURL)) return true;
442
+ if (state.failed) return false;
443
+ if (remaining === 0) return false;
444
+ await setTimeout(500);
445
+ }
446
+ return false;
207
447
  };
208
448
  const starting = /* @__PURE__ */ new Map();
209
449
  const ensureGateway = async (baseURL) => {
210
450
  if (await probeGateway(baseURL)) return;
211
- const pending = starting.get(baseURL);
212
- if (pending) return pending;
451
+ const pending$1 = starting.get(baseURL);
452
+ if (pending$1) return pending$1;
213
453
  const task = (async () => {
214
454
  const executable = await findExecutable();
215
455
  if (!executable) throw new Error(INSTALL_MESSAGE);
216
- await startGateway(executable);
217
- const wait = async (remaining) => {
218
- if (await probeGateway(baseURL)) return;
219
- if (remaining === 0) throw new Error("Magpie 网关启动超时,请运行 magpie serve 查看错误。");
220
- await setTimeout(500);
221
- return wait(remaining - 1);
222
- };
223
- await wait(30);
456
+ for (const args of startAttempts(executable)) {
457
+ const state = await startGateway(executable, args);
458
+ if (await waitForGateway(baseURL, args[0] === "tray" ? 60 : 30, state)) return;
459
+ if (args[0] === "tray" && !state.failed) throw new Error("Magpie app 网关尚未就绪,请在 app 中检查网关状态;未启动无窗口服务,以免抢占端口。");
460
+ }
461
+ throw new Error("Magpie 网关启动超时,请运行 magpie serve 查看错误。");
224
462
  })();
225
463
  starting.set(baseURL, task);
226
464
  try {
@@ -247,66 +485,71 @@ const fetchModels = async (baseURL) => {
247
485
  //#region src/index.ts
248
486
  const plugin = {
249
487
  id: "magpie.providers",
250
- setup: async (ctx) => {
251
- if (!ctx.provider) throw new Error("Magpie 插件需要 OpenCode V2 provider.transform。");
252
- const baseURL = await resolveBaseURL();
253
- await ensureGateway(baseURL);
254
- let inventory = buildInventory(await fetchModels(baseURL), baseURL);
255
- const { track, cleanup } = createTrackedSetup();
256
- let disposed = false;
257
- let refreshing = false;
488
+ setup: (ctx) => setupPlugin(ctx)
489
+ };
490
+ const setupPlugin = async (ctx) => {
491
+ if (!ctx.provider) throw new Error("Magpie 插件需要 OpenCode V2 provider.transform。");
492
+ const baseURL = await resolveBaseURL();
493
+ await ensureGateway(baseURL);
494
+ let catalog = await loadCatalogCache();
495
+ let inventory = buildInventory(await fetchModels(baseURL), baseURL, { catalog: catalog.data });
496
+ const { track, cleanup } = createTrackedSetup();
497
+ let disposed = false;
498
+ let refreshing = false;
499
+ try {
500
+ await track(ctx.provider.transform((editor) => {
501
+ inventory.forEach((entry) => {
502
+ editor.add(entry);
503
+ });
504
+ }));
505
+ await track(ctx.session.hook("http.request", async (event) => {
506
+ const url = new URL(event.request.url);
507
+ if (url.origin !== baseURL || !url.pathname.startsWith("/v1/")) return;
508
+ await ensureGateway(baseURL);
509
+ event.request.headers.set("X-Magpie-Session", event.sessionID);
510
+ event.request.headers.set("X-Magpie-Agent", "opencode");
511
+ }));
512
+ await reloadProviderCatalog(ctx);
513
+ } catch (error) {
514
+ await cleanup();
515
+ throw error;
516
+ }
517
+ const apply = async (next) => {
518
+ if (disposed || JSON.stringify(next) === JSON.stringify(inventory)) return;
519
+ const previous = inventory;
520
+ inventory = next;
258
521
  try {
259
- await track(ctx.provider.transform((editor) => {
260
- inventory.forEach((entry) => {
261
- editor.add(entry);
262
- });
263
- }));
264
- await track(ctx.session.hook("http.request", async (event) => {
265
- const url = new URL(event.request.url);
266
- if (url.origin !== baseURL || !url.pathname.startsWith("/v1/")) return;
267
- await ensureGateway(baseURL);
268
- event.request.headers.set("X-Magpie-Session", event.sessionID);
269
- event.request.headers.set("X-Magpie-Agent", "opencode");
270
- }));
271
522
  await reloadProviderCatalog(ctx);
272
523
  } catch (error) {
273
- await cleanup();
524
+ inventory = previous;
274
525
  throw error;
275
526
  }
276
- const refresh = async () => {
277
- if (disposed || refreshing) return;
278
- refreshing = true;
279
- try {
280
- await ensureGateway(baseURL);
281
- const next = buildInventory(await fetchModels(baseURL), baseURL);
282
- if (!disposed && JSON.stringify(next) !== JSON.stringify(inventory)) {
283
- const previous = inventory;
284
- inventory = next;
285
- try {
286
- await reloadProviderCatalog(ctx);
287
- } catch (error) {
288
- inventory = previous;
289
- throw error;
290
- }
291
- }
292
- } catch (error) {
293
- console.warn("[magpie] 模型刷新失败,保留上次目录:", error instanceof Error ? error.message : String(error));
294
- } finally {
295
- refreshing = false;
296
- }
297
- };
298
- const timer = setInterval(() => {
299
- refresh();
300
- }, 3e4);
301
- timer.unref();
302
- return async () => {
303
- disposed = true;
304
- clearInterval(timer);
305
- await cleanup();
306
- };
307
- }
527
+ };
528
+ const refresh = async () => {
529
+ if (disposed || refreshing) return;
530
+ refreshing = true;
531
+ try {
532
+ await ensureGateway(baseURL);
533
+ const rows = await fetchModels(baseURL);
534
+ catalog = await loadCatalogCache(hasUnpricedModel(inventory));
535
+ await apply(buildInventory(rows, baseURL, { catalog: catalog.data }));
536
+ } catch (error) {
537
+ console.warn("[magpie] 模型刷新失败,保留上次目录:", error instanceof Error ? error.message : String(error));
538
+ } finally {
539
+ refreshing = false;
540
+ }
541
+ };
542
+ const timer = setInterval(() => {
543
+ refresh();
544
+ }, 3e4);
545
+ timer.unref();
546
+ return async () => {
547
+ disposed = true;
548
+ clearInterval(timer);
549
+ await cleanup();
550
+ };
308
551
  };
309
552
  var src_default = plugin;
310
553
 
311
554
  //#endregion
312
- export { src_default as default };
555
+ export { src_default as default, setupPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-magpie-plugin",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Discover Magpie providers and models in OpenCode V2 with built-in pricing and automatic local gateway startup",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",