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.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/README.zh.md +50 -0
- package/client.js +1897 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +7 -0
- package/index.js +457 -0
- package/lib/balance.js +413 -0
- package/lib/credentials.js +174 -0
- package/lib/debug.js +70 -0
- package/lib/providers/deepseek.js +408 -0
- package/lib/providers/kimi.js +474 -0
- package/lib/providers/minimax.js +383 -0
- package/lib/providers/opencode.js +209 -0
- package/lib/providers/schedule.js +153 -0
- package/lib/providers/shared.js +324 -0
- package/lib/providers/status.js +133 -0
- package/lib/providers/zhipu.js +185 -0
- package/lib/providers.js +112 -0
- package/lib/remote.js +214 -0
- package/lib/status.js +196 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +82 -4
package/lib/balance.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The balance service: credential resolution, provider queries, caching, and
|
|
3
|
+
* the refresh triggers.
|
|
4
|
+
*
|
|
5
|
+
* The service is Host-only. It is the single place that holds a provider
|
|
6
|
+
* credential, so a browser never sees one.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createRouteCredentialResolver } from './credentials.js'
|
|
10
|
+
import { displayOf, readEndpointAdapter } from './providers/shared.js'
|
|
11
|
+
import { findAdapter, KIND_AMOUNT, KIND_QUOTA, PROVIDER_ADAPTERS } from './providers.js'
|
|
12
|
+
|
|
13
|
+
/** Default lifetime of one cached reading, in milliseconds. */
|
|
14
|
+
const DEFAULT_TTL_MS = 5 * 60 * 1000
|
|
15
|
+
|
|
16
|
+
/** Timeout for one provider request, in milliseconds. */
|
|
17
|
+
const REQUEST_TIMEOUT_MS = 15 * 1000
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The cache key of one reading.
|
|
21
|
+
*
|
|
22
|
+
* A provider route can meter different models separately (MiniMax reports one
|
|
23
|
+
* plan entry per model), so the model is part of the identity. Routes that do
|
|
24
|
+
* not care about the model keep their route-only key, exactly as before.
|
|
25
|
+
*
|
|
26
|
+
* @param {string} route Provider route.
|
|
27
|
+
* @param {string | undefined} model Provider-owned model id, when known.
|
|
28
|
+
* @returns {string} Cache key.
|
|
29
|
+
*/
|
|
30
|
+
function keyOf(route, model) {
|
|
31
|
+
return typeof model === 'string' && model !== '' ? `${route}\u0000${model}` : route
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Reject a promise when its timeout signal fires.
|
|
36
|
+
*
|
|
37
|
+
* A provider read that ignores the signal (a Host service call) would
|
|
38
|
+
* otherwise keep the in-flight entry alive forever; this bounds it at the
|
|
39
|
+
* caller's timeout without cancelling work that cannot be cancelled.
|
|
40
|
+
*
|
|
41
|
+
* @template T
|
|
42
|
+
* @param {Promise<T>} promise The read.
|
|
43
|
+
* @param {AbortSignal} signal Timeout signal.
|
|
44
|
+
* @returns {Promise<T>} The read, or a rejection once the signal fires.
|
|
45
|
+
*/
|
|
46
|
+
function withTimeout(promise, signal) {
|
|
47
|
+
if (signal.aborted) return Promise.reject(signal.reason)
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const onAbort = () => reject(signal.reason)
|
|
50
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
51
|
+
promise.then(
|
|
52
|
+
(value) => {
|
|
53
|
+
signal.removeEventListener('abort', onAbort)
|
|
54
|
+
resolve(value)
|
|
55
|
+
},
|
|
56
|
+
(error) => {
|
|
57
|
+
signal.removeEventListener('abort', onAbort)
|
|
58
|
+
reject(error)
|
|
59
|
+
},
|
|
60
|
+
)
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @typedef {import('./providers.js').BalanceView} BalanceView
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Compare a fresh reading with the one published before it.
|
|
70
|
+
*
|
|
71
|
+
* The browser was last told that reading, so the difference is exactly what
|
|
72
|
+
* moved since the number it is showing. The arrow the UI draws points the way
|
|
73
|
+
* that number went, so the difference is signed: a balance falling from 100 to
|
|
74
|
+
* 99.1 reports -0.9, and a top-up or a window reset reports a positive number.
|
|
75
|
+
* Readings of a different kind, or ones that failed on either side, carry no
|
|
76
|
+
* difference at all — a change from "failed" to "¥10" is not a measurement.
|
|
77
|
+
*
|
|
78
|
+
* @param {BalanceView} view The fresh reading.
|
|
79
|
+
* @param {BalanceView} before The reading to measure against.
|
|
80
|
+
* @returns {BalanceView} The reading, annotated when a difference exists.
|
|
81
|
+
*/
|
|
82
|
+
function withConsumption(view, before) {
|
|
83
|
+
if (view.status !== 'ready' || before.status !== 'ready') return view
|
|
84
|
+
if (view.kind === KIND_AMOUNT) {
|
|
85
|
+
if (typeof view.amount !== 'number' || typeof before.amount !== 'number') return view
|
|
86
|
+
return {
|
|
87
|
+
...view,
|
|
88
|
+
consumption: { kind: 'amount', delta: view.amount - before.amount, at: Date.now() },
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// A plan meters several windows at once, and the one the badge speaks for is
|
|
92
|
+
// the most-consumed one — which on an exhausted plan is pinned at zero and
|
|
93
|
+
// never moves. The turn's cost is better read from whichever window actually
|
|
94
|
+
// changed, so the largest movement wins.
|
|
95
|
+
const moved = largestWindowMove(view, before)
|
|
96
|
+
if (moved !== undefined) {
|
|
97
|
+
return { ...view, consumption: { kind: 'percent', delta: moved, at: Date.now() } }
|
|
98
|
+
}
|
|
99
|
+
if (typeof view.percent !== 'number' || typeof before.percent !== 'number') return view
|
|
100
|
+
return {
|
|
101
|
+
...view,
|
|
102
|
+
consumption: { kind: 'percent', delta: view.percent - before.percent, at: Date.now() },
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The biggest remaining-percent change across the windows both readings share.
|
|
108
|
+
* @param {BalanceView} view The fresh reading.
|
|
109
|
+
* @param {BalanceView} before The reading from the start of the turn.
|
|
110
|
+
* @returns {number | undefined} The change in percentage points, if any.
|
|
111
|
+
*/
|
|
112
|
+
function largestWindowMove(view, before) {
|
|
113
|
+
const previous = new Map(
|
|
114
|
+
(Array.isArray(before.windows) ? before.windows : [])
|
|
115
|
+
.filter((window) => typeof window.remainingPercent === 'number')
|
|
116
|
+
.map((window) => [window.id, window.remainingPercent]),
|
|
117
|
+
)
|
|
118
|
+
let largest
|
|
119
|
+
for (const window of Array.isArray(view.windows) ? view.windows : []) {
|
|
120
|
+
const was = previous.get(window.id)
|
|
121
|
+
if (was === undefined || typeof window.remainingPercent !== 'number') continue
|
|
122
|
+
const delta = window.remainingPercent - was
|
|
123
|
+
if (largest === undefined || Math.abs(delta) > Math.abs(largest)) largest = delta
|
|
124
|
+
}
|
|
125
|
+
return largest
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @typedef {object} BalanceServiceOptions
|
|
130
|
+
* @property {number} [ttlMs] Lifetime of one cached reading.
|
|
131
|
+
* @property {number} [requestTimeoutMs] Timeout for one provider request.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Host-side balance readings, keyed by provider route.
|
|
136
|
+
*/
|
|
137
|
+
export class BalanceService {
|
|
138
|
+
/**
|
|
139
|
+
* @param {object} deps Injected dependencies.
|
|
140
|
+
* @param {import('@deepseek-ai/cordis').Context} deps.ctx Cordis context.
|
|
141
|
+
* @param {(ref: string) => Promise<string | undefined>} deps.resolveCredential Resolves a credential reference to its value.
|
|
142
|
+
* @param {BalanceServiceOptions} [deps.options] Service options.
|
|
143
|
+
*/
|
|
144
|
+
constructor({ ctx, resolveCredential, options = {} }) {
|
|
145
|
+
this.ctx = ctx
|
|
146
|
+
this.resolveCredential = resolveCredential
|
|
147
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
|
|
148
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
|
|
149
|
+
|
|
150
|
+
// Which credential authorizes a route is the harness's fact, not this
|
|
151
|
+
// plugin's; the resolver asks it and only falls back to the adapter's own
|
|
152
|
+
// references when the harness cannot answer.
|
|
153
|
+
this.routeCredentials = createRouteCredentialResolver({ ctx, resolveCredential })
|
|
154
|
+
|
|
155
|
+
// Readings are cached per route and model: one route can meter different
|
|
156
|
+
// models separately, so a model switch must not answer with the previous
|
|
157
|
+
// model's reading.
|
|
158
|
+
/** @type {Map<string, {view: BalanceView, at: number}>} */
|
|
159
|
+
this.cache = new Map()
|
|
160
|
+
/**
|
|
161
|
+
* The reading each key published last, which the next one is measured
|
|
162
|
+
* against. Kept beside the cache rather than in it: the cache holds the
|
|
163
|
+
* plain reading, this holds the anchor a difference is computed from.
|
|
164
|
+
* @type {Map<string, BalanceView>}
|
|
165
|
+
*/
|
|
166
|
+
this.lastPublished = new Map()
|
|
167
|
+
/** @type {Map<string, Promise<BalanceView>>} */
|
|
168
|
+
this.inflight = new Map()
|
|
169
|
+
/** @type {Map<string, Set<(view: BalanceView) => void>>} */
|
|
170
|
+
this.listeners = new Map()
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The cache key of one reading.
|
|
175
|
+
*
|
|
176
|
+
* Only an adapter that meters models separately keeps the model in its key;
|
|
177
|
+
* a DeepSeek balance is the same figure whichever model asks for it, so a
|
|
178
|
+
* model switch must not leave a second cache entry and a second sweep
|
|
179
|
+
* target behind.
|
|
180
|
+
*
|
|
181
|
+
* @param {string} route Provider route.
|
|
182
|
+
* @param {string | undefined} model Provider-owned model id.
|
|
183
|
+
* @returns {string} Cache key.
|
|
184
|
+
*/
|
|
185
|
+
#key(route, model) {
|
|
186
|
+
const adapter = findAdapter(route)
|
|
187
|
+
return adapter?.modelScoped === true ? keyOf(route, model) : route
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Read one provider's balance, reusing a fresh cached reading.
|
|
192
|
+
* @param {string} route Provider route.
|
|
193
|
+
* @param {{force?: boolean, model?: string}} [options] Read options.
|
|
194
|
+
* @returns {Promise<BalanceView>} The reading.
|
|
195
|
+
*/
|
|
196
|
+
async read(route, options = {}) {
|
|
197
|
+
const model =
|
|
198
|
+
typeof options.model === 'string' && options.model !== '' ? options.model : undefined
|
|
199
|
+
const key = this.#key(route, model)
|
|
200
|
+
const cached = this.cache.get(key)
|
|
201
|
+
if (!options.force && cached && Date.now() - cached.at < this.ttlMs) {
|
|
202
|
+
return cached.view
|
|
203
|
+
}
|
|
204
|
+
const pending = this.inflight.get(key)
|
|
205
|
+
if (pending) return await pending
|
|
206
|
+
|
|
207
|
+
const request = this.#query(route, model)
|
|
208
|
+
.then((view) => {
|
|
209
|
+
// Only the published copy carries the difference. Caching it would let
|
|
210
|
+
// a later sweep republish a stale one.
|
|
211
|
+
const anchor = this.lastPublished.get(key)
|
|
212
|
+
const published = anchor ? withConsumption(view, anchor) : view
|
|
213
|
+
this.cache.set(key, { view, at: Date.now() })
|
|
214
|
+
// A reading that did not come back cleanly says nothing about movement,
|
|
215
|
+
// and anchoring the next one to it would attribute the whole gap to
|
|
216
|
+
// whatever moved in between.
|
|
217
|
+
if (view.status === 'ready') this.lastPublished.set(key, view)
|
|
218
|
+
else this.lastPublished.delete(key)
|
|
219
|
+
this.#publish(key, published)
|
|
220
|
+
return published
|
|
221
|
+
})
|
|
222
|
+
.finally(() => {
|
|
223
|
+
this.inflight.delete(key)
|
|
224
|
+
})
|
|
225
|
+
this.inflight.set(key, request)
|
|
226
|
+
return await request
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The cached reading, without refreshing it.
|
|
231
|
+
*
|
|
232
|
+
* Callers that only need to know what the last request answered — a debug
|
|
233
|
+
* probe, a test — read it here instead of paying for another request.
|
|
234
|
+
*
|
|
235
|
+
* @param {string} route Provider route.
|
|
236
|
+
* @param {string} [model] Provider-owned model id, when known.
|
|
237
|
+
* @returns {BalanceView | undefined} The cached reading, if any.
|
|
238
|
+
*/
|
|
239
|
+
peek(route, model) {
|
|
240
|
+
return this.cache.get(this.#key(route, model))?.view
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Drop one provider's cached reading so the next read refetches.
|
|
245
|
+
* @param {string} route Provider route.
|
|
246
|
+
* @param {string} [model] Provider-owned model id, when known.
|
|
247
|
+
*/
|
|
248
|
+
invalidate(route, model) {
|
|
249
|
+
const key = this.#key(route, model)
|
|
250
|
+
this.cache.delete(key)
|
|
251
|
+
// Forgetting the reading forgets the anchor too: a difference against a
|
|
252
|
+
// reading this installation no longer remembers is not a movement it saw.
|
|
253
|
+
this.lastPublished.delete(key)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* List every route this installation can read, with the display metadata the
|
|
258
|
+
* browser needs to name and draw it.
|
|
259
|
+
*
|
|
260
|
+
* The card offers these as a switcher, so a route only answers `configured`
|
|
261
|
+
* when its credential (or the service behind it) actually resolves here. One
|
|
262
|
+
* entry per route rather than per adapter: the two Zhipu routes carry
|
|
263
|
+
* different credentials, so an installation using the CN plan should see
|
|
264
|
+
* that route, not the international one.
|
|
265
|
+
*
|
|
266
|
+
* @returns {Promise<Array<{route: string, configured: boolean, name: {zh: string, en: string}, color: string, iconHint?: string}>>}
|
|
267
|
+
* The routes.
|
|
268
|
+
*/
|
|
269
|
+
async available() {
|
|
270
|
+
/** @type {Array<{route: string, configured: boolean, name: {zh: string, en: string}, color: string, iconHint?: string}>} */
|
|
271
|
+
const routes = []
|
|
272
|
+
for (const adapter of PROVIDER_ADAPTERS) {
|
|
273
|
+
for (const route of adapter.routes) {
|
|
274
|
+
let configured
|
|
275
|
+
if (adapter.readWithEnv) {
|
|
276
|
+
// A service-backed adapter is available when the service is mounted.
|
|
277
|
+
const service =
|
|
278
|
+
typeof this.ctx.get === 'function' ? this.ctx.get(adapter.service) : undefined
|
|
279
|
+
configured = service !== undefined
|
|
280
|
+
} else {
|
|
281
|
+
configured = (await this.routeCredentials.resolve(route, adapter)) !== undefined
|
|
282
|
+
}
|
|
283
|
+
routes.push({ route, configured, ...displayOf(adapter) })
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return routes
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Drop every cached reading.
|
|
291
|
+
*/
|
|
292
|
+
invalidateAll() {
|
|
293
|
+
this.cache.clear()
|
|
294
|
+
this.lastPublished.clear()
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Subscribe to readings for one provider route and model.
|
|
299
|
+
*
|
|
300
|
+
* The model is optional so a caller that only knows the route (a test, a
|
|
301
|
+
* debug tool) keeps working; the two-argument form stays supported.
|
|
302
|
+
*
|
|
303
|
+
* @param {string} route Provider route.
|
|
304
|
+
* @param {string | ((view: BalanceView) => void)} [model] Model id, or the listener.
|
|
305
|
+
* @param {(view: BalanceView) => void} [listener] Receives every new reading.
|
|
306
|
+
* @returns {() => void} Unsubscribe.
|
|
307
|
+
*/
|
|
308
|
+
subscribe(route, model, listener) {
|
|
309
|
+
let key
|
|
310
|
+
let callback = listener
|
|
311
|
+
if (typeof model === 'function') {
|
|
312
|
+
callback = model
|
|
313
|
+
key = this.#key(route, undefined)
|
|
314
|
+
} else {
|
|
315
|
+
key = this.#key(route, model)
|
|
316
|
+
}
|
|
317
|
+
if (typeof callback !== 'function')
|
|
318
|
+
throw new TypeError('a balance subscriber must be a function')
|
|
319
|
+
let set = this.listeners.get(key)
|
|
320
|
+
if (!set) {
|
|
321
|
+
set = new Set()
|
|
322
|
+
this.listeners.set(key, set)
|
|
323
|
+
}
|
|
324
|
+
set.add(callback)
|
|
325
|
+
return () => {
|
|
326
|
+
set?.delete(callback)
|
|
327
|
+
if (set && set.size === 0) this.listeners.delete(key)
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Publish a reading to the key's subscribers.
|
|
333
|
+
* @param {string} key Reading key.
|
|
334
|
+
* @param {BalanceView} view The reading.
|
|
335
|
+
*/
|
|
336
|
+
#publish(key, view) {
|
|
337
|
+
for (const listener of this.listeners.get(key) ?? []) {
|
|
338
|
+
try {
|
|
339
|
+
listener(view)
|
|
340
|
+
} catch (error) {
|
|
341
|
+
console.error('[model-allowance] listener failed', { key, error })
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Query one provider, translating every failure into a reading.
|
|
348
|
+
* @param {string} route Provider route.
|
|
349
|
+
* @param {string} [model] Provider-owned model id, when known.
|
|
350
|
+
* @returns {Promise<BalanceView>} The reading.
|
|
351
|
+
*/
|
|
352
|
+
async #query(route, model) {
|
|
353
|
+
const adapter = findAdapter(route)
|
|
354
|
+
if (!adapter) {
|
|
355
|
+
return { provider: route, status: 'unsupported', kind: KIND_QUOTA }
|
|
356
|
+
}
|
|
357
|
+
// A service-backed adapter brings its own authorization, so it needs no
|
|
358
|
+
// credential; every other adapter asks the harness which credential
|
|
359
|
+
// authorizes this route.
|
|
360
|
+
const hit = adapter.readWithEnv
|
|
361
|
+
? undefined
|
|
362
|
+
: await this.routeCredentials.resolve(route, adapter)
|
|
363
|
+
if (!adapter.readWithEnv && hit === undefined) {
|
|
364
|
+
return {
|
|
365
|
+
provider: route,
|
|
366
|
+
status: 'unconfigured',
|
|
367
|
+
kind: adapter.kind,
|
|
368
|
+
consoleUrl: adapter.consoleUrl,
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
// A reading is bounded by the request timeout alone. Cordis has no
|
|
372
|
+
// context lifetime signal: reading `ctx.signal` asks for a service named
|
|
373
|
+
// `signal`, which does not exist and throws without an inject.
|
|
374
|
+
const timeout = AbortSignal.timeout(this.requestTimeoutMs)
|
|
375
|
+
const signal = timeout
|
|
376
|
+
try {
|
|
377
|
+
const view = adapter.readWithEnv
|
|
378
|
+
? await withTimeout(
|
|
379
|
+
adapter.readWithEnv({ route, apiKey: hit?.value, ctx: this.ctx, signal, model }),
|
|
380
|
+
signal,
|
|
381
|
+
)
|
|
382
|
+
: await readEndpointAdapter(adapter, {
|
|
383
|
+
route,
|
|
384
|
+
apiKey: hit === undefined ? '' : hit.value,
|
|
385
|
+
signal,
|
|
386
|
+
model,
|
|
387
|
+
})
|
|
388
|
+
// The console link is a property of the route, not of the response, so
|
|
389
|
+
// every reading carries it — including one that failed authorization and
|
|
390
|
+
// is exactly when the user needs the way back to the console.
|
|
391
|
+
return { ...view, consoleUrl: view.consoleUrl ?? adapter.consoleUrl, updatedAt: Date.now() }
|
|
392
|
+
} catch (error) {
|
|
393
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
394
|
+
// An aborted request is a cancellation, not a provider failure.
|
|
395
|
+
if (timeout.aborted) {
|
|
396
|
+
return {
|
|
397
|
+
provider: route,
|
|
398
|
+
status: 'failed',
|
|
399
|
+
kind: adapter.kind,
|
|
400
|
+
error: 'timeout',
|
|
401
|
+
consoleUrl: adapter.consoleUrl,
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
provider: route,
|
|
406
|
+
status: 'failed',
|
|
407
|
+
kind: adapter.kind,
|
|
408
|
+
error: reason,
|
|
409
|
+
consoleUrl: adapter.consoleUrl,
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential discovery for provider routes.
|
|
3
|
+
*
|
|
4
|
+
* The harness already knows which credential authorizes which route: the
|
|
5
|
+
* `llm-pi-ai` plugin keeps a profile per route, and its configurable-provider
|
|
6
|
+
* directory names the catalog's native authentication env names. Asking it is
|
|
7
|
+
* both more accurate than a hand-maintained table and the only way a custom
|
|
8
|
+
* route (or a route whose profile names a non-default `apiKeyEnv`) can work.
|
|
9
|
+
*
|
|
10
|
+
* The chain, most authoritative first:
|
|
11
|
+
*
|
|
12
|
+
* 1. the route profile's `apiKeyEnv`, read through the settings service —
|
|
13
|
+
* exactly the reference the LLM request itself resolves;
|
|
14
|
+
* 2. the catalog's native authentication env names, from the llm directory.
|
|
15
|
+
*
|
|
16
|
+
* When the harness names the route, those two answers are authoritative and
|
|
17
|
+
* the adapter's own table is not consulted: the two Zhipu routes share a
|
|
18
|
+
* vendor but not a credential, so a fallback table that lists both keys would
|
|
19
|
+
* let one route answer for the other. Only a route the harness does not know —
|
|
20
|
+
* a composition without `llm-pi-ai`, or a bare test context — falls through to
|
|
21
|
+
* the adapter's `credentialRefs`.
|
|
22
|
+
*
|
|
23
|
+
* Every layer is optional: a composition without `llm` or `settings` falls
|
|
24
|
+
* through to the adapter's own table, which is what a bare Host or a test
|
|
25
|
+
* environment looks like. Only the reference list is cached — the value is
|
|
26
|
+
* resolved per read, so a changed key reaches the next reading without a
|
|
27
|
+
* restart.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* How long one directory-and-settings snapshot is trusted.
|
|
32
|
+
*
|
|
33
|
+
* `settings.describe()` walks every active plugin's schema, so it is far too
|
|
34
|
+
* expensive to call per read. A short trust window keeps an edited profile
|
|
35
|
+
* reaching the plugin without wiring a second event subscription, and the
|
|
36
|
+
* credential value itself is never cached.
|
|
37
|
+
*/
|
|
38
|
+
const SNAPSHOT_TTL_MS = 30_000
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Walk a settings path into a plain value.
|
|
42
|
+
* @param {unknown} value Root value.
|
|
43
|
+
* @param {readonly (string | number)[]} path Path segments.
|
|
44
|
+
* @returns {unknown} The value at the path, or undefined.
|
|
45
|
+
*/
|
|
46
|
+
function walkPath(value, path) {
|
|
47
|
+
let current = value
|
|
48
|
+
for (const segment of path) {
|
|
49
|
+
if (current === null || typeof current !== 'object') return undefined
|
|
50
|
+
current = /** @type {Record<string | number, unknown>} */ (current)[segment]
|
|
51
|
+
}
|
|
52
|
+
return current
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read the harness's provider directory and live settings once.
|
|
57
|
+
*
|
|
58
|
+
* Both reads are best-effort: a harness without the `llm` or `settings`
|
|
59
|
+
* service, or one whose configuration surface is unavailable, simply answers
|
|
60
|
+
* nothing here and the chain falls through.
|
|
61
|
+
*
|
|
62
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx Host context.
|
|
63
|
+
* @returns {{directory: Map<string, {settingsNs?: string, settingsPath?: readonly (string|number)[], nativeAuthEnv: readonly string[]}>, profiles: Map<string, unknown>}}
|
|
64
|
+
* The snapshot.
|
|
65
|
+
*/
|
|
66
|
+
function readHarnessSnapshot(ctx) {
|
|
67
|
+
/** @type {Map<string, {settingsNs?: string, settingsPath?: readonly (string|number)[], nativeAuthEnv: readonly string[]}>} */
|
|
68
|
+
const directory = new Map()
|
|
69
|
+
/** @type {Map<string, unknown>} */
|
|
70
|
+
const profiles = new Map()
|
|
71
|
+
const get = (name) => (typeof ctx.get === 'function' ? ctx.get(name) : undefined)
|
|
72
|
+
try {
|
|
73
|
+
const llm = get('llm')
|
|
74
|
+
const entries =
|
|
75
|
+
typeof llm?.listConfigurableProviders === 'function' ? llm.listConfigurableProviders() : []
|
|
76
|
+
for (const entry of entries ?? []) {
|
|
77
|
+
if (!entry || typeof entry.provider !== 'string') continue
|
|
78
|
+
directory.set(entry.provider, {
|
|
79
|
+
settingsNs: typeof entry.settingsNs === 'string' ? entry.settingsNs : undefined,
|
|
80
|
+
settingsPath: Array.isArray(entry.settingsPath) ? entry.settingsPath : undefined,
|
|
81
|
+
nativeAuthEnv: Array.isArray(entry.nativeAuth?.env)
|
|
82
|
+
? entry.nativeAuth.env.filter((ref) => typeof ref === 'string' && ref !== '')
|
|
83
|
+
: [],
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
const settings = get('settings')
|
|
87
|
+
const rows = typeof settings?.describe === 'function' ? settings.describe() : []
|
|
88
|
+
for (const row of rows ?? []) {
|
|
89
|
+
if (row && typeof row.ns === 'string') profiles.set(row.ns, row.value)
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
// A harness seam that is not mounted, or throws, is simply absent here.
|
|
93
|
+
}
|
|
94
|
+
return { directory, profiles }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @typedef {object} RouteCredentialResolver
|
|
99
|
+
* @property {(route: string, adapter: {credentialRefs?: readonly string[]}) => Promise<{ref: string, value: string} | undefined>} resolve
|
|
100
|
+
* Resolve the credential that authorizes one route.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Create the per-route credential resolver for one balance service.
|
|
105
|
+
* @param {object} deps Injected dependencies.
|
|
106
|
+
* @param {import('@deepseek-ai/cordis').Context} deps.ctx Host context.
|
|
107
|
+
* @param {(ref: string) => Promise<string | undefined>} deps.resolveCredential
|
|
108
|
+
* Resolves one credential reference to its value.
|
|
109
|
+
* @returns {RouteCredentialResolver} The resolver.
|
|
110
|
+
*/
|
|
111
|
+
export function createRouteCredentialResolver({ ctx, resolveCredential }) {
|
|
112
|
+
/** @type {{directory: ReturnType<typeof readHarnessSnapshot>['directory'], profiles: ReturnType<typeof readHarnessSnapshot>['profiles']} | undefined} */
|
|
113
|
+
let snapshot
|
|
114
|
+
let readAt = 0
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The current harness snapshot, refreshed on a slow clock.
|
|
118
|
+
* @returns {{directory: ReturnType<typeof readHarnessSnapshot>['directory'], profiles: ReturnType<typeof readHarnessSnapshot>['profiles']}} The snapshot.
|
|
119
|
+
*/
|
|
120
|
+
const harness = () => {
|
|
121
|
+
if (snapshot !== undefined && Date.now() - readAt < SNAPSHOT_TTL_MS) return snapshot
|
|
122
|
+
snapshot = readHarnessSnapshot(ctx)
|
|
123
|
+
readAt = Date.now()
|
|
124
|
+
return snapshot
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The credential references worth trying for one route, most authoritative
|
|
129
|
+
* first and without duplicates.
|
|
130
|
+
* @param {string} route Provider route.
|
|
131
|
+
* @param {{credentialRefs?: readonly string[]}} adapter Adapter serving the route.
|
|
132
|
+
* @returns {string[]} The references.
|
|
133
|
+
*/
|
|
134
|
+
function candidateRefs(route, adapter) {
|
|
135
|
+
/** @type {string[]} */
|
|
136
|
+
const refs = []
|
|
137
|
+
const seen = new Set()
|
|
138
|
+
/** @param {unknown} ref Candidate reference. */
|
|
139
|
+
const push = (ref) => {
|
|
140
|
+
if (typeof ref !== 'string' || ref === '' || seen.has(ref)) return
|
|
141
|
+
seen.add(ref)
|
|
142
|
+
refs.push(ref)
|
|
143
|
+
}
|
|
144
|
+
const { directory, profiles } = harness()
|
|
145
|
+
const entry = directory.get(route)
|
|
146
|
+
if (entry !== undefined) {
|
|
147
|
+
// The harness names this route, so its answer is authoritative.
|
|
148
|
+
if (entry.settingsNs !== undefined && entry.settingsPath !== undefined) {
|
|
149
|
+
// The profile's own apiKeyEnv is what the LLM request resolves, so it
|
|
150
|
+
// outranks the catalog default even when the two disagree.
|
|
151
|
+
const profile = walkPath(profiles.get(entry.settingsNs), entry.settingsPath)
|
|
152
|
+
if (profile !== null && typeof profile === 'object') {
|
|
153
|
+
push(/** @type {Record<string, unknown>} */ (profile).apiKeyEnv)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
for (const ref of entry.nativeAuthEnv) push(ref)
|
|
157
|
+
return refs
|
|
158
|
+
}
|
|
159
|
+
// The harness does not know this route — a composition without
|
|
160
|
+
// `llm-pi-ai`, or a bare test context — so the adapter's own table answers.
|
|
161
|
+
for (const ref of adapter.credentialRefs ?? []) push(ref)
|
|
162
|
+
return refs
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
async resolve(route, adapter) {
|
|
167
|
+
for (const ref of candidateRefs(route, adapter)) {
|
|
168
|
+
const value = await resolveCredential(ref)
|
|
169
|
+
if (typeof value === 'string' && value !== '') return { ref, value }
|
|
170
|
+
}
|
|
171
|
+
return undefined
|
|
172
|
+
},
|
|
173
|
+
}
|
|
174
|
+
}
|
package/lib/debug.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small debug log for diagnosing provider readings.
|
|
3
|
+
*
|
|
4
|
+
* Host diagnostics normally reach the process console, which a user cannot
|
|
5
|
+
* easily hand back. When `config.debug` is on, this writes the same facts to
|
|
6
|
+
* `<DSH_HOME>/model-allowance-debug.log` so a failing reading can be inspected
|
|
7
|
+
* after the fact. It stays off by default and writes nothing otherwise.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { appendFile, mkdir, rename, rm, stat } from 'node:fs/promises'
|
|
11
|
+
import { homedir } from 'node:os'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
|
|
14
|
+
/** File name inside the DSH home. */
|
|
15
|
+
const LOG_NAME = 'model-allowance-debug.log'
|
|
16
|
+
|
|
17
|
+
/** A debug log this large is handed back as `.1` before the next line. */
|
|
18
|
+
const MAX_LOG_BYTES = 2 * 1024 * 1024
|
|
19
|
+
|
|
20
|
+
/** Directory DSH keeps its profile data in. */
|
|
21
|
+
function dshHome() {
|
|
22
|
+
return process.env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Keep the debug log bounded.
|
|
27
|
+
* @param {string} file Log path.
|
|
28
|
+
* @returns {Promise<void>} Resolves once rotation was considered.
|
|
29
|
+
*/
|
|
30
|
+
async function rotate(file) {
|
|
31
|
+
try {
|
|
32
|
+
const info = await stat(file)
|
|
33
|
+
if (info.size < MAX_LOG_BYTES) return
|
|
34
|
+
const previous = `${file}.1`
|
|
35
|
+
await rm(previous, { force: true })
|
|
36
|
+
await rename(file, previous)
|
|
37
|
+
} catch {
|
|
38
|
+
// A missing or unreadable log is not a rotation failure worth reporting.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Append one line to the debug log.
|
|
44
|
+
* @param {string} message Line to write.
|
|
45
|
+
* @returns {Promise<void>} Resolves once the line is written.
|
|
46
|
+
*/
|
|
47
|
+
export async function logDebug(message) {
|
|
48
|
+
try {
|
|
49
|
+
const home = dshHome()
|
|
50
|
+
await mkdir(home, { recursive: true })
|
|
51
|
+
const file = join(home, LOG_NAME)
|
|
52
|
+
await rotate(file)
|
|
53
|
+
const line = `${new Date().toISOString()} ${message}\n`
|
|
54
|
+
await appendFile(file, line, 'utf8')
|
|
55
|
+
} catch {
|
|
56
|
+
// A debug log that cannot be written must never break a reading.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Describe an error with its stack, for one log line.
|
|
62
|
+
* @param {unknown} error The thrown value.
|
|
63
|
+
* @returns {string} A single-line description.
|
|
64
|
+
*/
|
|
65
|
+
export function describeError(error) {
|
|
66
|
+
if (error instanceof Error) {
|
|
67
|
+
return `${error.name}: ${error.message}${error.stack ? ` | ${error.stack.split('\n')[1]?.trim() ?? ''}` : ''}`
|
|
68
|
+
}
|
|
69
|
+
return String(error)
|
|
70
|
+
}
|