dsh-model-allowance 1.0.7 → 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/lib/balance.js CHANGED
@@ -96,6 +96,33 @@ function withTimeout(promise, signal) {
96
96
  })
97
97
  }
98
98
 
99
+ /** The consecutive-failure count from which force reads are throttled. */
100
+ const BACKOFF_MIN_FAILURES = 2
101
+
102
+ /** Upper bound of the exponential backoff window, in milliseconds. */
103
+ const MAX_BACKOFF_MS = 30 * 60 * 1000
104
+
105
+ /**
106
+ * The failure bookkeeping a fresh reading inherits from the cached one.
107
+ *
108
+ * A `failed` reading counts one more consecutive failure and stamps when it
109
+ * happened; a `ready` reading resets the streak. `unconfigured` and
110
+ * `unsupported` are facts about the installation, not provider failures, so
111
+ * they leave the streak untouched.
112
+ *
113
+ * @param {{failures?: number, failedAt?: number} | undefined} prior The cached entry, if any.
114
+ * @param {BalanceView} view The fresh reading.
115
+ * @returns {{failures: number, failedAt?: number}} The state to cache alongside the view.
116
+ */
117
+ function nextFailureState(prior, view) {
118
+ if (view.status === 'failed') {
119
+ const failures = (prior?.failures ?? 0) + 1
120
+ return { failures, failedAt: Date.now() }
121
+ }
122
+ if (view.status === 'ready') return { failures: 0 }
123
+ return { failures: prior?.failures ?? 0, failedAt: prior?.failedAt }
124
+ }
125
+
99
126
  /**
100
127
  * @typedef {import('./providers.js').BalanceView} BalanceView
101
128
  */
@@ -198,7 +225,7 @@ export class BalanceService {
198
225
  // Readings are cached per route and model: one route can meter different
199
226
  // models separately, so a model switch must not answer with the previous
200
227
  // model's reading.
201
- /** @type {Map<string, {view: BalanceView, at: number}>} */
228
+ /** @type {Map<string, {view: BalanceView, at: number, failures?: number, failedAt?: number}>} */
202
229
  this.cache = new Map()
203
230
  /**
204
231
  * The reading each key published last, which the next one is measured
@@ -230,10 +257,24 @@ export class BalanceService {
230
257
  return adapter?.modelScoped === true ? keyOf(route, model) : route
231
258
  }
232
259
 
260
+ /**
261
+ * The backoff window after a given consecutive-failure streak.
262
+ *
263
+ * The first failure retries on the next trigger as before; from the second
264
+ * one on, each retry waits twice as long as the last, capped so a route
265
+ * that stays down never grows past half an hour between attempts.
266
+ *
267
+ * @param {number} failures The consecutive-failure count.
268
+ * @returns {number} The window in milliseconds.
269
+ */
270
+ #backoffMs(failures) {
271
+ return Math.min(this.ttlMs * 2 ** (failures - 1), MAX_BACKOFF_MS)
272
+ }
273
+
233
274
  /**
234
275
  * Read one provider's balance, reusing a fresh cached reading.
235
276
  * @param {string} route Provider route.
236
- * @param {{force?: boolean, model?: string}} [options] Read options.
277
+ * @param {{force?: boolean, model?: string, bypassBackoff?: boolean}} [options] Read options.
237
278
  * @returns {Promise<BalanceView>} The reading.
238
279
  */
