dsh-model-allowance 1.1.1 → 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/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
@@ -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
+ }
@@ -26,6 +26,7 @@
26
26
  * Account Management page — the failure names that.
27
27
  */
28
28
  import { createHash, createHmac, randomUUID } from 'node:crypto'
29
+ import { readQwenPromotions } from './qwen_promotions.js'
29
30
  import {
30
31
  asObject,
31
32
  bindingWindow,
@@ -619,6 +620,8 @@ export const qwenTokenPlanAdapters = [
619
620
  mark: { icon: 'qwen', color: '#082DFF' },
620
621
  },
621
622
  readWithEnv: readPlanAllowance,
623
+ // The catalog's badges are public: the promotions read needs no key.
624
+ readPromotions: readQwenPromotions,
622
625
  fixtures: [
623
626
  {
624
627
  name: 'recorded monthly window with plan totals',
@@ -167,6 +167,10 @@ export function bindingWindow(windows) {
167
167
  * @param {{endpoint: string, url: string, parse: (env: {text?: string, json?: unknown}) => {state: string, summary?: string}}} [spec.status]
168
168
  * Live platform status source, when the vendor publishes one.
169
169
  * @param {import('./schedule.js').Schedule} [spec.schedule] Time-of-day pricing schedule.
170
+ * @param {readonly import('./promotions.js').Promotion[]} [spec.promotions]
171
+ * Model-scoped, date-limited usage promotions, when the vendor declares any.
172
+ * @param {(env: {signal: AbortSignal}) => Promise<readonly import('./promotions.js').Promotion[]>} [spec.readPromotions]
173
+ * Live promotions read (a public catalog), when the vendor publishes one.
170
174
  * @param {(env: {route: string, apiKey: string, body: Record<string, unknown>, model?: string}) => import('../providers.js').BalanceView} [spec.read]
171
175
  * Projection for an endpoint adapter.
172
176
  * @param {(env: import('../providers.js').AdapterEnv) => Promise<import('../providers.js').BalanceView>} [spec.readWithEnv]
@@ -254,6 +258,12 @@ export function defineAdapter(spec) {
254
258
  ) {
255
259
  throw new Error(`${where} declares an unreadable schedule`)
256
260
  }
261
+ if (spec.promotions !== undefined && !Array.isArray(spec.promotions)) {
262
+ throw new Error(`${where} declares unreadable promotions`)
263
+ }
264
+ if (spec.readPromotions !== undefined && typeof spec.readPromotions !== 'function') {
265
+ throw new Error(`${where} declares an unreadable promotions source`)
266
+ }
257
267
  const fixtures = spec.fixtures ?? []
258
268
  if (!Array.isArray(fixtures) || fixtures.length === 0) {
259
269
  throw new Error(`${where} ships no fixture, so nothing would prove it still parses`)
@@ -290,6 +300,10 @@ export function defineAdapter(spec) {
290
300
  parse: spec.status.parse,
291
301
  }),
292
302
  schedule: spec.schedule,
303
+ ...(spec.promotions === undefined || spec.promotions.length === 0
304
+ ? {}
305
+ : { promotions: Object.freeze([...spec.promotions]) }),
306
+ ...(spec.readPromotions === undefined ? {} : { readPromotions: spec.readPromotions }),
293
307
  read: spec.read,
294
308
  readWithEnv: spec.readWithEnv,
295
309
  fixtures: Object.freeze(fixtures.map((fixture) => Object.freeze({ ...fixture }))),
@@ -12,6 +12,7 @@
12
12
  * them, which the balance service now discovers per route.
13
13
  */
14
14
 
15
+ import { definePromotions } from './promotions.js'
15
16
  import { defineSchedule } from './schedule.js'
16
17
  import { asObject, bindingWindow, defineAdapter, KIND_QUOTA, parseAmount } from './shared.js'
17
18
 
@@ -41,6 +42,29 @@ const SCHEDULE = defineSchedule({
41
42
  note: { zh: '低谷时段积分按 50% 抵扣', en: 'Credits are halved off-peak' },
42
43
  })
43
44
 
45
+ /**
46
+ * GLM's limited-time double-usage window for the Flash model. The note is the
47
+ * vendor's announcement verbatim: the switch menu shows only a small ×2 badge
48
+ * on the covered model's row, and hovering the badge reads this one line.
49
+ * The brand spelling is what the badge tip displays; matching against the
50
+ * catalog's lowercase id is case-insensitive.
51
+ *
52
+ * @type {readonly import('./promotions.js').Promotion[]}
53
+ */
54
+ const PROMOTIONS = definePromotions([
55
+ {
56
+ models: ['GLM-5.3-Flash'],
57
+ chip: { zh: '×2', en: '×2' },
58
+ timezone: 'Asia/Shanghai',
59
+ from: '2026-11-24',
60
+ to: '2026-12-24',
61
+ note: {
62
+ zh: '11月24日至12月24日,GLM-5.3-Flash 限时双倍用量。',
63
+ en: 'Nov 24 – Dec 24: limited-time double usage for GLM-5.3-Flash.',
64
+ },
65
+ },
66
+ ])
67
+
44
68
  /**
45
69
  * Project one Zhipu limit body.
46
70
  * @param {{route: string, body: Record<string, unknown>}} env Projection context.
@@ -115,6 +139,7 @@ export const zaiAdapters = [
115
139
  read: readQuota,
116
140
  consoleUrl: CONSOLE,
117
141
  schedule: SCHEDULE,
142
+ promotions: PROMOTIONS,
118
143
  display: {
119
144
  name: { zh: '智谱 ZAI', en: 'Zhipu ZAI' },
120
145
  mark: { icon: 'zhipu', color: '#5668f5' },
package/lib/providers.js CHANGED
@@ -109,6 +109,10 @@ import { zaiAdapters } from './providers/zai.js'
109
109
  * Live platform status source, when the vendor publishes one.
110
110
  * @property {import('./providers/schedule.js').Schedule} [schedule]
111
111
  * Time-of-day pricing schedule, when the vendor prices by wall clock.
112
+ * @property {readonly import('./providers/promotions.js').Promotion[]} [promotions]
113
+ * Model-scoped, date-limited usage promotions, when the vendor declares any.
114
+ * @property {(env: {signal: AbortSignal}) => Promise<readonly import('./providers/promotions.js').Promotion[]>} [readPromotions]
115
+ * Live promotions read (a public catalog), when the vendor publishes one.
112
116
  * @property {(env: {route: string, apiKey: string, body: Record<string, unknown>, model?: string}) => BalanceView} [read]
113
117
  * Projection for an endpoint adapter.
114
118
  * @property {(env: AdapterEnv) => Promise<BalanceView>} [readWithEnv] Full read for an
package/lib/remote.js CHANGED
@@ -132,6 +132,19 @@ export class BalanceController extends TypertRemoteService {
132
132
  return this.ctx.modelAllowance.schedule(provider)
133
133
  }
134
134
 
135
+ /**
136
+ * The model-scoped usage promotions a vendor declares, when it has any.
137
+ *
138
+ * Stable declared data, like the schedule: the browser decides which
139
+ * promotions its own clock falls inside and marks the covered models.
140
+ *
141
+ * @param {string} provider Provider route.
142
+ * @returns {Promise<object | null>} The declarations, or null.
143
+ */
144
+ async promotions(provider) {
145
+ return this.ctx.modelAllowance.promotions(provider)
146
+ }
147
+
135
148
  /**
136
149
  * The provider a session with no model selection would use.
137
150
  *
@@ -228,6 +241,7 @@ BalanceController.__applyRemoteMarkers = [
228
241
  markRemote(BalanceController.prototype, 'testCredentials'),
229
242
  markRemote(BalanceController.prototype, 'status'),
230
243
  markRemote(BalanceController.prototype, 'schedule'),
244
+ markRemote(BalanceController.prototype, 'promotions'),
231
245
  markRemote(BalanceController.prototype, 'defaultProvider'),
232
246
  markRemote(BalanceController.prototype, 'refresh'),
233
247
  markRemote(BalanceController.prototype, 'watch', { mode: 'stream' }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-model-allowance",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Shows the current conversation model's provider balance or remaining allowance in the composer.",
6
6
  "license": "MIT",