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,3 @@
1
+ - insert:
2
+ - id: model-allowance
3
+ name: 'dsh-model-allowance'
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Model balance">
2
+ <title>Model balance</title>
3
+ <circle cx="32" cy="32" r="26" fill="none" stroke="currentColor" stroke-width="4"/>
4
+ <path d="M32 18a14 14 0 0 1 14 14" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"/>
5
+ <path d="M18 38a14 14 0 0 0 11 8.5" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round" opacity="0.45"/>
6
+ <circle cx="32" cy="32" r="4" fill="currentColor"/>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Host half of the model-allowance bundle.
3
+ *
4
+ * The Host owns every provider credential, queries provider balance endpoints,
5
+ * caches the readings, and publishes them through a Remote controller. The
6
+ * Client half only ever sees readings.
7
+ */
8
+
9
+ import { Service } from '@deepseek-ai/cordis'
10
+ import z from '@deepseek-ai/schemastery'
11
+ import { BalanceService } from './lib/balance.js'
12
+ import { describeError, logDebug } from './lib/debug.js'
13
+ import { holidayCoverage } from './lib/providers/schedule.js'
14
+ import { findAdapter, KIND_AMOUNT, KIND_QUOTA, PROVIDER_ADAPTERS } from './lib/providers.js'
15
+ import { BalanceController } from './lib/remote.js'
16
+ import { StatusService } from './lib/status.js'
17
+
18
+ /**
19
+ * The identity of one watched reading: a route and, when the caller knows it,
20
+ * the provider-owned model whose plan the route meters.
21
+ * @param {string} provider Provider route.
22
+ * @param {string | undefined} model Provider-owned model id.
23
+ * @returns {string} The key.
24
+ */
25
+ function activeKey(provider, model) {
26
+ const scoped = findAdapter(provider)?.modelScoped === true
27
+ return scoped && typeof model === 'string' && model !== ''
28
+ ? `${provider}\u0000${model}`
29
+ : provider
30
+ }
31
+
32
+ /**
33
+ * Normalize the optional model option.
34
+ * @param {unknown} model Candidate model id.
35
+ * @returns {string | undefined} A non-empty model id, when one was given.
36
+ */
37
+ function modelOf(model) {
38
+ return typeof model === 'string' && model !== '' ? model : undefined
39
+ }
40
+
41
+ /**
42
+ * The resolved plugin configuration.
43
+ * @typedef {object} ModelAllowanceConfig
44
+ * @property {number} [ttlMs] Lifetime of one cached reading, and the sweep period.
45
+ * @property {number} [requestTimeoutMs] Timeout for one provider request.
46
+ * @property {number} [statusTtlMs] Lifetime of one successful platform status.
47
+ * @property {number} [statusFailureTtlMs] Lifetime of a failed platform status.
48
+ * @property {number} [statusTimeoutMs] Timeout for one platform status request.
49
+ * @property {boolean} [debug] Write diagnostics to the debug log.
50
+ */
51
+
52
+ /**
53
+ * The Host-side balance service, registered as `ctx.modelAllowance`.
54
+ */
55
+ class ModelAllowanceService extends Service {
56
+ /**
57
+ * Services this plugin depends on.
58
+ */
59
+ static inject = ['timer', 'credentials']
60
+
61
+ /**
62
+ * @param {import('@deepseek-ai/cordis').Context} ownerContext Owning context.
63
+ * @param {ModelAllowanceConfig} config Resolved configuration.
64
+ */
65
+ constructor(ownerContext, config) {
66
+ super(ownerContext, 'modelAllowance')
67
+ this.config = config
68
+
69
+ /** @type {BalanceService} */
70
+ this.balance = new BalanceService({
71
+ ctx: ownerContext,
72
+ resolveCredential: async (ref) => {
73
+ const credentials = ownerContext.get('credentials')
74
+ const resolved = await credentials?.resolve(ref)
75
+ return resolved?.value
76
+ },
77
+ options: {
78
+ ttlMs: typeof config.ttlMs === 'number' ? config.ttlMs : undefined,
79
+ requestTimeoutMs:
80
+ typeof config.requestTimeoutMs === 'number' ? config.requestTimeoutMs : undefined,
81
+ },
82
+ })
83
+
84
+ /**
85
+ * Readings a browser asked about recently, keyed by route and model.
86
+ *
87
+ * `count` is the number of live streams watching the key; `until` keeps a
88
+ * unary reader's key in the sweep for one cache lifetime. A key is swept
89
+ * only while one of the two says it is still in use, so switching away
90
+ * from a provider stops its requests instead of refreshing it forever.
91
+ * @type {Map<string, {provider: string, model: string | undefined, count: number, until: number}>}
92
+ */
93
+ this.active = new Map()
94
+
95
+ /**
96
+ * Platform status readings. Every source is a public page, so this half
97
+ * needs no credential — only the vendor's status URL.
98
+ */
99
+ this.statusService = new StatusService({
100
+ ctx: ownerContext,
101
+ options: {
102
+ ttlMs: config.statusTtlMs,
103
+ failureTtlMs: config.statusFailureTtlMs,
104
+ timeoutMs: config.statusTimeoutMs,
105
+ },
106
+ })
107
+
108
+ // The Remote controller is a service of its own; it registers under the
109
+ // `balanceController` key and exposes the `balance` wire namespace.
110
+ this.controller = new BalanceController(ownerContext)
111
+ }
112
+
113
+ /**
114
+ * Read one provider's balance.
115
+ *
116
+ * A unary read keeps the route in the sweep for one cache lifetime, which
117
+ * covers a client that cannot open a stream; the effect is bounded by time,
118
+ * unlike the old append-only set.
119
+ *
120
+ * @param {string} provider Provider route.
121
+ * @param {{force?: boolean, model?: string}} [options] Read options.
122
+ * @returns {Promise<import('./lib/providers.js').BalanceView>} The reading.
123
+ */
124
+ async read(provider, options) {
125
+ const model = modelOf(options?.model)
126
+ this.markActive(provider, model)
127
+ const view = await this.balance.read(provider, { ...options, model })
128
+ if (this.config.debug === true && view.status !== 'ready') {
129
+ await logDebug(
130
+ `read route=${provider} model=${model ?? '-'} status=${view.status} error=${view.error ?? '-'}`,
131
+ )
132
+ }
133
+ return view
134
+ }
135
+
136
+ /**
137
+ * Keep one route/model reading in the periodic and turn-end sweeps.
138
+ *
139
+ * A stream holds this for its whole lifetime; releasing it keeps the key
140
+ * alive for one cache lifetime so a just-closed badge does not stop the
141
+ * final write from landing. After that it expires unless read again.
142
+ *
143
+ * @param {string} provider Provider route.
144
+ * @param {string} [model] Provider-owned model id, when known.
145
+ * @returns {() => void} Releases the key.
146
+ */
147
+ track(provider, model) {
148
+ const normalized = modelOf(model)
149
+ const key = activeKey(provider, normalized)
150
+ const entry = this.active.get(key) ?? {
151
+ provider,
152
+ model: normalized,
153
+ count: 0,
154
+ until: 0,
155
+ }
156
+ entry.count += 1
157
+ entry.until = Math.max(entry.until, Date.now() + this.balance.ttlMs)
158
+ this.active.set(key, entry)
159
+ let released = false
160
+ return () => {
161
+ if (released) return
162
+ released = true
163
+ entry.count = Math.max(0, entry.count - 1)
164
+ entry.until = Date.now() + this.balance.ttlMs
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Mark one reading as recently asked about without holding a stream.
170
+ *
171
+ * Deliberately a normal method, not a `#private` one: Cordis calls service
172
+ * methods through a context shadow, and a private member would fail its
173
+ * brand check with "Receiver must be an instance of class".
174
+ *
175
+ * @param {string} provider Provider route.
176
+ * @param {string | undefined} model Provider-owned model id.
177
+ */
178
+ markActive(provider, model) {
179
+ const key = activeKey(provider, model)
180
+ const entry = this.active.get(key)
181
+ if (entry !== undefined && entry.count > 0) return
182
+ this.active.set(key, {
183
+ provider,
184
+ model,
185
+ count: entry?.count ?? 0,
186
+ until: Date.now() + this.balance.ttlMs,
187
+ })
188
+ }
189
+
190
+ /**
191
+ * Subscribe to new readings for one provider and model.
192
+ * @param {string} provider Provider route.
193
+ * @param {string} [model] Provider-owned model id, when known.
194
+ * @param {(view: import('./lib/providers.js').BalanceView) => void} [listener] Receives every reading.
195
+ * @returns {() => void} Unsubscribe.
196
+ */
197
+ subscribe(provider, model, listener) {
198
+ return this.balance.subscribe(provider, model, listener)
199
+ }
200
+
201
+ /**
202
+ * List the providers this installation can read.
203
+ * @returns {Promise<Array<{route: string, configured: boolean}>>} The routes.
204
+ */
205
+ async list() {
206
+ return await this.balance.available()
207
+ }
208
+
209
+ /**
210
+ * Read one provider's platform status, for the card's status row.
211
+ *
212
+ * A route whose vendor publishes no status page answers `unknown` and the
213
+ * browser hides the row, so this never needs a guard at the call site.
214
+ *
215
+ * @param {string} provider Provider route.
216
+ * @returns {Promise<import('./lib/status.js').StatusView>} The status reading.
217
+ */
218
+ async status(provider) {
219
+ return await this.statusService.read(provider)
220
+ }
221
+
222
+ /**
223
+ * The pricing schedule a provider meters by, when it publishes one.
224
+ *
225
+ * The schedule is declared data, not a reading: the browser evaluates it
226
+ * against its own clock, so the countdown never needs another round trip.
227
+ *
228
+ * @param {string} provider Provider route.
229
+ * @returns {object | null} The schedule, or null when the vendor prices flat.
230
+ */
231
+ schedule(provider) {
232
+ const schedule = findAdapter(provider)?.schedule
233
+ return schedule === undefined ? null : { provider, ...schedule }
234
+ }
235
+
236
+ /**
237
+ * The provider a session with no model selection would use.
238
+ *
239
+ * A session that has not taken a turn yet carries no `modelSelection`
240
+ * projection, so the browser cannot name a provider from the log. The
241
+ * installation's default model is the answer the model selector itself falls
242
+ * back to, so the badge follows the same one.
243
+ *
244
+ * @returns {string | undefined} Provider route, when the installation names one.
245
+ */
246
+ defaultProvider() {
247
+ try {
248
+ const selection = this.ctx.get('agentDefaultModel')?.currentSelection?.()
249
+ const provider = selection?.provider
250
+ return typeof provider === 'string' && provider.length > 0 ? provider : undefined
251
+ } catch {
252
+ // A deployment without a default-model service simply has none.
253
+ return undefined
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Refresh every reading a browser is currently watching, or asked for within
259
+ * one cache lifetime.
260
+ * @param {{minAgeMs?: number}} [options] Skip readings newer than this.
261
+ * @returns {Promise<void>} Resolves when the refreshes settle.
262
+ */
263
+ async refreshAll(options = {}) {
264
+ const minAgeMs = typeof options.minAgeMs === 'number' ? options.minAgeMs : 0
265
+ const now = Date.now()
266
+ /** @type {Array<{provider: string, model: string | undefined, count: number, until: number}>} */
267
+ const targets = []
268
+ for (const [key, entry] of this.active) {
269
+ if (entry.count > 0 || entry.until > now) {
270
+ targets.push(entry)
271
+ } else {
272
+ // Nothing has looked at this key for a whole cache lifetime.
273
+ this.active.delete(key)
274
+ }
275
+ }
276
+ if (targets.length === 0) return
277
+ await Promise.all(
278
+ targets.map((entry) => {
279
+ // The periodic sweep runs on its own clock; a turn-end refresh may
280
+ // have just read the same key, and forcing it again would spend a
281
+ // second request for nothing.
282
+ if (minAgeMs > 0) {
283
+ const cached = this.balance.peek(entry.provider, entry.model)
284
+ if (cached?.updatedAt !== undefined && now - cached.updatedAt < minAgeMs) return cached
285
+ }
286
+ return this.balance
287
+ .read(entry.provider, { force: true, model: entry.model })
288
+ .then((view) => {
289
+ if (this.config.debug === true && view.consumption !== undefined) {
290
+ void logDebug(
291
+ `movement route=${entry.provider} model=${entry.model ?? '-'} status=${view.status}` +
292
+ ` consumption=${view.consumption.kind}:${String(view.consumption.delta)}`,
293
+ )
294
+ }
295
+ return view
296
+ })
297
+ }),
298
+ )
299
+ }
300
+
301
+ /**
302
+ * Run after construction: install the refresh triggers and, when debugging,
303
+ * probe every adapter once and record what happened.
304
+ * @returns {void} Nothing to clean up; the triggers live on the fiber.
305
+ */
306
+ [Service.init]() {
307
+ const ctx = this.ctx
308
+
309
+ // Vendor holiday lists change annually and are the one piece of schedule
310
+ // data that goes silently wrong. Surface a stale list once at startup.
311
+ const thisYear = new Date().getFullYear()
312
+ for (const adapter of PROVIDER_ADAPTERS) {
313
+ const coverage =
314
+ adapter.schedule === undefined ? undefined : holidayCoverage(adapter.schedule)
315
+ if (coverage !== undefined && coverage.to < thisYear) {
316
+ console.warn(
317
+ `[model-allowance] ${adapter.id} holiday data ends in ${String(coverage.to)}; ` +
318
+ `extend it for ${String(thisYear)}`,
319
+ )
320
+ }
321
+ }
322
+
323
+ // Both listeners are `global`. `session/event` is emitted from the
324
+ // session's own scope, so a plugin context that is not an ancestor of that
325
+ // scope never sees it — the turn-end refresh was silently dead for that
326
+ // reason, and the badge only ever moved on the periodic sweep. The harness
327
+ // registers its own cross-session listeners the same way.
328
+ const GLOBAL = { global: true }
329
+
330
+ // A finished turn consumed provider quota, so the reading it belongs to is
331
+ // stale. Refreshing here is what turns "the number is old" into "here is
332
+ // what moved".
333
+ ctx.on(
334
+ 'session/event',
335
+ (_session, event) => {
336
+ if (event.type !== 'turn/end') return
337
+ if (this.config.debug === true) {
338
+ void logDebug(`turn end: refreshing ${String(this.active.size)} reading(s)`)
339
+ }
340
+ this.refreshAll().catch((error) => {
341
+ console.error('[model-allowance] turn refresh failed', { error })
342
+ })
343
+ },
344
+ GLOBAL,
345
+ )
346
+
347
+ // A periodic sweep keeps a long-lived session's reading current. It skips
348
+ // a reading the turn-end trigger just refreshed, so the two clocks cannot
349
+ // spend two provider requests on the same number.
350
+ ctx.timer.interval(() => {
351
+ this.refreshAll({ minAgeMs: 10 * 1000 }).catch((error) => {
352
+ console.error('[model-allowance] periodic refresh failed', { error })
353
+ })
354
+ }, this.balance.ttlMs)
355
+
356
+ if (this.config.debug === true) this.probe()
357
+ }
358
+
359
+ /**
360
+ * Read every adapter once and write the outcome to the debug log.
361
+ *
362
+ * A reading that fails inside the browser is hard to report back, so this
363
+ * runs the same Host code at activation and leaves a trail.
364
+ * @returns {void} Starts the probe; failures are logged, never thrown.
365
+ */
366
+ probe() {
367
+ const ctx = this.ctx
368
+ void (async () => {
369
+ await logDebug(`=== probe: ${PROVIDER_ADAPTERS.length} adapters ===`)
370
+ await logDebug(`deepseekAccount present: ${String(ctx.get('deepseekAccount') !== undefined)}`)
371
+ try {
372
+ const routes = await this.list()
373
+ await logDebug(
374
+ `available=${JSON.stringify(routes.filter((route) => route.configured).map((route) => route.route))}`,
375
+ )
376
+ } catch (error) {
377
+ await logDebug(`available probe THREW ${describeError(error)}`)
378
+ }
379
+ for (const adapter of PROVIDER_ADAPTERS) {
380
+ const route = adapter.routes[0]
381
+ try {
382
+ const view = await this.balance.read(route, { force: true })
383
+ await logDebug(
384
+ `adapter=${adapter.id} route=${route} status=${view.status}` +
385
+ ` kind=${view.kind ?? '-'}` +
386
+ ` amount=${view.amount ?? '-'} percent=${view.percent ?? '-'}` +
387
+ ` error=${view.error ?? '-'}`,
388
+ )
389
+ if (Array.isArray(view.windows) && view.windows.length > 0) {
390
+ await logDebug(` windows=${JSON.stringify(view.windows)}`)
391
+ }
392
+ if (adapter.status !== undefined) {
393
+ const platform = await this.statusService.read(route)
394
+ await logDebug(
395
+ ` platform=${platform.state}` +
396
+ (platform.summary ? ` summary=${platform.summary}` : '') +
397
+ (platform.error ? ` error=${platform.error}` : ''),
398
+ )
399
+ }
400
+ } catch (error) {
401
+ await logDebug(`adapter=${adapter.id} route=${route} THREW ${describeError(error)}`)
402
+ }
403
+ }
404
+ // An unknown route is not an adapter, but the client may still ask.
405
+ await logDebug(`no-adapter route probe: ${String(findAdapter('__none__') === undefined)}`)
406
+ await logDebug('=== probe done ===')
407
+ })().catch((error) => {
408
+ console.error('[model-allowance] probe failed', { error })
409
+ })
410
+ }
411
+ }
412
+
413
+ /**
414
+ * The plugin's configuration schema.
415
+ */
416
+ ModelAllowanceService.Config = z.object({
417
+ /** Lifetime of one cached reading, in milliseconds; also the sweep period. */
418
+ ttlMs: z
419
+ .number()
420
+ .min(30_000)
421
+ .max(24 * 60 * 60 * 1000)
422
+ .default(5 * 60 * 1000),
423
+ /** Timeout for one provider request, in milliseconds. */
424
+ requestTimeoutMs: z
425
+ .number()
426
+ .min(1000)
427
+ .max(120 * 1000)
428
+ .default(15 * 1000),
429
+ /** Lifetime of one successful platform-status reading. */
430
+ statusTtlMs: z
431
+ .number()
432
+ .min(5_000)
433
+ .max(60 * 60 * 1000)
434
+ .default(60 * 1000),
435
+ /** How long a failed platform-status fetch is remembered. */
436
+ statusFailureTtlMs: z
437
+ .number()
438
+ .min(1000)
439
+ .max(30 * 60 * 1000)
440
+ .default(30 * 1000),
441
+ /** Timeout for one platform-status request. */
442
+ statusTimeoutMs: z
443
+ .number()
444
+ .min(1000)
445
+ .max(60 * 1000)
446
+ .default(8 * 1000),
447
+ /** Write each reading and its failure reason to `$DSH_HOME/model-allowance-debug.log`. */
448
+ debug: z.boolean().default(false),
449
+ })
450
+
451
+ export {
452
+ KIND_AMOUNT,
453
+ KIND_QUOTA,
454
+ ModelAllowanceService as default,
455
+ ModelAllowanceService,
456
+ PROVIDER_ADAPTERS,
457
+ }