239
280
  async read(route, options = {}) {
@@ -244,6 +285,20 @@ export class BalanceService {
244
285
  if (!options.force && cached && Date.now() - cached.at < this.ttlMs) {
245
286
  return cached.view
246
287
  }
288
+ // A route that keeps failing is retried on a backoff, not on every trigger:
289
+ // a force read inside the backoff window answers with the cached failure
290
+ // instead of hitting the provider again. The manual refresh path passes
291
+ // `bypassBackoff` so the user's click is never throttled.
292
+ if (
293
+ options.force &&
294
+ !options.bypassBackoff &&
295
+ cached &&
296
+ (cached.failures ?? 0) >= BACKOFF_MIN_FAILURES &&
297
+ cached.failedAt !== undefined &&
298
+ Date.now() - cached.failedAt < this.#backoffMs(cached.failures ?? 0)
299
+ ) {
300
+ return cached.view
301
+ }
247
302
  const pending = this.inflight.get(key)
248
303
  if (pending) return await pending
249
304
 
@@ -253,7 +308,8 @@ export class BalanceService {
253
308
  // a later sweep republish a stale one.
254
309
  const anchor = this.lastPublished.get(key)
255
310
  const published = anchor ? withConsumption(view, anchor) : view
256
- this.cache.set(key, { view, at: Date.now() })
311
+ const prior = this.cache.get(key)
312
+ this.cache.set(key, { view, at: Date.now(), ...nextFailureState(prior, view) })
257
313
  // A reading that did not come back cleanly says nothing about movement,
258
314
  // and anchoring the next one to it would attribute the whole gap to
259
315
  // whatever moved in between.
@@ -486,6 +542,7 @@ export class BalanceService {
486
542
  status: 'unconfigured',
487
543
  kind: adapter.kind,
488
544
  consoleUrl: adapter.consoleUrl,
545
+ ...(adapter.setupUrl === undefined ? {} : { setupUrl: adapter.setupUrl }),
489
546
  }
490
547
  }
491
548
  // A reading is bounded by the request timeout alone. Cordis has no
@@ -507,8 +564,16 @@ export class BalanceService {
507
564
  })
508
565
  // The console link is a property of the route, not of the response, so
509
566
  // every reading carries it — including one that failed authorization and
510
- // is exactly when the user needs the way back to the console.
511
- return { ...view, consoleUrl: view.consoleUrl ?? adapter.consoleUrl, updatedAt: Date.now() }
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
+ }
512
577
  } catch (error) {
513
578
  const reason = error instanceof Error ? error.message : String(error)
514
579
  // An aborted request is a cancellation, not a provider failure.
package/lib/debug.js CHANGED
@@ -5,6 +5,11 @@
5
5
  * easily hand back. When `config.debug` is on, this writes the same facts to
6
6
  * `<DSH_HOME>/model-allowance-debug.log` so a failing reading can be inspected
7
7
  * after the fact. It stays off by default and writes nothing otherwise.
8
+ *
9
+ * Writes go through an in-memory queue and are appended in batches, one
10
+ * `setImmediate` turn at a time: the home directory is created once per
11
+ * process, rotation is checked once per batch instead of once per line, and a
12
+ * failed batch is dropped silently — a debug log must never break a reading.
8
13
  */
9
14
 
10
15
  import { appendFile, mkdir, rename, rm, stat } from 'node:fs/promises'
@@ -14,7 +19,7 @@ import { join } from 'node:path'
14
19
  /** File name inside the DSH home. */
15
20
  const LOG_NAME = 'model-allowance-debug.log'
16
21
 
17
- /** A debug log this large is handed back as `.1` before the next line. */
22
+ /** A debug log this large is handed back as `.1` before the next batch. */
18
23
  const MAX_LOG_BYTES = 2 * 1024 * 1024
19
24
 
20
25
  /** Directory DSH keeps its profile data in. */
@@ -22,8 +27,20 @@ function dshHome() {
22
27
  return process.env.DSH_HOME ?? join(homedir(), '.dsh')
23
28
  }
24
29
 
30
+ /** Lines waiting for the next batch, each with the promise to settle. */
31
+ let queue = []
32
+
33
+ /** Directory and file path, cached after the first successful mkdir. */
34
+ let logFile = null
35
+
36
+ /** A batch flush currently running (append calls must stay ordered). */
37
+ let flushing = false
38
+
39
+ /** A flush turn already scheduled for whatever is in the queue. */
40
+ let flushScheduled = false
41
+
25
42
  /**
26
- * Keep the debug log bounded.
43
+ * Keep the debug log bounded; checked once per batch.
27
44
  * @param {string} file Log path.
28
45
  * @returns {Promise<void>} Resolves once rotation was considered.
29
46
  */
@@ -40,23 +57,65 @@ async function rotate(file) {
40
57
  }
41
58
 
42
59
  /**
43
- * Append one line to the debug log.
44
- * @param {string} message Line to write.
45
- * @returns {Promise<void>} Resolves once the line is written.
60
+ * Queue one line and make sure a flush turn is pending.
61
+ * @param {{ line: string, resolve: () => void }} entry Line to write.
62
+ * @returns {void}
46
63
  */
47
- export async function logDebug(message) {
64
+ function enqueue(entry) {
65
+ queue.push(entry)
66
+ if (flushScheduled) return
67
+ flushScheduled = true
68
+ setImmediate(() => {
69
+ flushScheduled = false
70
+ runFlush()
71
+ })
72
+ }
73
+
74
+ /**
75
+ * Append every queued line in one `appendFile` call.
76
+ * @returns {Promise<void>} Completes when this batch is settled.
77
+ */
78
+ async function runFlush() {
79
+ if (flushing || queue.length === 0) return
80
+ flushing = true
81
+ const batch = queue
82
+ queue = []
48
83
  try {
49
- const home = dshHome()
50
- await mkdir(home, { recursive: true })
51
- const file = join(home, LOG_NAME)
52
- await rotate(file)
53
- const line = `${new Date().toISOString()} ${message}\n`
54
- await appendFile(file, line, 'utf8')
84
+ if (logFile === null) {
85
+ const home = dshHome()
86
+ await mkdir(home, { recursive: true })
87
+ logFile = join(home, LOG_NAME)
88
+ }
89
+ await rotate(logFile)
90
+ await appendFile(logFile, batch.map((entry) => entry.line).join(''), 'utf8')
55
91
  } catch {
56
- // A debug log that cannot be written must never break a reading.
92
+ // A debug log that cannot be written must never break a reading: the
93
+ // batch is dropped, its callers still resolve.
94
+ } finally {
95
+ flushing = false
96
+ for (const entry of batch) entry.resolve()
97
+ if (queue.length > 0) {
98
+ flushScheduled = true
99
+ setImmediate(() => {
100
+ flushScheduled = false
101
+ runFlush()
102
+ })
103
+ }
57
104
  }
58
105
  }
59
106
 
107
+ /**
108
+ * Append one line to the debug log.
109
+ * @param {string} message Line to write.
110
+ * @returns {Promise<void>} Resolves once the line reached disk (or the write
111
+ * failed and the line was dropped).
112
+ */
113
+ export function logDebug(message) {
114
+ return new Promise((resolve) => {
115
+ enqueue({ line: `${new Date().toISOString()} ${message}\n`, resolve })
116
+ })
117
+ }
118
+
60
119
  /**
61
120
  * Describe an error with its stack, for one log line.
62
121
  * @param {unknown} error The thrown value.
@@ -8,6 +8,7 @@
8
8
  * itself can read.
9
9
  */
10
10
 
11
+ import { DEEPSEEK_HOLIDAYS } from './holidays.js'
11
12
  import { defineSchedule } from './schedule.js'
12
13
  import { asObject, defineAdapter, KIND_AMOUNT, parseAmount } from './shared.js'
13
14
  import {
@@ -48,9 +49,8 @@ const STATUS = Object.freeze({
48
49
  * statutory holidays are off-peak all day; a working weekend stays a weekend
49
50
  * under the rule, which names Monday to Friday.
50
51
  *
51
- * The holiday list covers the State Council's 2026 arrangement (国办发明电
52
- * 〔2025〕7号) and 2027 arrangement (国办发明电〔2026〕10号). Extend it when
53
- * the next year's notice is published.
52
+ * The holiday list lives in `./holidays.js`; extend it there when the next
53
+ * year's State Council notice is published.
54
54
  */
55
55
  const SCHEDULE = defineSchedule({
56
56
  timezone: 'Asia/Shanghai',
@@ -60,85 +60,7 @@ const SCHEDULE = defineSchedule({
60
60
  { from: '09:00', to: '12:00' },
61
61
  { from: '14:00', to: '18:00' },
62
62
  ],
63
- holidays: [
64
- // 元旦
65
- '2026-01-01',
66
- '2026-01-02',
67
- '2026-01-03',
68
- // 春节
69
- '2026-02-15',
70
- '2026-02-16',
71
- '2026-02-17',
72
- '2026-02-18',
73
- '2026-02-19',
74
- '2026-02-20',
75
- '2026-02-21',
76
- '2026-02-22',
77
- '2026-02-23',
78
- // 清明节
79
- '2026-04-04',
80
- '2026-04-05',
81
- '2026-04-06',
82
- // 劳动节
83
- '2026-05-01',
84
- '2026-05-02',
85
- '2026-05-03',
86
- '2026-05-04',
87
- '2026-05-05',
88
- // 端午节
89
- '2026-06-19',
90
- '2026-06-20',
91
- '2026-06-21',
92
- // 中秋节
93
- '2026-09-25',
94
- '2026-09-26',
95
- '2026-09-27',
96
- // 国庆节
97
- '2026-10-01',
98
- '2026-10-02',
99
- '2026-10-03',
100
- '2026-10-04',
101
- '2026-10-05',
102
- '2026-10-06',
103
- '2026-10-07',
104
- // ===== 2027年(国办发明电〔2026〕10号)=====
105
- // 元旦
106
- '2027-01-01',
107
- '2027-01-02',
108
- '2027-01-03',
109
- // 春节
110
- '2027-02-05',
111
- '2027-02-06',
112
- '2027-02-07',
113
- '2027-02-08',
114
- '2027-02-09',
115
- '2027-02-10',
116
- '2027-02-11',
117
- '2027-02-12',
118
- '2027-02-13',
119
- // 清明节
120
- '2027-04-03',
121
- '2027-04-04',
122
- '2027-04-05',
123
- // 劳动节
124
- '2027-05-01',
125
- '2027-05-02',
126
- '2027-05-03',
127
- '2027-05-04',
128
- '2027-05-05',
129
- // 端午节
130
- '2027-06-09',
131
- // 中秋节
132
- '2027-09-15',
133
- // 国庆节
134
- '2027-10-01',
135
- '2027-10-02',
136
- '2027-10-03',
137
- '2027-10-04',
138
- '2027-10-05',
139
- '2027-10-06',
140
- '2027-10-07',
141
- ],
63
+ holidays: DEEPSEEK_HOLIDAYS,
142
64
  note: { zh: '低谷时段 API 价格减半', en: 'API prices are halved off-peak' },
143
65
  })
144
66
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Chinese statutory holidays, externalized from the DeepSeek pricing schedule.
3
+ *
4
+ * The list covers the State Council's 2026 arrangement (国办发明电
5
+ * 〔2025〕7号) and 2027 arrangement (国办发明电〔2026〕10号). Extend it when
6
+ * the next year's notice is published; index.js warns on the console when the
7
+ * list no longer covers the current year.
8
+ */
9
+
10
+ /** @type {string[]} Dates in `YYYY-MM-DD`, grouped by holiday. */
11
+ export const DEEPSEEK_HOLIDAYS = [
12
+ // 元旦
13
+ '2026-01-01',
14
+ '2026-01-02',
15
+ '2026-01-03',
16
+ // 春节
17
+ '2026-02-15',
18
+ '2026-02-16',
19
+ '2026-02-17',
20
+ '2026-02-18',
21
+ '2026-02-19',
22
+ '2026-02-20',
23
+ '2026-02-21',
24
+ '2026-02-22',
25
+ '2026-02-23',
26
+ // 清明节
27
+ '2026-04-04',
28
+ '2026-04-05',
29
+ '2026-04-06',
30
+ // 劳动节
31
+ '2026-05-01',
32
+ '2026-05-02',
33
+ '2026-05-03',
34
+ '2026-05-04',
35
+ '2026-05-05',
36
+ // 端午节
37
+ '2026-06-19',
38
+ '2026-06-20',
39
+ '2026-06-21',
40
+ // 中秋节
41
+ '2026-09-25',
42
+ '2026-09-26',
43
+ '2026-09-27',
44
+ // 国庆节
45
+ '2026-10-01',
46
+ '2026-10-02',
47
+ '2026-10-03',
48
+ '2026-10-04',
49
+ '2026-10-05',
50
+ '2026-10-06',
51
+ '2026-10-07',
52
+ // ===== 2027年(国办发明电〔2026〕10号)=====
53
+ // 元旦
54
+ '2027-01-01',
55
+ '2027-01-02',
56
+ '2027-01-03',
57
+ // 春节
58
+ '2027-02-05',
59
+ '2027-02-06',
60
+ '2027-02-07',
61
+ '2027-02-08',
62
+ '2027-02-09',
63
+ '2027-02-10',
64
+ '2027-02-11',
65
+ '2027-02-12',
66
+ '2027-02-13',
67
+ // 清明节
68
+ '2027-04-03',
69
+ '2027-04-04',
70
+ '2027-04-05',
71
+ // 劳动节
72
+ '2027-05-01',
73
+ '2027-05-02',
74
+ '2027-05-03',
75
+ '2027-05-04',
76
+ '2027-05-05',
77
+ // 端午节
78
+ '2027-06-09',
79
+ // 中秋节
80
+ '2027-09-15',
81
+ // 国庆节
82
+ '2027-10-01',
83
+ '2027-10-02',
84
+ '2027-10-03',
85
+ '2027-10-04',
86
+ '2027-10-05',
87
+ '2027-10-06',
88
+ '2027-10-07',
89
+ ]
@@ -24,11 +24,6 @@ import { defineAdapter, KIND_AMOUNT } from './shared.js'
24
24
  * @returns {import('../providers.js').ProviderAdapter} The placeholder adapter.
25
25
  */
26
26
  function placeholderAdapter({ id, routes, name, color, icon, consoleUrl }) {
27
- const safeConsole =
28
- typeof consoleUrl === 'string' && consoleUrl.startsWith('https://')
29
- ? consoleUrl
30
- : 'https://example.com'
31
-
32
27
  return defineAdapter({
33
28
  id,
34
29
  routes,
@@ -38,7 +33,7 @@ function placeholderAdapter({ id, routes, name, color, icon, consoleUrl }) {
38
33
  status: 'unsupported',
39
34
  kind: KIND_AMOUNT,
40
35
  }),
41
- consoleUrl: safeConsole,
36
+ consoleUrl,
42
37
  display: {
43
38
  name: { zh: name.zh, en: name.en },
44
39
  mark: { ...(typeof icon === 'string' ? { icon } : {}), color },
@@ -407,48 +402,6 @@ export const openrouterAdapters = [
407
402
  }),
408
403
  ]
409
404
 
410
- // ============================================================================
411
- // Qwen Token Plan
412
- // ============================================================================
413
- export const qwenTokenPlanAdapters = [
414
- placeholderAdapter({
415
- id: 'qwen-token-plan',
416
- routes: ['qwen-token-plan'],
417
- name: { zh: '通义千问 Token Plan', en: 'Qwen Token Plan' },
418
- color: '#082DFF',
419
- icon: 'qwen',
420
- consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
421
- }),
422
- ]
423
-
424
- // ============================================================================
425
- // Qwen Token Plan CN
426
- // ============================================================================
427
- export const qwenTokenPlanCnAdapters = [
428
- placeholderAdapter({
429
- id: 'qwen-token-plan-cn',
430
- routes: ['qwen-token-plan-cn'],
431
- name: { zh: '通义千问 Token Plan (国内)', en: 'Qwen Token Plan (CN)' },
432
- color: '#082DFF',
433
- icon: 'qwen',
434
- consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
435
- }),
436
- ]
437
-
438
- // ============================================================================
439
- // Qwen Token Plan Individual
440
- // ============================================================================
441
- export const qwenTokenPlanIndividualAdapters = [
442
- placeholderAdapter({
443
- id: 'qwen-token-plan-individual',
444
- routes: ['qwen-token-plan-individual'],
445
- name: { zh: '通义千问个人版', en: 'Qwen Token Plan Individual' },
446
- color: '#082DFF',
447
- icon: 'qwen',
448
- consoleUrl: 'https://platform.qianwenai.com/home/analytics/token-plan/individual',
449
- }),
450
- ]
451
-
452
405
  // ============================================================================
453
406
  // Radius
454
407
  // ============================================================================
@@ -520,60 +473,9 @@ export const xaiAdapters = [
520
473
  ]
521
474
 
522
475
  // ============================================================================
523
- // Xiaomi (小米)
524
- // ============================================================================
525
- export const xiaomiAdapters = [
526
- placeholderAdapter({
527
- id: 'xiaomi',
528
- routes: ['xiaomi'],
529
- name: { zh: '小米', en: 'Xiaomi' },
530
- color: '#ff6700',
531
- icon: 'xiaomi',
532
- consoleUrl: 'https://ai.xiaomi.com/',
533
- }),
534
- ]
535
-
536
- // ============================================================================
537
- // Xiaomi Token Plan AMS
538
- // ============================================================================
539
- export const xiaomiTokenPlanAmsAdapters = [
540
- placeholderAdapter({
541
- id: 'xiaomi-token-plan-ams',
542
- routes: ['xiaomi-token-plan-ams'],
543
- name: { zh: '小米 Token Plan (阿姆斯特丹)', en: 'Xiaomi Token Plan (AMS)' },
544
- color: '#ff6700',
545
- icon: 'xiaomi',
546
- consoleUrl: 'https://ai.xiaomi.com/',
547
- }),
548
- ]
549
-
550
- // ============================================================================
551
- // Xiaomi Token Plan CN
552
- // ============================================================================
553
- export const xiaomiTokenPlanCnAdapters = [
554
- placeholderAdapter({
555
- id: 'xiaomi-token-plan-cn',
556
- routes: ['xiaomi-token-plan-cn'],
557
- name: { zh: '小米 Token Plan (国内)', en: 'Xiaomi Token Plan (CN)' },
558
- color: '#ff6700',
559
- icon: 'xiaomi',
560
- consoleUrl: 'https://ai.xiaomi.com/',
561
- }),
562
- ]
563
-
564
- // ============================================================================
565
- // Xiaomi Token Plan SGP
476
+ // Xiaomi MiMo (already implemented in xiaomi.js)
477
+ // Note: Xiaomi MiMo has full implementation in xiaomi.js
566
478
  // ============================================================================
567
- export const xiaomiTokenPlanSgpAdapters = [
568
- placeholderAdapter({
569
- id: 'xiaomi-token-plan-sgp',
570
- routes: ['xiaomi-token-plan-sgp'],
571
- name: { zh: '小米 Token Plan (新加坡)', en: 'Xiaomi Token Plan (SGP)' },
572
- color: '#ff6700',
573
- icon: 'xiaomi',
574
- consoleUrl: 'https://ai.xiaomi.com/',
575
- }),
576
- ]
577
479
 
578
480
  // ============================================================================
579
481
  // Zhipu ZAI (already implemented in zai.js)