dsh-model-allowance 1.1.0 → 1.2.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 +23 -5
- package/README.zh.md +17 -5
- package/client.js +694 -97
- package/index.js +69 -0
- package/lib/balance.js +11 -2
- package/lib/providers/placeholder.js +0 -42
- package/lib/providers/promotions.js +169 -0
- package/lib/providers/qwen_promotions.js +223 -0
- package/lib/providers/qwen_token_plan.js +716 -0
- package/lib/providers/shared.js +24 -0
- package/lib/providers/zai.js +25 -0
- package/lib/providers.js +9 -6
- package/lib/remote.js +32 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { Service } from '@deepseek-ai/cordis'
|
|
|
10
10
|
import z from '@deepseek-ai/schemastery'
|
|
11
11
|
import { BalanceService } from './lib/balance.js'
|
|
12
12
|
import { describeError, logDebug } from './lib/debug.js'
|
|
13
|
+
import { promotionExpired } from './lib/providers/promotions.js'
|
|
13
14
|
import { holidayCoverage } from './lib/providers/schedule.js'
|
|
14
15
|
import { findAdapter, KIND_AMOUNT, KIND_QUOTA, PROVIDER_ADAPTERS } from './lib/providers.js'
|
|
15
16
|
import { BalanceController } from './lib/remote.js'
|
|
@@ -38,6 +39,12 @@ function modelOf(model) {
|
|
|
38
39
|
return typeof model === 'string' && model !== '' ? model : undefined
|
|
39
40
|
}
|
|
40
41
|
|
|
42
|
+
/** How long a successful live promotions read is reused: offers change rarely. */
|
|
43
|
+
const PROMOTIONS_TTL_MS = 60 * 60 * 1000
|
|
44
|
+
|
|
45
|
+
/** How long a failed live promotions read is remembered before trying again. */
|
|
46
|
+
const PROMOTIONS_FAILURE_TTL_MS = 5 * 60 * 1000
|
|
47
|
+
|
|
41
48
|
/**
|
|
42
49
|
* The resolved plugin configuration.
|
|
43
50
|
* @typedef {object} ModelAllowanceConfig
|
|
@@ -92,6 +99,14 @@ class ModelAllowanceService extends Service {
|
|
|
92
99
|
*/
|
|
93
100
|
this.active = new Map()
|
|
94
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Live promotions reads, keyed by route: the last outcome and when it
|
|
104
|
+
* landed. A success is reused for an hour; a failure is remembered briefly
|
|
105
|
+
* so a catalog outage costs one request per backoff, not one per open.
|
|
106
|
+
* @type {Map<string, {at: number, ok: boolean, value?: readonly object[]}>}
|
|
107
|
+
*/
|
|
108
|
+
this.promotionReads = new Map()
|
|
109
|
+
|
|
95
110
|
/**
|
|
96
111
|
* Platform status readings. Every source is a public page, so this half
|
|
97
112
|
* needs no credential — only the vendor's status URL.
|
|
@@ -233,6 +248,49 @@ class ModelAllowanceService extends Service {
|
|
|
233
248
|
return schedule === undefined ? null : { provider, ...schedule }
|
|
234
249
|
}
|
|
235
250
|
|
|
251
|
+
/**
|
|
252
|
+
* The model-scoped usage promotions a vendor has, when it has any.
|
|
253
|
+
*
|
|
254
|
+
* A static declaration is returned as-is: the browser decides which date
|
|
255
|
+
* windows its own clock falls inside, so a badge appears and disappears
|
|
256
|
+
* without another round trip. A live source (a public catalog) is read on
|
|
257
|
+
* a slow cache and returned without a window — its badge is its own truth.
|
|
258
|
+
* Either way a promotion never changes a balance reading: the allowance is
|
|
259
|
+
* the same; what it buys on the covered models is what differs.
|
|
260
|
+
*
|
|
261
|
+
* @param {string} provider Provider route.
|
|
262
|
+
* @returns {Promise<object | null>} The promotions, or null when there are none.
|
|
263
|
+
*/
|
|
264
|
+
async promotions(provider) {
|
|
265
|
+
const adapter = findAdapter(provider)
|
|
266
|
+
if (adapter === undefined) return null
|
|
267
|
+
if (adapter.promotions !== undefined) {
|
|
268
|
+
return { provider, promotions: adapter.promotions }
|
|
269
|
+
}
|
|
270
|
+
if (typeof adapter.readPromotions !== 'function') return null
|
|
271
|
+
const now = Date.now()
|
|
272
|
+
const cached = this.promotionReads.get(provider)
|
|
273
|
+
const ttl = cached?.ok === true ? PROMOTIONS_TTL_MS : PROMOTIONS_FAILURE_TTL_MS
|
|
274
|
+
if (cached !== undefined && now - cached.at < ttl) {
|
|
275
|
+
return cached.ok === true && cached.value.length > 0
|
|
276
|
+
? { provider, promotions: cached.value }
|
|
277
|
+
: null
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
const value = await adapter.readPromotions({
|
|
281
|
+
signal: AbortSignal.timeout(this.config.requestTimeoutMs),
|
|
282
|
+
})
|
|
283
|
+
this.promotionReads.set(provider, { at: now, ok: true, value })
|
|
284
|
+
return value.length > 0 ? { provider, promotions: value } : null
|
|
285
|
+
} catch (error) {
|
|
286
|
+
this.promotionReads.set(provider, { at: now, ok: false })
|
|
287
|
+
if (this.config.debug === true) {
|
|
288
|
+
await logDebug(`promotions route=${provider} failed: ${describeError(error)}`)
|
|
289
|
+
}
|
|
290
|
+
return null
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
236
294
|
/**
|
|
237
295
|
* The provider a session with no model selection would use.
|
|
238
296
|
*
|
|
@@ -318,6 +376,17 @@ class ModelAllowanceService extends Service {
|
|
|
318
376
|
`extend it for ${String(thisYear)}`,
|
|
319
377
|
)
|
|
320
378
|
}
|
|
379
|
+
// A promotion is a dated event: once its last day has passed in the
|
|
380
|
+
// vendor's own zone, the declaration is dead weight. The browser already
|
|
381
|
+
// stops showing it; this warns the maintainer to remove it.
|
|
382
|
+
for (const promotion of adapter.promotions ?? []) {
|
|
383
|
+
if (promotion.to !== undefined && promotionExpired(promotion, Date.now())) {
|
|
384
|
+
console.warn(
|
|
385
|
+
`[model-allowance] ${adapter.id} promotion for ${promotion.models.join(', ')} ` +
|
|
386
|
+
`ended ${promotion.to}; remove the declaration`,
|
|
387
|
+
)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
321
390
|
}
|
|
322
391
|
|
|
323
392
|
// Both listeners are `global`. `session/event` is emitted from the
|
package/lib/balance.js
CHANGED
|
@@ -542,6 +542,7 @@ export class BalanceService {
|
|
|
542
542
|
status: 'unconfigured',
|
|
543
543
|
kind: adapter.kind,
|
|
544
544
|
consoleUrl: adapter.consoleUrl,
|
|
545
|
+
...(adapter.setupUrl === undefined ? {} : { setupUrl: adapter.setupUrl }),
|
|
545
546
|
}
|
|
546
547
|
}
|
|
547
548
|
// A reading is bounded by the request timeout alone. Cordis has no
|
|
@@ -563,8 +564,16 @@ export class BalanceService {
|
|
|
563
564
|
})
|
|
564
565
|
// The console link is a property of the route, not of the response, so
|
|
565
566
|
// every reading carries it — including one that failed authorization and
|
|
566
|
-
// is exactly when the user needs the way back to the console.
|
|
567
|
-
|
|
567
|
+
// is exactly when the user needs the way back to the console. The setup
|
|
568
|
+
// guide rides the unconfigured reading, where the card links it.
|
|
569
|
+
return {
|
|
570
|
+
...view,
|
|
571
|
+
consoleUrl: view.consoleUrl ?? adapter.consoleUrl,
|
|
572
|
+
...(view.status === 'unconfigured' && adapter.setupUrl !== undefined
|
|
573
|
+
? { setupUrl: adapter.setupUrl }
|
|
574
|
+
: {}),
|
|
575
|
+
updatedAt: Date.now(),
|
|
576
|
+
}
|
|
568
577
|
} catch (error) {
|
|
569
578
|
const reason = error instanceof Error ? error.message : String(error)
|
|
570
579
|
// An aborted request is a cancellation, not a provider failure.
|
|
@@ -402,48 +402,6 @@ export const openrouterAdapters = [
|
|
|
402
402
|
}),
|
|
403
403
|
]
|
|
404
404
|
|
|
405
|
-
// ============================================================================
|
|
406
|
-
// Qwen Token Plan
|
|
407
|
-
// ============================================================================
|
|
408
|
-
export const qwenTokenPlanAdapters = [
|
|
409
|
-
placeholderAdapter({
|
|
410
|
-
id: 'qwen-token-plan',
|
|
411
|
-
routes: ['qwen-token-plan'],
|
|
412
|
-
name: { zh: '通义千问 Token Plan', en: 'Qwen Token Plan' },
|
|
413
|
-
color: '#082DFF',
|
|
414
|
-
icon: 'qwen',
|
|
415
|
-
consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
|
|
416
|
-
}),
|
|
417
|
-
]
|
|
418
|
-
|
|
419
|
-
// ============================================================================
|
|
420
|
-
// Qwen Token Plan CN
|
|
421
|
-
// ============================================================================
|
|
422
|
-
export const qwenTokenPlanCnAdapters = [
|
|
423
|
-
placeholderAdapter({
|
|
424
|
-
id: 'qwen-token-plan-cn',
|
|
425
|
-
routes: ['qwen-token-plan-cn'],
|
|
426
|
-
name: { zh: '通义千问 Token Plan (国内)', en: 'Qwen Token Plan (CN)' },
|
|
427
|
-
color: '#082DFF',
|
|
428
|
-
icon: 'qwen',
|
|
429
|
-
consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
|
|
430
|
-
}),
|
|
431
|
-
]
|
|
432
|
-
|
|
433
|
-
// ============================================================================
|
|
434
|
-
// Qwen Token Plan Individual
|
|
435
|
-
// ============================================================================
|
|
436
|
-
export const qwenTokenPlanIndividualAdapters = [
|
|
437
|
-
placeholderAdapter({
|
|
438
|
-
id: 'qwen-token-plan-individual',
|
|
439
|
-
routes: ['qwen-token-plan-individual'],
|
|
440
|
-
name: { zh: '通义千问个人版', en: 'Qwen Token Plan Individual' },
|
|
441
|
-
color: '#082DFF',
|
|
442
|
-
icon: 'qwen',
|
|
443
|
-
consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
|
|
444
|
-
}),
|
|
445
|
-
]
|
|
446
|
-
|
|
447
405
|
// ============================================================================
|
|
448
406
|
// Radius
|
|
449
407
|
// ============================================================================
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-scoped usage promotions.
|
|
3
|
+
*
|
|
4
|
+
* A vendor occasionally declares that the same plan allowance supports more
|
|
5
|
+
* usage of specific models — for a dated window, or for as long as its catalog
|
|
6
|
+
* says so. The card's only statement of that is a small badge on the covered
|
|
7
|
+
* model's row in the switch menu; hovering the badge reads the vendor's
|
|
8
|
+
* one-line announcement. Nothing else is written out: the allowance itself
|
|
9
|
+
* never changes, so no reading, panel block, or countdown is involved.
|
|
10
|
+
*
|
|
11
|
+
* Two sources share one shape. A static declaration carries its own date
|
|
12
|
+
* window, and the browser evaluates it against its own clock, so the badge
|
|
13
|
+
* appears and disappears with no extra round trips. A live source (a public
|
|
14
|
+
* catalog API) carries no window: its badge is its own truth, and the Host
|
|
15
|
+
* re-reads it on a slow cache.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** ISO calendar date, in the promotion's own zone. */
|
|
19
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
|
|
20
|
+
|
|
21
|
+
/** HH:MM in 24-hour wall time; `24:00` is the day's end. */
|
|
22
|
+
const TIME_PATTERN = /^(?:(?:[01]\d|2[0-3]):[0-5]\d|24:00)$/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Minutes since midnight for one `HH:MM` wall time.
|
|
26
|
+
* @param {string} time Wall-clock time.
|
|
27
|
+
* @returns {number} Minutes since midnight.
|
|
28
|
+
*/
|
|
29
|
+
export function timeToMinutes(time) {
|
|
30
|
+
const [hour, minute] = time.split(':').map(Number)
|
|
31
|
+
return hour * 60 + minute
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* One promotion, as {@link definePromotions} normalizes it.
|
|
36
|
+
* @typedef {object} Promotion
|
|
37
|
+
* @property {readonly string[]} models Provider-owned model ids the promotion
|
|
38
|
+
* covers. The browser matches them case-insensitively against the catalog.
|
|
39
|
+
* @property {{zh: string, en: string}} chip The badge label, in the vendor's
|
|
40
|
+
* own words, e.g. `×2` or `限时夜间4折`.
|
|
41
|
+
* @property {{zh: string, en: string}} note The vendor's one-line announcement,
|
|
42
|
+
* shown when the pointer rests on the badge.
|
|
43
|
+
* @property {string} [timezone] IANA zone the date range and daily window refer to.
|
|
44
|
+
* @property {string} [from] First covered calendar date, inclusive, ISO in that
|
|
45
|
+
* zone. Absent together with `to` for a live source.
|
|
46
|
+
* @property {string} [to] Last covered calendar date, inclusive, ISO in that zone.
|
|
47
|
+
* @property {{from: string, to: string}} [daily] The hours of each covered day
|
|
48
|
+
* the offer runs, `HH:MM` in that zone. A `to` earlier than `from` crosses
|
|
49
|
+
* midnight (22:00–08:00 is the night). Absent means the whole day.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Declare promotions, refusing an unusable declaration.
|
|
54
|
+
*
|
|
55
|
+
* Both windows are optional — a live source's badge may need neither — but
|
|
56
|
+
* each is facts together: a date range is a zone and two calendar days in it,
|
|
57
|
+
* both ends inclusive; a daily window is a zone and two wall times in it.
|
|
58
|
+
*
|
|
59
|
+
* @param {Array<{models: string[], chip: {zh: string, en: string}, note: {zh: string, en: string}, timezone?: string, from?: string, to?: string, daily?: {from: string, to: string}}>} specs The declarations.
|
|
60
|
+
* @returns {readonly Promotion[]} The frozen promotions.
|
|
61
|
+
*/
|
|
62
|
+
export function definePromotions(specs) {
|
|
63
|
+
const where = 'promotions'
|
|
64
|
+
if (!Array.isArray(specs)) throw new Error(`${where} must be a list`)
|
|
65
|
+
return Object.freeze(
|
|
66
|
+
specs.map((spec, index) => {
|
|
67
|
+
const at = `${where}[${String(index)}]`
|
|
68
|
+
const models = spec?.models
|
|
69
|
+
if (!Array.isArray(models) || models.length === 0) {
|
|
70
|
+
throw new Error(`${at} names no model`)
|
|
71
|
+
}
|
|
72
|
+
for (const model of models) {
|
|
73
|
+
if (typeof model !== 'string' || model.trim() === '') {
|
|
74
|
+
throw new Error(`${at} has an empty model id`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const field of ['chip', 'note']) {
|
|
78
|
+
for (const key of ['zh', 'en']) {
|
|
79
|
+
const text = spec?.[field]?.[key]
|
|
80
|
+
if (typeof text !== 'string' || text === '') {
|
|
81
|
+
throw new Error(`${at} needs a ${field} for ${key}`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const hasDates = spec.from !== undefined || spec.to !== undefined
|
|
86
|
+
const hasDaily = spec.daily !== undefined
|
|
87
|
+
if (hasDates || hasDaily) {
|
|
88
|
+
if (typeof spec.timezone !== 'string' || spec.timezone === '') {
|
|
89
|
+
throw new Error(`${at} needs an IANA time zone`)
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
new Intl.DateTimeFormat('en-US', { timeZone: spec.timezone })
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error(`${at} names an unknown time zone "${spec.timezone}"`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (hasDates) {
|
|
98
|
+
for (const key of ['from', 'to']) {
|
|
99
|
+
const date = spec[key]
|
|
100
|
+
if (typeof date !== 'string' || !DATE_PATTERN.test(date)) {
|
|
101
|
+
throw new Error(`${at} has a ${key} date that is not YYYY-MM-DD`)
|
|
102
|
+
}
|
|
103
|
+
if (Number.isNaN(Date.parse(`${date}T00:00:00Z`))) {
|
|
104
|
+
throw new Error(`${at} has an invalid ${key} date ${date}`)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (spec.to < spec.from) throw new Error(`${at} ends before it starts`)
|
|
108
|
+
}
|
|
109
|
+
if (hasDaily) {
|
|
110
|
+
for (const key of ['from', 'to']) {
|
|
111
|
+
const time = spec.daily?.[key]
|
|
112
|
+
if (typeof time !== 'string' || !TIME_PATTERN.test(time)) {
|
|
113
|
+
throw new Error(`${at} has a daily ${key} that is not HH:MM`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return Object.freeze({
|
|
118
|
+
models: Object.freeze(models.map((model) => model.trim())),
|
|
119
|
+
chip: Object.freeze({ zh: spec.chip.zh, en: spec.chip.en }),
|
|
120
|
+
note: Object.freeze({ zh: spec.note.zh, en: spec.note.en }),
|
|
121
|
+
...(hasDates || hasDaily ? { timezone: spec.timezone } : {}),
|
|
122
|
+
...(hasDates ? { from: spec.from, to: spec.to } : {}),
|
|
123
|
+
...(hasDaily ? { daily: Object.freeze({ from: spec.daily.from, to: spec.daily.to }) } : {}),
|
|
124
|
+
})
|
|
125
|
+
}),
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Zone date formatters, built once: constructing one is not free. */
|
|
130
|
+
const ZONE_DATE_FORMATTERS = new Map()
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The calendar date of one instant in a named zone, as `YYYY-MM-DD`.
|
|
134
|
+
* @param {number} ms The instant.
|
|
135
|
+
* @param {string} timeZone IANA zone.
|
|
136
|
+
* @returns {string} The zone's date.
|
|
137
|
+
*/
|
|
138
|
+
export function zoneDateOf(ms, timeZone) {
|
|
139
|
+
let formatter = ZONE_DATE_FORMATTERS.get(timeZone)
|
|
140
|
+
if (formatter === undefined) {
|
|
141
|
+
formatter = new Intl.DateTimeFormat('en-US', {
|
|
142
|
+
timeZone,
|
|
143
|
+
year: 'numeric',
|
|
144
|
+
month: '2-digit',
|
|
145
|
+
day: '2-digit',
|
|
146
|
+
})
|
|
147
|
+
ZONE_DATE_FORMATTERS.set(timeZone, formatter)
|
|
148
|
+
}
|
|
149
|
+
const parts = formatter.formatToParts(new Date(ms))
|
|
150
|
+
const value = (type) => parts.find((part) => part.type === type)?.value ?? ''
|
|
151
|
+
return `${value('year')}-${value('month')}-${value('day')}`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether a dated promotion's last covered day has wholly passed in its zone.
|
|
156
|
+
*
|
|
157
|
+
* Startup diagnostics use this to surface a declaration nobody removed after
|
|
158
|
+
* the event ended; the browser needs no such check, since an expired
|
|
159
|
+
* promotion simply stops matching its date range. A windowless promotion
|
|
160
|
+
* never expires this way — its source decides when it ends.
|
|
161
|
+
*
|
|
162
|
+
* @param {Promotion} promotion The declaration.
|
|
163
|
+
* @param {number} ms The instant to judge at.
|
|
164
|
+
* @returns {boolean} True once the zone's date is past `to`.
|
|
165
|
+
*/
|
|
166
|
+
export function promotionExpired(promotion, ms) {
|
|
167
|
+
if (promotion.to === undefined || promotion.timezone === undefined) return false
|
|
168
|
+
return zoneDateOf(ms, promotion.timezone) > promotion.to
|
|
169
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen Token Plan's public model catalog, read for its promotion badges.
|
|
3
|
+
*
|
|
4
|
+
* The console's model-center list is a public query — no credential, no
|
|
5
|
+
* cookie — and each model it lists may carry the vendor's own badge: a short
|
|
6
|
+
* label (`限时夜间4折`) and a one-line description. The adapter reads them
|
|
7
|
+
* live instead of declaring them: when the vendor ends an offer, its badge
|
|
8
|
+
* leaves the catalog and the menu follows on the next read.
|
|
9
|
+
*
|
|
10
|
+
* The card states only a multiplier, so the label's rate is converted
|
|
11
|
+
* (`5折` → ×2, `4折` → ×2.5, free → ×∞) and the hours the description names
|
|
12
|
+
* become a daily window the browser evaluates — a night offer badges only
|
|
13
|
+
* at night. The hover tip keeps the vendor's description verbatim.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { definePromotions } from './promotions.js'
|
|
17
|
+
import { asObject } from './shared.js'
|
|
18
|
+
|
|
19
|
+
/** The catalog's offers run on Beijing time, the console's own zone. */
|
|
20
|
+
const OFFER_ZONE = 'Asia/Shanghai'
|
|
21
|
+
|
|
22
|
+
/** A discount label names its rate: `限时夜间4折` is four tenths of the price. */
|
|
23
|
+
const DISCOUNT_PATTERN = /(\d+(?:\.\d+)?)\s*折/
|
|
24
|
+
|
|
25
|
+
/** The description names the hours: `每晚 22:00 - 次日 08:00 期间`. */
|
|
26
|
+
const HOURS_PATTERN = /(\d{1,2}:\d{2})\s*(?:[-–—~~]|至|到)\s*(次日\s*)?(\d{1,2}:\d{2})/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The badge label for one offer: the usage multiplier it buys, and nothing
|
|
30
|
+
* else. A `N折` price is `10/N` times the usage; a free offer is unbounded.
|
|
31
|
+
* A label that names no rate gets no badge — the card only states multipliers.
|
|
32
|
+
*
|
|
33
|
+
* @param {string} label The vendor's badge label.
|
|
34
|
+
* @returns {string | undefined} The badge text, e.g. `×2.5`, or undefined.
|
|
35
|
+
*/
|
|
36
|
+
function multiplierChip(label) {
|
|
37
|
+
const discount = DISCOUNT_PATTERN.exec(label)
|
|
38
|
+
if (discount !== null) {
|
|
39
|
+
const rate = Number(discount[1])
|
|
40
|
+
if (rate > 0 && rate <= 10) {
|
|
41
|
+
const multiplier = Math.round((10 / rate) * 100) / 100
|
|
42
|
+
return `×${String(multiplier)}`
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (label.includes('免费')) return '×∞'
|
|
46
|
+
return undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The daily hours one description names, when it names any.
|
|
51
|
+
*
|
|
52
|
+
* `22:00 - 次日 08:00` is the night: a `to` earlier than `from` crosses
|
|
53
|
+
* midnight. A description without hours means the whole day.
|
|
54
|
+
*
|
|
55
|
+
* @param {string} description The vendor's badge description.
|
|
56
|
+
* @returns {{from: string, to: string} | undefined} The window, when named.
|
|
57
|
+
*/
|
|
58
|
+
function dailyHours(description) {
|
|
59
|
+
const hours = HOURS_PATTERN.exec(description)
|
|
60
|
+
if (hours === null) return undefined
|
|
61
|
+
const pad = (time) => {
|
|
62
|
+
const [h, m] = time.split(':')
|
|
63
|
+
return `${h.padStart(2, '0')}:${m}`
|
|
64
|
+
}
|
|
65
|
+
return { from: pad(hours[1]), to: pad(hours[3]) }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The model-center list API behind the console gateway. */
|
|
69
|
+
const CATALOG_API = 'zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listTokenPlanModels'
|
|
70
|
+
|
|
71
|
+
/** The public gateway endpoint; the query needs no authorization. */
|
|
72
|
+
const CATALOG_URL =
|
|
73
|
+
'https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian' +
|
|
74
|
+
`&action=BroadScopeAspnGateway&api=${encodeURIComponent(CATALOG_API)}`
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The form body of one catalog query: the personal edition's first page.
|
|
78
|
+
* @returns {string} The urlencoded body.
|
|
79
|
+
*/
|
|
80
|
+
function catalogBody() {
|
|
81
|
+
const params = JSON.stringify({
|
|
82
|
+
Api: CATALOG_API,
|
|
83
|
+
V: '1.0',
|
|
84
|
+
Data: {
|
|
85
|
+
input: { pageNo: 1, pageSize: 100, edition: 'PERSONAL' },
|
|
86
|
+
cornerstoneParam: {
|
|
87
|
+
domain: 'platform.qianwenai.com',
|
|
88
|
+
consoleSite: 'QIANWENAI',
|
|
89
|
+
console: 'ONE_CONSOLE',
|
|
90
|
+
xsp_lang: 'zh-CN',
|
|
91
|
+
protocol: 'V2',
|
|
92
|
+
productCode: 'p_efm',
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
return new URLSearchParams({
|
|
97
|
+
product: 'sfm_bailian',
|
|
98
|
+
action: 'BroadScopeAspnGateway',
|
|
99
|
+
region: 'cn-beijing',
|
|
100
|
+
params,
|
|
101
|
+
}).toString()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Project one catalog reply onto promotions.
|
|
106
|
+
*
|
|
107
|
+
* A model with a badge label becomes one promotion: the label is the badge,
|
|
108
|
+
* the description is the hover tip, both verbatim. A model without a badge
|
|
109
|
+
* is simply not promoted. A gateway refusal throws — the caller caches the
|
|
110
|
+
* failure and shows no badge rather than a stale one.
|
|
111
|
+
*
|
|
112
|
+
* @param {Record<string, unknown>} body The decoded reply.
|
|
113
|
+
* @returns {readonly import('./promotions.js').Promotion[]} The promotions.
|
|
114
|
+
*/
|
|
115
|
+
export function projectTokenPlanModels(body) {
|
|
116
|
+
const data = asObject(body?.data)
|
|
117
|
+
if (data.success === false) {
|
|
118
|
+
const code = typeof data.errorCode === 'string' ? data.errorCode : ''
|
|
119
|
+
const message = typeof data.errorMsg === 'string' ? data.errorMsg : ''
|
|
120
|
+
throw new Error(message !== '' ? message : code !== '' ? code : 'catalog refused the query')
|
|
121
|
+
}
|
|
122
|
+
const payload = asObject(asObject(asObject(data.DataV2).data).data)
|
|
123
|
+
const list = Array.isArray(payload.list) ? payload.list : []
|
|
124
|
+
const specs = []
|
|
125
|
+
for (const entry of list) {
|
|
126
|
+
const model = asObject(entry)
|
|
127
|
+
const id = typeof model.modelId === 'string' ? model.modelId.trim() : ''
|
|
128
|
+
const label = typeof model.badgeLabel === 'string' ? model.badgeLabel.trim() : ''
|
|
129
|
+
if (id === '' || label === '') continue
|
|
130
|
+
const chip = multiplierChip(label)
|
|
131
|
+
// The card only states multipliers: an offer without a derivable rate
|
|
132
|
+
// gets no badge rather than a label it cannot express.
|
|
133
|
+
if (chip === undefined) continue
|
|
134
|
+
const description =
|
|
135
|
+
typeof model.badgeDescription === 'string' && model.badgeDescription.trim() !== ''
|
|
136
|
+
? model.badgeDescription.trim()
|
|
137
|
+
: label
|
|
138
|
+
const daily = dailyHours(description)
|
|
139
|
+
specs.push({
|
|
140
|
+
models: [id],
|
|
141
|
+
chip: { zh: chip, en: chip },
|
|
142
|
+
note: { zh: description, en: description },
|
|
143
|
+
timezone: OFFER_ZONE,
|
|
144
|
+
...(daily === undefined ? {} : { daily }),
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
return definePromotions(specs)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Read the public catalog and project its badges.
|
|
152
|
+
* @param {{signal: AbortSignal}} env Query context.
|
|
153
|
+
* @returns {Promise<readonly import('./promotions.js').Promotion[]>} The promotions.
|
|
154
|
+
*/
|
|
155
|
+
export async function readQwenPromotions({ signal }) {
|
|
156
|
+
const response = await fetch(CATALOG_URL, {
|
|
157
|
+
method: 'POST',
|
|
158
|
+
headers: {
|
|
159
|
+
accept: 'application/json, text/plain, */*',
|
|
160
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
161
|
+
},
|
|
162
|
+
body: catalogBody(),
|
|
163
|
+
signal,
|
|
164
|
+
})
|
|
165
|
+
if (!response.ok) throw new Error(`listTokenPlanModels: HTTP ${String(response.status)}`)
|
|
166
|
+
return projectTokenPlanModels(asObject(await response.json()))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// --- recorded response ------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* A trimmed catalog reply: two badge offers, one free offer, one plain model.
|
|
173
|
+
* Recorded from the public endpoint on 2026-12-03 (descriptions shortened).
|
|
174
|
+
*/
|
|
175
|
+
export const RECORDED_TOKEN_PLAN_MODELS = {
|
|
176
|
+
code: '200',
|
|
177
|
+
data: {
|
|
178
|
+
DataV2: {
|
|
179
|
+
ret: ['SUCCESS::接口调用成功'],
|
|
180
|
+
data: {
|
|
181
|
+
codeEnum: 'SUCCESS',
|
|
182
|
+
code: '200',
|
|
183
|
+
data: {
|
|
184
|
+
total: 4,
|
|
185
|
+
pageNo: 1,
|
|
186
|
+
pageSize: 100,
|
|
187
|
+
list: [
|
|
188
|
+
{
|
|
189
|
+
modelId: 'auto',
|
|
190
|
+
provider: 'qwen',
|
|
191
|
+
badgeLabel: '限时夜间4折',
|
|
192
|
+
badgeDescription: '每晚 22:00 - 次日 08:00 期间调用模型,Credits 消耗低至 4 折。',
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
modelId: 'qwen4-max',
|
|
196
|
+
provider: 'qwen',
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
modelId: 'deepseek-v4.1-flash',
|
|
200
|
+
provider: 'deepseek',
|
|
201
|
+
badgeLabel: '限时夜间5折',
|
|
202
|
+
badgeDescription: '每晚 22:00 - 次日 08:00 期间调用模型,Credits 消耗低至 5 折。',
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
modelId: 'decision-model-preview',
|
|
206
|
+
provider: 'qwen-domain-model',
|
|
207
|
+
badgeLabel: '限时免费',
|
|
208
|
+
badgeDescription:
|
|
209
|
+
'当前模型处于预览阶段,服务能力及调用配额可能根据运行情况动态调整。',
|
|
210
|
+
},
|
|
211
|
+
],
|
|
212
|
+
},
|
|
213
|
+
success: true,
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
success: true,
|
|
217
|
+
httpStatus: 200,
|
|
218
|
+
errorCode: '',
|
|
219
|
+
errorMsg: '',
|
|
220
|
+
},
|
|
221
|
+
httpStatusCode: '200',
|
|
222
|
+
successResponse: true,
|
|
223
|
+
}
|