dsh-model-allowance 1.1.0 → 1.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/README.md +14 -2
- package/README.zh.md +10 -2
- package/client.js +443 -5
- package/lib/balance.js +11 -2
- package/lib/providers/placeholder.js +0 -42
- package/lib/providers/qwen_token_plan.js +713 -0
- package/lib/providers/shared.js +10 -0
- package/lib/providers.js +5 -6
- package/lib/remote.js +18 -0
- package/package.json +1 -1
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen Token Plan allowance adapter (Bailian personal plan, CN site).
|
|
3
|
+
*
|
|
4
|
+
* The plan key (`sk-sp-…`) only authorizes inference; the usage lives behind
|
|
5
|
+
* the Bailian console gateway. The chain is the one Alibaba's own `bl` CLI
|
|
6
|
+
* walks, verified against a real account:
|
|
7
|
+
*
|
|
8
|
+
* 1. ACS3-HMAC-SHA256 signs `POST modelstudio.cn-beijing.aliyuncs.com
|
|
9
|
+
* /modelstudio/cli/generateAccessToken`, which answers a temporary
|
|
10
|
+
* `cliAccessToken`;
|
|
11
|
+
* 2. `POST bailian-cs.console.aliyun.com/cli/api.json?action=BroadScopeAspnGateway`
|
|
12
|
+
* carries that token to `zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage`,
|
|
13
|
+
* whose payload reports each window as `per<N><unit>Percentage` (share
|
|
14
|
+
* used, 0–1) plus `per<N><unit>ResetTime` (epoch milliseconds).
|
|
15
|
+
*
|
|
16
|
+
* Absolute totals are enrichment, not the reading: the subscription names the
|
|
17
|
+
* `specCode`, and `quota-config` carries that spec's per-window totals. A
|
|
18
|
+
* reading without them still reports the share left and the reset.
|
|
19
|
+
*
|
|
20
|
+
* The AccessKey pair is read from the credential store (the settings page's
|
|
21
|
+
* "Model Allowance" section stores it, after `testQwenPlanCredentials` has
|
|
22
|
+
* walked this same chain against the live endpoints). A RAM user's AccessKey
|
|
23
|
+
* is refused with `BailianGateway.Team.NotAuthorised` until the main account
|
|
24
|
+
* grants it the AliyunTokenPlanReadOnlyAccess and AliyunBSSReadOnlyAccess
|
|
25
|
+
* policies and the Subscribe Plan permission on the Model Studio console's
|
|
26
|
+
* Account Management page — the failure names that.
|
|
27
|
+
*/
|
|
28
|
+
import { createHash, createHmac, randomUUID } from 'node:crypto'
|
|
29
|
+
import {
|
|
30
|
+
asObject,
|
|
31
|
+
bindingWindow,
|
|
32
|
+
defineAdapter,
|
|
33
|
+
KIND_QUOTA,
|
|
34
|
+
parseAmount,
|
|
35
|
+
parseInstant,
|
|
36
|
+
} from './shared.js'
|
|
37
|
+
|
|
38
|
+
/** Credential references the settings page stores the AccessKey pair under. */
|
|
39
|
+
export const ACCESS_KEY_ID_REF = 'ALIBABA_CLOUD_ACCESS_KEY_ID'
|
|
40
|
+
export const ACCESS_KEY_SECRET_REF = 'ALIBABA_CLOUD_ACCESS_KEY_SECRET'
|
|
41
|
+
|
|
42
|
+
/** The guide that walks obtaining the AccessKey pair, linked from the UI. */
|
|
43
|
+
export const SETUP_DOC_URL =
|
|
44
|
+
'https://github.com/MeiK2333/dsh-model-allowance/blob/master/docs/qwen-token-plen-cn/README.md'
|
|
45
|
+
|
|
46
|
+
/** The console token endpoint (ROA-style: the Action travels in headers). */
|
|
47
|
+
const ACS_HOST = 'modelstudio.cn-beijing.aliyuncs.com'
|
|
48
|
+
const ACS_PATH = '/modelstudio/cli/generateAccessToken'
|
|
49
|
+
const ACS_ACTION = 'GenerateCLIAccessToken'
|
|
50
|
+
const ACS_VERSION = '2026-02-10'
|
|
51
|
+
|
|
52
|
+
/** The console gateway the usage APIs sit behind. */
|
|
53
|
+
const GATEWAY_HOST = 'bailian-cs.console.aliyun.com'
|
|
54
|
+
const GATEWAY_ACTION = 'BroadScopeAspnGateway'
|
|
55
|
+
const GATEWAY_REGION = 'cn-beijing'
|
|
56
|
+
const USAGE_API = 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage'
|
|
57
|
+
const SUBSCRIPTION_API = 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/subscription'
|
|
58
|
+
const QUOTA_CONFIG_API = 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/quota-config'
|
|
59
|
+
|
|
60
|
+
/** What a RAM user's AccessKey needs; said in the failure that names it. */
|
|
61
|
+
const RAM_HINT =
|
|
62
|
+
"grant the AccessKey's RAM user the AliyunTokenPlanReadOnlyAccess and " +
|
|
63
|
+
'AliyunBSSReadOnlyAccess policies and the Subscribe Plan or Administrator permission ' +
|
|
64
|
+
"on the Model Studio console's Account Management page, or use the main account's AccessKey"
|
|
65
|
+
|
|
66
|
+
const CONTENT_TYPE = 'application/json'
|
|
67
|
+
const SIGNED_HEADERS =
|
|
68
|
+
'content-type;host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version'
|
|
69
|
+
|
|
70
|
+
/** A usage window: `per5HourPercentage` → five-hour, `per1MonthPercentage` → month. */
|
|
71
|
+
const WINDOW_PATTERN = /^per(\d+)(Hour|Day|Week|Month)Percentage$/
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @typedef {import('./shared.js').BalanceWindow & {usedShare: number}} UsageWindow
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
/** @type {Record<string, 'hour' | 'day' | 'week' | 'month'>} */
|
|
78
|
+
const WINDOW_UNITS = { Hour: 'hour', Day: 'day', Week: 'week', Month: 'month' }
|
|
79
|
+
|
|
80
|
+
/** `quota-config` totals, by the window they meter. */
|
|
81
|
+
const TOTAL_WINDOWS = { five_hour: 'per5Hour', monthly: 'per1Month' }
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Build the ACS3-HMAC-SHA256 headers for one console API call.
|
|
85
|
+
*
|
|
86
|
+
* Time and nonce are parameters so the algorithm is pinned by a golden
|
|
87
|
+
* vector; a signing typo is invisible until a live call is refused.
|
|
88
|
+
*
|
|
89
|
+
* @param {object} input The call to sign.
|
|
90
|
+
* @param {string} input.accessKeyId AccessKey ID.
|
|
91
|
+
* @param {string} input.secretAccessKey AccessKey secret.
|
|
92
|
+
* @param {string} input.host Request host.
|
|
93
|
+
* @param {string} input.path Request path.
|
|
94
|
+
* @param {string} input.action `x-acs-action` value.
|
|
95
|
+
* @param {string} input.version `x-acs-version` value.
|
|
96
|
+
* @param {string} input.body Request body.
|
|
97
|
+
* @param {string} input.date `x-acs-date`, ISO 8601 UTC to the second.
|
|
98
|
+
* @param {string} input.nonce `x-acs-signature-nonce`.
|
|
99
|
+
* @returns {Record<string, string>} The request headers, `authorization` included.
|
|
100
|
+
*/
|
|
101
|
+
export function acs3Authorization({
|
|
102
|
+
accessKeyId,
|
|
103
|
+
secretAccessKey,
|
|
104
|
+
host,
|
|
105
|
+
path,
|
|
106
|
+
action,
|
|
107
|
+
version,
|
|
108
|
+
body,
|
|
109
|
+
date,
|
|
110
|
+
nonce,
|
|
111
|
+
}) {
|
|
112
|
+
const hashedBody = createHash('sha256').update(body).digest('hex')
|
|
113
|
+
const canonicalHeaders =
|
|
114
|
+
`content-type:${CONTENT_TYPE}\n` +
|
|
115
|
+
`host:${host}\n` +
|
|
116
|
+
`x-acs-action:${action}\n` +
|
|
117
|
+
`x-acs-content-sha256:${hashedBody}\n` +
|
|
118
|
+
`x-acs-date:${date}\n` +
|
|
119
|
+
`x-acs-signature-nonce:${nonce}\n` +
|
|
120
|
+
`x-acs-version:${version}\n`
|
|
121
|
+
const canonicalRequest = `POST\n${path}\n\n${canonicalHeaders}\n${SIGNED_HEADERS}\n${hashedBody}`
|
|
122
|
+
const canonicalHash = createHash('sha256').update(canonicalRequest).digest('hex')
|
|
123
|
+
const stringToSign = `ACS3-HMAC-SHA256\n${canonicalHash}`
|
|
124
|
+
const signature = createHmac('sha256', secretAccessKey).update(stringToSign).digest('hex')
|
|
125
|
+
return {
|
|
126
|
+
'content-type': CONTENT_TYPE,
|
|
127
|
+
'x-acs-action': action,
|
|
128
|
+
'x-acs-version': version,
|
|
129
|
+
'x-acs-date': date,
|
|
130
|
+
'x-acs-signature-nonce': nonce,
|
|
131
|
+
'x-acs-content-sha256': hashedBody,
|
|
132
|
+
authorization:
|
|
133
|
+
`ACS3-HMAC-SHA256 Credential=${accessKeyId},` +
|
|
134
|
+
`SignedHeaders=${SIGNED_HEADERS},Signature=${signature}`,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The current instant in the `x-acs-date` format.
|
|
140
|
+
* @returns {string} ISO 8601 UTC to the second.
|
|
141
|
+
*/
|
|
142
|
+
function acsDate() {
|
|
143
|
+
return new Date().toISOString().replace(/\.\d+Z$/, 'Z')
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Resolve one credential reference through the Host's credential store.
|
|
148
|
+
* @param {{resolve: (ref: string) => Promise<{value?: unknown} | undefined>} | undefined} credentials
|
|
149
|
+
* The credential service, when the host offers one.
|
|
150
|
+
* @param {string} ref Reference name.
|
|
151
|
+
* @returns {Promise<string | undefined>} The value, when it is present.
|
|
152
|
+
*/
|
|
153
|
+
async function resolveCredential(credentials, ref) {
|
|
154
|
+
if (credentials === undefined) return undefined
|
|
155
|
+
try {
|
|
156
|
+
const hit = await credentials.resolve(ref)
|
|
157
|
+
const value = hit?.value
|
|
158
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
159
|
+
} catch {
|
|
160
|
+
// An unresolvable reference is simply absent here.
|
|
161
|
+
return undefined
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Exchange the AccessKey pair for a console token.
|
|
167
|
+
* @param {object} input The call.
|
|
168
|
+
* @param {string} input.accessKeyId AccessKey ID.
|
|
169
|
+
* @param {string} input.secretAccessKey AccessKey secret.
|
|
170
|
+
* @param {AbortSignal} input.signal Cancellation.
|
|
171
|
+
* @returns {Promise<{token?: string, error?: string}>} The token, or the refusal.
|
|
172
|
+
*/
|
|
173
|
+
async function consoleToken({ accessKeyId, secretAccessKey, signal }) {
|
|
174
|
+
const headers = acs3Authorization({
|
|
175
|
+
accessKeyId,
|
|
176
|
+
secretAccessKey,
|
|
177
|
+
host: ACS_HOST,
|
|
178
|
+
path: ACS_PATH,
|
|
179
|
+
action: ACS_ACTION,
|
|
180
|
+
version: ACS_VERSION,
|
|
181
|
+
body: '',
|
|
182
|
+
date: acsDate(),
|
|
183
|
+
nonce: randomUUID(),
|
|
184
|
+
})
|
|
185
|
+
const response = await fetch(`https://${ACS_HOST}${ACS_PATH}`, {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers,
|
|
188
|
+
body: '',
|
|
189
|
+
signal,
|
|
190
|
+
})
|
|
191
|
+
if (!response.ok) return { error: `GenerateCLIAccessToken: HTTP ${String(response.status)}` }
|
|
192
|
+
const body = asObject(await response.json())
|
|
193
|
+
const direct = body.cliAccessToken
|
|
194
|
+
const nested = asObject(body.data).cliAccessToken
|
|
195
|
+
const token = typeof direct === 'string' ? direct : typeof nested === 'string' ? nested : ''
|
|
196
|
+
if (token === '') return { error: 'GenerateCLIAccessToken returned no cliAccessToken' }
|
|
197
|
+
return { token }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Call one console gateway JSON API.
|
|
202
|
+
*
|
|
203
|
+
* The gateway wraps the business payload in `params`/`region` form fields and
|
|
204
|
+
* answers a two-level envelope; the caller digs the payload out.
|
|
205
|
+
*
|
|
206
|
+
* @param {string} token Console token.
|
|
207
|
+
* @param {string} api Console API name.
|
|
208
|
+
* @param {Record<string, unknown>} data Business parameters.
|
|
209
|
+
* @param {AbortSignal} signal Cancellation.
|
|
210
|
+
* @returns {Promise<{envelope?: Record<string, unknown>, error?: string}>} The envelope, or the refusal.
|
|
211
|
+
*/
|
|
212
|
+
async function gatewayCall(token, api, data, signal) {
|
|
213
|
+
const payload = {
|
|
214
|
+
...asObject(data),
|
|
215
|
+
cornerstoneParam: {
|
|
216
|
+
protocol: 'V2',
|
|
217
|
+
console: 'ONE_CONSOLE',
|
|
218
|
+
productCode: 'p_efm',
|
|
219
|
+
switchUserType: 3,
|
|
220
|
+
consoleSite: 'BAILIAN_ALIYUN',
|
|
221
|
+
},
|
|
222
|
+
}
|
|
223
|
+
const params = JSON.stringify({ Api: api, V: '1.0', Data: payload })
|
|
224
|
+
const body = `params=${encodeURIComponent(params)}®ion=${encodeURIComponent(GATEWAY_REGION)}`
|
|
225
|
+
const url =
|
|
226
|
+
`https://${GATEWAY_HOST}/cli/api.json?action=${GATEWAY_ACTION}&product=sfm_bailian` +
|
|
227
|
+
`&api=${encodeURIComponent(api)}`
|
|
228
|
+
const response = await fetch(url, {
|
|
229
|
+
method: 'POST',
|
|
230
|
+
headers: {
|
|
231
|
+
accept: '*/*',
|
|
232
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
233
|
+
authorization: `Bearer ${token}`,
|
|
234
|
+
},
|
|
235
|
+
body,
|
|
236
|
+
signal,
|
|
237
|
+
})
|
|
238
|
+
if (!response.ok) return { error: `${api}: HTTP ${String(response.status)}` }
|
|
239
|
+
return { envelope: asObject(await response.json()) }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The business payload inside the gateway's envelope.
|
|
244
|
+
*
|
|
245
|
+
* Depth varies by API and console build, so every nesting the gateway has
|
|
246
|
+
* been seen to use is tried and the first node `wanted` accepts wins.
|
|
247
|
+
*
|
|
248
|
+
* @param {Record<string, unknown>} envelope The envelope.
|
|
249
|
+
* @param {(node: Record<string, unknown>) => boolean} wanted Recognizes the payload.
|
|
250
|
+
* @returns {Record<string, unknown> | undefined} The payload, when present.
|
|
251
|
+
*/
|
|
252
|
+
function gatewayPayload(envelope, wanted) {
|
|
253
|
+
const data = asObject(envelope.data)
|
|
254
|
+
const candidates = [
|
|
255
|
+
asObject(asObject(asObject(data.DataV2).data).data),
|
|
256
|
+
asObject(asObject(data.DataV2).data),
|
|
257
|
+
asObject(data.data),
|
|
258
|
+
data,
|
|
259
|
+
]
|
|
260
|
+
return candidates.find((node) => wanted(node))
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* A gateway refusal as one message, naming the grants when it is the RAM one.
|
|
265
|
+
* @param {Record<string, unknown>} envelope The envelope.
|
|
266
|
+
* @returns {string | undefined} The refusal, when the gateway refused.
|
|
267
|
+
*/
|
|
268
|
+
function gatewayError(envelope) {
|
|
269
|
+
const data = asObject(envelope.data)
|
|
270
|
+
if (data.success !== false) return undefined
|
|
271
|
+
const code = typeof data.errorCode === 'string' ? data.errorCode : ''
|
|
272
|
+
const message = typeof data.errorMsg === 'string' ? data.errorMsg : ''
|
|
273
|
+
const detail = code !== '' && message !== '' && message !== code ? `${code}: ${message}` : code
|
|
274
|
+
const refusal = detail !== '' ? detail : message !== '' ? message : 'unknown gateway error'
|
|
275
|
+
return code.includes('NotAuthorised') ? `${refusal} — ${RAM_HINT}` : refusal
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Percentages are compared and displayed at two decimals.
|
|
280
|
+
* @param {number} value The raw percentage.
|
|
281
|
+
* @returns {number} The rounded percentage, clamped to 0–100.
|
|
282
|
+
*/
|
|
283
|
+
function roundPercent(value) {
|
|
284
|
+
return Math.min(100, Math.max(0, Math.round(value * 100) / 100))
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* A refused read as a reading: a provider refusal is data, not a crash.
|
|
289
|
+
* @param {string} route Provider route.
|
|
290
|
+
* @param {string} error The refusal.
|
|
291
|
+
* @returns {import('../providers.js').BalanceView} The failed reading.
|
|
292
|
+
*/
|
|
293
|
+
function failed(route, error) {
|
|
294
|
+
return { provider: route, status: 'failed', kind: KIND_QUOTA, error }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Read the usage payload's quota windows.
|
|
299
|
+
*
|
|
300
|
+
* The vendor words every window the same way — `per<N><unit>Percentage` is
|
|
301
|
+
* the share used and `per<N><unit>ResetTime` its reset — so one pattern
|
|
302
|
+
* reports whatever windows a plan enforces instead of a hardcoded month.
|
|
303
|
+
*
|
|
304
|
+
* @param {Record<string, unknown>} payload The usage payload.
|
|
305
|
+
* @returns {UsageWindow[]} The windows.
|
|
306
|
+
*/
|
|
307
|
+
function usageWindows(payload) {
|
|
308
|
+
/** @type {UsageWindow[]} */
|
|
309
|
+
const windows = []
|
|
310
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
311
|
+
const match = WINDOW_PATTERN.exec(key)
|
|
312
|
+
if (match === null) continue
|
|
313
|
+
const usedShare = parseAmount(value)
|
|
314
|
+
if (usedShare === undefined) continue
|
|
315
|
+
const id = `per${match[1]}${match[2]}`
|
|
316
|
+
const resetAt = parseInstant(payload[`${id}ResetTime`])
|
|
317
|
+
windows.push({
|
|
318
|
+
id,
|
|
319
|
+
unit: WINDOW_UNITS[match[2]],
|
|
320
|
+
count: Number(match[1]),
|
|
321
|
+
usedShare,
|
|
322
|
+
remainingPercent: roundPercent((1 - usedShare) * 100),
|
|
323
|
+
...(resetAt === undefined ? {} : { resetAt }),
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
return windows
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* The `quota-config` totals of one spec, keyed by the window they meter.
|
|
331
|
+
* @param {Record<string, unknown> | undefined} payload The quota-config payload.
|
|
332
|
+
* @param {string | undefined} specCode The subscription's spec, when known.
|
|
333
|
+
* @returns {Map<string, number>} Window id to total allowance.
|
|
334
|
+
*/
|
|
335
|
+
function planTotals(payload, specCode) {
|
|
336
|
+
/** @type {Map<string, number>} */
|
|
337
|
+
const totals = new Map()
|
|
338
|
+
const spec = specCode === undefined ? undefined : asObject(payload?.[specCode])
|
|
339
|
+
for (const [key, windowId] of Object.entries(TOTAL_WINDOWS)) {
|
|
340
|
+
const total = parseAmount(spec?.[key])
|
|
341
|
+
if (total !== undefined) totals.set(windowId, total)
|
|
342
|
+
}
|
|
343
|
+
return totals
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Project the windows onto the shared reading shape.
|
|
348
|
+
*
|
|
349
|
+
* The top level speaks for the monthly window — the one a personal plan
|
|
350
|
+
* meters — falling back to the binding window when a plan has no month.
|
|
351
|
+
*
|
|
352
|
+
* @param {string} route Provider route.
|
|
353
|
+
* @param {UsageWindow[]} windows The windows.
|
|
354
|
+
* @param {Map<string, number>} totals Known per-window totals.
|
|
355
|
+
* @returns {import('../providers.js').BalanceView} The reading.
|
|
356
|
+
*/
|
|
357
|
+
function projectPlan(route, windows, totals) {
|
|
358
|
+
for (const window of windows) {
|
|
359
|
+
const total = totals.get(window.id)
|
|
360
|
+
if (total === undefined) continue
|
|
361
|
+
window.total = total
|
|
362
|
+
window.used = Math.round(total * window.usedShare)
|
|
363
|
+
}
|
|
364
|
+
const month = windows.find((window) => window.id === 'per1Month')
|
|
365
|
+
const chosen = month ?? bindingWindow(windows)
|
|
366
|
+
const total = chosen?.total
|
|
367
|
+
const used = chosen?.used
|
|
368
|
+
return {
|
|
369
|
+
provider: route,
|
|
370
|
+
status: 'ready',
|
|
371
|
+
kind: KIND_QUOTA,
|
|
372
|
+
...(chosen === undefined ? {} : { percent: chosen.remainingPercent }),
|
|
373
|
+
...(chosen?.resetAt === undefined ? {} : { resetsAt: chosen.resetAt }),
|
|
374
|
+
...(total === undefined || used === undefined ? {} : { total, remaining: total - used }),
|
|
375
|
+
windows: windows.map(({ usedShare, ...window }) => window),
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Walk the credential test chain: exchange a console token, then read the
|
|
381
|
+
* usage windows with it.
|
|
382
|
+
*
|
|
383
|
+
* The settings page runs this against the entered AccessKey pair before it
|
|
384
|
+
* saves, so a stored credential is one the live endpoints accepted. The RAM
|
|
385
|
+
* refusal arrives here with the grants it asks for.
|
|
386
|
+
*
|
|
387
|
+
* @param {object} input The test.
|
|
388
|
+
* @param {string} input.accessKeyId AccessKey ID.
|
|
389
|
+
* @param {string} input.secretAccessKey AccessKey secret.
|
|
390
|
+
* @param {AbortSignal} [input.signal] Cancellation.
|
|
391
|
+
* @returns {Promise<{ok: true} | {ok: false, error: string}>} The outcome.
|
|
392
|
+
*/
|
|
393
|
+
export async function testQwenPlanCredentials({ accessKeyId, secretAccessKey, signal }) {
|
|
394
|
+
const abort = signal ?? AbortSignal.timeout(15_000)
|
|
395
|
+
const token = await consoleToken({ accessKeyId, secretAccessKey, signal: abort })
|
|
396
|
+
if (token.error !== undefined) return { ok: false, error: token.error }
|
|
397
|
+
const usage = await gatewayCall(token.token ?? '', USAGE_API, {}, abort)
|
|
398
|
+
if (usage.error !== undefined) return { ok: false, error: usage.error }
|
|
399
|
+
const envelope = usage.envelope ?? {}
|
|
400
|
+
const payload = gatewayPayload(envelope, (node) =>
|
|
401
|
+
Object.keys(node).some((key) => WINDOW_PATTERN.test(key)),
|
|
402
|
+
)
|
|
403
|
+
const windows = payload === undefined ? [] : usageWindows(payload)
|
|
404
|
+
if (windows.length === 0) {
|
|
405
|
+
return {
|
|
406
|
+
ok: false,
|
|
407
|
+
error: gatewayError(envelope) ?? 'Token Plan usage response carried no quota window',
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return { ok: true }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Read one route's Token Plan allowance.
|
|
415
|
+
*
|
|
416
|
+
* @param {import('../providers.js').AdapterEnv} env Query context.
|
|
417
|
+
* @returns {Promise<import('../providers.js').BalanceView>} The reading.
|
|
418
|
+
*/
|
|
419
|
+
async function readPlanAllowance({ route, ctx, signal }) {
|
|
420
|
+
const credentials = typeof ctx?.get === 'function' ? ctx.get('credentials') : undefined
|
|
421
|
+
const accessKeyId = await resolveCredential(credentials, ACCESS_KEY_ID_REF)
|
|
422
|
+
const secretAccessKey = await resolveCredential(credentials, ACCESS_KEY_SECRET_REF)
|
|
423
|
+
if (accessKeyId === undefined || secretAccessKey === undefined) {
|
|
424
|
+
return { provider: route, status: 'unconfigured', kind: KIND_QUOTA }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const token = await consoleToken({ accessKeyId, secretAccessKey, signal })
|
|
428
|
+
if (token.error !== undefined) return failed(route, token.error)
|
|
429
|
+
|
|
430
|
+
const usage = await gatewayCall(token.token, USAGE_API, {}, signal)
|
|
431
|
+
if (usage.error !== undefined) return failed(route, usage.error)
|
|
432
|
+
const envelope = usage.envelope ?? {}
|
|
433
|
+
const payload = gatewayPayload(envelope, (node) =>
|
|
434
|
+
Object.keys(node).some((key) => WINDOW_PATTERN.test(key)),
|
|
435
|
+
)
|
|
436
|
+
const windows = payload === undefined ? [] : usageWindows(payload)
|
|
437
|
+
if (windows.length === 0) {
|
|
438
|
+
return failed(
|
|
439
|
+
route,
|
|
440
|
+
gatewayError(envelope) ?? 'Token Plan usage response carried no quota window',
|
|
441
|
+
)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Totals are enrichment: a plan whose subscription or quota-config cannot
|
|
445
|
+
// be read still reports the share left and the reset.
|
|
446
|
+
let specCode
|
|
447
|
+
let totals = new Map()
|
|
448
|
+
try {
|
|
449
|
+
const subscription = await gatewayCall(token.token, SUBSCRIPTION_API, {}, signal)
|
|
450
|
+
const subscriptionPayload =
|
|
451
|
+
subscription.envelope === undefined
|
|
452
|
+
? undefined
|
|
453
|
+
: gatewayPayload(subscription.envelope, (node) => typeof node.specCode === 'string')
|
|
454
|
+
specCode =
|
|
455
|
+
typeof subscriptionPayload?.specCode === 'string' ? subscriptionPayload.specCode : undefined
|
|
456
|
+
if (specCode !== undefined) {
|
|
457
|
+
const quotaConfig = await gatewayCall(token.token, QUOTA_CONFIG_API, {}, signal)
|
|
458
|
+
if (quotaConfig.envelope !== undefined) {
|
|
459
|
+
totals = planTotals(
|
|
460
|
+
gatewayPayload(quotaConfig.envelope, (node) => typeof node[specCode] === 'object'),
|
|
461
|
+
specCode,
|
|
462
|
+
)
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
} catch {
|
|
466
|
+
// A reading is the usage; the totals are best-effort.
|
|
467
|
+
}
|
|
468
|
+
return projectPlan(route, windows, totals)
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// --- recorded responses ----------------------------------------------------
|
|
472
|
+
|
|
473
|
+
/** The console token reply (identifier altered). */
|
|
474
|
+
const RECORDED_TOKEN = { cliAccessToken: 'recorded-console-token' }
|
|
475
|
+
|
|
476
|
+
/** The usage reply of a personal lite plan: one monthly window. */
|
|
477
|
+
const RECORDED_USAGE = {
|
|
478
|
+
code: '200',
|
|
479
|
+
data: {
|
|
480
|
+
DataV2: {
|
|
481
|
+
ret: ['SUCCESS::接口调用成功'],
|
|
482
|
+
data: {
|
|
483
|
+
msg: 'Success.',
|
|
484
|
+
code: 'SUCCESS',
|
|
485
|
+
data: { per1MonthPercentage: 0.9545502269, per1MonthResetTime: 1796572800000 },
|
|
486
|
+
requestId: 'recorded',
|
|
487
|
+
success: true,
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
success: true,
|
|
491
|
+
httpStatus: 200,
|
|
492
|
+
errorCode: '',
|
|
493
|
+
api: USAGE_API,
|
|
494
|
+
errorMsg: '',
|
|
495
|
+
},
|
|
496
|
+
httpStatusCode: '200',
|
|
497
|
+
requestId: 'recorded',
|
|
498
|
+
successResponse: true,
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** The usage reply of a plan metering a five-hour and a weekly window. */
|
|
502
|
+
const RECORDED_SHORT_WINDOWS = {
|
|
503
|
+
code: '200',
|
|
504
|
+
data: {
|
|
505
|
+
DataV2: {
|
|
506
|
+
ret: ['SUCCESS::接口调用成功'],
|
|
507
|
+
data: {
|
|
508
|
+
msg: 'Success.',
|
|
509
|
+
code: 'SUCCESS',
|
|
510
|
+
data: {
|
|
511
|
+
per5HourPercentage: 0.1,
|
|
512
|
+
per5HourResetTime: 1796572800000,
|
|
513
|
+
per1WeekPercentage: 0.5,
|
|
514
|
+
per1WeekResetTime: 1797004800000,
|
|
515
|
+
},
|
|
516
|
+
requestId: 'recorded',
|
|
517
|
+
success: true,
|
|
518
|
+
},
|
|
519
|
+
},
|
|
520
|
+
success: true,
|
|
521
|
+
errorCode: '',
|
|
522
|
+
api: USAGE_API,
|
|
523
|
+
errorMsg: '',
|
|
524
|
+
},
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** The subscription reply naming the plan's spec. */
|
|
528
|
+
const RECORDED_SUBSCRIPTION = {
|
|
529
|
+
code: '200',
|
|
530
|
+
data: {
|
|
531
|
+
DataV2: {
|
|
532
|
+
ret: ['SUCCESS::接口调用成功'],
|
|
533
|
+
data: {
|
|
534
|
+
msg: 'Success.',
|
|
535
|
+
code: 'SUCCESS',
|
|
536
|
+
data: {
|
|
537
|
+
instanceCode: 'recorded-instance',
|
|
538
|
+
specCode: 'lite',
|
|
539
|
+
remainingDays: 17,
|
|
540
|
+
startTime: 1793967403000,
|
|
541
|
+
endTime: 1796572800000,
|
|
542
|
+
autoRenewFlag: false,
|
|
543
|
+
status: 'VALID',
|
|
544
|
+
},
|
|
545
|
+
requestId: 'recorded',
|
|
546
|
+
success: true,
|
|
547
|
+
},
|
|
548
|
+
},
|
|
549
|
+
success: true,
|
|
550
|
+
errorCode: '',
|
|
551
|
+
api: SUBSCRIPTION_API,
|
|
552
|
+
errorMsg: '',
|
|
553
|
+
},
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** The quota-config reply: the totals of every personal spec. */
|
|
557
|
+
const RECORDED_QUOTA_CONFIG = {
|
|
558
|
+
code: '200',
|
|
559
|
+
data: {
|
|
560
|
+
DataV2: {
|
|
561
|
+
ret: ['SUCCESS::接口调用成功'],
|
|
562
|
+
data: {
|
|
563
|
+
msg: 'Success.',
|
|
564
|
+
code: 'SUCCESS',
|
|
565
|
+
data: {
|
|
566
|
+
standard: { five_hour: 3000, monthly: 80000 },
|
|
567
|
+
addon_quota: { extrabundle: 20000 },
|
|
568
|
+
lite: { five_hour: 700, monthly: 20000 },
|
|
569
|
+
pro: { five_hour: 12000, monthly: 200000 },
|
|
570
|
+
essential: { five_hour: 1800, monthly: 45000 },
|
|
571
|
+
},
|
|
572
|
+
requestId: 'recorded',
|
|
573
|
+
success: true,
|
|
574
|
+
},
|
|
575
|
+
},
|
|
576
|
+
success: true,
|
|
577
|
+
errorCode: '',
|
|
578
|
+
api: QUOTA_CONFIG_API,
|
|
579
|
+
errorMsg: '',
|
|
580
|
+
},
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** The reply a RAM user without the Token Plan grants gets. */
|
|
584
|
+
const RECORDED_NOT_AUTHORISED = {
|
|
585
|
+
code: '200',
|
|
586
|
+
data: {
|
|
587
|
+
success: false,
|
|
588
|
+
httpStatus: 200,
|
|
589
|
+
errorCode: 'BailianGateway.Team.NotAuthorised',
|
|
590
|
+
api: USAGE_API,
|
|
591
|
+
errorMsg: 'BailianGateway.Team.NotAuthorised',
|
|
592
|
+
},
|
|
593
|
+
httpStatusCode: '200',
|
|
594
|
+
requestId: 'recorded',
|
|
595
|
+
successResponse: true,
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** A configured AccessKey pair, as the settings page stores it. */
|
|
599
|
+
const RECORDED_CREDENTIALS = {
|
|
600
|
+
resolve: async (ref) =>
|
|
601
|
+
ref === ACCESS_KEY_ID_REF
|
|
602
|
+
? { value: 'LTAIrecorded' }
|
|
603
|
+
: ref === ACCESS_KEY_SECRET_REF
|
|
604
|
+
? { value: 'recorded-secret' }
|
|
605
|
+
: undefined,
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** The declared adapters this module serves. */
|
|
609
|
+
export const qwenTokenPlanAdapters = [
|
|
610
|
+
defineAdapter({
|
|
611
|
+
id: 'qwen-token-plan',
|
|
612
|
+
routes: ['qwen-token-plan', 'qwen-token-plan-cn', 'qwen-token-plan-individual'],
|
|
613
|
+
kind: KIND_QUOTA,
|
|
614
|
+
consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
|
|
615
|
+
setupUrl: SETUP_DOC_URL,
|
|
616
|
+
credentialRefs: [ACCESS_KEY_ID_REF, ACCESS_KEY_SECRET_REF],
|
|
617
|
+
display: {
|
|
618
|
+
name: { zh: '通义千问 Token Plan', en: 'Qwen Token Plan' },
|
|
619
|
+
mark: { icon: 'qwen', color: '#082DFF' },
|
|
620
|
+
},
|
|
621
|
+
readWithEnv: readPlanAllowance,
|
|
622
|
+
fixtures: [
|
|
623
|
+
{
|
|
624
|
+
name: 'recorded monthly window with plan totals',
|
|
625
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
626
|
+
responses: [RECORDED_TOKEN, RECORDED_USAGE, RECORDED_SUBSCRIPTION, RECORDED_QUOTA_CONFIG],
|
|
627
|
+
expect: {
|
|
628
|
+
status: 'ready',
|
|
629
|
+
kind: KIND_QUOTA,
|
|
630
|
+
percent: 4.54,
|
|
631
|
+
resetsAt: 1796572800000,
|
|
632
|
+
total: 20000,
|
|
633
|
+
remaining: 909,
|
|
634
|
+
windows: [
|
|
635
|
+
{
|
|
636
|
+
id: 'per1Month',
|
|
637
|
+
unit: 'month',
|
|
638
|
+
count: 1,
|
|
639
|
+
used: 19091,
|
|
640
|
+
total: 20000,
|
|
641
|
+
remainingPercent: 4.54,
|
|
642
|
+
resetAt: 1796572800000,
|
|
643
|
+
},
|
|
644
|
+
],
|
|
645
|
+
},
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
name: 'usage only still reports the share left',
|
|
649
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
650
|
+
responses: [RECORDED_TOKEN, RECORDED_USAGE],
|
|
651
|
+
expect: {
|
|
652
|
+
status: 'ready',
|
|
653
|
+
percent: 4.54,
|
|
654
|
+
resetsAt: 1796572800000,
|
|
655
|
+
windows: [{ id: 'per1Month', remainingPercent: 4.54 }],
|
|
656
|
+
},
|
|
657
|
+
absent: ['total', 'remaining', 'windows[0].total', 'windows[0].used'],
|
|
658
|
+
},
|
|
659
|
+
{
|
|
660
|
+
// The badge speaks for the window closest to its limit, so the top
|
|
661
|
+
// level carries the weekly one; the five-hour window keeps its own
|
|
662
|
+
// totals inside the list.
|
|
663
|
+
name: 'a five-hour and a weekly window meter one plan',
|
|
664
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
665
|
+
responses: [
|
|
666
|
+
RECORDED_TOKEN,
|
|
667
|
+
RECORDED_SHORT_WINDOWS,
|
|
668
|
+
RECORDED_SUBSCRIPTION,
|
|
669
|
+
RECORDED_QUOTA_CONFIG,
|
|
670
|
+
],
|
|
671
|
+
expect: {
|
|
672
|
+
status: 'ready',
|
|
673
|
+
percent: 50,
|
|
674
|
+
resetsAt: 1797004800000,
|
|
675
|
+
windows: [
|
|
676
|
+
{
|
|
677
|
+
id: 'per5Hour',
|
|
678
|
+
unit: 'hour',
|
|
679
|
+
count: 5,
|
|
680
|
+
used: 70,
|
|
681
|
+
total: 700,
|
|
682
|
+
remainingPercent: 90,
|
|
683
|
+
resetAt: 1796572800000,
|
|
684
|
+
},
|
|
685
|
+
{
|
|
686
|
+
id: 'per1Week',
|
|
687
|
+
unit: 'week',
|
|
688
|
+
count: 1,
|
|
689
|
+
remainingPercent: 50,
|
|
690
|
+
resetAt: 1797004800000,
|
|
691
|
+
},
|
|
692
|
+
],
|
|
693
|
+
},
|
|
694
|
+
absent: ['total', 'remaining'],
|
|
695
|
+
},
|
|
696
|
+
{
|
|
697
|
+
name: 'a gateway refusal names the RAM grants',
|
|
698
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
699
|
+
responses: [RECORDED_TOKEN, RECORDED_NOT_AUTHORISED],
|
|
700
|
+
expect: {
|
|
701
|
+
status: 'failed',
|
|
702
|
+
kind: KIND_QUOTA,
|
|
703
|
+
error: `BailianGateway.Team.NotAuthorised — ${RAM_HINT}`,
|
|
704
|
+
},
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
name: 'no AccessKey configured',
|
|
708
|
+
services: {},
|
|
709
|
+
expect: { status: 'unconfigured', kind: KIND_QUOTA },
|
|
710
|
+
},
|
|
711
|
+
],
|
|
712
|
+
}),
|
|
713
|
+
]
|