dsh-model-allowance 1.1.1 → 1.2.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.
@@ -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
@@ -17,6 +17,7 @@
17
17
  import { deepseekAdapters } from './providers/deepseek.js'
18
18
  import { kimiCodingAdapters } from './providers/kimi_coding.js'
19
19
  import { minimaxCnAdapters } from './providers/minimax_cn.js'
20
+ import { openaiCodexAdapters } from './providers/openai_codex.js'
20
21
  import { opencodeGoAdapters } from './providers/opencode_go.js'
21
22
  import {
22
23
  amazonBedrockAdapters,
@@ -40,7 +41,6 @@ import {
40
41
  moonshotaiCnAdapters,
41
42
  nvidiaAdapters,
42
43
  openaiAdapters,
43
- openaiCodexAdapters,
44
44
  opencodeAdapters,
45
45
  openrouterAdapters,
46
46
  radiusAdapters,
@@ -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
@@ -129,6 +133,7 @@ export const PROVIDER_ADAPTERS = Object.freeze([
129
133
  ...opencodeGoAdapters,
130
134
  ...xiaomiAdapters,
131
135
  ...qwenTokenPlanAdapters,
136
+ ...openaiCodexAdapters,
132
137
  // Placeholder adapters (unsupported status)
133
138
  ...amazonBedrockAdapters,
134
139
  ...antLingAdapters,
@@ -151,7 +156,6 @@ export const PROVIDER_ADAPTERS = Object.freeze([
151
156
  ...moonshotaiCnAdapters,
152
157
  ...nvidiaAdapters,
153
158
  ...openaiAdapters,
154
- ...openaiCodexAdapters,
155
159
  ...opencodeAdapters,
156
160
  ...openrouterAdapters,
157
161
  ...radiusAdapters,
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.1",
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",