dsh-model-allowance 0.0.0-stage → 1.0.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,383 @@
1
+ /**
2
+ * MiniMax adapter.
3
+ *
4
+ * The coding plan answers a GET with bearer auth; a POST with a `key` body is
5
+ * the pay-as-you-go shape and returns 404 for a plan key, so the GET is the
6
+ * only form worth asking. The plan meters a 5-hour window and a 7-day window
7
+ * and reports both as remaining percentages plus the closing timestamp of
8
+ * each — a single "remaining" number cannot express that.
9
+ *
10
+ * A token-plan key can carry several `model_remains` buckets: MiniMax reports
11
+ * `general` beside `video` on the same account. The session's model picks the
12
+ * bucket when it matches; otherwise the canonical text plan wins.
13
+ */
14
+
15
+ import {
16
+ asObject,
17
+ bindingWindow,
18
+ defineAdapter,
19
+ KIND_QUOTA,
20
+ parseAmount,
21
+ windowLength,
22
+ } from './shared.js'
23
+ import { statuspageView } from './status.js'
24
+
25
+ /**
26
+ * MiniMax's plan usage page. Verified 2026-11-06 — the docs name this console
27
+ * path and redirect away from the older `platform.minimaxi.com` host.
28
+ */
29
+ const CONSOLE = 'https://platform.minimax.cn/console/usage'
30
+
31
+ /**
32
+ * MiniMax publishes its live status on an Atlassian Statuspage. Verified
33
+ * 2026-11-06 against `/api/v2/status.json`.
34
+ */
35
+ const STATUS = Object.freeze({
36
+ endpoint: 'https://status.minimaxi.com/api/v2/status.json',
37
+ url: 'https://status.minimaxi.com',
38
+ parse: statuspageView,
39
+ })
40
+
41
+ /**
42
+ * Normalize a model name for matching.
43
+ *
44
+ * DSH's provider-owned model id and MiniMax's `model_name` come from different
45
+ * catalogs — `MiniMax-M2` and `general`, for instance — so the comparison
46
+ * ignores case and separators before falling back to a substring match.
47
+ *
48
+ * @param {unknown} value Raw model name.
49
+ * @returns {string} Normalized name, or an empty string.
50
+ */
51
+ function normalizeModelName(value) {
52
+ return typeof value === 'string' ? value.toLowerCase().replace(/[^a-z0-9]+/g, '') : ''
53
+ }
54
+
55
+ /**
56
+ * The model name one plan entry declares.
57
+ * @param {Record<string, unknown>} plan One `model_remains` entry.
58
+ * @returns {string} The name, or an empty string.
59
+ */
60
+ function planName(plan) {
61
+ for (const key of ['model_name', 'model', 'model_id']) {
62
+ if (typeof plan[key] === 'string' && plan[key] !== '') return /** @type {string} */ (plan[key])
63
+ }
64
+ return ''
65
+ }
66
+
67
+ /**
68
+ * The remaining share a plan entry reports, used to pick the most constrained
69
+ * entry when the caller's model matches none.
70
+ * @param {Record<string, unknown>} plan One plan entry.
71
+ * @returns {number} Remaining percent, or Infinity when the entry reports none.
72
+ */
73
+ function constraintOf(plan) {
74
+ if (typeof plan.current_interval_remaining_percent === 'number') {
75
+ return plan.current_interval_remaining_percent
76
+ }
77
+ if (typeof plan.current_weekly_remaining_percent === 'number') {
78
+ return plan.current_weekly_remaining_percent
79
+ }
80
+ return Number.POSITIVE_INFINITY
81
+ }
82
+
83
+ /**
84
+ * Pick the plan entry the badge should speak for.
85
+ *
86
+ * The session's model is authoritative when it matches an entry. A provider
87
+ * id such as `MiniMax-M2` rarely equals MiniMax's own bucket name, so an exact
88
+ * normalized match is followed by a substring match. With no match — and for
89
+ * callers that only know the route — the canonical `general` plan is preferred
90
+ * (MiniMax reports `video` beside it on the same account), then the most
91
+ * constrained entry. This keeps the reading deterministic instead of
92
+ * depending on response order.
93
+ *
94
+ * @param {Record<string, unknown>[]} plans Usable plan entries.
95
+ * @param {string | undefined} model Provider-owned model id, when known.
96
+ * @returns {Record<string, unknown>} The chosen entry.
97
+ */
98
+ function pickPlan(plans, model) {
99
+ const wanted = normalizeModelName(model)
100
+ if (wanted !== '') {
101
+ const exact = plans.find((plan) => normalizeModelName(planName(plan)) === wanted)
102
+ if (exact !== undefined) return exact
103
+ const partial = plans.find((plan) => {
104
+ const name = normalizeModelName(planName(plan))
105
+ return name !== '' && (name.includes(wanted) || wanted.includes(name))
106
+ })
107
+ if (partial !== undefined) return partial
108
+ }
109
+ const general = plans.find((plan) => normalizeModelName(planName(plan)) === 'general')
110
+ if (general !== undefined) return general
111
+ return plans.reduce(
112
+ (best, plan) => (constraintOf(plan) < constraintOf(best) ? plan : best),
113
+ plans[0],
114
+ )
115
+ }
116
+
117
+ /**
118
+ * Project one MiniMax plan body.
119
+ *
120
+ * A model bucket carries an interval window and a weekly window, each with its
121
+ * own status flag. A zero status means that window does not apply to this
122
+ * account (an old plan without a weekly limit, for instance), so its
123
+ * percentage must be skipped rather than reported as `0%` left.
124
+ *
125
+ * @param {{route: string, body: Record<string, unknown>, model?: string}} env Projection context.
126
+ * @returns {import('../providers.js').BalanceView} The reading.
127
+ */
128
+ function readTokenPlan({ route, body, model }) {
129
+ const base = asObject(body.base_resp)
130
+ if (typeof base.status_code === 'number' && base.status_code !== 0) {
131
+ return {
132
+ provider: route,
133
+ status: 'failed',
134
+ kind: KIND_QUOTA,
135
+ error: String(base.status_msg ?? base.status_code),
136
+ }
137
+ }
138
+ const plans = (Array.isArray(body.model_remains) ? body.model_remains : [])
139
+ .map((plan) => asObject(plan))
140
+ .filter((plan) => planName(plan) !== '' || constraintOf(plan) !== Number.POSITIVE_INFINITY)
141
+ if (plans.length === 0) {
142
+ return { provider: route, status: 'failed', kind: KIND_QUOTA, error: 'no plan in response' }
143
+ }
144
+ const best = pickPlan(plans, model)
145
+
146
+ /** A window is active unless its status flag explicitly says otherwise. */
147
+ const activeWindow = (status) => status === undefined || status === null || status !== 0
148
+
149
+ /**
150
+ * Project one MiniMax window onto the shared shape.
151
+ * @param {string} id Window identity.
152
+ * @param {string} prefix Field prefix, `current_interval` or `current_weekly`.
153
+ * @param {string} startKey Start timestamp field.
154
+ * @param {string} endKey End timestamp field.
155
+ * @param {string} percentKey Remaining-percent field.
156
+ * @param {string} statusKey Window status flag.
157
+ * @returns {import('./shared.js').BalanceWindow | undefined} The window, when the plan reports it.
158
+ */
159
+ const windowOf = (id, prefix, startKey, endKey, percentKey, statusKey) => {
160
+ if (!activeWindow(best[statusKey])) return undefined
161
+ const end = parseAmount(best[endKey])
162
+ const start = parseAmount(best[startKey])
163
+ const remainingPercent = parseAmount(best[percentKey])
164
+ if (end === undefined && remainingPercent === undefined) return undefined
165
+ const length = windowLength(end !== undefined && start !== undefined ? end - start : undefined)
166
+ // The coding plan reports percentage only; the count fields are zero
167
+ // unless the account also meters by request count.
168
+ const total = parseAmount(best[`${prefix}_total_count`])
169
+ const used = parseAmount(best[`${prefix}_usage_count`])
170
+ return {
171
+ id,
172
+ ...length,
173
+ ...(total !== undefined && total > 0 ? { total, used: used ?? 0 } : {}),
174
+ ...(remainingPercent === undefined ? {} : { remainingPercent }),
175
+ ...(end === undefined ? {} : { resetAt: end }),
176
+ }
177
+ }
178
+
179
+ const windows = /** @type {import('./shared.js').BalanceWindow[]} */ (
180
+ [
181
+ windowOf(
182
+ 'session',
183
+ 'current_interval',
184
+ 'start_time',
185
+ 'end_time',
186
+ 'current_interval_remaining_percent',
187
+ 'current_interval_status',
188
+ ),
189
+ windowOf(
190
+ 'weekly',
191
+ 'current_weekly',
192
+ 'weekly_start_time',
193
+ 'weekly_end_time',
194
+ 'current_weekly_remaining_percent',
195
+ 'current_weekly_status',
196
+ ),
197
+ ].filter((window) => window !== undefined)
198
+ )
199
+
200
+ if (windows.length === 0) {
201
+ return { provider: route, status: 'failed', kind: KIND_QUOTA, error: 'no usage in response' }
202
+ }
203
+ const binding = bindingWindow(windows)
204
+ const session = windows.find((window) => window.id === 'session')
205
+ // The badge speaks for the short interval window; the top-level fields are
206
+ // its fallback when a reader ignores `windows`.
207
+ const percent = session?.remainingPercent ?? binding?.remainingPercent
208
+ const resetsAt = session?.resetAt ?? binding?.resetAt
209
+ return {
210
+ provider: route,
211
+ status: 'ready',
212
+ kind: KIND_QUOTA,
213
+ remainingMs: parseAmount(best.remains_time),
214
+ ...(percent === undefined ? {} : { percent }),
215
+ ...(resetsAt === undefined ? {} : { resetsAt }),
216
+ windows,
217
+ consoleUrl: CONSOLE,
218
+ }
219
+ }
220
+
221
+ /** MiniMax's coding-plan route. */
222
+ export const minimaxAdapters = [
223
+ defineAdapter({
224
+ id: 'minimax-token-plan',
225
+ routes: ['minimax-cn'],
226
+ kind: KIND_QUOTA,
227
+ modelScoped: true,
228
+ endpoint: 'https://api.minimaxi.com/v1/token_plan/remains',
229
+ auth: 'bearer',
230
+ credentialRefs: ['MINIMAX_CN_API_KEY'],
231
+ read: readTokenPlan,
232
+ consoleUrl: CONSOLE,
233
+ status: STATUS,
234
+ display: {
235
+ name: { zh: 'MiniMax', en: 'MiniMax' },
236
+ mark: { icon: 'minimax', color: '#e21680' },
237
+ },
238
+ fixtures: [
239
+ {
240
+ name: 'recorded five-hour and weekly windows',
241
+ response: {
242
+ model_remains: [
243
+ {
244
+ start_time: 1793937039924,
245
+ end_time: 1793937039924 + 5 * 3_600_000,
246
+ remains_time: 16380448,
247
+ current_interval_total_count: 0,
248
+ current_interval_usage_count: 0,
249
+ current_interval_remaining_percent: 82,
250
+ weekly_start_time: 1793727425969,
251
+ weekly_end_time: 1793727425969 + 7 * 86_400_000,
252
+ weekly_remains_time: 393566493,
253
+ current_weekly_total_count: 0,
254
+ current_weekly_usage_count: 0,
255
+ current_weekly_remaining_percent: 66,
256
+ },
257
+ ],
258
+ base_resp: { status_code: 0, status_msg: 'success' },
259
+ },
260
+ apiKey: 'sk-cp-test',
261
+ expect: {
262
+ status: 'ready',
263
+ kind: KIND_QUOTA,
264
+ percent: 82,
265
+ // Two windows, and the long one is seven days — calling it a month
266
+ // would be wrong.
267
+ windows: [
268
+ {
269
+ id: 'session',
270
+ unit: 'hour',
271
+ count: 5,
272
+ remainingPercent: 82,
273
+ resetAt: 1793937039924 + 5 * 3_600_000,
274
+ },
275
+ {
276
+ id: 'weekly',
277
+ unit: 'day',
278
+ count: 7,
279
+ remainingPercent: 66,
280
+ resetAt: 1793727425969 + 7 * 86_400_000,
281
+ },
282
+ ],
283
+ },
284
+ // A coding-plan key reports no request counts, so no used/total is invented.
285
+ absent: ['windows[0].total', 'windows[1].total'],
286
+ },
287
+ {
288
+ name: 'multiple model buckets choose the requested model',
289
+ response: {
290
+ model_remains: [
291
+ {
292
+ model_name: 'video',
293
+ start_time: 1793937039924,
294
+ end_time: 1793937039924 + 2 * 3_600_000,
295
+ current_interval_status: 1,
296
+ current_interval_remaining_percent: 100,
297
+ current_weekly_status: 1,
298
+ weekly_start_time: 1793727425969,
299
+ weekly_end_time: 1793727425969 + 7 * 86_400_000,
300
+ current_weekly_remaining_percent: 100,
301
+ },
302
+ {
303
+ model_name: 'general',
304
+ start_time: 1793937039924,
305
+ end_time: 1793937039924 + 5 * 3_600_000,
306
+ current_interval_status: 1,
307
+ current_interval_remaining_percent: 98,
308
+ current_weekly_status: 1,
309
+ weekly_start_time: 1793727425969,
310
+ weekly_end_time: 1793727425969 + 7 * 86_400_000,
311
+ current_weekly_remaining_percent: 67,
312
+ },
313
+ ],
314
+ base_resp: { status_code: 0, status_msg: 'success' },
315
+ },
316
+ apiKey: 'sk-cp-test',
317
+ // The session model (MiniMax-M2) does not equal MiniMax's own bucket
318
+ // names; `general` is the canonical text plan beside `video`.
319
+ model: 'MiniMax-M2',
320
+ expect: {
321
+ status: 'ready',
322
+ percent: 98,
323
+ windows: [
324
+ { id: 'session', remainingPercent: 98 },
325
+ { id: 'weekly', remainingPercent: 67 },
326
+ ],
327
+ },
328
+ },
329
+ {
330
+ name: 'a model name that matches a non-canonical bucket wins',
331
+ response: {
332
+ model_remains: [
333
+ {
334
+ model_name: 'general',
335
+ current_interval_remaining_percent: 98,
336
+ current_interval_status: 1,
337
+ },
338
+ {
339
+ model_name: 'video',
340
+ current_interval_remaining_percent: 40,
341
+ current_interval_status: 1,
342
+ },
343
+ ],
344
+ base_resp: { status_code: 0, status_msg: 'success' },
345
+ },
346
+ apiKey: 'sk-cp-test',
347
+ model: 'video',
348
+ expect: { status: 'ready', percent: 40 },
349
+ },
350
+ {
351
+ name: 'an inactive weekly window is omitted',
352
+ response: {
353
+ model_remains: [
354
+ {
355
+ model_name: 'general',
356
+ start_time: 1793937039924,
357
+ end_time: 1793937039924 + 5 * 3_600_000,
358
+ current_interval_status: 1,
359
+ current_interval_remaining_percent: 80,
360
+ current_weekly_status: 0,
361
+ weekly_end_time: 1793727425969 + 7 * 86_400_000,
362
+ current_weekly_remaining_percent: 0,
363
+ },
364
+ ],
365
+ base_resp: { status_code: 0, status_msg: 'success' },
366
+ },
367
+ apiKey: 'sk-cp-test',
368
+ expect: {
369
+ status: 'ready',
370
+ percent: 80,
371
+ windows: [{ id: 'session', remainingPercent: 80 }],
372
+ },
373
+ // A window the plan marks inactive must not read as 0% left.
374
+ absent: ['windows[1]'],
375
+ },
376
+ {
377
+ name: 'plan rejected',
378
+ response: { base_resp: { status_code: 1004, status_msg: 'invalid api key' } },
379
+ expect: { status: 'failed', error: 'invalid api key' },
380
+ },
381
+ ],
382
+ }),
383
+ ]
@@ -0,0 +1,209 @@
1
+ /**
2
+ * OpenCode Go adapter.
3
+ *
4
+ * The Go plan meters three windows and reports each as the share already
5
+ * spent — the opposite direction of every other vendor this plugin reads —
6
+ * plus the instant it resets. `GET /zen/go/v1/usage` is the only endpoint the
7
+ * plan answers; its sibling paths return 404 even with a valid key.
8
+ */
9
+
10
+ import {
11
+ asObject,
12
+ bindingWindow,
13
+ defineAdapter,
14
+ KIND_QUOTA,
15
+ parseAmount,
16
+ parseInstant,
17
+ } from './shared.js'
18
+ import { normalizeState, STATUS_OPERATIONAL, STATUS_UNKNOWN } from './status.js'
19
+
20
+ /** The Go plan page, where the plan itself is managed. Verified 2026-11-06. */
21
+ const CONSOLE = 'https://opencode.ai/go'
22
+
23
+ /**
24
+ * OpenCode published its own status API, and it names Go as a component —
25
+ * which is the plan this adapter reads. Verified 2026-11-06; the overall
26
+ * `status` is the answer, and the per-service components explain it.
27
+ *
28
+ * @type {{endpoint: string, url: string, parse: (env: {json?: unknown}) => {state: string, summary?: string}}}
29
+ */
30
+ const STATUS = Object.freeze({
31
+ endpoint: 'https://status.opencode.ai/api/status',
32
+ url: 'https://status.opencode.ai',
33
+ parse: parseStatus,
34
+ })
35
+
36
+ /**
37
+ * Project one OpenCode status body.
38
+ *
39
+ * The degraded components are the useful part of the answer — "go · upstream"
40
+ * says what is wrong where, which the single overall word cannot.
41
+ *
42
+ * @param {{json?: unknown}} env Source payload.
43
+ * @returns {{state: string, summary?: string}} The projected reading.
44
+ */
45
+ function parseStatus({ json }) {
46
+ const body = asObject(json)
47
+ const state = normalizeState(body.status) ?? STATUS_UNKNOWN
48
+ /** @type {string[]} */
49
+ const affected = []
50
+ for (const entry of Array.isArray(body.components) ? body.components : []) {
51
+ const record = asObject(entry)
52
+ const componentState = normalizeState(record.status)
53
+ if (componentState === undefined || componentState === STATUS_OPERATIONAL) continue
54
+ const service = typeof record.service === 'string' ? record.service : ''
55
+ const reason =
56
+ typeof record.reason === 'string' && record.reason !== '' && record.reason !== 'none'
57
+ ? record.reason
58
+ : ''
59
+ const label = service === '' ? reason : reason === '' ? service : `${service} · ${reason}`
60
+ if (label !== '') affected.push(label)
61
+ }
62
+ return {
63
+ state,
64
+ ...(affected.length === 0 || state === STATUS_OPERATIONAL
65
+ ? {}
66
+ : { summary: affected.join(', ') }),
67
+ }
68
+ }
69
+
70
+ /**
71
+ * The three windows the Go plan meters, in display order, with the length
72
+ * each one names. `rolling` is the plan's short window; the docs call it 5
73
+ * hours.
74
+ * @type {ReadonlyArray<readonly [string, {id: string, unit: 'hour'|'week'|'month', count?: number}]>}
75
+ */
76
+ const WINDOWS = [
77
+ ['rolling', { id: 'session', unit: 'hour', count: 5 }],
78
+ ['weekly', { id: 'weekly', unit: 'week' }],
79
+ ['monthly', { id: 'monthly', unit: 'month' }],
80
+ ]
81
+
82
+ /**
83
+ * Project one OpenCode Go usage body.
84
+ * @param {{route: string, body: Record<string, unknown>}} env Projection context.
85
+ * @returns {import('../providers.js').BalanceView} The reading.
86
+ */
87
+ function readUsage({ route, body }) {
88
+ const usage = asObject(body.usage)
89
+ /** @type {import('./shared.js').BalanceWindow[]} */
90
+ const windows = []
91
+ for (const [key, shape] of WINDOWS) {
92
+ const entry = asObject(usage[key])
93
+ const spent = parseAmount(entry.percent)
94
+ if (spent === undefined) continue
95
+ const resetAt = parseInstant(entry.resetsAt)
96
+ windows.push({
97
+ ...shape,
98
+ // `percent` here is what was spent; the shared shape carries what is
99
+ // left.
100
+ remainingPercent: Math.max(0, 100 - spent),
101
+ ...(resetAt === undefined ? {} : { resetAt }),
102
+ })
103
+ }
104
+ if (windows.length === 0) {
105
+ return { provider: route, status: 'failed', kind: KIND_QUOTA, error: 'no usage in response' }
106
+ }
107
+ const binding = bindingWindow(windows)
108
+ return {
109
+ provider: route,
110
+ status: 'ready',
111
+ kind: KIND_QUOTA,
112
+ ...(binding?.remainingPercent === undefined ? {} : { percent: binding.remainingPercent }),
113
+ ...(binding?.resetAt === undefined ? {} : { resetsAt: binding.resetAt }),
114
+ windows,
115
+ consoleUrl: CONSOLE,
116
+ }
117
+ }
118
+
119
+ /** OpenCode Go's route. */
120
+ export const opencodeAdapters = [
121
+ defineAdapter({
122
+ id: 'opencode-go',
123
+ routes: ['opencode-go'],
124
+ kind: KIND_QUOTA,
125
+ endpoint: 'https://opencode.ai/zen/go/v1/usage',
126
+ auth: 'bearer',
127
+ // The catalog names OPENCODE_API_KEY for this route; the plan's own
128
+ // documentation names OPENCODE_GO_API_KEY. Both are tried, the catalog
129
+ // first, because the name has already drifted once.
130
+ credentialRefs: ['OPENCODE_API_KEY', 'OPENCODE_GO_API_KEY'],
131
+ read: readUsage,
132
+ consoleUrl: CONSOLE,
133
+ status: STATUS,
134
+ display: {
135
+ name: { zh: 'OpenCode Go', en: 'OpenCode Go' },
136
+ mark: { icon: 'opencode', color: '#64748b' },
137
+ },
138
+ fixtures: [
139
+ {
140
+ name: 'recorded three windows',
141
+ response: {
142
+ usage: {
143
+ rolling: { status: 'ok', percent: 1, resetsAt: '2026-08-14T06:44:12.569Z' },
144
+ weekly: { status: 'ok', percent: 12, resetsAt: '2026-08-17T00:00:00.569Z' },
145
+ monthly: { status: 'ok', percent: 35, resetsAt: '2026-08-30T02:03:31.569Z' },
146
+ },
147
+ },
148
+ apiKey: 'sk-test',
149
+ expect: {
150
+ status: 'ready',
151
+ kind: KIND_QUOTA,
152
+ // The monthly window is the binding one at 35% spent.
153
+ percent: 65,
154
+ windows: [
155
+ {
156
+ id: 'session',
157
+ unit: 'hour',
158
+ count: 5,
159
+ remainingPercent: 99,
160
+ resetAt: Date.parse('2026-08-14T06:44:12.569Z'),
161
+ },
162
+ {
163
+ id: 'weekly',
164
+ unit: 'week',
165
+ remainingPercent: 88,
166
+ resetAt: Date.parse('2026-08-17T00:00:00.569Z'),
167
+ },
168
+ {
169
+ id: 'monthly',
170
+ unit: 'month',
171
+ remainingPercent: 65,
172
+ resetAt: Date.parse('2026-08-30T02:03:31.569Z'),
173
+ },
174
+ ],
175
+ },
176
+ },
177
+ {
178
+ name: 'exhausted window clamps at zero',
179
+ response: {
180
+ usage: {
181
+ rolling: { status: 'ok', percent: 140, resetsAt: '2026-08-14T06:44:12.569Z' },
182
+ monthly: { status: 'capped', percent: 70 },
183
+ },
184
+ },
185
+ expect: {
186
+ status: 'ready',
187
+ percent: 0,
188
+ windows: [
189
+ {
190
+ id: 'session',
191
+ unit: 'hour',
192
+ count: 5,
193
+ remainingPercent: 0,
194
+ resetAt: Date.parse('2026-08-14T06:44:12.569Z'),
195
+ },
196
+ { id: 'monthly', unit: 'month', remainingPercent: 30 },
197
+ ],
198
+ },
199
+ // A window that reports no reset instant must not invent one.
200
+ absent: ['windows[1].resetAt'],
201
+ },
202
+ {
203
+ name: 'key rejected',
204
+ httpStatus: 401,
205
+ expect: { status: 'failed', error: 'HTTP 401' },
206
+ },
207
+ ],
208
+ }),
209
+ ]