@fish-under-sea/magpie-dragonapi 1.0.0 → 1.0.2
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/index.mjs +148 -16
- package/lib/site.mjs +30 -2
- package/package.json +3 -3
- package/page/star.png +0 -0
- package/ui/index.html +0 -4
package/index.mjs
CHANGED
|
@@ -16,9 +16,10 @@
|
|
|
16
16
|
// 的沙箱,页面自己发不出任何请求,只能把自己导航过去。界面由那个服务提供。
|
|
17
17
|
|
|
18
18
|
import { readFileSync } from 'node:fs'
|
|
19
|
-
import { join } from 'node:path'
|
|
19
|
+
import { dirname, join } from 'node:path'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
20
21
|
|
|
21
|
-
import { DEFAULT_SITE, currencyOf, readTokenUsage, createKey, revealKey, readKeys } from './lib/site.mjs'
|
|
22
|
+
import { DEFAULT_SITE, currencyOf, readTokenUsage, readTokenModels, createKey, revealKey, readKeys } from './lib/site.mjs'
|
|
22
23
|
import { buildCatalog } from './lib/catalog.mjs'
|
|
23
24
|
import { createCatalogSource } from './lib/catalog-source.mjs'
|
|
24
25
|
import { createStatusSource } from './lib/status-source.mjs'
|
|
@@ -83,19 +84,24 @@ function makeContext(input, options) {
|
|
|
83
84
|
if (tail) secrets.set(tail, secret)
|
|
84
85
|
const md = auth.metadata && typeof auth.metadata === 'object' ? auth.metadata : {}
|
|
85
86
|
const group = String(md.group || '')
|
|
86
|
-
|
|
87
|
+
const allowed = Array.isArray(md.allowed)
|
|
88
|
+
? md.allowed.map((v) => String(v)).filter(Boolean)
|
|
89
|
+
: (Array.isArray(state.accounts[tail]?.allowed) ? state.accounts[tail].allowed : null)
|
|
90
|
+
if (tail && (group || (allowed && allowed.length))) {
|
|
87
91
|
const had = state.accounts[tail] || {}
|
|
88
92
|
state.accounts[tail] = {
|
|
89
|
-
label: String(md.label || had.label || `${group} · ${maskKey(secret)}`),
|
|
93
|
+
label: String(md.label || had.label || (group ? `${group} · ${maskKey(secret)}` : maskKey(secret))),
|
|
90
94
|
group,
|
|
91
95
|
masked: maskKey(secret),
|
|
92
96
|
tail,
|
|
93
|
-
|
|
97
|
+
// models 是数量,allowed 是这把钥匙实际可用的模型名(不含分组前缀)。
|
|
98
|
+
models: Number(md.modelCount) || Number(md.models) || had.models || (allowed ? allowed.length : 0),
|
|
99
|
+
allowed: allowed || had.allowed,
|
|
94
100
|
boundAt: Number(had.boundAt) || Number(md.boundAt) || Date.now(),
|
|
95
101
|
}
|
|
96
102
|
persist()
|
|
97
103
|
}
|
|
98
|
-
return { secret, tail, group }
|
|
104
|
+
return { secret, tail, group, allowed: allowed || null }
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
return {
|
|
@@ -194,16 +200,20 @@ export default async function dragonapi(input, options) {
|
|
|
194
200
|
get icon() {
|
|
195
201
|
// 站点图标(Ciallo 立绘):包内 png 编成 data URI。宿主只收 https 与
|
|
196
202
|
// data:image,联网抓会在断网时变成灰书页。
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
203
|
+
//
|
|
204
|
+
// 不能拼 `new URL('.', import.meta.url).pathname`:Windows 上 pathname
|
|
205
|
+
// 是 `/C:/...`,join 出来是 `\C:\...`,读不到文件,供应商图标就退成
|
|
206
|
+
// 灰方块。ctx.dir 在宿主里是配置目录,不是包目录,也不能当包根用。
|
|
207
|
+
const roots = []
|
|
208
|
+
try { roots.push(dirname(fileURLToPath(import.meta.url))) } catch { /* 不是 file URL */ }
|
|
209
|
+
if (ctx.dir) roots.push(String(ctx.dir))
|
|
210
|
+
for (const root of roots) {
|
|
201
211
|
try {
|
|
202
|
-
const
|
|
203
|
-
const png = readFileSync(join(here, 'page', 'icon.png'))
|
|
212
|
+
const png = readFileSync(join(root, 'page', 'icon.png'))
|
|
204
213
|
return 'data:image/png;base64,' + png.toString('base64')
|
|
205
|
-
} catch {
|
|
214
|
+
} catch { /* 换下一个根目录 */ }
|
|
206
215
|
}
|
|
216
|
+
return ''
|
|
207
217
|
},
|
|
208
218
|
|
|
209
219
|
get methods() {
|
|
@@ -211,8 +221,16 @@ export default async function dragonapi(input, options) {
|
|
|
211
221
|
{
|
|
212
222
|
type: 'api',
|
|
213
223
|
label: 'DragonAPI API Key',
|
|
214
|
-
|
|
215
|
-
//
|
|
224
|
+
// 自己问 key(KeyAsked):这样 authorize 能拿到输入、先向站点验证,
|
|
225
|
+
// 而不是宿主把任意字符串当成钥匙存下来、再给它挂上整张目录。
|
|
226
|
+
prompts: [
|
|
227
|
+
{ type: 'password', key: 'key', message: 'DragonAPI API Key', placeholder: 'sk-…' },
|
|
228
|
+
],
|
|
229
|
+
async authorize(inputs) {
|
|
230
|
+
const key = String(inputs?.key || inputs?.apiKey || inputs?.token || '').trim()
|
|
231
|
+
if (!key) throw new Error('请填写 DragonAPI 的 sk- 钥匙')
|
|
232
|
+
return authorizeKey(ctx, key)
|
|
233
|
+
},
|
|
216
234
|
},
|
|
217
235
|
]
|
|
218
236
|
// 有 PAT 才出现第二条:用访问令牌按分组建一把新钥匙,并自动绑成账号。
|
|
@@ -333,10 +351,12 @@ export default async function dragonapi(input, options) {
|
|
|
333
351
|
*/
|
|
334
352
|
async models(_given, hookCtx) {
|
|
335
353
|
let group = ''
|
|
354
|
+
let allowed = null
|
|
336
355
|
try {
|
|
337
356
|
const auth = hookCtx?.auth
|
|
338
357
|
const found = ctx.remember(auth)
|
|
339
358
|
group = found?.group || ''
|
|
359
|
+
allowed = Array.isArray(found?.allowed) ? found.allowed : null
|
|
340
360
|
} catch { /* auth 形状不对就按「无分组」处理 */ }
|
|
341
361
|
|
|
342
362
|
try {
|
|
@@ -350,8 +370,12 @@ export default async function dragonapi(input, options) {
|
|
|
350
370
|
// 保护 1:列表单调不减。站点偶发少给几个模型时用上一次实时表补齐,
|
|
351
371
|
// 否则宿主会把这些「消失」的模型从用户选择里移除。
|
|
352
372
|
let table = group ? pickGroup(built.models, group) : built.models
|
|
373
|
+
// 用户手动添加的钥匙:只留 /v1/models 说它能用的那些,而不是整组目录。
|
|
374
|
+
if (allowed && allowed.length) table = pickAllowed(table, allowed, group)
|
|
353
375
|
const lastGood = ctx.memory.lastGood
|
|
354
|
-
|
|
376
|
+
// allowed 是站点对这把钥匙的精确授权:不能再把上一次的全组表补回来,
|
|
377
|
+
// 否则「只导入钥匙包含的模型」又被 lastGood 破坏了。
|
|
378
|
+
if (lastGood && !(allowed && allowed.length)) {
|
|
355
379
|
for (const id of Object.keys(lastGood)) {
|
|
356
380
|
if (!table[id] && (!group || id.startsWith(group + '/'))) table[id] = lastGood[id]
|
|
357
381
|
}
|
|
@@ -429,6 +453,114 @@ function pickGroupIf(models, group) {
|
|
|
429
453
|
return group ? pickGroup(models, group) : { ...models }
|
|
430
454
|
}
|
|
431
455
|
|
|
456
|
+
/** pickAllowed 只留钥匙在站点上真正可用的模型,按裸模型名去重。 */
|
|
457
|
+
function pickAllowed(models, allowed, group) {
|
|
458
|
+
const want = new Set(allowed.map((v) => String(v)))
|
|
459
|
+
const seen = new Set()
|
|
460
|
+
const out = {}
|
|
461
|
+
for (const [id, m] of Object.entries(models)) {
|
|
462
|
+
const cut = id.indexOf('/')
|
|
463
|
+
const bare = cut >= 0 ? id.slice(cut + 1) : id
|
|
464
|
+
if (!want.has(bare)) continue
|
|
465
|
+
if (group && (cut < 0 || id.slice(0, cut) !== group)) continue
|
|
466
|
+
if (seen.has(bare)) continue
|
|
467
|
+
seen.add(bare)
|
|
468
|
+
out[id] = m
|
|
469
|
+
}
|
|
470
|
+
return out
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* authorizeKey 验证一把 sk- 钥匙,并算出它实际能用的模型。
|
|
475
|
+
*
|
|
476
|
+
* 站点 `/api/usage/token/` 是钥匙可访问的,用它做鉴权;模型列表用
|
|
477
|
+
* `/v1/models` 拿(会按分组、model_limits、启用状态过滤)。只把交集写进
|
|
478
|
+
* auth metadata,provider.models 之后就不会再给整张目录。
|
|
479
|
+
*/
|
|
480
|
+
async function authorizeKey(ctx, key) {
|
|
481
|
+
let usage
|
|
482
|
+
try {
|
|
483
|
+
usage = await readTokenUsage(ctx.site, key)
|
|
484
|
+
} catch (e) {
|
|
485
|
+
throw new Error(`钥匙验证失败:${String(e?.message || e)}。请确认这是 DragonAPI 的 sk- 钥匙,且没有被禁用/过期。`)
|
|
486
|
+
}
|
|
487
|
+
let allowed = []
|
|
488
|
+
let modelsError = ''
|
|
489
|
+
try {
|
|
490
|
+
allowed = await readTokenModels(ctx.site, key)
|
|
491
|
+
} catch (e) {
|
|
492
|
+
modelsError = String(e?.message || e)
|
|
493
|
+
}
|
|
494
|
+
// 站点没开 /v1/models 时,model_limits 是同一把钥匙的授权清单,可以兜底;
|
|
495
|
+
// 两者都没有才拒绝,不能因为接口缺失就把有效钥匙挡在门外。
|
|
496
|
+
if (!allowed.length && usage.modelLimitsEnabled && usage.modelLimits) {
|
|
497
|
+
allowed = Object.keys(usage.modelLimits)
|
|
498
|
+
}
|
|
499
|
+
if (usage.modelLimitsEnabled && usage.modelLimits) {
|
|
500
|
+
const limits = Object.keys(usage.modelLimits)
|
|
501
|
+
if (limits.length && allowed.length) {
|
|
502
|
+
const set = new Set(limits)
|
|
503
|
+
allowed = allowed.filter((m) => set.has(m))
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (!allowed.length) {
|
|
507
|
+
throw new Error(modelsError
|
|
508
|
+
? `钥匙有效,但读不到它的模型:${modelsError}`
|
|
509
|
+
: '这把钥匙在站点上没有可用模型:先在控制台给它开放模型/分组,再重新添加。')
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const cat = await ctx.catalog.get({})
|
|
513
|
+
const st = await ctx.status.get({})
|
|
514
|
+
const built = cat.env
|
|
515
|
+
? buildCatalog(cat.env, { cur: currencyOf(st), enabledGroups: [], site: ctx.site })
|
|
516
|
+
: { models: {} }
|
|
517
|
+
const known = new Set(Object.keys(built.models).map((id) => {
|
|
518
|
+
const cut = id.indexOf('/')
|
|
519
|
+
return cut >= 0 ? id.slice(cut + 1) : id
|
|
520
|
+
}))
|
|
521
|
+
allowed = [...new Set(allowed.filter((m) => known.has(m)))]
|
|
522
|
+
if (!allowed.length) {
|
|
523
|
+
throw new Error('站点返回的模型和当前模型目录对不上,稍后重试;如果一直这样,把插件页面里的模型目录刷新一次。')
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const tail = tailOf(key)
|
|
527
|
+
let group = ''
|
|
528
|
+
if (ctx.state.pat) {
|
|
529
|
+
try {
|
|
530
|
+
const keys = await readKeys(ctx.site, ctx.state.pat)
|
|
531
|
+
const hit = keys.find((k) => k.key && tail && k.key.endsWith(tail))
|
|
532
|
+
if (hit?.group) group = hit.group
|
|
533
|
+
} catch { /* 没有 PAT 或不给读列表,就走下面的模型匹配 */ }
|
|
534
|
+
}
|
|
535
|
+
if (!group) {
|
|
536
|
+
const want = new Set(allowed)
|
|
537
|
+
const score = new Map()
|
|
538
|
+
for (const id of Object.keys(built.models)) {
|
|
539
|
+
const cut = id.indexOf('/')
|
|
540
|
+
if (cut < 0) continue
|
|
541
|
+
const g = id.slice(0, cut)
|
|
542
|
+
const bare = id.slice(cut + 1)
|
|
543
|
+
if (!want.has(bare)) continue
|
|
544
|
+
score.set(g, (score.get(g) || 0) + 1)
|
|
545
|
+
}
|
|
546
|
+
group = [...score.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] || ''
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
return {
|
|
550
|
+
type: 'success',
|
|
551
|
+
key,
|
|
552
|
+
metadata: {
|
|
553
|
+
group,
|
|
554
|
+
label: group ? `${group} · ${maskKey(key)}` : maskKey(key),
|
|
555
|
+
masked: maskKey(key),
|
|
556
|
+
tail,
|
|
557
|
+
boundAt: Date.now(),
|
|
558
|
+
modelCount: allowed.length,
|
|
559
|
+
allowed,
|
|
560
|
+
},
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
432
564
|
/** 金额:读不到站点参数时也不把额度原值当钱。 */
|
|
433
565
|
function fmt(quota, cur) {
|
|
434
566
|
const n = Number(quota)
|
package/lib/site.mjs
CHANGED
|
@@ -257,9 +257,37 @@ export async function readTokenUsage(site, key) {
|
|
|
257
257
|
}
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
+
/**
|
|
261
|
+
* 用一把 sk- 钥匙问站点「它到底能用哪些模型」。
|
|
262
|
+
*
|
|
263
|
+
* `/v1/models` 会按钥匙的分组、model_limits 与启用状态过滤,所以这比
|
|
264
|
+
* 「按分组套整张目录」准确:用户拿到的才是这把钥匙真正能调的模型。
|
|
265
|
+
*/
|
|
266
|
+
export async function readTokenModels(site, key, { timeoutMs } = {}) {
|
|
267
|
+
const origin = String(site || '').replace(/\/+$/, '')
|
|
268
|
+
const res = await fetch(origin + '/v1/models', {
|
|
269
|
+
headers: {
|
|
270
|
+
accept: 'application/json',
|
|
271
|
+
authorization: 'Bearer ' + String(key || ''),
|
|
272
|
+
'user-agent': 'magpie-dragonapi',
|
|
273
|
+
},
|
|
274
|
+
signal: Number(timeoutMs) > 0 ? AbortSignal.timeout(Number(timeoutMs)) : undefined,
|
|
275
|
+
})
|
|
276
|
+
if (res.status === 401 || res.status === 403) {
|
|
277
|
+
throw new SiteError('这把钥匙被站点拒绝(401/403)', { kind: 'auth' })
|
|
278
|
+
}
|
|
279
|
+
if (!res.ok) throw new SiteError(`/v1/models 返回 HTTP ${res.status}`, { kind: 'response' })
|
|
280
|
+
const body = await res.json().catch(() => null)
|
|
281
|
+
const list = Array.isArray(body?.data) ? body.data
|
|
282
|
+
: Array.isArray(body?.models) ? body.models
|
|
283
|
+
: Array.isArray(body) ? body
|
|
284
|
+
: null
|
|
285
|
+
if (!list) throw new SiteError('/v1/models 返回了未知模型结构', { kind: 'response' })
|
|
286
|
+
return list.map((m) => String(m?.id ?? m?.name ?? m)).filter(Boolean)
|
|
287
|
+
}
|
|
288
|
+
|
|
260
289
|
/** 逐条用量。保守只取最近最多 100 条,service 明确标注 partial。 */
|
|
261
|
-
export async function readTokenLogs(site, key, options = {}) {
|
|
262
|
-
const env = await siteCall(site, `/api/log/token?${logQuery(options)}`, {
|
|
290
|
+
export async function readTokenLogs(site, key, options = {}) { const env = await siteCall(site, `/api/log/token?${logQuery(options)}`, {
|
|
263
291
|
auth: { kind: 'key', token: key },
|
|
264
292
|
})
|
|
265
293
|
return logItems(env, '/api/log/token')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fish-under-sea/magpie-dragonapi",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "DragonAPI for magpie: a provider plugin whose models, groups and prices come from the site's public /api/pricing, with balance and per-call usage from an sk- key, plus a local page that lists the market (read-only), shows usage and can mint new keys for a group.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.mjs",
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
45
45
|
"magpie": {
|
|
46
|
-
"icon": "page/
|
|
47
|
-
"name": "
|
|
46
|
+
"icon": "page/icon.png",
|
|
47
|
+
"name": "@fish-under-sea/magpie-dragonapi",
|
|
48
48
|
"summary": {
|
|
49
49
|
"zh": "把 DragonAPI 接进 magpie:模型目录、余额与用量,外加一个按分组建钥匙的本地控制台。",
|
|
50
50
|
"en": "DragonAPI for magpie: model catalog, balance and usage, plus a local console for minting per-group keys."
|
package/page/star.png
CHANGED
|
Binary file
|