@fish-under-sea/magpie-dragonapi 0.2.1 → 1.0.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/README.md +42 -18
- package/index.mjs +7 -7
- package/lib/dashboard.mjs +69 -0
- package/lib/pricing.mjs +35 -4
- package/lib/service.mjs +177 -30
- package/lib/site.mjs +304 -38
- package/lib/usage.mjs +12 -0
- package/package.json +3 -3
- package/page/icon.png +0 -0
- package/page/index.html +2 -2
- package/page/star.png +0 -0
- package/ui/app.js +2124 -431
- package/ui/demo.js +256 -0
- package/ui/icon.png +0 -0
- package/ui/index.html +221 -95
- package/ui/model-agg.js +458 -0
- package/ui/style.css +1633 -65
- package/page/icon.svg +0 -12
package/lib/site.mjs
CHANGED
|
@@ -43,7 +43,50 @@ export class SiteError extends Error {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
/**
|
|
46
|
+
/** 粘贴 PAT 时常带请求头前缀、引号与不可见字符;保存与发请求必须同一口径。 */
|
|
47
|
+
export function normalizePat(value) {
|
|
48
|
+
return String(value ?? '')
|
|
49
|
+
.replace(/[\s-'"`“”‘’]/gu, '')
|
|
50
|
+
.replace(/^(?:(?:authorization:?)|bearer)+/i, '')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function requireSuccess(env, path) {
|
|
54
|
+
if (env?.success === false) {
|
|
55
|
+
throw new SiteError(`${path}:${env.message || env.error?.message || '站点拒绝读取'}`, {
|
|
56
|
+
status: 200, code: String(env.code || env.error?.code || ''),
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
return env
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function objectData(env, path) {
|
|
63
|
+
requireSuccess(env, path)
|
|
64
|
+
if (!env?.data || typeof env.data !== 'object' || Array.isArray(env.data)) {
|
|
65
|
+
throw new SiteError(`${path} 返回了未知数据结构`, { kind: 'response' })
|
|
66
|
+
}
|
|
67
|
+
return env.data
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 仅接受已知日志形状;读失败/版本变化不能冒充空日志。 */
|
|
71
|
+
function logItems(env, path) {
|
|
72
|
+
requireSuccess(env, path)
|
|
73
|
+
if (Array.isArray(env)) return env
|
|
74
|
+
const d = env?.data
|
|
75
|
+
if (Array.isArray(d)) return d
|
|
76
|
+
if (Array.isArray(d?.items)) return d.items
|
|
77
|
+
if (Array.isArray(d?.data)) return d.data
|
|
78
|
+
throw new SiteError(`${path} 返回了未知日志结构`, { kind: 'response' })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function logQuery({ pageSize = 100, start, end } = {}) {
|
|
82
|
+
const q = new URLSearchParams({ p: '0', page_size: String(Math.max(1, Math.min(100, Number(pageSize) || 100))) })
|
|
83
|
+
// 调用方的时间窗是毫秒,站点的筛选参数是 Unix 秒。
|
|
84
|
+
if (Number.isFinite(start)) q.set('start_timestamp', String(Math.floor(start / 1000)))
|
|
85
|
+
if (Number.isFinite(end)) q.set('end_timestamp', String(Math.floor(end / 1000)))
|
|
86
|
+
return q
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** headersFor 把「凭据 + 种类」说清。调用方给错就直接抛,不留隐式回退。 */
|
|
47
90
|
function headersFor(auth) {
|
|
48
91
|
const h = { accept: 'application/json', 'user-agent': 'magpie-dragonapi' }
|
|
49
92
|
if (!auth) return h
|
|
@@ -56,8 +99,9 @@ function headersFor(auth) {
|
|
|
56
99
|
return h
|
|
57
100
|
}
|
|
58
101
|
if (auth.kind === 'pat') {
|
|
59
|
-
|
|
60
|
-
h.authorization = 'Bearer ' +
|
|
102
|
+
const pat = normalizePat(raw)
|
|
103
|
+
h.authorization = 'Bearer ' + pat
|
|
104
|
+
h['new-api-access-token'] = pat
|
|
61
105
|
return h
|
|
62
106
|
}
|
|
63
107
|
throw new Error(`未知的凭据种类:${String(auth.kind)}`)
|
|
@@ -196,8 +240,7 @@ export async function readPricing(site, { etag, lastModified } = {}) {
|
|
|
196
240
|
/** 一把钥匙的额度与用量。这是 sk- 通道里最要紧的一个端点。 */
|
|
197
241
|
export async function readTokenUsage(site, key) {
|
|
198
242
|
const env = await siteCall(site, '/api/usage/token/', { auth: { kind: 'key', token: key } })
|
|
199
|
-
const d = env
|
|
200
|
-
if (!d || typeof d !== 'object') throw new Error('/api/usage/token/ 没有 data')
|
|
243
|
+
const d = objectData(env, '/api/usage/token/')
|
|
201
244
|
return {
|
|
202
245
|
name: String(d.name || ''),
|
|
203
246
|
granted: Number(d.total_granted) || 0,
|
|
@@ -214,34 +257,182 @@ export async function readTokenUsage(site, key) {
|
|
|
214
257
|
}
|
|
215
258
|
}
|
|
216
259
|
|
|
217
|
-
/**
|
|
218
|
-
export async function readTokenLogs(site, key,
|
|
219
|
-
const env = await siteCall(site, `/api/log/token
|
|
260
|
+
/** 逐条用量。保守只取最近最多 100 条,service 明确标注 partial。 */
|
|
261
|
+
export async function readTokenLogs(site, key, options = {}) {
|
|
262
|
+
const env = await siteCall(site, `/api/log/token?${logQuery(options)}`, {
|
|
220
263
|
auth: { kind: 'key', token: key },
|
|
221
264
|
})
|
|
222
|
-
|
|
223
|
-
const d = env?.data
|
|
224
|
-
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : Array.isArray(d?.data) ? d.data : []
|
|
225
|
-
return items
|
|
265
|
+
return logItems(env, '/api/log/token')
|
|
226
266
|
}
|
|
227
267
|
|
|
228
268
|
/** PAT 能读到的账户资料。 */
|
|
229
|
-
export async function readSelf(site, pat) {
|
|
230
|
-
const env = await siteCall(site, '/api/user/self', { auth: { kind: 'pat', token: pat } })
|
|
231
|
-
const d = env
|
|
232
|
-
if (!
|
|
269
|
+
export async function readSelf(site, pat, { timeoutMs } = {}) {
|
|
270
|
+
const env = await siteCall(site, '/api/user/self', { auth: { kind: 'pat', token: pat }, timeoutMs })
|
|
271
|
+
const d = objectData(env, '/api/user/self')
|
|
272
|
+
if (!('id' in d) && !('username' in d)) throw new SiteError('/api/user/self 返回了未知账户结构', { kind: 'response' })
|
|
233
273
|
return {
|
|
234
274
|
id: Number(d.id) || 0,
|
|
235
275
|
username: String(d.username || ''),
|
|
236
276
|
displayName: String(d.display_name || ''),
|
|
237
277
|
group: String(d.group || ''),
|
|
238
|
-
quota:
|
|
239
|
-
usedQuota:
|
|
278
|
+
quota: numberOf(d.quota) ?? null,
|
|
279
|
+
usedQuota: numberOf(d.used_quota) ?? null,
|
|
240
280
|
affCode: String(d.aff_code || ''),
|
|
241
281
|
raw: d,
|
|
242
282
|
}
|
|
243
283
|
}
|
|
244
284
|
|
|
285
|
+
/**
|
|
286
|
+
* 推荐计划的数据:邀请码、已邀请人数、累计奖励额度。
|
|
287
|
+
*
|
|
288
|
+
* `/api/user/aff` 是 New API 的可选端点,不是每个站点都开;形状也可能变,
|
|
289
|
+
* 所以这里全部按可选处理——拿不到就返回 null,让界面如实显示「站点没有提供」,
|
|
290
|
+
* 而不是把 undefined 印出来。
|
|
291
|
+
*/
|
|
292
|
+
export async function readAff(site, pat) {
|
|
293
|
+
const results = await Promise.allSettled([
|
|
294
|
+
siteCall(site, '/api/user/aff', { auth: { kind: 'pat', token: pat } }).then((env) => {
|
|
295
|
+
requireSuccess(env, '/api/user/aff')
|
|
296
|
+
if (typeof env?.data === 'string') return { aff_code: env.data }
|
|
297
|
+
return objectData(env, '/api/user/aff')
|
|
298
|
+
}),
|
|
299
|
+
readSelf(site, pat).then((self) => self.raw),
|
|
300
|
+
])
|
|
301
|
+
const failed = results.filter((r) => r.status === 'rejected')
|
|
302
|
+
// 一端成功时保留可读字段;另一端的鉴权错误必须原样放 note,不能说成未开放。
|
|
303
|
+
if (failed.length === results.length) throw failed.find((r) => r.reason?.isAuth)?.reason || failed[0].reason
|
|
304
|
+
const aff = results[0].status === 'fulfilled' ? results[0].value : {}
|
|
305
|
+
const self = results[1].status === 'fulfilled' ? results[1].value : {}
|
|
306
|
+
const out = { code: String(aff.aff_code ?? aff.affCode ?? self.aff_code ?? '') }
|
|
307
|
+
const fields = {
|
|
308
|
+
count: ['aff_count', 'affCount'], quota: ['aff_quota', 'affQuota'],
|
|
309
|
+
historyQuota: ['aff_history_quota'], pending: ['aff_pending_quota', 'pending_quota'],
|
|
310
|
+
}
|
|
311
|
+
for (const [name, aliases] of Object.entries(fields)) {
|
|
312
|
+
const value = aliases.map((key) => self[key] ?? aff[key]).find((v) => numberOf(v) !== undefined)
|
|
313
|
+
if (value !== undefined) out[name] = numberOf(value)
|
|
314
|
+
}
|
|
315
|
+
out.note = failed.map((r) => String(r.reason?.message || r.reason)).join(';')
|
|
316
|
+
return out
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function numberOf(value) {
|
|
320
|
+
if (typeof value !== 'number' && (typeof value !== 'string' || !value.trim())) return undefined
|
|
321
|
+
const n = Number(value)
|
|
322
|
+
return Number.isFinite(n) ? n : undefined
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const BILLING_PREFERENCES = new Set(['subscription_first', 'wallet_first', 'subscription_only', 'wallet_only'])
|
|
326
|
+
|
|
327
|
+
/** wallet:read 的只读探针也用相同结构校验,不能把 HTML/未知 JSON 当成功。 */
|
|
328
|
+
export async function readSubscriptionSelf(site, pat, { timeoutMs } = {}) {
|
|
329
|
+
const env = await siteCall(site, '/api/subscription/self', { auth: { kind: 'pat', token: pat }, timeoutMs })
|
|
330
|
+
const d = objectData(env, '/api/subscription/self')
|
|
331
|
+
if (!Array.isArray(d.subscriptions) && !Array.isArray(d.all_subscriptions)) {
|
|
332
|
+
throw new SiteError('/api/subscription/self 返回了未知订阅结构', { kind: 'response' })
|
|
333
|
+
}
|
|
334
|
+
for (const key of ['subscriptions', 'all_subscriptions']) {
|
|
335
|
+
if (d[key] !== undefined && !Array.isArray(d[key])) throw new SiteError(`/api/subscription/self 的 ${key} 不是数组`, { kind: 'response' })
|
|
336
|
+
for (const item of d[key] || []) {
|
|
337
|
+
const s = item?.subscription ?? item
|
|
338
|
+
if (!s || typeof s !== 'object' || Array.isArray(s) || numberOf(s.id) === undefined || numberOf(s.plan_id) === undefined) {
|
|
339
|
+
throw new SiteError('/api/subscription/self 返回了未知订阅条目', { kind: 'response' })
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return d
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function readSubscriptionPlans(site, pat) {
|
|
347
|
+
const path = '/api/subscription/plans'
|
|
348
|
+
const env = requireSuccess(await siteCall(site, path, { auth: { kind: 'pat', token: pat } }), path)
|
|
349
|
+
const data = env?.data
|
|
350
|
+
const items = Array.isArray(data) ? data : data?.plans
|
|
351
|
+
if (!Array.isArray(items)) throw new SiteError(`${path} 返回了未知套餐结构`, { kind: 'response' })
|
|
352
|
+
return items.map((item) => {
|
|
353
|
+
const plan = item?.plan ?? item
|
|
354
|
+
if (!plan || typeof plan !== 'object' || Array.isArray(plan) || numberOf(plan.id) === undefined) {
|
|
355
|
+
throw new SiteError(`${path} 返回了未知套餐条目`, { kind: 'response' })
|
|
356
|
+
}
|
|
357
|
+
return plan
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** 订阅额度是 quota,套餐售价则保留原币,不走 quota 汇率。 */
|
|
362
|
+
export async function readSubscriptions(site, pat, cur, now = Date.now()) {
|
|
363
|
+
const [selfResult, plansResult] = await Promise.allSettled([
|
|
364
|
+
readSubscriptionSelf(site, pat), readSubscriptionPlans(site, pat),
|
|
365
|
+
])
|
|
366
|
+
if (selfResult.status === 'rejected') throw selfResult.reason
|
|
367
|
+
const self = selfResult.value
|
|
368
|
+
const rawPlans = plansResult.status === 'fulfilled' ? plansResult.value : []
|
|
369
|
+
const byId = new Map(rawPlans.map((p) => [String(p.id), p]))
|
|
370
|
+
const ms = (v) => { const n = numberOf(v); return n === undefined ? null : n * 1000 }
|
|
371
|
+
const plans = rawPlans.map((p) => {
|
|
372
|
+
const amount = numberOf(p.price_amount ?? p.price)
|
|
373
|
+
const currency = typeof p.currency === 'string' ? p.currency : ''
|
|
374
|
+
const quota = numberOf(p.total_amount ?? p.amount_total)
|
|
375
|
+
const durationValue = numberOf(p.duration_value)
|
|
376
|
+
return {
|
|
377
|
+
id: numberOf(p.id), title: String(p.title || `套餐 #${p.id}`),
|
|
378
|
+
subtitle: String(p.subtitle || ''),
|
|
379
|
+
durationUnit: String(p.duration_unit || ''), durationValue: durationValue ?? null,
|
|
380
|
+
totalRaw: quota ?? null, total: quota === undefined ? '' : quota === 0 ? '不限量' : text(quota, cur),
|
|
381
|
+
unlimited: quota === 0, quotaResetPeriod: String(p.quota_reset_period || ''),
|
|
382
|
+
upgradeGroup: String(p.upgrade_group || ''),
|
|
383
|
+
priceAmount: amount ?? null, priceCurrency: currency,
|
|
384
|
+
price: amount === undefined ? '' : `${currency ? currency + ' ' : ''}${amount.toFixed(2)}`,
|
|
385
|
+
}
|
|
386
|
+
})
|
|
387
|
+
const seen = new Set()
|
|
388
|
+
const subscriptions = [...(self.subscriptions || []), ...(self.all_subscriptions || [])].flatMap((item) => {
|
|
389
|
+
const s = item?.subscription ?? item
|
|
390
|
+
if (!s || typeof s !== 'object' || Array.isArray(s) || numberOf(s.id) === undefined || numberOf(s.plan_id) === undefined) {
|
|
391
|
+
throw new SiteError('/api/subscription/self 返回了未知订阅条目', { kind: 'response' })
|
|
392
|
+
}
|
|
393
|
+
if (seen.has(String(s.id))) return []
|
|
394
|
+
seen.add(String(s.id))
|
|
395
|
+
const plan = item?.plan ?? byId.get(String(s.plan_id))
|
|
396
|
+
const total = numberOf(s.amount_total ?? s.total_amount)
|
|
397
|
+
const used = numberOf(s.amount_used ?? s.used_amount)
|
|
398
|
+
const remaining = total !== undefined && used !== undefined ? total - used : undefined
|
|
399
|
+
const endAt = ms(s.end_time)
|
|
400
|
+
const startAt = ms(s.start_time)
|
|
401
|
+
const unlimited = total === 0
|
|
402
|
+
return [{
|
|
403
|
+
id: numberOf(s.id), planId: numberOf(s.plan_id), title: String(plan?.title || `套餐 #${s.plan_id}`),
|
|
404
|
+
status: s.status ?? null,
|
|
405
|
+
active: s.status === 'active' && endAt !== null && endAt > now && (startAt === null || startAt <= now),
|
|
406
|
+
startAt, endAt, nextResetAt: ms(s.next_reset_time),
|
|
407
|
+
totalRaw: total ?? null, usedRaw: used ?? null, remainingRaw: unlimited ? null : remaining ?? null,
|
|
408
|
+
total: total === undefined ? '' : unlimited ? '不限量' : text(total, cur),
|
|
409
|
+
used: used === undefined ? '' : text(used, cur),
|
|
410
|
+
remaining: unlimited || remaining === undefined ? '' : text(remaining, cur),
|
|
411
|
+
unlimited, progress: total > 0 && used !== undefined ? used / total * 100 : null,
|
|
412
|
+
}]
|
|
413
|
+
})
|
|
414
|
+
return {
|
|
415
|
+
subscriptions, plans,
|
|
416
|
+
billingPreference: BILLING_PREFERENCES.has(self.billing_preference) ? self.billing_preference : null,
|
|
417
|
+
plansError: plansResult.status === 'rejected' ? String(plansResult.reason?.message || plansResult.reason) : '',
|
|
418
|
+
at: now,
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* 把推荐计划的累计奖励转入余额。
|
|
424
|
+
*
|
|
425
|
+
* 端点 `/api/user/aff_transfer` 是 New API 的标准接口(无请求体,整笔转入)。
|
|
426
|
+
* 我们没有它的返回结构可依,所以原样把站点的 message 带回去——
|
|
427
|
+
* 成功失败都以站点为准,不在这里替它编一句「已转入」。
|
|
428
|
+
*/
|
|
429
|
+
export async function transferAff(site, pat) {
|
|
430
|
+
const env = await siteCall(site, '/api/user/aff_transfer', {
|
|
431
|
+
method: 'POST',
|
|
432
|
+
auth: { kind: 'pat', token: pat },
|
|
433
|
+
})
|
|
434
|
+
return { ok: env?.success !== false, message: String(env?.message || ''), data: env?.data ?? null }
|
|
435
|
+
}
|
|
245
436
|
/** 当前账号可用的分组。建钥匙时要从这里挑,不能凭目录里的分组名瞎猜。 */
|
|
246
437
|
export async function readUsableGroups(site, pat) {
|
|
247
438
|
const env = await siteCall(site, '/api/user/self/groups', { auth: { kind: 'pat', token: pat } })
|
|
@@ -253,12 +444,13 @@ export async function readUsableGroups(site, pat) {
|
|
|
253
444
|
}
|
|
254
445
|
|
|
255
446
|
/** 钥匙列表。站点只给打码后的 key。 */
|
|
256
|
-
export async function readKeys(site, pat, { pageSize = 100 } = {}) {
|
|
257
|
-
const env = await siteCall(site, `/api/token/?p=0&size=${Math.max(1, Math.min(100, pageSize))}`, {
|
|
258
|
-
auth: { kind: 'pat', token: pat },
|
|
259
|
-
})
|
|
447
|
+
export async function readKeys(site, pat, { pageSize = 100, timeoutMs } = {}) {
|
|
448
|
+
const env = requireSuccess(await siteCall(site, `/api/token/?p=0&size=${Math.max(1, Math.min(100, pageSize))}`, {
|
|
449
|
+
auth: { kind: 'pat', token: pat }, timeoutMs,
|
|
450
|
+
}), '/api/token/')
|
|
260
451
|
const d = env?.data
|
|
261
|
-
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items :
|
|
452
|
+
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : null
|
|
453
|
+
if (!items) throw new SiteError('/api/token/ 返回了未知钥匙列表结构', { kind: 'response' })
|
|
262
454
|
return items.map((t) => ({
|
|
263
455
|
id: Number(t?.id) || 0,
|
|
264
456
|
name: String(t?.name || ''),
|
|
@@ -269,6 +461,7 @@ export async function readKeys(site, pat, { pageSize = 100 } = {}) {
|
|
|
269
461
|
remain: Number(t?.remain_quota) || 0,
|
|
270
462
|
unlimited: t?.unlimited_quota === true,
|
|
271
463
|
createdAt: Number(t?.created_time) || 0,
|
|
464
|
+
lastUsedAt: Number(t?.accessed_time) || 0,
|
|
272
465
|
expiredAt: Number(t?.expired_time) || 0,
|
|
273
466
|
}))
|
|
274
467
|
}
|
|
@@ -299,6 +492,26 @@ export async function createKey(site, pat, { name, group, unlimited = true, rema
|
|
|
299
492
|
return { ok: true }
|
|
300
493
|
}
|
|
301
494
|
|
|
495
|
+
/** 更新一把钥匙(改名/分组/额度/过期/状态)。 */
|
|
496
|
+
export async function updateKey(site, pat, id, { name, group, unlimited = true, remainQuota = 0, expiredAt = -1, status } = {}) {
|
|
497
|
+
const body = {
|
|
498
|
+
id: Math.floor(Number(id)),
|
|
499
|
+
name: String(name || '').slice(0, 50),
|
|
500
|
+
group: String(group || ''),
|
|
501
|
+
unlimited_quota: unlimited === true,
|
|
502
|
+
remain_quota: unlimited ? 0 : Math.max(0, Math.floor(Number(remainQuota) || 0)),
|
|
503
|
+
expired_time: Number.isFinite(expiredAt) ? Math.floor(expiredAt) : -1,
|
|
504
|
+
model_limits_enabled: false,
|
|
505
|
+
model_limits: '',
|
|
506
|
+
allow_ips: '',
|
|
507
|
+
allow_user_quota_query: true,
|
|
508
|
+
}
|
|
509
|
+
if (Number.isFinite(Number(status))) body.status = Number(status)
|
|
510
|
+
const env = await siteCall(site, '/api/token/', { method: 'PUT', body, auth: { kind: 'pat', token: pat } })
|
|
511
|
+
if (env?.success === false) throw new Error(env?.message || '站点拒绝更新钥匙')
|
|
512
|
+
return { ok: true }
|
|
513
|
+
}
|
|
514
|
+
|
|
302
515
|
/** 读一把钥匙的明文。需要 api_key:reveal 权限。 */
|
|
303
516
|
export async function revealKey(site, pat, id) {
|
|
304
517
|
const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}/key`, {
|
|
@@ -344,16 +557,68 @@ export async function verifyPat(site, pat) {
|
|
|
344
557
|
* 用 PAT 打过去、或者干脆传空串,都只会拿到 401。之前探测 `usage:read`
|
|
345
558
|
* 用的正是 `readTokenLogs(site, '')`,所以这个 scope 永远探不出来。
|
|
346
559
|
*/
|
|
347
|
-
export async function readUsageSelf(site, pat,
|
|
348
|
-
const env = await siteCall(site, `/api/log/self
|
|
349
|
-
auth: { kind: 'pat', token: pat },
|
|
560
|
+
export async function readUsageSelf(site, pat, options = {}) {
|
|
561
|
+
const env = await siteCall(site, `/api/log/self?${logQuery(options)}`, {
|
|
562
|
+
auth: { kind: 'pat', token: pat }, timeoutMs: options.timeoutMs,
|
|
563
|
+
})
|
|
564
|
+
return logItems(env, '/api/log/self')
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 分页读账户日志:返回 `{ items, total }`。
|
|
569
|
+
* `/api/log/self` 的 `data.total` 是整个时间窗的条数,分页时用它算总页数。
|
|
570
|
+
*/
|
|
571
|
+
export async function readUsageSelfPage(site, pat, options = {}) {
|
|
572
|
+
const q = new URLSearchParams({
|
|
573
|
+
p: String(Math.max(1, Number(options.page || 1))),
|
|
574
|
+
page_size: String(Math.max(1, Math.min(100, Number(options.pageSize) || 100))),
|
|
575
|
+
})
|
|
576
|
+
if (Number.isFinite(options.start)) q.set('start_timestamp', String(Math.floor(options.start / 1000)))
|
|
577
|
+
if (Number.isFinite(options.end)) q.set('end_timestamp', String(Math.floor(options.end / 1000)))
|
|
578
|
+
const env = await siteCall(site, `/api/log/self?${q}`, {
|
|
579
|
+
auth: { kind: 'pat', token: pat }, timeoutMs: options.timeoutMs,
|
|
580
|
+
})
|
|
581
|
+
requireSuccess(env, '/api/log/self')
|
|
582
|
+
const d = env?.data
|
|
583
|
+
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : Array.isArray(d?.data) ? d.data : null
|
|
584
|
+
if (!items) throw new SiteError('/api/log/self 返回了未知日志结构', { kind: 'response' })
|
|
585
|
+
const total = Number(d?.total ?? d?.total_count ?? d?.count ?? items.length) || items.length
|
|
586
|
+
return { items, total }
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* PAT 通道的数据看板(`/api/data/self`):按时间桶 × 模型的行。
|
|
591
|
+
* 参数是毫秒时间窗与粒度(hour / day / week),站点只接受秒级时间戳。
|
|
592
|
+
*/
|
|
593
|
+
export async function readDataSelf(site, pat, options = {}) {
|
|
594
|
+
const q = new URLSearchParams();
|
|
595
|
+
if (options.start) q.set('start_timestamp', String(Math.floor(options.start / 1000)));
|
|
596
|
+
if (options.end) q.set('end_timestamp', String(Math.floor(options.end / 1000)));
|
|
597
|
+
q.set('time_granularity', options.granularity || 'hour');
|
|
598
|
+
const env = await siteCall(site, `/api/data/self?${q}`, {
|
|
599
|
+
auth: { kind: 'pat', token: pat }, timeoutMs: options.timeoutMs,
|
|
600
|
+
});
|
|
601
|
+
const d = env && env.data;
|
|
602
|
+
return (Array.isArray(d) ? d : Object.values(d || {})).filter(Boolean);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* PAT 通道的日志汇总(`/api/log/self/stat`):quota / rpm / tpm。
|
|
607
|
+
*
|
|
608
|
+
* 这是站点日志页顶部三个数字的真实来源:quota 按所选时间窗统计(就是页面上的
|
|
609
|
+
* 「用量」),rpm / tpm 是站点侧的分钟速率(没有请求时就是 0,不是缺失)。
|
|
610
|
+
*/
|
|
611
|
+
export async function readUsageStatsSelf(site, pat, options = {}) {
|
|
612
|
+
const env = await siteCall(site, `/api/log/self/stat?${logQuery(options)}`, {
|
|
613
|
+
auth: { kind: 'pat', token: pat }, timeoutMs: options.timeoutMs,
|
|
350
614
|
})
|
|
351
|
-
|
|
352
|
-
return
|
|
615
|
+
const d = objectData(env, '/api/log/self/stat')
|
|
616
|
+
const n = (v) => { const x = Number(v); return Number.isFinite(x) ? x : 0 }
|
|
617
|
+
return { quota: n(d?.quota), rpm: n(d?.rpm), tpm: n(d?.tpm) }
|
|
353
618
|
}
|
|
354
619
|
|
|
355
620
|
/**
|
|
356
|
-
* probePat
|
|
621
|
+
* probePat 并行探四个只读端点,判断这份 PAT 到底能干什么。
|
|
357
622
|
*
|
|
358
623
|
* 为什么要「宽松」:站点把一份令牌的 scope 卡得很细,`/api/user/self` 要
|
|
359
624
|
* `profile:read`。只用它做准入门槛时,一份只能读钥匙列表的 PAT 会被整份
|
|
@@ -361,25 +626,26 @@ export async function readUsageSelf(site, pat, { pageSize = 1 } = {}) {
|
|
|
361
626
|
*
|
|
362
627
|
* 所以判定分三种,调用方据此决定「拒收 / 收下但警告 / 收下」:
|
|
363
628
|
*
|
|
364
|
-
* authRejected /
|
|
629
|
+
* authRejected / 四个端点全部 401/403 —— 令牌本身不行,拒收
|
|
365
630
|
* verified / 至少一个端点通了 —— 令牌有效,记录能用的 scope
|
|
366
631
|
* networkOnly / 一个都没通,但错误都不是鉴权错误 —— 站点连不上,令牌先存下
|
|
367
632
|
*/
|
|
368
633
|
export async function probePat(site, pat) {
|
|
634
|
+
const timeoutMs = 12_000
|
|
369
635
|
const checks = [
|
|
370
|
-
{ scope: 'profile:read', run: () => readSelf(site, pat) },
|
|
371
|
-
{ scope: 'api_key:read', run: () => readKeys(site, pat, { pageSize: 1 }) },
|
|
372
|
-
{ scope: 'usage:read', run: () => readUsageSelf(site, pat) },
|
|
636
|
+
{ scope: 'profile:read', run: () => readSelf(site, pat, { timeoutMs }) },
|
|
637
|
+
{ scope: 'api_key:read', run: () => readKeys(site, pat, { pageSize: 1, timeoutMs }) },
|
|
638
|
+
{ scope: 'usage:read', run: () => readUsageSelf(site, pat, { pageSize: 1, timeoutMs }) },
|
|
639
|
+
{ scope: 'wallet:read', run: () => readSubscriptionSelf(site, pat, { timeoutMs }) },
|
|
373
640
|
]
|
|
374
641
|
|
|
375
|
-
const results =
|
|
376
|
-
for (const check of checks) {
|
|
642
|
+
const results = await Promise.all(checks.map(async (check) => {
|
|
377
643
|
try {
|
|
378
|
-
|
|
644
|
+
return { scope: check.scope, ok: true, value: await check.run() }
|
|
379
645
|
} catch (error) {
|
|
380
|
-
|
|
646
|
+
return { scope: check.scope, ok: false, error }
|
|
381
647
|
}
|
|
382
|
-
}
|
|
648
|
+
}))
|
|
383
649
|
|
|
384
650
|
const ok = results.filter((r) => r.ok)
|
|
385
651
|
const failed = results.filter((r) => !r.ok)
|
package/lib/usage.mjs
CHANGED
|
@@ -52,6 +52,10 @@ export function fmtStamp(sec) {
|
|
|
52
52
|
/** firstToken 取首字耗时(秒)。站点有时给 ttft,有时给 first_token_time。 */
|
|
53
53
|
function firstToken(row) {
|
|
54
54
|
const o = otherOf(row)
|
|
55
|
+
// 站点(本部署)把首字耗时写在 other.frt,单位是毫秒;-1000 表示缓存命中/未记录。
|
|
56
|
+
// 之前只认 ttft,于是所有请求的首字都显示「—」。
|
|
57
|
+
const frt = num(o?.frt) ?? num(row?.frt)
|
|
58
|
+
if (frt !== undefined && frt > 0) return frt / 1000
|
|
55
59
|
return num(row?.ttft) ?? num(o?.ttft) ?? num(row?.first_token_time) ?? num(o?.first_token_time)
|
|
56
60
|
}
|
|
57
61
|
|
|
@@ -110,6 +114,14 @@ export function rowsOf(items, cur, account = '') {
|
|
|
110
114
|
model,
|
|
111
115
|
group: pick(r?.group, other?.group),
|
|
112
116
|
tokenName: pick(r?.token_name, r?.tokenName),
|
|
117
|
+
id: pick(r?.id, r?.log_id),
|
|
118
|
+
requestId: pick(r?.request_id, r?.requestId),
|
|
119
|
+
upRequestId: pick(r?.upstream_request_id, other?.upstream_request_id, r?.upRequestId),
|
|
120
|
+
// 这条请求是钱包扣费还是订阅扣费:站点写在 other.billing_source 里。
|
|
121
|
+
// 页面据此给费用胶囊换图标——两者额度口径不同,不能长一个样。
|
|
122
|
+
billingSource: pick(other?.billing_source, other?.billingSource, r?.billing_source),
|
|
123
|
+
// 分组倍率(站点写在 other 里),分组列第二行用。
|
|
124
|
+
groupRatio: num(other?.group_ratio) ?? num(other?.user_group_ratio) ?? num(r?.group_ratio),
|
|
113
125
|
upModel: pick(other?.upstream_model, other?.up_model, other?.request_model),
|
|
114
126
|
respModel: pick(other?.response_model, other?.downstream_model),
|
|
115
127
|
effort: pick(other?.reasoning_effort, other?.effort),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fish-under-sea/magpie-dragonapi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
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,7 +43,7 @@
|
|
|
43
43
|
"access": "public"
|
|
44
44
|
},
|
|
45
45
|
"magpie": {
|
|
46
|
-
"icon": "page/
|
|
46
|
+
"icon": "page/star.png",
|
|
47
47
|
"name": "DragonAPI",
|
|
48
48
|
"summary": {
|
|
49
49
|
"zh": "把 DragonAPI 接进 magpie:模型目录、余额与用量,外加一个按分组建钥匙的本地控制台。",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"de": "DragonAPI"
|
|
59
59
|
},
|
|
60
60
|
"file": "page/index.html",
|
|
61
|
-
"icon": "page/
|
|
61
|
+
"icon": "page/star.png",
|
|
62
62
|
"service": {
|
|
63
63
|
"port": 3517,
|
|
64
64
|
"option": "port"
|
package/page/icon.png
ADDED
|
Binary file
|
package/page/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
-
<title
|
|
6
|
+
<title>@fish-under-sea/magpie-dragonapi</title>
|
|
7
7
|
<style>
|
|
8
8
|
:root { color-scheme: light dark; }
|
|
9
9
|
html, body { margin: 0; height: 100%; }
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
</head>
|
|
24
24
|
<body>
|
|
25
25
|
<div class="box">
|
|
26
|
-
<b
|
|
26
|
+
<b>@fish-under-sea/magpie-dragonapi</b>
|
|
27
27
|
<span id="said">正在连接到本地服务…</span>
|
|
28
28
|
</div>
|
|
29
29
|
<script src="_magpie/bridge.js"></script>
|
package/page/star.png
ADDED
|
Binary file
|