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,185 @@
1
+ /**
2
+ * Zhipu adapter.
3
+ *
4
+ * Zhipu reports credit limits; it publishes no monetary balance. A limit
5
+ * carries `unit` (a length code) and `number` (how many of them), so
6
+ * `unit: 3, number: 5` is the 5-hour window and `unit: 6, number: 1` the
7
+ * weekly one. The quota itself is `usage`, and `currentValue` is what has been
8
+ * spent — not the other way round.
9
+ *
10
+ * Both the CN and international routes read through the CN monitor endpoint
11
+ * today. The routes differ only in the credential the harness stores for
12
+ * them, which the balance service now discovers per route.
13
+ */
14
+
15
+ import { defineSchedule } from './schedule.js'
16
+ import { asObject, bindingWindow, defineAdapter, KIND_QUOTA, parseAmount } from './shared.js'
17
+
18
+ /**
19
+ * Zhipu's coding-plan overview. Verified 2026-11-06 — Zhipu split API keys
20
+ * from plan keys in October 2026 and retired the old usercenter path.
21
+ */
22
+ const CONSOLE = 'https://bigmodel.cn/coding-plan/personal/overview'
23
+
24
+ /**
25
+ * The plan charges half the credits outside its peak windows, and the docs
26
+ * name them plainly: Monday to Friday, 14:00–18:00 UTC+8, with no holiday
27
+ * exception. Verified 2026-11-06 against the coding-plan overview.
28
+ *
29
+ * Both routes the adapter serves share this schedule: it is a property of the
30
+ * GLM Coding Plan, and the CN and international routes address the same plan
31
+ * family.
32
+ *
33
+ * @type {import('./schedule.js').Schedule}
34
+ */
35
+ const SCHEDULE = defineSchedule({
36
+ timezone: 'Asia/Shanghai',
37
+ timezoneLabel: { zh: '北京时间', en: 'Beijing time' },
38
+ days: [1, 2, 3, 4, 5],
39
+ windows: [{ from: '14:00', to: '18:00' }],
40
+ holidays: [],
41
+ note: { zh: '低谷时段积分按 50% 抵扣', en: 'Credits are halved off-peak' },
42
+ })
43
+
44
+ /**
45
+ * Project one Zhipu limit body.
46
+ * @param {{route: string, body: Record<string, unknown>}} env Projection context.
47
+ * @returns {import('../providers.js').BalanceView} The reading.
48
+ */
49
+ function readQuota({ route, body }) {
50
+ if (typeof body.code === 'number' && body.code !== 200) {
51
+ return {
52
+ provider: route,
53
+ status: 'failed',
54
+ kind: KIND_QUOTA,
55
+ error: String(body.msg ?? body.code),
56
+ }
57
+ }
58
+ const data = asObject(body.data)
59
+ const limits = Array.isArray(data.limits) ? data.limits : []
60
+ if (limits.length === 0) {
61
+ return { provider: route, status: 'failed', kind: KIND_QUOTA, error: 'no limits in response' }
62
+ }
63
+
64
+ /**
65
+ * Decode one limit entry.
66
+ * @param {Record<string, unknown>} limit One limit entry.
67
+ * @param {number} index Position, used for a stable identity.
68
+ * @returns {import('./shared.js').BalanceWindow} The window.
69
+ */
70
+ const windowOf = (limit, index) => {
71
+ const code = parseAmount(limit.unit)
72
+ const count = parseAmount(limit.number)
73
+ const unit = code === 3 ? 'hour' : code === 6 ? 'week' : 'unknown'
74
+ const total = parseAmount(limit.usage)
75
+ const used = parseAmount(limit.currentValue)
76
+ const spentPercent = parseAmount(limit.percentage)
77
+ const resetAt = parseAmount(limit.nextResetTime)
78
+ const id = unit === 'hour' ? 'session' : unit === 'week' ? 'weekly' : `limit-${String(index)}`
79
+ return {
80
+ id,
81
+ unit,
82
+ ...(count === undefined ? {} : { count }),
83
+ ...(used === undefined ? {} : { used }),
84
+ ...(total === undefined ? {} : { total }),
85
+ ...(spentPercent === undefined ? {} : { remainingPercent: 100 - spentPercent }),
86
+ ...(resetAt === undefined ? {} : { resetAt }),
87
+ }
88
+ }
89
+
90
+ const windows = limits.map((limit, index) => windowOf(asObject(limit), index))
91
+
92
+ // The most-spent window is the one that actually constrains the account.
93
+ const binding = bindingWindow(windows)
94
+
95
+ return {
96
+ provider: route,
97
+ status: 'ready',
98
+ kind: KIND_QUOTA,
99
+ ...(binding?.remainingPercent === undefined ? {} : { percent: binding.remainingPercent }),
100
+ ...(binding?.resetAt === undefined ? {} : { resetsAt: binding.resetAt }),
101
+ windows,
102
+ consoleUrl: CONSOLE,
103
+ }
104
+ }
105
+
106
+ /** Zhipu's coding-plan routes: the CN plan and the international route. */
107
+ export const zhipuAdapters = [
108
+ defineAdapter({
109
+ id: 'zhipu-quota',
110
+ routes: ['zai', 'zai-coding-cn'],
111
+ kind: KIND_QUOTA,
112
+ endpoint: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',
113
+ auth: 'raw',
114
+ credentialRefs: ['ZAI_API_KEY', 'ZAI_CODING_CN_API_KEY'],
115
+ read: readQuota,
116
+ consoleUrl: CONSOLE,
117
+ schedule: SCHEDULE,
118
+ display: {
119
+ name: { zh: '智谱 GLM', en: 'Zhipu GLM' },
120
+ mark: { icon: 'zhipu', color: '#5668f5' },
121
+ },
122
+ fixtures: [
123
+ {
124
+ name: 'recorded limits',
125
+ response: {
126
+ code: 200,
127
+ data: {
128
+ limits: [
129
+ {
130
+ type: 'CREDIT_LIMIT',
131
+ unit: 3,
132
+ number: 5,
133
+ usage: 2000,
134
+ currentValue: 0,
135
+ remaining: 2000,
136
+ percentage: 0,
137
+ },
138
+ {
139
+ type: 'CREDIT_LIMIT',
140
+ unit: 6,
141
+ number: 1,
142
+ usage: 10000,
143
+ currentValue: 10071,
144
+ remaining: 0,
145
+ percentage: 100,
146
+ nextResetTime: 1794305132998,
147
+ },
148
+ ],
149
+ level: 'lite',
150
+ },
151
+ },
152
+ apiKey: 'test-key',
153
+ expect: {
154
+ status: 'ready',
155
+ kind: KIND_QUOTA,
156
+ // The exhausted window is the binding constraint on the account.
157
+ percent: 0,
158
+ windows: [
159
+ {
160
+ id: 'session',
161
+ unit: 'hour',
162
+ count: 5,
163
+ total: 2000,
164
+ used: 0,
165
+ remainingPercent: 100,
166
+ },
167
+ {
168
+ id: 'weekly',
169
+ unit: 'week',
170
+ total: 10000,
171
+ used: 10071,
172
+ remainingPercent: 0,
173
+ resetAt: 1794305132998,
174
+ },
175
+ ],
176
+ },
177
+ },
178
+ {
179
+ name: 'envelope rejected',
180
+ response: { code: 1000, msg: 'token expired' },
181
+ expect: { status: 'failed', error: 'token expired' },
182
+ },
183
+ ],
184
+ }),
185
+ ]
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Provider balance adapters: the registry.
3
+ *
4
+ * Every adapter declares the routes it serves, the credential reference that
5
+ * authorizes the query, how the request is authenticated, and how the response
6
+ * is projected onto the shared {@link BalanceView} shape. One vendor lives in
7
+ * one file under `lib/providers/`, so adding a vendor is adding a file: this
8
+ * module only collects them and answers "which adapter serves this route".
9
+ *
10
+ * The quantity a provider reports is not always money. DeepSeek reports a
11
+ * currency balance; MiniMax, Zhipu, Kimi, and OpenCode report a subscription
12
+ * allowance. The `kind` field keeps the two apart so the UI can say the right
13
+ * thing.
14
+ */
15
+
16
+ import { deepseekAdapters } from './providers/deepseek.js'
17
+ import { kimiAdapters } from './providers/kimi.js'
18
+ import { minimaxAdapters } from './providers/minimax.js'
19
+ import { opencodeAdapters } from './providers/opencode.js'
20
+ import { KIND_AMOUNT, KIND_QUOTA } from './providers/shared.js'
21
+ import { zhipuAdapters } from './providers/zhipu.js'
22
+
23
+ /**
24
+ * @typedef {object} BalanceView
25
+ * @property {string} provider Route the reading belongs to.
26
+ * @property {'ready'|'unsupported'|'unconfigured'|'failed'} status Reading outcome.
27
+ * @property {'amount'|'quota'} kind Quantity dimension of the reading.
28
+ * @property {number} [amount] Monetary balance, for `kind === 'amount'`.
29
+ * @property {string} [currency] Currency of `amount`, e.g. `CNY`.
30
+ * @property {number} [remaining] Remaining allowance, for `kind === 'quota'`.
31
+ * @property {number} [total] Total allowance, for `kind === 'quota'`.
32
+ * @property {number} [percent] Remaining percentage, for `kind === 'quota'`.
33
+ * @property {number} [remainingMs] Remaining time in the reported window, in milliseconds.
34
+ * @property {number} [resetsAt] Epoch milliseconds of the next allowance reset.
35
+ * @property {readonly import('./providers/shared.js').BalanceWindow[]} [windows] Per-window detail for a metered plan.
36
+ * @property {{kind: 'amount'|'percent', delta: number, at: number}} [consumption] Movement since the previous reading.
37
+ * @property {string} [consoleUrl] Provider console for a manual top-up or quota check.
38
+ * @property {number} [updatedAt] Epoch milliseconds of the reading.
39
+ * @property {string} [error] Failure detail for `status === 'failed'`.
40
+ */
41
+
42
+ /**
43
+ * What a `readWithEnv` adapter may use to answer one reading.
44
+ * @typedef {object} AdapterEnv
45
+ * @property {string} route Provider route being read.
46
+ * @property {string | undefined} apiKey Resolved credential value, when the adapter needs one.
47
+ * @property {import('@deepseek-ai/cordis').Context} ctx Host context, for service-backed adapters.
48
+ * @property {AbortSignal} signal Cancellation.
49
+ * @property {string} [model] Provider-owned model id, when the caller knows it.
50
+ */
51
+
52
+ /**
53
+ * One declared provider adapter, as {@link defineAdapter} normalizes it.
54
+ * @typedef {object} ProviderAdapter
55
+ * @property {string} id Adapter identity.
56
+ * @property {readonly string[]} routes Provider routes this adapter serves.
57
+ * @property {'amount'|'quota'} kind Quantity dimension of the reading.
58
+ * @property {boolean} [modelScoped] Whether the reading is per provider-owned model.
59
+ * @property {string} consoleUrl Provider console for a manual check.
60
+ * @property {string} [service] Host service this adapter reads through, when it needs no key.
61
+ * @property {{endpoint: string, auth: 'bearer'|'raw'}} [http] Endpoint and signing
62
+ * style, when the service performs the request.
63
+ * @property {readonly string[]} credentialRefs Credential references to try when
64
+ * the harness cannot name one for the route.
65
+ * @property {{name: {zh: string, en: string}, mark: {icon?: string, color: string}}} display
66
+ * Display metadata the browser needs to name and draw the route.
67
+ * @property {{endpoint: string, url: string, parse: (env: {text?: string, json?: unknown}) => {state: string, summary?: string}}} [status]
68
+ * Live platform status source, when the vendor publishes one.
69
+ * @property {import('./providers/schedule.js').Schedule} [schedule]
70
+ * Time-of-day pricing schedule, when the vendor prices by wall clock.
71
+ * @property {(env: {route: string, apiKey: string, body: Record<string, unknown>, model?: string}) => BalanceView} [read]
72
+ * Projection for an endpoint adapter.
73
+ * @property {(env: AdapterEnv) => Promise<BalanceView>} [readWithEnv] Full read for an
74
+ * adapter that needs more than an API key, such as a Host service.
75
+ * @property {readonly object[]} fixtures Recorded responses proving the projection.
76
+ */
77
+
78
+ /**
79
+ * The registry of provider balance adapters, in switcher order.
80
+ * @type {readonly ProviderAdapter[]}
81
+ */
82
+ export const PROVIDER_ADAPTERS = Object.freeze([
83
+ ...deepseekAdapters,
84
+ ...minimaxAdapters,
85
+ ...zhipuAdapters,
86
+ ...kimiAdapters,
87
+ ...opencodeAdapters,
88
+ ])
89
+
90
+ /** Route to the adapter serving it, resolved once at load. */
91
+ const BY_ROUTE = new Map()
92
+ for (const adapter of PROVIDER_ADAPTERS) {
93
+ for (const route of adapter.routes) {
94
+ // Two adapters answering the same route would make a reading depend on
95
+ // load order; refuse the declaration instead.
96
+ if (BY_ROUTE.has(route)) {
97
+ throw new Error(`two provider adapters declare the route "${route}"`)
98
+ }
99
+ BY_ROUTE.set(route, adapter)
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Find the adapter serving one provider route.
105
+ * @param {string} route Provider route, e.g. `minimax-cn`.
106
+ * @returns {ProviderAdapter | undefined} The adapter, when one serves the route.
107
+ */
108
+ export function findAdapter(route) {
109
+ return BY_ROUTE.get(route)
110
+ }
111
+
112
+ export { KIND_AMOUNT, KIND_QUOTA }
package/lib/remote.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The Remote controller exposing balance readings to the browser.
3
+ *
4
+ * The controller is the only thing a browser can reach. It never returns a
5
+ * credential: a reading carries the amount or allowance, the outcome, and a
6
+ * console link.
7
+ */
8
+
9
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
10
+
11
+ /**
12
+ * Apply the protocol's `@Remote` marker to a method without decorator syntax.
13
+ *
14
+ * The decorator's first argument is the decorated method and its second is the
15
+ * decorator context. The protocol registers an initializer through the
16
+ * context, and that initializer writes the marker onto the service prototype.
17
+ * The protocol accepts an identical marker again, so applying it once per
18
+ * method is enough.
19
+ *
20
+ * @param {object} prototype Class prototype carrying the method.
21
+ * @param {string} method Name of the public instance method.
22
+ * @param {{mode?: 'stream'}} [options] Remote options.
23
+ * @returns {(instance: object) => void} Runs the captured initializer against an instance.
24
+ */
25
+ function markRemote(prototype, method, options) {
26
+ /** @type {Array<() => void>} */
27
+ const initializers = []
28
+ const context = /** @type {any} */ ({
29
+ name: method,
30
+ private: false,
31
+ static: false,
32
+ addInitializer(initializer) {
33
+ initializers.push(initializer)
34
+ },
35
+ })
36
+ const decorated = prototype[method]
37
+ // With options the protocol returns a decorator; without them it registers
38
+ // the marker directly. Both register through `context.addInitializer`.
39
+ if (options) {
40
+ Remote(options)(decorated, context)
41
+ } else {
42
+ Remote(decorated, context)
43
+ }
44
+ return (instance) => {
45
+ for (const initializer of initializers) initializer.call(instance)
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Balance readings for the current conversation's provider.
51
+ */
52
+ export class BalanceController extends TypertRemoteService {
53
+ /**
54
+ * @param {import('@deepseek-ai/cordis').Context} ctx Owning Cordis context.
55
+ */
56
+ constructor(ctx) {
57
+ super(ctx, 'balanceController', { namespace: 'balance' })
58
+ for (const apply of BalanceController.__applyRemoteMarkers) apply(this)
59
+ }
60
+
61
+ /**
62
+ * Advertise the wire capabilities this Host supports.
63
+ *
64
+ * A browser bundle can be newer than the Host process during an in-place
65
+ * plugin update. The client asks this before sending the optional `model`
66
+ * argument, so an older Host that only knows `(provider)` keeps working.
67
+ *
68
+ * @returns {Promise<{modelScoped: boolean}>} The capabilities.
69
+ */
70
+ async capabilities() {
71
+ return { modelScoped: true }
72
+ }
73
+
74
+ /**
75
+ * Read one provider's balance.
76
+ * @param {string} provider Provider route, e.g. `minimax-cn`.
77
+ * @param {string} [model] Provider-owned model id, when the session names one.
78
+ * @returns {Promise<import('./providers.js').BalanceView>} The reading.
79
+ */
80
+ async balance(provider, model) {
81
+ return await this.ctx.modelAllowance.read(provider, { model })
82
+ }
83
+
84
+ /**
85
+ * List the providers this installation can read, for the card's switcher.
86
+ * @returns {Promise<Array<{route: string, configured: boolean}>>} The routes.
87
+ */
88
+ async list() {
89
+ return await this.ctx.modelAllowance.list()
90
+ }
91
+
92
+ /**
93
+ * Read one provider's platform status.
94
+ *
95
+ * The card shows it beside the reading, so a number that failed to arrive
96
+ * can be told apart from a platform that is having a bad day.
97
+ *
98
+ * @param {string} provider Provider route.
99
+ * @returns {Promise<import('./status.js').StatusView>} The status reading.
100
+ */
101
+ async status(provider) {
102
+ return await this.ctx.modelAllowance.status(provider)
103
+ }
104
+
105
+ /**
106
+ * The pricing schedule a provider meters by, when it publishes one.
107
+ *
108
+ * The card turns it into a phase and a countdown locally, so this answer is
109
+ * stable data rather than a reading.
110
+ *
111
+ * @param {string} provider Provider route.
112
+ * @returns {Promise<object | null>} The schedule, or null.
113
+ */
114
+ async schedule(provider) {
115
+ return this.ctx.modelAllowance.schedule(provider)
116
+ }
117
+
118
+ /**
119
+ * The provider a session with no model selection would use.
120
+ *
121
+ * A session with no turns yet has no projection to read, and rendering
122
+ * nothing there would leave the composer without a badge until the first
123
+ * message. The installation's default model answers it.
124
+ *
125
+ * @returns {Promise<{provider?: string}>} The default provider, when known.
126
+ */
127
+ async defaultProvider() {
128
+ return { provider: this.ctx.modelAllowance.defaultProvider() }
129
+ }
130
+
131
+ /**
132
+ * Force a fresh reading, bypassing the cache.
133
+ * @param {string} provider Provider route.
134
+ * @param {string} [model] Provider-owned model id, when the session names one.
135
+ * @returns {Promise<import('./providers.js').BalanceView>} The reading.
136
+ */
137
+ async refresh(provider, model) {
138
+ return await this.ctx.modelAllowance.read(provider, { force: true, model })
139
+ }
140
+
141
+ /**
142
+ * Stream balance readings for one provider and model until the stream ends.
143
+ *
144
+ * The stream opens with the current reading, then publishes every later
145
+ * reading the service produces for that route and model. The opening read
146
+ * itself publishes to subscribers on a cache miss, so the first frame is
147
+ * dropped when it repeats the opening value.
148
+ *
149
+ * @param {string} provider Provider route.
150
+ * @param {string | undefined} model Provider-owned model id, when the session names one.
151
+ * @param {AbortSignal} signal Stream lifetime.
152
+ * @returns {AsyncGenerator<import('./providers.js').BalanceView>} Readings.
153
+ */
154
+ async *watch(provider, model, signal) {
155
+ const service = this.ctx.modelAllowance
156
+ const queue = []
157
+ let wake
158
+ const notify = () => {
159
+ wake?.()
160
+ wake = undefined
161
+ }
162
+ const unsubscribe = service.subscribe(provider, model, (view) => {
163
+ queue.push(view)
164
+ notify()
165
+ })
166
+ // A live stream is the only thing that should keep a route in the periodic
167
+ // sweep; releasing it starts the one-lifetime grace period.
168
+ const release = service.track(provider, model)
169
+ const abort = () => notify()
170
+ signal.addEventListener('abort', abort, { once: true })
171
+ let opening
172
+ try {
173
+ opening = await service.read(provider, { model })
174
+ yield opening
175
+ while (!signal.aborted) {
176
+ if (queue.length > 0) {
177
+ const next = queue.shift()
178
+ if (next === undefined) continue
179
+ // The opening read published to the subscriber before it returned;
180
+ // that frame is the same reading and must not be yielded twice.
181
+ if (next === opening) continue
182
+ if (
183
+ opening?.updatedAt !== undefined &&
184
+ next.updatedAt !== undefined &&
185
+ next.updatedAt <= opening.updatedAt
186
+ ) {
187
+ continue
188
+ }
189
+ yield next
190
+ continue
191
+ }
192
+ await new Promise((resolve) => {
193
+ wake = resolve
194
+ })
195
+ }
196
+ } finally {
197
+ unsubscribe()
198
+ release()
199
+ signal.removeEventListener('abort', abort)
200
+ }
201
+ }
202
+ }
203
+
204
+ /** Marker initializers applied to every instance of the controller. */
205
+ BalanceController.__applyRemoteMarkers = [
206
+ markRemote(BalanceController.prototype, 'capabilities'),
207
+ markRemote(BalanceController.prototype, 'balance'),
208
+ markRemote(BalanceController.prototype, 'list'),
209
+ markRemote(BalanceController.prototype, 'status'),
210
+ markRemote(BalanceController.prototype, 'schedule'),
211
+ markRemote(BalanceController.prototype, 'defaultProvider'),
212
+ markRemote(BalanceController.prototype, 'refresh'),
213
+ markRemote(BalanceController.prototype, 'watch', { mode: 'stream' }),
214
+ ]