@fish-under-sea/magpie-dragonapi 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +140 -2
- package/index.mjs +452 -0
- package/lib/catalog-source.mjs +87 -0
- package/lib/catalog.mjs +200 -0
- package/lib/pricing.mjs +256 -0
- package/lib/service.mjs +498 -0
- package/lib/site.mjs +301 -0
- package/lib/status-source.mjs +44 -0
- package/lib/store.mjs +86 -0
- package/lib/usage.mjs +202 -0
- package/package.json +70 -4
- package/page/boot.js +112 -0
- package/page/icon.svg +12 -0
- package/page/index.html +32 -0
- package/serve.mjs +110 -0
- package/ui/app.js +1722 -0
- package/ui/index.html +259 -0
- package/ui/style.css +968 -0
package/lib/site.mjs
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// 站点客户端:DragonAPI 的每一次出站请求都从这里走。
|
|
2
|
+
//
|
|
3
|
+
// 两条通道,凭据不同,能做的事也不同:
|
|
4
|
+
//
|
|
5
|
+
// sk- 钥匙 中转鉴权用。能调模型、能读这把钥匙的余额与逐条用量。
|
|
6
|
+
// nap_ 令牌 控制台鉴权(PAT,带 scope)。能读账户、分组、钥匙列表,
|
|
7
|
+
// 也能建钥匙 / 删钥匙 / 看完整钥匙。建不了 PAT:站点要求
|
|
8
|
+
// 浏览器会话,插件代不了。
|
|
9
|
+
//
|
|
10
|
+
// 所以这里把两者分开:调用方必须说清用的是哪一种,不允许「有哪个用哪个」
|
|
11
|
+
// 的隐式回退——那把 PAT 当成钥匙发出去,会得到一条让人摸不着头脑的 401。
|
|
12
|
+
|
|
13
|
+
/** 站点根地址。可以由插件 options 覆盖(自建站、测试站)。 */
|
|
14
|
+
export const DEFAULT_SITE = 'https://newapi.dragon3api.com'
|
|
15
|
+
|
|
16
|
+
/** 一次请求最多等多久。站点正常时都在 1 秒内,超过这个数就该报错而不是挂着。 */
|
|
17
|
+
const TIMEOUT_MS = 20_000
|
|
18
|
+
|
|
19
|
+
/** keyOf 把「凭据 + 种类」说清。调用方给错就直接抛,不留隐式回退。 */
|
|
20
|
+
function headersFor(auth) {
|
|
21
|
+
const h = { accept: 'application/json', 'user-agent': 'magpie-dragonapi' }
|
|
22
|
+
if (!auth) return h
|
|
23
|
+
const raw = String(auth.token || '').trim()
|
|
24
|
+
if (!raw) return h
|
|
25
|
+
if (auth.kind === 'key') {
|
|
26
|
+
// 中转鉴权只认 sk-;站点自己也会 TrimPrefix("sk-"),但我们保留前缀,
|
|
27
|
+
// 因为 /api/usage/token/ 的实现里同样会 TrimPrefix,两种写法都认。
|
|
28
|
+
h.authorization = 'Bearer ' + raw
|
|
29
|
+
return h
|
|
30
|
+
}
|
|
31
|
+
if (auth.kind === 'pat') {
|
|
32
|
+
// 控制台鉴权:PAT 形如 nap_xxx,直接放 Bearer。
|
|
33
|
+
h.authorization = 'Bearer ' + raw
|
|
34
|
+
return h
|
|
35
|
+
}
|
|
36
|
+
throw new Error(`未知的凭据种类:${String(auth.kind)}`)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** siteCall 发一次请求并把 JSON 解析出来;非 2xx 抛出带站点原话的错误。 */
|
|
40
|
+
export async function siteCall(site, path, { method = 'GET', body, auth, timeoutMs = TIMEOUT_MS, headers } = {}) {
|
|
41
|
+
const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
|
|
42
|
+
const url = base + path
|
|
43
|
+
const init = {
|
|
44
|
+
method,
|
|
45
|
+
headers: { ...headersFor(auth), ...(headers || {}) },
|
|
46
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
47
|
+
}
|
|
48
|
+
if (body !== undefined) {
|
|
49
|
+
init.headers['content-type'] = 'application/json'
|
|
50
|
+
init.body = JSON.stringify(body)
|
|
51
|
+
}
|
|
52
|
+
const res = await fetch(url, init)
|
|
53
|
+
const text = await res.text()
|
|
54
|
+
let parsed = null
|
|
55
|
+
try {
|
|
56
|
+
parsed = text ? JSON.parse(text) : null
|
|
57
|
+
} catch {
|
|
58
|
+
// 站点偶尔会回一页 HTML(Cloudflare 挑战、502 页)。原样带一点正文出来,
|
|
59
|
+
// 否则排查时只剩「不是 JSON」这一句,看不出发生了什么。
|
|
60
|
+
throw new Error(`${path} 返回的不是 JSON(HTTP ${res.status}):${text.slice(0, 160).replace(/\s+/g, ' ')}`)
|
|
61
|
+
}
|
|
62
|
+
if (!res.ok) {
|
|
63
|
+
const why = parsed?.message || parsed?.error?.message || parsed?.error || ''
|
|
64
|
+
const code = parsed?.code || parsed?.error?.code || ''
|
|
65
|
+
throw new Error(`${path} HTTP ${res.status}${code ? ' ' + code : ''}${why ? ':' + why : ''}`)
|
|
66
|
+
}
|
|
67
|
+
return parsed
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 站点参数。钱怎么显示、额度怎么折算全在这里。 */
|
|
71
|
+
export async function readStatus(site) {
|
|
72
|
+
const env = await siteCall(site, '/api/status')
|
|
73
|
+
const d = env?.data
|
|
74
|
+
if (!d || typeof d !== 'object') throw new Error('/api/status 没有 data')
|
|
75
|
+
return {
|
|
76
|
+
siteName: String(d.system_name || 'DragonAPI'),
|
|
77
|
+
version: String(d.version || ''),
|
|
78
|
+
quotaPerUnit: Number(d.quota_per_unit) > 0 ? Number(d.quota_per_unit) : 500000,
|
|
79
|
+
// 站点自己的显示规则:quota_display_type 是 USD / CNY / TOKENS / CUSTOM,
|
|
80
|
+
// display_in_currency 决定是否按货币展示。这两个都要读,只读一个会算错。
|
|
81
|
+
displayType: String(d.quota_display_type || 'USD').toUpperCase(),
|
|
82
|
+
displayInCurrency: d.display_in_currency === true,
|
|
83
|
+
usdExchangeRate: Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate) > 0
|
|
84
|
+
? Number(d.usd_exchange_rate ?? d.custom_currency_exchange_rate)
|
|
85
|
+
: 1,
|
|
86
|
+
customSymbol: typeof d.custom_currency_symbol === 'string' ? d.custom_currency_symbol.trim() : '',
|
|
87
|
+
customRate: Number(d.custom_currency_exchange_rate) > 0 ? Number(d.custom_currency_exchange_rate) : 1,
|
|
88
|
+
turnstile: d.turnstile_check === true,
|
|
89
|
+
logo: String(d.logo || ''),
|
|
90
|
+
raw: d,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* currencyOf 把站点参数折成「怎么印钱」。
|
|
96
|
+
*
|
|
97
|
+
* 符号优先级:quota_display_type 认识的码 → 非占位符的自定义符号 → 默认。
|
|
98
|
+
* 站点给的 custom_currency_symbol 常常是通用占位符 ¤,直接显示很难看。
|
|
99
|
+
* 读不到就返回一组保守默认值,但绝不把 per 折成 1——那会把额度原值当金额,
|
|
100
|
+
* 余额直接放大五十万倍。
|
|
101
|
+
*/
|
|
102
|
+
export function currencyOf(status) {
|
|
103
|
+
const byCode = { CNY: '¥', USD: '$', EUR: '€', GBP: '£', JPY: '¥' }
|
|
104
|
+
const code = String(status?.displayType || 'USD').toUpperCase()
|
|
105
|
+
const custom = String(status?.customSymbol || '')
|
|
106
|
+
const symbol = byCode[code]
|
|
107
|
+
|| (custom && custom !== '¤' ? custom : (code === 'CNY' ? '¥' : '$'))
|
|
108
|
+
const per = Number(status?.quotaPerUnit) > 0 ? Number(status.quotaPerUnit) : 500000
|
|
109
|
+
// 币种汇率:USD 恒为 1;CNY 用站点汇率;CUSTOM 用自定义汇率。
|
|
110
|
+
const rate = code === 'USD' ? 1
|
|
111
|
+
: code === 'CNY' ? (Number(status?.usdExchangeRate) > 0 ? Number(status.usdExchangeRate) : 1)
|
|
112
|
+
: code === 'CUSTOM' ? (Number(status?.customRate) > 0 ? Number(status.customRate) : 1)
|
|
113
|
+
: 1
|
|
114
|
+
return { symbol, per, rate, code, display: status?.displayInCurrency !== false }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** money 把 quota 折成站点显示的那笔钱(保留两位,用于余额与流水)。 */
|
|
118
|
+
export function money(quota, cur) {
|
|
119
|
+
const n = Number(quota)
|
|
120
|
+
if (!Number.isFinite(n)) return '—'
|
|
121
|
+
const base = n / (cur.per > 0 ? cur.per : 1)
|
|
122
|
+
const value = cur.display && cur.rate > 0 ? base * cur.rate : base
|
|
123
|
+
return value.toFixed(2)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** text 是带符号的一笔钱。 */
|
|
127
|
+
export function text(quota, cur) {
|
|
128
|
+
return cur.symbol + money(quota, cur)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 公开目录。不需要任何凭据,站点本来就把它给所有人看。 */
|
|
132
|
+
export async function readPricing(site, { etag, lastModified } = {}) {
|
|
133
|
+
const headers = {}
|
|
134
|
+
// 条件请求:实测站点认 If-None-Match 与 If-Modified-Since,命中回 304。
|
|
135
|
+
// 目录动得不勤,这一条能把轮询成本压到几乎为零。
|
|
136
|
+
if (etag) headers['if-none-match'] = etag
|
|
137
|
+
if (lastModified) headers['if-modified-since'] = lastModified
|
|
138
|
+
const base = String(site || DEFAULT_SITE).replace(/\/+$/, '')
|
|
139
|
+
const res = await fetch(base + '/api/pricing', {
|
|
140
|
+
headers: { accept: 'application/json', 'user-agent': 'magpie-dragonapi', ...headers },
|
|
141
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
142
|
+
})
|
|
143
|
+
if (res.status === 304) return { notModified: true, etag, lastModified }
|
|
144
|
+
const nextEtag = res.headers.get('etag') || ''
|
|
145
|
+
const nextLast = res.headers.get('last-modified') || ''
|
|
146
|
+
const text_ = await res.text()
|
|
147
|
+
let env
|
|
148
|
+
try {
|
|
149
|
+
env = JSON.parse(text_)
|
|
150
|
+
} catch {
|
|
151
|
+
throw new Error(`/api/pricing 返回的不是 JSON(HTTP ${res.status})`)
|
|
152
|
+
}
|
|
153
|
+
if (!res.ok || env?.success === false) {
|
|
154
|
+
throw new Error(`/api/pricing HTTP ${res.status}:${env?.message || '站点拒绝'}`)
|
|
155
|
+
}
|
|
156
|
+
return { notModified: false, env, etag: nextEtag, lastModified: nextLast }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 一把钥匙的额度与用量。这是 sk- 通道里最要紧的一个端点。 */
|
|
160
|
+
export async function readTokenUsage(site, key) {
|
|
161
|
+
const env = await siteCall(site, '/api/usage/token/', { auth: { kind: 'key', token: key } })
|
|
162
|
+
const d = env?.data
|
|
163
|
+
if (!d || typeof d !== 'object') throw new Error('/api/usage/token/ 没有 data')
|
|
164
|
+
return {
|
|
165
|
+
name: String(d.name || ''),
|
|
166
|
+
granted: Number(d.total_granted) || 0,
|
|
167
|
+
used: Number(d.total_used) || 0,
|
|
168
|
+
available: Number(d.total_available) || 0,
|
|
169
|
+
unlimited: d.unlimited_quota === true,
|
|
170
|
+
expiresAt: Number(d.expires_at) || 0,
|
|
171
|
+
modelLimits: d.model_limits && typeof d.model_limits === 'object' ? d.model_limits : null,
|
|
172
|
+
modelLimitsEnabled: d.model_limits_enabled === true,
|
|
173
|
+
// 钥匙允许查用户额度时才有;不允许就没有这个字段,别当成 0。
|
|
174
|
+
userQuota: d.user_quota && typeof d.user_quota === 'object'
|
|
175
|
+
? { available: Number(d.user_quota.total_available) || 0, used: Number(d.user_quota.total_used) || 0 }
|
|
176
|
+
: null,
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 逐条用量。站点按钥匙给最近 1000 条。 */
|
|
181
|
+
export async function readTokenLogs(site, key, { pageSize = 100 } = {}) {
|
|
182
|
+
const env = await siteCall(site, `/api/log/token?p=0&page_size=${Math.max(1, Math.min(1000, pageSize))}`, {
|
|
183
|
+
auth: { kind: 'key', token: key },
|
|
184
|
+
})
|
|
185
|
+
if (env?.success === false) throw new Error(env?.message || '站点拒绝读用量')
|
|
186
|
+
const d = env?.data
|
|
187
|
+
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : Array.isArray(d?.data) ? d.data : []
|
|
188
|
+
return items
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** PAT 能读到的账户资料。 */
|
|
192
|
+
export async function readSelf(site, pat) {
|
|
193
|
+
const env = await siteCall(site, '/api/user/self', { auth: { kind: 'pat', token: pat } })
|
|
194
|
+
const d = env?.data
|
|
195
|
+
if (!d || typeof d !== 'object') throw new Error('/api/user/self 没有 data')
|
|
196
|
+
return {
|
|
197
|
+
id: Number(d.id) || 0,
|
|
198
|
+
username: String(d.username || ''),
|
|
199
|
+
displayName: String(d.display_name || ''),
|
|
200
|
+
group: String(d.group || ''),
|
|
201
|
+
quota: Number(d.quota) || 0,
|
|
202
|
+
usedQuota: Number(d.used_quota) || 0,
|
|
203
|
+
affCode: String(d.aff_code || ''),
|
|
204
|
+
raw: d,
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 当前账号可用的分组。建钥匙时要从这里挑,不能凭目录里的分组名瞎猜。 */
|
|
209
|
+
export async function readUsableGroups(site, pat) {
|
|
210
|
+
const env = await siteCall(site, '/api/user/self/groups', { auth: { kind: 'pat', token: pat } })
|
|
211
|
+
const d = env?.data
|
|
212
|
+
// 这个端点历史上给过两种形状:字符串数组,或 {组名: 说明} 对象。
|
|
213
|
+
if (Array.isArray(d)) return d.map((x) => String(x)).filter(Boolean)
|
|
214
|
+
if (d && typeof d === 'object') return Object.keys(d)
|
|
215
|
+
return []
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 钥匙列表。站点只给打码后的 key。 */
|
|
219
|
+
export async function readKeys(site, pat, { pageSize = 100 } = {}) {
|
|
220
|
+
const env = await siteCall(site, `/api/token/?p=0&size=${Math.max(1, Math.min(100, pageSize))}`, {
|
|
221
|
+
auth: { kind: 'pat', token: pat },
|
|
222
|
+
})
|
|
223
|
+
const d = env?.data
|
|
224
|
+
const items = Array.isArray(d) ? d : Array.isArray(d?.items) ? d.items : []
|
|
225
|
+
return items.map((t) => ({
|
|
226
|
+
id: Number(t?.id) || 0,
|
|
227
|
+
name: String(t?.name || ''),
|
|
228
|
+
key: String(t?.key || ''),
|
|
229
|
+
group: String(t?.group || ''),
|
|
230
|
+
status: Number(t?.status) || 0,
|
|
231
|
+
used: Number(t?.used_quota) || 0,
|
|
232
|
+
remain: Number(t?.remain_quota) || 0,
|
|
233
|
+
unlimited: t?.unlimited_quota === true,
|
|
234
|
+
createdAt: Number(t?.created_time) || 0,
|
|
235
|
+
expiredAt: Number(t?.expired_time) || 0,
|
|
236
|
+
}))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 建一把钥匙。
|
|
241
|
+
*
|
|
242
|
+
* 关键点:这个端点不需要浏览器会话,也不需要二次验证(上游 AddToken 里
|
|
243
|
+
* 没有 RequireSecurityProof),所以带着 api_key:write 的 PAT 就能建。
|
|
244
|
+
* 但**响应里不含钥匙明文**——只有 {success, message},明文得再调一次 reveal。
|
|
245
|
+
* 也就是说「建钥匙」与「拿明文」是两次请求,中间失败会留下一把没人知道
|
|
246
|
+
* 明文的钥匙,所以调用方必须把这两步当成一件事处理(见 service.mjs)。
|
|
247
|
+
*/
|
|
248
|
+
export async function createKey(site, pat, { name, group, unlimited = true, remainQuota = 0, expiredAt = -1 }) {
|
|
249
|
+
const body = {
|
|
250
|
+
name: String(name || '').slice(0, 50),
|
|
251
|
+
group: String(group || ''),
|
|
252
|
+
unlimited_quota: unlimited === true,
|
|
253
|
+
remain_quota: unlimited ? 0 : Math.max(0, Math.floor(Number(remainQuota) || 0)),
|
|
254
|
+
expired_time: Number.isFinite(expiredAt) ? Math.floor(expiredAt) : -1,
|
|
255
|
+
model_limits_enabled: false,
|
|
256
|
+
model_limits: '',
|
|
257
|
+
allow_ips: '',
|
|
258
|
+
allow_user_quota_query: true,
|
|
259
|
+
}
|
|
260
|
+
const env = await siteCall(site, '/api/token/', { method: 'POST', body, auth: { kind: 'pat', token: pat } })
|
|
261
|
+
if (env?.success === false) throw new Error(env?.message || '站点拒绝建钥匙')
|
|
262
|
+
return { ok: true }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** 读一把钥匙的明文。需要 api_key:reveal 权限。 */
|
|
266
|
+
export async function revealKey(site, pat, id) {
|
|
267
|
+
const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}/key`, {
|
|
268
|
+
method: 'POST',
|
|
269
|
+
auth: { kind: 'pat', token: pat },
|
|
270
|
+
})
|
|
271
|
+
if (env?.success === false) throw new Error(env?.message || '站点拒绝给出钥匙')
|
|
272
|
+
const secret = String(env?.data?.key || '')
|
|
273
|
+
if (!secret) throw new Error('站点没有返回钥匙明文')
|
|
274
|
+
return secret
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 删一把钥匙。 */
|
|
278
|
+
export async function deleteKey(site, pat, id) {
|
|
279
|
+
const env = await siteCall(site, `/api/token/${Math.floor(Number(id))}`, {
|
|
280
|
+
method: 'DELETE',
|
|
281
|
+
auth: { kind: 'pat', token: pat },
|
|
282
|
+
})
|
|
283
|
+
if (env?.success === false) throw new Error(env?.message || '站点拒绝删除钥匙')
|
|
284
|
+
return { ok: true }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 校验一份凭据是不是真的能用,并尽量取回它代表的名字。
|
|
289
|
+
*
|
|
290
|
+
* 这里刻意分成两条:sk- 走 /api/usage/token/,PAT 走 /api/user/self。
|
|
291
|
+
* 用错通道会得到 401,而 401 的正文长得差不多,很容易被误读成「钥匙失效」。
|
|
292
|
+
*/
|
|
293
|
+
export async function verifyKey(site, key) {
|
|
294
|
+
const usage = await readTokenUsage(site, key)
|
|
295
|
+
return { ok: true, kind: 'key', name: usage.name, usage }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export async function verifyPat(site, pat) {
|
|
299
|
+
const self = await readSelf(site, pat)
|
|
300
|
+
return { ok: true, kind: 'pat', user: self }
|
|
301
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// 站点参数源:/api/status 的缓存与降级。
|
|
2
|
+
//
|
|
3
|
+
// 与目录源分开,因为它们的失效策略不同:目录变了要重列模型,站点参数
|
|
4
|
+
// (币种、汇率、额度折算)变了只影响「钱怎么印」,不需要惊动宿主。
|
|
5
|
+
//
|
|
6
|
+
// 降级原则只有一条:读不到就沿用上一次成功的值,一次都没成功过才用默认值。
|
|
7
|
+
// 绝不把 quota_per_unit 退成 1——那会把额度原值当金额,余额直接放大五十万倍。
|
|
8
|
+
|
|
9
|
+
import { readStatus } from './site.mjs'
|
|
10
|
+
|
|
11
|
+
/** 站点参数多久算过期。这些几乎不变,十分钟足够。 */
|
|
12
|
+
export const DEFAULT_TTL = 10 * 60e3
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* createStatusSource 造一个站点参数源。
|
|
16
|
+
*
|
|
17
|
+
* @param {object} o
|
|
18
|
+
* @param {string} o.site
|
|
19
|
+
* @param {object} [o.seed] 上次落盘的参数(冷启动先顶上,别让页面等)
|
|
20
|
+
* @param {function} [o.fetchStatus]
|
|
21
|
+
* @param {function} [o.onRead] 读到新值时回调(用来落盘)
|
|
22
|
+
*/
|
|
23
|
+
export function createStatusSource({ site, seed = null, fetchStatus = readStatus, onRead } = {}) {
|
|
24
|
+
let state = { at: 0, value: seed || null, error: '' }
|
|
25
|
+
|
|
26
|
+
async function get({ force = false } = {}) {
|
|
27
|
+
const now = Date.now()
|
|
28
|
+
if (!force && state.value && now - state.at < DEFAULT_TTL) return state.value
|
|
29
|
+
try {
|
|
30
|
+
const v = await fetchStatus(site)
|
|
31
|
+
state = { at: now, value: v, error: '' }
|
|
32
|
+
try { onRead?.(v) } catch { /* 落盘失败不影响这次读取 */ }
|
|
33
|
+
return v
|
|
34
|
+
} catch (error) {
|
|
35
|
+
state = { ...state, at: now, error: String(error?.message || error) }
|
|
36
|
+
return state.value
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const snapshot = () => state.value
|
|
41
|
+
const lastError = () => state.error
|
|
42
|
+
|
|
43
|
+
return { get, snapshot, lastError }
|
|
44
|
+
}
|
package/lib/store.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// 本地状态:PAT、已绑定账号的元数据、目录快照。
|
|
2
|
+
//
|
|
3
|
+
// 存在 magpie 自己的配置目录里(宿主把 `settings.Dir()` 作为 `input.directory`
|
|
4
|
+
// 交给插件),文件名固定 `dragonapi-state.json`,原子写(临时文件 + rename)。
|
|
5
|
+
//
|
|
6
|
+
// **这里绝不落盘任何钥匙明文。** 钥匙本身由 magpie 的 plugin-auth.json 保管
|
|
7
|
+
// (那是宿主的事),这里只记「哪个账号对应哪个分组、打码后是什么样」,
|
|
8
|
+
// 用来在页面上把账号和钥匙对上号。PAT 是个例外——它必须明文存在本地,
|
|
9
|
+
// 因为每次建钥匙都要用它,而 magpie 的 auth 表存的是供应商凭据不是这个。
|
|
10
|
+
// PAT 只写在这个 0600 的文件里,不写日志、不回显完整值。
|
|
11
|
+
|
|
12
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync, existsSync } from 'node:fs'
|
|
13
|
+
import { dirname, join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
const FILE_NAME = 'dragonapi-state.json'
|
|
16
|
+
|
|
17
|
+
/** emptyState 是「什么都没配过」的样子。 */
|
|
18
|
+
function emptyState() {
|
|
19
|
+
return {
|
|
20
|
+
version: 1,
|
|
21
|
+
pat: '',
|
|
22
|
+
patHint: '',
|
|
23
|
+
patScopes: [],
|
|
24
|
+
// 已绑定的账号:key 是 magpie 的账号键(provider 或 provider#slot),
|
|
25
|
+
// 记的是它对应的站点分组与打码钥匙,供页面显示。
|
|
26
|
+
accounts: {},
|
|
27
|
+
// 上一次成功的目录快照,冷启动时先给宿主一份非空的表。
|
|
28
|
+
catalog: null,
|
|
29
|
+
catalogAt: 0,
|
|
30
|
+
updatedAt: 0,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** statePath 是状态文件的位置。 */
|
|
35
|
+
export function statePath(dir) {
|
|
36
|
+
return join(dir || '.', FILE_NAME)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** loadState 读状态;文件不存在或坏了都返回空状态,不抛。 */
|
|
40
|
+
export function loadState(dir) {
|
|
41
|
+
const p = statePath(dir)
|
|
42
|
+
if (!existsSync(p)) return emptyState()
|
|
43
|
+
try {
|
|
44
|
+
const raw = JSON.parse(readFileSync(p, 'utf8'))
|
|
45
|
+
if (!raw || typeof raw !== 'object') return emptyState()
|
|
46
|
+
return {
|
|
47
|
+
...emptyState(),
|
|
48
|
+
...raw,
|
|
49
|
+
accounts: raw.accounts && typeof raw.accounts === 'object' ? raw.accounts : {},
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
// 坏文件不能把插件带崩:当成没配过,下一次写入会覆盖它。
|
|
53
|
+
return emptyState()
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** saveState 原子写状态。写失败返回 false,不抛——状态存不下不该让插件停摆。 */
|
|
58
|
+
export function saveState(dir, state) {
|
|
59
|
+
const p = statePath(dir)
|
|
60
|
+
try {
|
|
61
|
+
mkdirSync(dirname(p), { recursive: true })
|
|
62
|
+
const tmp = p + '.tmp-' + process.pid
|
|
63
|
+
const body = JSON.stringify({ ...state, updatedAt: Date.now() }, null, 2)
|
|
64
|
+
writeFileSync(tmp, body, { mode: 0o600 })
|
|
65
|
+
try { chmodSync(tmp, 0o600) } catch { /* Windows 上 chmod 基本无效,忽略 */ }
|
|
66
|
+
renameSync(tmp, p)
|
|
67
|
+
return true
|
|
68
|
+
} catch {
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** maskKey 把钥匙打码成 `sk-a**********9f3c`,与站点自己的写法一致。 */
|
|
74
|
+
export function maskKey(key) {
|
|
75
|
+
const s = String(key || '')
|
|
76
|
+
if (!s) return ''
|
|
77
|
+
if (s.length <= 4) return '*'.repeat(s.length)
|
|
78
|
+
if (s.length <= 8) return s.slice(0, 2) + '****' + s.slice(-2)
|
|
79
|
+
return s.slice(0, 4) + '**********' + s.slice(-4)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** tailOf 取钥匙后四位,用来在页面里把账号和站点钥匙对上号。 */
|
|
83
|
+
export function tailOf(key) {
|
|
84
|
+
const s = String(key || '')
|
|
85
|
+
return s.length >= 8 ? s.slice(-4) : ''
|
|
86
|
+
}
|
package/lib/usage.mjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// 用量:把站点的逐条日志折成页面能直接画的形状。
|
|
2
|
+
//
|
|
3
|
+
// 站点的 /api/log/token 每条字段写法不统一(有时在顶层,有时塞在 other 里),
|
|
4
|
+
// 所以这里逐个字段兜底。这套解析与 NearToken 的同名逻辑高度同构——那个站点
|
|
5
|
+
// 也是 New API 部署,日志形状一致。
|
|
6
|
+
|
|
7
|
+
import { text } from './site.mjs'
|
|
8
|
+
|
|
9
|
+
/** num 只接受真正的数字,字符串数字也认;其它一律 undefined。 */
|
|
10
|
+
function num(v) {
|
|
11
|
+
if (typeof v === 'number' && Number.isFinite(v)) return v
|
|
12
|
+
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v)
|
|
13
|
+
return undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** otherOf 把 other 字段(可能是 JSON 字符串)拆成对象。 */
|
|
17
|
+
function otherOf(row) {
|
|
18
|
+
const o = row?.other
|
|
19
|
+
if (!o) return null
|
|
20
|
+
if (typeof o === 'object') return o
|
|
21
|
+
if (typeof o === 'string') {
|
|
22
|
+
try { return JSON.parse(o) } catch { return null }
|
|
23
|
+
}
|
|
24
|
+
return null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** pick 取第一个非空的字符串。 */
|
|
28
|
+
function pick(...vals) {
|
|
29
|
+
for (const v of vals) {
|
|
30
|
+
if (typeof v === 'string' && v.trim()) return v.trim()
|
|
31
|
+
}
|
|
32
|
+
return ''
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 站点日志的 type 值 → 人话。 */
|
|
36
|
+
const LOG_KINDS = { 1: '充值', 2: '消耗', 3: '管理', 4: '系统', 5: '错误', 6: '退款' }
|
|
37
|
+
|
|
38
|
+
function kindOf(type) {
|
|
39
|
+
const n = Number(type)
|
|
40
|
+
return LOG_KINDS[n] || (Number.isFinite(n) ? `类型 ${n}` : '—')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** fmtStamp 把 Unix 秒折成 `MM-DD HH:mm`。 */
|
|
44
|
+
export function fmtStamp(sec) {
|
|
45
|
+
const n = Number(sec)
|
|
46
|
+
if (!Number.isFinite(n) || n <= 0) return ''
|
|
47
|
+
const d = new Date(n * 1000)
|
|
48
|
+
const p = (x) => String(x).padStart(2, '0')
|
|
49
|
+
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** firstToken 取首字耗时(秒)。站点有时给 ttft,有时给 first_token_time。 */
|
|
53
|
+
function firstToken(row) {
|
|
54
|
+
const o = otherOf(row)
|
|
55
|
+
return num(row?.ttft) ?? num(o?.ttft) ?? num(row?.first_token_time) ?? num(o?.first_token_time)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* detailOf 拼「计价说明」。
|
|
60
|
+
* 站点把计价档位与单价塞在 other 里,键名随版本变,这里按常见写法逐个兜底。
|
|
61
|
+
*/
|
|
62
|
+
function detailOf(other, quota) {
|
|
63
|
+
if (!other || typeof other !== 'object') return ''
|
|
64
|
+
const tier = pick(other?.tier, other?.billing_tier, other?.group)
|
|
65
|
+
const inPrice = num(other?.model_ratio) ?? num(other?.input_price)
|
|
66
|
+
const outPrice = num(other?.completion_ratio) ?? num(other?.output_price)
|
|
67
|
+
const parts = []
|
|
68
|
+
if (tier) parts.push(tier)
|
|
69
|
+
if (inPrice !== undefined || outPrice !== undefined) {
|
|
70
|
+
parts.push(`${inPrice ?? '—'} / ${outPrice ?? '—'}`)
|
|
71
|
+
}
|
|
72
|
+
if (!parts.length && quota !== undefined) return ''
|
|
73
|
+
return parts.join(' · ')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* rowsOf 把站点原始日志折成页面行。
|
|
78
|
+
*
|
|
79
|
+
* @param {Array} items /api/log/token 的 data
|
|
80
|
+
* @param {object} cur currencyOf 的结果
|
|
81
|
+
* @param {string} account 这个账号在 magpie 里的键(多账号时用来区分来源)
|
|
82
|
+
*/
|
|
83
|
+
export function rowsOf(items, cur, account = '') {
|
|
84
|
+
const out = []
|
|
85
|
+
for (const r of Array.isArray(items) ? items : []) {
|
|
86
|
+
if (!r || typeof r !== 'object') continue
|
|
87
|
+
const other = otherOf(r)
|
|
88
|
+
const at = num(r?.created_at) ?? num(r?.createdAt) ?? 0
|
|
89
|
+
const prompt = num(r?.prompt_tokens) ?? num(other?.prompt_tokens)
|
|
90
|
+
const completion = num(r?.completion_tokens) ?? num(other?.completion_tokens)
|
|
91
|
+
const secs = num(r?.use_time) ?? num(other?.use_time)
|
|
92
|
+
const quota = num(r?.quota) ?? num(other?.quota)
|
|
93
|
+
const model = pick(r?.model_name, r?.modelName, other?.model_name)
|
|
94
|
+
const detail = detailOf(other, quota)
|
|
95
|
+
// 模型与说明都空的行没有信息量,丢掉(与宿主的口径一致)。
|
|
96
|
+
if (!model && !detail) continue
|
|
97
|
+
// 吞吐 = 输出 token / 生成耗时;用总时长做分母会明显偏低。
|
|
98
|
+
const ttft = firstToken(r)
|
|
99
|
+
const tps = completion && secs
|
|
100
|
+
? (() => {
|
|
101
|
+
const gen = ttft !== undefined && secs > ttft ? secs - ttft : secs
|
|
102
|
+
return gen > 0 ? Math.round(completion / gen) : undefined
|
|
103
|
+
})()
|
|
104
|
+
: undefined
|
|
105
|
+
out.push({
|
|
106
|
+
at: at * 1000,
|
|
107
|
+
atText: fmtStamp(at),
|
|
108
|
+
account,
|
|
109
|
+
kind: kindOf(r?.type),
|
|
110
|
+
model,
|
|
111
|
+
group: pick(r?.group, other?.group),
|
|
112
|
+
tokenName: pick(r?.token_name, r?.tokenName),
|
|
113
|
+
upModel: pick(other?.upstream_model, other?.up_model, other?.request_model),
|
|
114
|
+
respModel: pick(other?.response_model, other?.downstream_model),
|
|
115
|
+
effort: pick(other?.reasoning_effort, other?.effort),
|
|
116
|
+
input: prompt,
|
|
117
|
+
output: completion,
|
|
118
|
+
cache: num(r?.cache_tokens) ?? num(other?.cache_tokens),
|
|
119
|
+
bytes: num(r?.request_size) ?? num(other?.request_size),
|
|
120
|
+
cost: quota === undefined ? '' : text(quota, cur),
|
|
121
|
+
costRaw: quota,
|
|
122
|
+
tps,
|
|
123
|
+
ttft,
|
|
124
|
+
dur: secs,
|
|
125
|
+
detail,
|
|
126
|
+
isStream: r?.is_stream === true || r?.isStream === true,
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
// 最新在最上面:按时间显式降序,不依赖站点返回顺序。
|
|
130
|
+
out.sort((a, b) => (b.at || 0) - (a.at || 0))
|
|
131
|
+
return out
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* summarize 把一堆行按窗口汇总:总额、token、按模型、按时间桶。
|
|
136
|
+
*
|
|
137
|
+
* @param {Array} rows rowsOf 的结果
|
|
138
|
+
* @param {object} cur
|
|
139
|
+
* @param {number} start 窗口起点(毫秒)
|
|
140
|
+
* @param {number} end 窗口终点(毫秒)
|
|
141
|
+
*/
|
|
142
|
+
export function summarize(rows, cur, start, end) {
|
|
143
|
+
const span = Math.max(1, end - start)
|
|
144
|
+
// 桶的粒度:一天按小时,一周按 6 小时,一个月按天。
|
|
145
|
+
const bucketMs = span <= 26 * 3600e3 ? 3600e3 : span <= 8 * 24 * 3600e3 ? 6 * 3600e3 : 24 * 3600e3
|
|
146
|
+
const byModel = new Map()
|
|
147
|
+
const byBucket = new Map()
|
|
148
|
+
let spent = 0
|
|
149
|
+
let tokens = 0
|
|
150
|
+
for (const r of rows) {
|
|
151
|
+
if (!r.at || r.at < start || r.at > end) continue
|
|
152
|
+
const cost = Number(r.costRaw) || 0
|
|
153
|
+
const tok = (Number(r.input) || 0) + (Number(r.output) || 0)
|
|
154
|
+
spent += cost
|
|
155
|
+
tokens += tok
|
|
156
|
+
const key = r.model || '(未知)'
|
|
157
|
+
const had = byModel.get(key) || { model: key, tokens: 0, costRaw: 0, calls: 0 }
|
|
158
|
+
had.tokens += tok
|
|
159
|
+
had.costRaw += cost
|
|
160
|
+
had.calls += 1
|
|
161
|
+
byModel.set(key, had)
|
|
162
|
+
const b = Math.floor((r.at - start) / bucketMs) * bucketMs + start
|
|
163
|
+
const hb = byBucket.get(b) || { at: b, costRaw: 0, tokens: 0 }
|
|
164
|
+
hb.costRaw += cost
|
|
165
|
+
hb.tokens += tok
|
|
166
|
+
byBucket.set(b, hb)
|
|
167
|
+
}
|
|
168
|
+
const models = [...byModel.values()]
|
|
169
|
+
.sort((a, b) => b.costRaw - a.costRaw)
|
|
170
|
+
.map((m) => ({ ...m, cost: text(m.costRaw, cur) }))
|
|
171
|
+
const buckets = [...byBucket.values()]
|
|
172
|
+
.sort((a, b) => a.at - b.at)
|
|
173
|
+
.map((b) => ({ ...b, cost: text(b.costRaw, cur) }))
|
|
174
|
+
return {
|
|
175
|
+
start,
|
|
176
|
+
end,
|
|
177
|
+
spent: text(spent, cur),
|
|
178
|
+
spentRaw: spent,
|
|
179
|
+
tokens,
|
|
180
|
+
byModel: models,
|
|
181
|
+
buckets,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 窗口的起止(毫秒)。range ∈ day | week | month。 */
|
|
186
|
+
export function windowOf(range, now = Date.now()) {
|
|
187
|
+
const d = new Date(now)
|
|
188
|
+
if (range === 'week') {
|
|
189
|
+
// 最近 7 天(含今天),按本地零点切。
|
|
190
|
+
const start = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 6).getTime()
|
|
191
|
+
const end = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime()
|
|
192
|
+
return { start, end }
|
|
193
|
+
}
|
|
194
|
+
if (range === 'month') {
|
|
195
|
+
const start = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 29).getTime()
|
|
196
|
+
const end = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime()
|
|
197
|
+
return { start, end }
|
|
198
|
+
}
|
|
199
|
+
const start = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
|
|
200
|
+
const end = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime()
|
|
201
|
+
return { start, end }
|
|
202
|
+
}
|