dsh-model-allowance 1.0.7 → 1.1.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/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.
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 },
@@ -520,60 +515,9 @@ export const xaiAdapters = [
520
515
  ]
521
516
 
522
517
  // ============================================================================
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
518
+ // Xiaomi MiMo (already implemented in xiaomi.js)
519
+ // Note: Xiaomi MiMo has full implementation in xiaomi.js
552
520
  // ============================================================================
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
566
- // ============================================================================
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
521
 
578
522
  // ============================================================================
579
523
  // Zhipu ZAI (already implemented in zai.js)
@@ -12,8 +12,8 @@
12
12
  * no extra round trips.
13
13
  */
14
14
 
15
- /** HH:MM in 24-hour wall time. */
16
- const TIME_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/
15
+ /** HH:MM in 24-hour wall time; `24:00` is the day's end. */
16
+ const TIME_PATTERN = /^(?:(?:[01]\d|2[0-3]):[0-5]\d|24:00)$/
17
17
 
18
18
  /** ISO calendar date, in the schedule's own zone. */
19
19
  const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
@@ -21,17 +21,19 @@ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
21
21
  /**
22
22
  * Parse one `HH:MM` string to minutes since midnight.
23
23
  * @param {string} value Wall-clock time.
24
- * @returns {number} Minutes since midnight.
24
+ * @returns {number} Minutes since midnight, or NaN when unparsable.
25
25
  */
26
26
  export function timeToMinutes(value) {
27
- const match = TIME_PATTERN.exec(value)
28
- return Number(match[1]) * 60 + Number(match[2])
27
+ const text = String(value)
28
+ if (!TIME_PATTERN.test(text)) return Number.NaN
29
+ const [hour, minute] = text.split(':').map(Number)
30
+ return hour * 60 + minute
29
31
  }
30
32
 
31
33
  /**
32
34
  * @typedef {object} ScheduleWindow
33
35
  * @property {string} from Wall-clock start, `HH:MM`.
34
- * @property {string} to Wall-clock end, `HH:MM`; must be later than `from`.
36
+ * @property {string} to Wall-clock end, `HH:MM` or `24:00`; must be later than `from`.
35
37
  */
36
38
 
37
39
  /**
@@ -152,7 +152,7 @@ export function bindingWindow(windows) {
152
152
  * balance route.
153
153
  * @param {'amount'|'quota'} spec.kind Quantity dimension of the reading.
154
154
  * @param {boolean} [spec.modelScoped] Whether the reading is per model.
155
- * @param {string} spec.consoleUrl Provider console for a manual check.
155
+ * @param {string} [spec.consoleUrl] Provider console for a manual check.
156
156
  * @param {{name: {zh: string, en: string}, mark: {icon?: string, color: string}}} spec.display
157
157
  * Display metadata the browser needs to name and draw the route.
158
158
  * @param {string} [spec.service] Host service this adapter reads through.
@@ -185,8 +185,10 @@ export function defineAdapter(spec) {
185
185
  if (spec.kind !== KIND_AMOUNT && spec.kind !== KIND_QUOTA) {
186
186
  throw new Error(`${where} must declare kind "${KIND_AMOUNT}" or "${KIND_QUOTA}"`)
187
187
  }
188
- if (typeof spec.consoleUrl !== 'string' || !spec.consoleUrl.startsWith('https://')) {
189
- throw new Error(`${where} needs an https console link`)
188
+ if (spec.consoleUrl !== undefined) {
189
+ if (typeof spec.consoleUrl !== 'string' || !spec.consoleUrl.startsWith('https://')) {
190
+ throw new Error(`${where} needs an https console link`)
191
+ }
190
192
  }
191
193
  if (spec.status !== undefined) {
192
194
  if (typeof spec.status !== 'object' || spec.status === null) {
@@ -256,7 +258,7 @@ export function defineAdapter(spec) {
256
258
  : { modelRoutes: Object.freeze([...spec.modelRoutes]) }),
257
259
  kind: spec.kind,
258
260
  ...(spec.modelScoped === true ? { modelScoped: true } : {}),
259
- consoleUrl: spec.consoleUrl,
261
+ ...(spec.consoleUrl === undefined ? {} : { consoleUrl: spec.consoleUrl }),
260
262
  service: spec.service,
261
263
  http: hasEndpoint ? Object.freeze({ endpoint: spec.endpoint, auth: spec.auth }) : undefined,
262
264
  credentialRefs: Object.freeze([...(spec.credentialRefs ?? [])]),