opencode-magpie-plugin 0.1.4 → 0.1.5

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
@@ -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.5"]
59
59
  }
60
60
  ```
61
61
 
@@ -138,7 +138,14 @@ 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 报价,不根据 `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.5
147
+
148
+ 新增 models.dev 缓存作为缺价兜底,不改动内置费率和 provider 覆盖。补充的价格来自 models.dev,对应目录更新后可能变化;以实际服务账单为准。
142
149
 
143
150
  Cursor 使用 `cursor` 覆盖,WorkBuddy 使用 `codebuddy` 覆盖;其他已识别服务按表中对应 provider 处理。Routing group 只用 Magpie 提供的价格,不按成员猜测。明确记录的零价格仍视为有效价格。
144
151
 
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, 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,
@@ -208,8 +402,8 @@ const startGateway = async (executable) => {
208
402
  const starting = /* @__PURE__ */ new Map();
209
403
  const ensureGateway = async (baseURL) => {
210
404
  if (await probeGateway(baseURL)) return;
211
- const pending = starting.get(baseURL);
212
- if (pending) return pending;
405
+ const pending$1 = starting.get(baseURL);
406
+ if (pending$1) return pending$1;
213
407
  const task = (async () => {
214
408
  const executable = await findExecutable();
215
409
  if (!executable) throw new Error(INSTALL_MESSAGE);
@@ -247,66 +441,71 @@ const fetchModels = async (baseURL) => {
247
441
  //#region src/index.ts
248
442
  const plugin = {
249
443
  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;
444
+ setup: (ctx) => setupPlugin(ctx)
445
+ };
446
+ const setupPlugin = async (ctx) => {
447
+ if (!ctx.provider) throw new Error("Magpie 插件需要 OpenCode V2 provider.transform。");
448
+ const baseURL = await resolveBaseURL();
449
+ await ensureGateway(baseURL);
450
+ let catalog = await loadCatalogCache();
451
+ let inventory = buildInventory(await fetchModels(baseURL), baseURL, { catalog: catalog.data });
452
+ const { track, cleanup } = createTrackedSetup();
453
+ let disposed = false;
454
+ let refreshing = false;
455
+ try {
456
+ await track(ctx.provider.transform((editor) => {
457
+ inventory.forEach((entry) => {
458
+ editor.add(entry);
459
+ });
460
+ }));
461
+ await track(ctx.session.hook("http.request", async (event) => {
462
+ const url = new URL(event.request.url);
463
+ if (url.origin !== baseURL || !url.pathname.startsWith("/v1/")) return;
464
+ await ensureGateway(baseURL);
465
+ event.request.headers.set("X-Magpie-Session", event.sessionID);
466
+ event.request.headers.set("X-Magpie-Agent", "opencode");
467
+ }));
468
+ await reloadProviderCatalog(ctx);
469
+ } catch (error) {
470
+ await cleanup();
471
+ throw error;
472
+ }
473
+ const apply = async (next) => {
474
+ if (disposed || JSON.stringify(next) === JSON.stringify(inventory)) return;
475
+ const previous = inventory;
476
+ inventory = next;
258
477
  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
478
  await reloadProviderCatalog(ctx);
272
479
  } catch (error) {
273
- await cleanup();
480
+ inventory = previous;
274
481
  throw error;
275
482
  }
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
- }
483
+ };
484
+ const refresh = async () => {
485
+ if (disposed || refreshing) return;
486
+ refreshing = true;
487
+ try {
488
+ await ensureGateway(baseURL);
489
+ const rows = await fetchModels(baseURL);
490
+ catalog = await loadCatalogCache(hasUnpricedModel(inventory));
491
+ await apply(buildInventory(rows, baseURL, { catalog: catalog.data }));
492
+ } catch (error) {
493
+ console.warn("[magpie] 模型刷新失败,保留上次目录:", error instanceof Error ? error.message : String(error));
494
+ } finally {
495
+ refreshing = false;
496
+ }
497
+ };
498
+ const timer = setInterval(() => {
499
+ refresh();
500
+ }, 3e4);
501
+ timer.unref();
502
+ return async () => {
503
+ disposed = true;
504
+ clearInterval(timer);
505
+ await cleanup();
506
+ };
308
507
  };
309
508
  var src_default = plugin;
310
509
 
311
510
  //#endregion
312
- export { src_default as default };
511
+ 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.5",
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",