dsh-model-allowance 0.0.0-stage → 1.0.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.
@@ -0,0 +1,474 @@
1
+ /**
2
+ * Kimi for Coding adapter.
3
+ *
4
+ * The official kimi-cli exposes the plan through `GET {base}/usages` with the
5
+ * account key. The body has changed shape across releases: older responses
6
+ * carry one `usage` bucket plus rate-limit `limits`, newer ones carry a
7
+ * `usages` map whose entries report a 0–1 `used_ratio`. Both shapes are read
8
+ * here, a window this module cannot decode is skipped, and duplicate windows
9
+ * reported by both shapes are merged rather than shown twice.
10
+ */
11
+
12
+ import {
13
+ asObject,
14
+ bindingWindow,
15
+ defineAdapter,
16
+ KIND_QUOTA,
17
+ parseAmount,
18
+ parseInstant,
19
+ windowLength,
20
+ } from './shared.js'
21
+ import { statuspageView } from './status.js'
22
+
23
+ /**
24
+ * Kimi's plan usage lives under 我的 → 设置 → 订阅 in the web app, which is
25
+ * this route. Verified 2026-11-06.
26
+ */
27
+ const CONSOLE = 'https://www.kimi.com/settings'
28
+
29
+ /**
30
+ * Moonshot — the platform behind Kimi — publishes its live status on an
31
+ * Atlassian Statuspage; it is the closest official source for the coding
32
+ * plan's backend. Verified 2026-11-06 against `/api/v2/status.json`.
33
+ */
34
+ const STATUS = Object.freeze({
35
+ endpoint: 'https://status.moonshot.cn/api/v2/status.json',
36
+ url: 'https://status.moonshot.cn',
37
+ parse: statuspageView,
38
+ })
39
+
40
+ /**
41
+ * Scale one Kimi window duration to milliseconds.
42
+ * @param {unknown} window The `window` object of a limit entry.
43
+ * @returns {number | undefined} The length, when the unit is known.
44
+ */
45
+ function windowMs(window) {
46
+ const record = asObject(window)
47
+ const duration = parseAmount(record.duration)
48
+ if (duration === undefined || duration <= 0) return undefined
49
+ const unit = String(record.timeUnit ?? '').toUpperCase()
50
+ if (unit.endsWith('MINUTE')) return duration * 60_000
51
+ if (unit.endsWith('HOUR')) return duration * 3_600_000
52
+ if (unit.endsWith('DAY')) return duration * 86_400_000
53
+ if (unit.endsWith('WEEK')) return duration * 7 * 86_400_000
54
+ return undefined
55
+ }
56
+
57
+ /** Clamp a percentage into the range a progress bar can show. */
58
+ function clampPercent(value) {
59
+ return Math.min(100, Math.max(0, Math.round(value * 100) / 100))
60
+ }
61
+
62
+ /**
63
+ * The remaining share one bucket reports.
64
+ *
65
+ * The newer `usages` map reports `used_ratio` as a 0–1 fraction; older buckets
66
+ * report `limit` with `used` or `remaining`; some report a percentage already.
67
+ * Read every form so a renamed response does not blank the card.
68
+ *
69
+ * @param {Record<string, unknown>} bucket One usage bucket.
70
+ * @returns {number | undefined} Remaining percent, when the bucket reports it.
71
+ */
72
+ function remainingPercent(bucket) {
73
+ const percent = parseAmount(bucket.remaining_percent ?? bucket.remainingPercent)
74
+ if (percent !== undefined) return clampPercent(percent)
75
+
76
+ const ratio = parseAmount(bucket.used_ratio ?? bucket.usedRatio)
77
+ if (ratio !== undefined) {
78
+ if (ratio > 1) return clampPercent(100 - ratio)
79
+ return clampPercent((1 - ratio) * 100)
80
+ }
81
+
82
+ const total = parseAmount(bucket.limit)
83
+ const used = parseAmount(bucket.used)
84
+ const remaining = parseAmount(bucket.remaining)
85
+ if (total !== undefined && total > 0) {
86
+ if (used !== undefined) return clampPercent((1 - used / total) * 100)
87
+ if (remaining !== undefined) return clampPercent((remaining / total) * 100)
88
+ }
89
+ return undefined
90
+ }
91
+
92
+ /**
93
+ * The countable fields one bucket reports.
94
+ * @param {Record<string, unknown>} bucket One usage bucket.
95
+ * @returns {{total?: number, used?: number}} The partial window fields.
96
+ */
97
+ function counts(bucket) {
98
+ const total = parseAmount(bucket.limit)
99
+ const remaining = parseAmount(bucket.remaining)
100
+ let used = parseAmount(bucket.used)
101
+ if (used === undefined && total !== undefined && remaining !== undefined) used = total - remaining
102
+ return {
103
+ ...(total === undefined ? {} : { total }),
104
+ ...(used === undefined ? {} : { used }),
105
+ }
106
+ }
107
+
108
+ /**
109
+ * The reset instant one bucket reports.
110
+ * @param {Record<string, unknown>} bucket One usage bucket.
111
+ * @returns {{resetAt?: number}} The partial window fields.
112
+ */
113
+ function resetOf(bucket) {
114
+ const resetAt = parseInstant(
115
+ bucket.resetTime ?? bucket.reset_time ?? bucket.resetAt ?? bucket.reset_at,
116
+ )
117
+ return resetAt === undefined ? {} : { resetAt }
118
+ }
119
+
120
+ /**
121
+ * The window shape a `usages` key names.
122
+ * @param {string} key Entry key such as `limit_5h` or `monthTotal`.
123
+ * @returns {{id: string, unit: 'hour'|'day'|'week'|'month'|'unknown', count?: number, label?: {zh: string, en: string}}} The shape.
124
+ */
125
+ function usageShape(key) {
126
+ const normalized = key.toLowerCase().replace(/[^a-z0-9]+/g, '')
127
+ if (normalized.includes('5h') || normalized.includes('5hour') || normalized.includes('session')) {
128
+ return { id: 'session', unit: 'hour', count: 5 }
129
+ }
130
+ if (normalized.includes('7d') || normalized.includes('weekly') || normalized.includes('week')) {
131
+ return { id: 'weekly', unit: 'week' }
132
+ }
133
+ if (normalized.includes('monthtotal')) {
134
+ return {
135
+ id: 'monthly-total',
136
+ unit: 'month',
137
+ label: { zh: '每月总额度', en: 'Monthly total' },
138
+ }
139
+ }
140
+ if (normalized.includes('monthcode')) {
141
+ return {
142
+ id: 'monthly-code',
143
+ unit: 'month',
144
+ label: { zh: '每月代码额度', en: 'Monthly code' },
145
+ }
146
+ }
147
+ if (normalized.includes('month')) return { id: 'monthly', unit: 'month' }
148
+ if (normalized.includes('day')) return { id: `usages-${key}`, unit: 'day' }
149
+ if (normalized.includes('hour')) return { id: `usages-${key}`, unit: 'hour' }
150
+ return { id: `usages-${key}`, unit: 'unknown' }
151
+ }
152
+
153
+ /**
154
+ * Project one Kimi usage body.
155
+ * @param {{route: string, body: Record<string, unknown>}} env Projection context.
156
+ * @returns {import('../providers.js').BalanceView} The reading.
157
+ */
158
+ function readUsage({ route, body }) {
159
+ /** @type {import('./shared.js').BalanceWindow[]} */
160
+ const windows = []
161
+ /** @type {Map<string, import('./shared.js').BalanceWindow>} */
162
+ const byId = new Map()
163
+
164
+ /**
165
+ * Append one window, merging a duplicate reported by another shape.
166
+ * @param {import('./shared.js').BalanceWindow} window The window to append.
167
+ */
168
+ const pushWindow = (window) => {
169
+ const existing = byId.get(window.id)
170
+ if (existing === undefined) {
171
+ byId.set(window.id, window)
172
+ windows.push(window)
173
+ return
174
+ }
175
+ // Prefer the first (newer `usages` map) values, but fill in counts the
176
+ // other shape carries so the panel can still show used / total.
177
+ const existingRecord = /** @type {Record<string, unknown>} */ (existing)
178
+ const windowRecord = /** @type {Record<string, unknown>} */ (window)
179
+ for (const key of ['count', 'total', 'used', 'resetAt']) {
180
+ if (existingRecord[key] === undefined && windowRecord[key] !== undefined) {
181
+ existingRecord[key] = windowRecord[key]
182
+ }
183
+ }
184
+ }
185
+
186
+ // Newer responses: one used-ratio entry per plan window.
187
+ const usages = asObject(body.usages)
188
+ for (const [key, entry] of Object.entries(usages)) {
189
+ const raw = asObject(entry)
190
+ const record = { ...asObject(raw.detail), ...raw }
191
+ const percent = remainingPercent(record)
192
+ if (percent === undefined) continue
193
+ pushWindow({
194
+ ...usageShape(key),
195
+ remainingPercent: percent,
196
+ ...resetOf(record),
197
+ })
198
+ }
199
+
200
+ // Older responses: one weekly bucket with limit/used/remaining.
201
+ const weekly = asObject(body.usage)
202
+ const weeklyPercent = remainingPercent(weekly)
203
+ if (weeklyPercent !== undefined) {
204
+ pushWindow({
205
+ id: 'weekly',
206
+ unit: 'week',
207
+ ...counts(weekly),
208
+ remainingPercent: weeklyPercent,
209
+ ...resetOf(weekly),
210
+ })
211
+ }
212
+
213
+ // Rate-limit windows: `detail` is the older nesting; newer entries carry the
214
+ // fields directly on the entry. A single object is accepted as a one-entry
215
+ // list, which some gateways return.
216
+ const limitEntries = Array.isArray(body.limits)
217
+ ? body.limits
218
+ : body.limits !== null && typeof body.limits === 'object'
219
+ ? [body.limits]
220
+ : []
221
+ for (const entry of limitEntries) {
222
+ const record = asObject(entry)
223
+ const detail = asObject(record.detail)
224
+ const bucket = { ...detail, ...record }
225
+ const percent = remainingPercent(bucket)
226
+ if (percent === undefined) continue
227
+ const length = windowLength(windowMs(record.window))
228
+ const id =
229
+ length.unit === 'hour'
230
+ ? 'session'
231
+ : length.unit === 'day' && length.count === 7
232
+ ? 'weekly'
233
+ : `limit-${String(windows.length)}`
234
+ pushWindow({
235
+ id,
236
+ ...length,
237
+ ...counts(bucket),
238
+ remainingPercent: percent,
239
+ ...resetOf(bucket),
240
+ })
241
+ }
242
+
243
+ if (windows.length === 0) {
244
+ return {
245
+ provider: route,
246
+ status: 'failed',
247
+ kind: KIND_QUOTA,
248
+ error: 'no usage in response',
249
+ }
250
+ }
251
+ // The total monthly allowance is the broadest window; keep it at the bottom
252
+ // so the narrower code allowance reads above it.
253
+ windows.sort(
254
+ (left, right) => Number(left.id === 'monthly-total') - Number(right.id === 'monthly-total'),
255
+ )
256
+ const binding = bindingWindow(windows)
257
+ return {
258
+ provider: route,
259
+ status: 'ready',
260
+ kind: KIND_QUOTA,
261
+ ...(binding?.remainingPercent === undefined ? {} : { percent: binding.remainingPercent }),
262
+ ...(binding?.resetAt === undefined ? {} : { resetsAt: binding.resetAt }),
263
+ windows,
264
+ consoleUrl: CONSOLE,
265
+ }
266
+ }
267
+
268
+ /** Kimi for Coding's route. */
269
+ export const kimiAdapters = [
270
+ defineAdapter({
271
+ id: 'kimi-coding',
272
+ routes: ['kimi-coding'],
273
+ kind: KIND_QUOTA,
274
+ endpoint: 'https://api.kimi.com/coding/v1/usages',
275
+ auth: 'bearer',
276
+ credentialRefs: ['KIMI_API_KEY'],
277
+ read: readUsage,
278
+ consoleUrl: CONSOLE,
279
+ status: STATUS,
280
+ display: {
281
+ name: { zh: 'Kimi Coding', en: 'Kimi Coding' },
282
+ mark: { icon: 'kimi', color: '#636ff6' },
283
+ },
284
+ fixtures: [
285
+ {
286
+ name: 'recorded weekly and five-hour windows',
287
+ response: {
288
+ user: { userId: 'u1', membership: { level: 'LEVEL_STANDARD' } },
289
+ usage: {
290
+ limit: '100',
291
+ used: '40',
292
+ remaining: '60',
293
+ resetTime: '2026-08-04T11:05:18Z',
294
+ },
295
+ limits: [
296
+ {
297
+ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' },
298
+ detail: {
299
+ limit: '100',
300
+ used: '25',
301
+ remaining: '75',
302
+ resetTime: '2026-07-28T16:05:18Z',
303
+ },
304
+ },
305
+ ],
306
+ parallel: { limit: '30' },
307
+ },
308
+ apiKey: 'sk-test',
309
+ expect: {
310
+ status: 'ready',
311
+ kind: KIND_QUOTA,
312
+ // The weekly window is the binding one at 40% spent.
313
+ percent: 60,
314
+ windows: [
315
+ {
316
+ id: 'weekly',
317
+ unit: 'week',
318
+ total: 100,
319
+ used: 40,
320
+ remainingPercent: 60,
321
+ resetAt: Date.parse('2026-08-04T11:05:18Z'),
322
+ },
323
+ {
324
+ id: 'session',
325
+ unit: 'hour',
326
+ count: 5,
327
+ total: 100,
328
+ used: 25,
329
+ remainingPercent: 75,
330
+ resetAt: Date.parse('2026-07-28T16:05:18Z'),
331
+ },
332
+ ],
333
+ },
334
+ },
335
+ {
336
+ name: 'newer usages map with used ratios',
337
+ response: {
338
+ usages: {
339
+ limit_5h: { used_ratio: 0.2, reset_time: '2026-11-06T06:05:18Z' },
340
+ limit_7d: { used_ratio: 0.45, reset_time: '2026-11-10T00:00:00Z' },
341
+ limit_month_total: { used_ratio: 0.1, reset_time: '2026-12-01T00:00:00Z' },
342
+ limit_month_code: { used_ratio: 0.05, reset_time: '2026-12-01T00:00:00Z' },
343
+ },
344
+ // The same 5h window may also arrive in the older limits shape; it
345
+ // must be merged into the existing window, not shown twice.
346
+ limits: [
347
+ {
348
+ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' },
349
+ limit: '100',
350
+ used: '20',
351
+ resetTime: '2026-11-06T06:05:18Z',
352
+ },
353
+ ],
354
+ },
355
+ apiKey: 'sk-test',
356
+ expect: {
357
+ status: 'ready',
358
+ percent: 55,
359
+ windows: [
360
+ {
361
+ id: 'session',
362
+ unit: 'hour',
363
+ count: 5,
364
+ remainingPercent: 80,
365
+ resetAt: Date.parse('2026-11-06T06:05:18Z'),
366
+ },
367
+ {
368
+ id: 'weekly',
369
+ unit: 'week',
370
+ remainingPercent: 55,
371
+ resetAt: Date.parse('2026-11-10T00:00:00Z'),
372
+ },
373
+ {
374
+ id: 'monthly-code',
375
+ unit: 'month',
376
+ label: { zh: '每月代码额度', en: 'Monthly code' },
377
+ remainingPercent: 95,
378
+ },
379
+ {
380
+ id: 'monthly-total',
381
+ unit: 'month',
382
+ label: { zh: '每月总额度', en: 'Monthly total' },
383
+ remainingPercent: 90,
384
+ },
385
+ ],
386
+ },
387
+ },
388
+ {
389
+ name: 'rate limits carry their fields at the top level',
390
+ response: {
391
+ limits: [
392
+ {
393
+ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' },
394
+ limit: '100',
395
+ used: '60',
396
+ resetTime: '2026-11-06T06:05:18Z',
397
+ },
398
+ ],
399
+ },
400
+ apiKey: 'sk-test',
401
+ expect: {
402
+ status: 'ready',
403
+ percent: 40,
404
+ windows: [
405
+ {
406
+ id: 'session',
407
+ unit: 'hour',
408
+ count: 5,
409
+ total: 100,
410
+ used: 60,
411
+ remainingPercent: 40,
412
+ },
413
+ ],
414
+ },
415
+ },
416
+ {
417
+ name: 'a remaining-only bucket still yields counts',
418
+ response: {
419
+ usage: { limit: '100', remaining: '60', resetTime: '2026-08-04T11:05:18Z' },
420
+ },
421
+ apiKey: 'sk-test',
422
+ expect: {
423
+ status: 'ready',
424
+ percent: 60,
425
+ windows: [
426
+ {
427
+ id: 'weekly',
428
+ unit: 'week',
429
+ total: 100,
430
+ used: 40,
431
+ remainingPercent: 60,
432
+ },
433
+ ],
434
+ },
435
+ },
436
+ {
437
+ name: 'malformed week, decodable rate limit',
438
+ response: {
439
+ usage: { limit: 'nope', used: '1', resetTime: null },
440
+ limits: [
441
+ {
442
+ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' },
443
+ detail: { limit: '100', used: '10', resetTime: '2026-07-28T16:05:18Z' },
444
+ },
445
+ ],
446
+ },
447
+ expect: {
448
+ status: 'ready',
449
+ percent: 90,
450
+ windows: [
451
+ {
452
+ id: 'session',
453
+ unit: 'hour',
454
+ count: 5,
455
+ total: 100,
456
+ used: 10,
457
+ remainingPercent: 90,
458
+ },
459
+ ],
460
+ },
461
+ },
462
+ {
463
+ name: 'no decodable window',
464
+ response: { usage: {}, limits: [] },
465
+ expect: { status: 'failed', error: 'no usage in response' },
466
+ },
467
+ {
468
+ name: 'key rejected',
469
+ httpStatus: 401,
470
+ expect: { status: 'failed', error: 'HTTP 401' },
471
+ },
472
+ ],
473
+ }),
474
+ ]