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.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Xiaomi MiMo adapters.
3
+ *
4
+ * Two authorizations exist and they do not mix: the pay-as-you-go route reads
5
+ * the account wallet with an `sk-` key, and each Token Plan cluster reads its
6
+ * subscription credits with a region-scoped `tp-` key. A plan key asked for the
7
+ * wallet answers 401, so every route keeps its own credential.
8
+ *
9
+ * The wallet reports one `balance_infos` entry whose `total_available` already
10
+ * sums cash, gift, and available credit with the frozen part added back — the
11
+ * reading takes that figure instead of adding the components itself.
12
+ *
13
+ * The plan reports one credit quota per billing period. The period timestamps
14
+ * are UTC wall clocks without a zone marker, so they are parsed as UTC here
15
+ * rather than through the shared local-time reader.
16
+ */
17
+
18
+ import { defineSchedule } from './schedule.js'
19
+ import {
20
+ asObject,
21
+ defineAdapter,
22
+ KIND_AMOUNT,
23
+ KIND_QUOTA,
24
+ parseAmount,
25
+ windowLength,
26
+ } from './shared.js'
27
+
28
+ /** MiMo's wallet page. Verified 2026-11-16. */
29
+ const BALANCE_CONSOLE = 'https://platform.xiaomimimo.com/console/balance'
30
+
31
+ /** MiMo's plan management page. Verified 2026-11-16. */
32
+ const PLAN_CONSOLE = 'https://platform.xiaomimimo.com/console/plan-manage'
33
+
34
+ /**
35
+ * The CN plan consumes credits at 0.8x between 00:00 and 08:00 Beijing time
36
+ * every day, so the peak window — full-rate consumption — runs 08:00 to
37
+ * midnight, every day of the week.
38
+ */
39
+ const CN_SCHEDULE = defineSchedule({
40
+ timezone: 'Asia/Shanghai',
41
+ timezoneLabel: { zh: '北京时间', en: 'Beijing time' },
42
+ days: [0, 1, 2, 3, 4, 5, 6],
43
+ windows: [{ from: '08:00', to: '24:00' }],
44
+ holidays: [],
45
+ note: {
46
+ zh: '低谷时段(每日 00:00–08:00)积分按 0.8 倍消耗',
47
+ en: 'Credits are consumed at 0.8x off-peak, daily 00:00–08:00',
48
+ },
49
+ })
50
+
51
+ /**
52
+ * Project one MiMo wallet body.
53
+ * @param {{route: string, body: Record<string, unknown>}} env Projection context.
54
+ * @returns {import('../providers.js').BalanceView} The reading.
55
+ */
56
+ function readBalance({ route, body }) {
57
+ const infos = Array.isArray(body.balance_infos) ? body.balance_infos : []
58
+ if (infos.length === 0) {
59
+ return { provider: route, status: 'failed', kind: KIND_AMOUNT, error: 'no balance in response' }
60
+ }
61
+ const primary = asObject(infos[0])
62
+ const amount = parseAmount(primary.total_available)
63
+ if (amount === undefined) {
64
+ return { provider: route, status: 'failed', kind: KIND_AMOUNT, error: 'no balance in response' }
65
+ }
66
+ const currency = typeof primary.currency === 'string' ? primary.currency : 'CNY'
67
+ return {
68
+ provider: route,
69
+ status: 'ready',
70
+ kind: KIND_AMOUNT,
71
+ amount,
72
+ currency,
73
+ consoleUrl: BALANCE_CONSOLE,
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Parse a MiMo period timestamp: `YYYY-MM-DD HH:mm:ss` in UTC, with no zone
79
+ * marker. The shared instant reader would take it as host local time and shift
80
+ * the reset by the host's offset, so the zone is pinned here.
81
+ * @param {unknown} value Raw timestamp.
82
+ * @returns {number | undefined} Epoch milliseconds, or undefined when unparsable.
83
+ */
84
+ function parseUtcInstant(value) {
85
+ if (typeof value !== 'string') return undefined
86
+ const text = value.trim()
87
+ if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(text)) return undefined
88
+ const parsed = Date.parse(`${text.replace(' ', 'T')}Z`)
89
+ return Number.isFinite(parsed) ? parsed : undefined
90
+ }
91
+
92
+ /**
93
+ * Project one MiMo Token Plan body.
94
+ *
95
+ * The plan meters a single billing period, so the reading carries one window:
96
+ * the period's credits with its closing instant as the reset. A missing period
97
+ * still reports the quota, as an unsized window.
98
+ *
99
+ * @param {{route: string, body: Record<string, unknown>}} env Projection context.
100
+ * @returns {import('../providers.js').BalanceView} The reading.
101
+ */
102
+ function readTokenPlan({ route, body }) {
103
+ const quota = asObject(body.quota)
104
+ const total = parseAmount(quota.total_credits)
105
+ if (total === undefined || total <= 0) {
106
+ return { provider: route, status: 'failed', kind: KIND_QUOTA, error: 'no quota in response' }
107
+ }
108
+ const used = parseAmount(quota.used_credits)
109
+ const remaining = parseAmount(quota.remaining_credits)
110
+ const remainingPercent = remaining === undefined ? undefined : (remaining / total) * 100
111
+ const period = asObject(body.period)
112
+ const start = parseUtcInstant(period.start_at)
113
+ const end = parseUtcInstant(period.end_at)
114
+ const window = {
115
+ id: 'monthly',
116
+ ...windowLength(start !== undefined && end !== undefined ? end - start : undefined),
117
+ total,
118
+ ...(used === undefined ? {} : { used }),
119
+ ...(remainingPercent === undefined ? {} : { remainingPercent }),
120
+ ...(end === undefined ? {} : { resetAt: end }),
121
+ }
122
+ return {
123
+ provider: route,
124
+ status: 'ready',
125
+ kind: KIND_QUOTA,
126
+ ...(remainingPercent === undefined ? {} : { percent: remainingPercent }),
127
+ ...(end === undefined ? {} : { resetsAt: end }),
128
+ windows: [window],
129
+ consoleUrl: PLAN_CONSOLE,
130
+ }
131
+ }
132
+
133
+ /** The recorded CN plan body, shared by the three cluster fixtures. */
134
+ const RECORDED_PLAN = {
135
+ object: 'token_plan',
136
+ plan_code: 'lite',
137
+ period: { start_at: '2026-11-16 06:42:34', end_at: '2026-12-16 23:59:59' },
138
+ quota: { total_credits: 4100000000, used_credits: 4042860, remaining_credits: 4095957140 },
139
+ auto_renew: false,
140
+ claw_enabled: false,
141
+ }
142
+
143
+ /** What the recorded plan body must project to, on any cluster. */
144
+ const RECORDED_PLAN_EXPECT = {
145
+ status: 'ready',
146
+ kind: KIND_QUOTA,
147
+ percent: (4095957140 / 4100000000) * 100,
148
+ // The period is a UTC wall clock: reading it as local time would shift the
149
+ // reset by the host's offset and fail here.
150
+ resetsAt: Date.parse('2026-12-16T23:59:59Z'),
151
+ windows: [
152
+ {
153
+ id: 'monthly',
154
+ unit: 'month',
155
+ count: 1,
156
+ total: 4100000000,
157
+ used: 4042860,
158
+ remainingPercent: (4095957140 / 4100000000) * 100,
159
+ resetAt: Date.parse('2026-12-16T23:59:59Z'),
160
+ },
161
+ ],
162
+ }
163
+
164
+ /**
165
+ * Declare one Token Plan cluster adapter. The clusters share the projection
166
+ * and differ only in endpoint, credential, and name.
167
+ * @param {object} spec Cluster specification.
168
+ * @param {string} spec.id Adapter identity.
169
+ * @param {string} spec.cluster Cluster host prefix, e.g. `token-plan-cn`.
170
+ * @param {string} spec.credentialRef Credential reference for the bare-host fallback.
171
+ * @param {{zh: string, en: string}} spec.name Display name.
172
+ * @param {import('./schedule.js').Schedule} [spec.schedule] Pricing schedule, when this cluster has one.
173
+ * @param {readonly import('./shared.js').AdapterFixture[]} [spec.extraFixtures] Additional fixtures for this cluster.
174
+ * @returns {import('../providers.js').ProviderAdapter} The adapter.
175
+ */
176
+ function tokenPlanAdapter({ id, cluster, credentialRef, name, schedule, extraFixtures = [] }) {
177
+ return defineAdapter({
178
+ id,
179
+ routes: [id],
180
+ kind: KIND_QUOTA,
181
+ endpoint: `https://${cluster}.xiaomimimo.com/v1/platform/token_plan`,
182
+ auth: 'bearer',
183
+ credentialRefs: [credentialRef],
184
+ read: readTokenPlan,
185
+ consoleUrl: PLAN_CONSOLE,
186
+ schedule,
187
+ display: {
188
+ name,
189
+ mark: { icon: 'xiaomi', color: '#1F2329' },
190
+ },
191
+ fixtures: [
192
+ {
193
+ name: 'recorded billing period',
194
+ response: RECORDED_PLAN,
195
+ apiKey: 'tp-test',
196
+ expect: RECORDED_PLAN_EXPECT,
197
+ },
198
+ ...extraFixtures,
199
+ ],
200
+ })
201
+ }
202
+
203
+ /** Xiaomi MiMo's wallet route and three Token Plan clusters. */
204
+ export const xiaomiAdapters = [
205
+ defineAdapter({
206
+ id: 'xiaomi',
207
+ routes: ['xiaomi'],
208
+ kind: KIND_AMOUNT,
209
+ endpoint: 'https://api.xiaomimimo.com/v1/platform/balance',
210
+ auth: 'bearer',
211
+ credentialRefs: ['XIAOMI_API_KEY'],
212
+ read: readBalance,
213
+ consoleUrl: BALANCE_CONSOLE,
214
+ display: {
215
+ name: { zh: 'Xiaomi MiMo', en: 'Xiaomi MiMo' },
216
+ mark: { icon: 'xiaomi', color: '#1F2329' },
217
+ },
218
+ fixtures: [
219
+ {
220
+ name: 'recorded wallet',
221
+ response: {
222
+ object: 'balance',
223
+ is_available: true,
224
+ balance_infos: [
225
+ {
226
+ currency: 'CNY',
227
+ cash_balance: '0.00',
228
+ gift_balance: '5.00',
229
+ frozen_balance: '0.00',
230
+ credit_limit: '0.00',
231
+ credit_available: '0.00',
232
+ total_available: '5.00',
233
+ },
234
+ ],
235
+ },
236
+ apiKey: 'sk-test',
237
+ // total_available already sums the components; the reading takes it whole.
238
+ expect: { status: 'ready', kind: KIND_AMOUNT, amount: 5, currency: 'CNY' },
239
+ },
240
+ {
241
+ name: 'empty balance list',
242
+ response: { object: 'balance', is_available: false, balance_infos: [] },
243
+ expect: { status: 'failed', error: 'no balance in response' },
244
+ },
245
+ {
246
+ name: 'key rejected',
247
+ httpStatus: 401,
248
+ expect: { status: 'failed', error: 'HTTP 401' },
249
+ },
250
+ ],
251
+ }),
252
+ tokenPlanAdapter({
253
+ id: 'xiaomi-token-plan-cn',
254
+ cluster: 'token-plan-cn',
255
+ credentialRef: 'XIAOMI_TOKEN_PLAN_CN_API_KEY',
256
+ name: { zh: 'Xiaomi MiMo Token Plan (国内)', en: 'Xiaomi MiMo Token Plan (CN)' },
257
+ schedule: CN_SCHEDULE,
258
+ // The projection is shared, so one cluster proving the failure paths
259
+ // proves all three.
260
+ extraFixtures: [
261
+ {
262
+ name: 'no quota in response',
263
+ response: { object: 'token_plan', plan_code: 'lite' },
264
+ expect: { status: 'failed', error: 'no quota in response' },
265
+ },
266
+ {
267
+ name: 'key rejected',
268
+ httpStatus: 401,
269
+ expect: { status: 'failed', error: 'HTTP 401' },
270
+ },
271
+ ],
272
+ }),
273
+ tokenPlanAdapter({
274
+ id: 'xiaomi-token-plan-ams',
275
+ cluster: 'token-plan-ams',
276
+ credentialRef: 'XIAOMI_TOKEN_PLAN_AMS_API_KEY',
277
+ name: { zh: 'Xiaomi MiMo Token Plan (阿姆斯特丹)', en: 'Xiaomi MiMo Token Plan (AMS)' },
278
+ }),
279
+ tokenPlanAdapter({
280
+ id: 'xiaomi-token-plan-sgp',
281
+ cluster: 'token-plan-sgp',
282
+ credentialRef: 'XIAOMI_TOKEN_PLAN_SGP_API_KEY',
283
+ name: { zh: 'Xiaomi MiMo Token Plan (新加坡)', en: 'Xiaomi MiMo Token Plan (SGP)' },
284
+ }),
285
+ ]
package/lib/providers.js CHANGED
@@ -7,10 +7,11 @@
7
7
  * one file under `lib/providers/`, so adding a vendor is adding a file: this
8
8
  * module only collects them and answers "which adapter serves this route".
9
9
  *
10
- * The quantity a provider reports is not always money. DeepSeek reports a
11
- * currency balance; MiniMax (CN), Zhipu ZAI, Kimi Coding, and OpenCode Go
12
- * report a subscription allowance. The `kind` field keeps the two apart so
13
- * the UI can say the right thing.
10
+ * The quantity a provider reports is not always money. DeepSeek and Xiaomi
11
+ * MiMo's pay-as-you-go route report a currency balance; MiniMax (CN), Zhipu
12
+ * ZAI, Kimi Coding, OpenCode Go, and MiMo's Token Plan clusters report a
13
+ * subscription allowance. The `kind` field keeps the two apart so the UI can
14
+ * say the right thing.
14
15
  */
15
16
 
16
17
  import { deepseekAdapters } from './providers/deepseek.js'
@@ -50,12 +51,9 @@ import {
50
51
  typesafeAdapters,
51
52
  vercelAiGatewayAdapters,
52
53
  xaiAdapters,
53
- xiaomiAdapters,
54
- xiaomiTokenPlanAmsAdapters,
55
- xiaomiTokenPlanCnAdapters,
56
- xiaomiTokenPlanSgpAdapters,
57
54
  } from './providers/placeholder.js'
58
55
  import { KIND_AMOUNT, KIND_QUOTA } from './providers/shared.js'
56
+ import { xiaomiAdapters } from './providers/xiaomi.js'
59
57
  import { zaiAdapters } from './providers/zai.js'
60
58
 
61
59
  /**
@@ -98,7 +96,7 @@ import { zaiAdapters } from './providers/zai.js'
98
96
  * another id, so a reading for one of them answers through this adapter.
99
97
  * @property {'amount'|'quota'} kind Quantity dimension of the reading.
100
98
  * @property {boolean} [modelScoped] Whether the reading is per provider-owned model.
101
- * @property {string} consoleUrl Provider console for a manual check.
99
+ * @property {string} [consoleUrl] Provider console for a manual check.
102
100
  * @property {string} [service] Host service this adapter reads through, when it needs no key.
103
101
  * @property {{endpoint: string, auth: 'bearer'|'raw'}} [http] Endpoint and signing
104
102
  * style, when the service performs the request.
@@ -128,6 +126,7 @@ export const PROVIDER_ADAPTERS = Object.freeze([
128
126
  ...zaiAdapters,
129
127
  ...kimiCodingAdapters,
130
128
  ...opencodeGoAdapters,
129
+ ...xiaomiAdapters,
131
130
  // Placeholder adapters (unsupported status)
132
131
  ...amazonBedrockAdapters,
133
132
  ...antLingAdapters,
@@ -161,10 +160,6 @@ export const PROVIDER_ADAPTERS = Object.freeze([
161
160
  ...typesafeAdapters,
162
161
  ...vercelAiGatewayAdapters,
163
162
  ...xaiAdapters,
164
- ...xiaomiAdapters,
165
- ...xiaomiTokenPlanAmsAdapters,
166
- ...xiaomiTokenPlanCnAdapters,
167
- ...xiaomiTokenPlanSgpAdapters,
168
163
  ])
169
164
 
170
165
  /** Route to the adapter serving it, resolved once at load. */
package/lib/remote.js CHANGED
@@ -135,7 +135,9 @@ export class BalanceController extends TypertRemoteService {
135
135
  * @returns {Promise<import('./providers.js').BalanceView>} The reading.
136
136
  */
137
137
  async refresh(provider, model) {
138
- return await this.ctx.modelAllowance.read(provider, { force: true, model })
138
+ // A manual refresh is the user's click, not a background trigger: it must
139
+ // not be held back by the failure backoff the automatic reads use.
140
+ return await this.ctx.modelAllowance.read(provider, { force: true, model, bypassBackoff: true })
139
141
  }
140
142
 
141
143
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-model-allowance",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
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",
@@ -67,6 +67,7 @@
67
67
  "typecheck": "tsc --noEmit",
68
68
  "prepack": "npm run build"
69
69
  },
70
+ "packageManager": "pnpm@12.10.1",
70
71
  "devDependencies": {
71
72
  "@biomejs/biome": "^2.6.5",
72
73
  "@deepseek-ai/cordis": "^4.1.0",