@jxgame2020/dsh-token-quota 0.1.44 → 0.1.51
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/lib/client.js +625 -178
- package/lib/index.js +172 -130
- package/lib/types/client/TokenQuotaPanel.js +60 -17
- package/lib/types/client/TokenQuotaStash.d.ts +10 -0
- package/lib/types/client/TokenQuotaStash.js +252 -0
- package/lib/types/client/index.js +88 -4
- package/lib/types/client/locales.d.ts +8 -0
- package/lib/types/client/locales.js +8 -0
- package/lib/types/client/mic.js +1 -1
- package/lib/types/client/stash.d.ts +37 -0
- package/lib/types/client/stash.js +47 -0
- package/lib/types/index.d.ts +16 -5
- package/lib/types/index.js +214 -152
- package/lib/types/types.d.ts +4 -2
- package/package.json +1 -1
package/lib/types/index.js
CHANGED
|
@@ -38,8 +38,8 @@ import z from '@deepseek-ai/schemastery';
|
|
|
38
38
|
// the service listens to without importing any runtime value.
|
|
39
39
|
import '@deepseek-ai/dsh-agent';
|
|
40
40
|
import { LlmError } from '@deepseek-ai/dsh-llm';
|
|
41
|
-
import { TOKEN_QUOTA_EXCEEDED_CODE,
|
|
42
|
-
import {
|
|
41
|
+
import { TOKEN_QUOTA_EXCEEDED_CODE, tokenQuotaKey, TOKEN_QUOTA_DEFAULT_MUSIC, TOKEN_QUOTA_MAX_NOTES, TOKEN_QUOTA_DEFAULT_BALANCE, TOKEN_QUOTA_DEFAULT_TRANSCRIBE, } from "./types.js";
|
|
42
|
+
import { splitTokenQuotaKey } from "./invariant.js";
|
|
43
43
|
/** The plugin's package name, used to locate the profile dependency and the registry endpoint. */
|
|
44
44
|
const PACKAGE_NAME = '@jxgame2020/dsh-token-quota';
|
|
45
45
|
/** npm registry endpoint for the plugin's latest version. */
|
|
@@ -191,7 +191,7 @@ function isNewer(latest, current) {
|
|
|
191
191
|
return false;
|
|
192
192
|
}
|
|
193
193
|
/** Settings schema resolving the per-model daily caps document. */
|
|
194
|
-
const
|
|
194
|
+
const TOKEN_QUOTA_SETTINGS_FIELDS = {
|
|
195
195
|
limits: z.dict(z.number().step(1).min(0)).default({}),
|
|
196
196
|
monitored: z.array(z.string()).default([]),
|
|
197
197
|
// `switchPriority` is a legacy value accepted for documents saved by older
|
|
@@ -240,7 +240,7 @@ const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
|
|
|
240
240
|
apiKeyEnv: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv),
|
|
241
241
|
model: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model),
|
|
242
242
|
}).default({ ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE }),
|
|
243
|
-
}
|
|
243
|
+
};
|
|
244
244
|
/** Two-digit zero-pad helper. */
|
|
245
245
|
function pad2(value) {
|
|
246
246
|
return String(value).padStart(2, '0');
|
|
@@ -281,9 +281,92 @@ function usageTokens(usage) {
|
|
|
281
281
|
}
|
|
282
282
|
/** DeepSeek's public API host; used to recognise DeepSeek-family providers. */
|
|
283
283
|
const DEEPSEEK_BALANCE_HOST = 'api.deepseek.com';
|
|
284
|
+
/** TeamoRouter's host; its model and billing endpoints share this domain. */
|
|
285
|
+
const TEAMOROUTER_HOST = 'teamorouter.cn';
|
|
286
|
+
/** Fallback currency per family, used before the first successful fetch. */
|
|
287
|
+
const BALANCE_DEFAULT_CURRENCY = {
|
|
288
|
+
deepseek: 'CNY',
|
|
289
|
+
teamorouter: 'USD',
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* Recognise which balance family a provider belongs to, from its endpoint, its
|
|
293
|
+
* credential reference, or its route id. Returns undefined for providers whose
|
|
294
|
+
* balance this plugin cannot query.
|
|
295
|
+
* @param provider - registered provider route id.
|
|
296
|
+
* @param keyEnv - the provider's declared `apiKeyEnv`, when it has one.
|
|
297
|
+
* @param baseURL - the provider's endpoint base, when it declares one.
|
|
298
|
+
* @returns the matching family, or undefined.
|
|
299
|
+
*/
|
|
300
|
+
function balanceKindOf(provider, keyEnv, baseURL) {
|
|
301
|
+
const host = (baseURL ?? '').toLowerCase();
|
|
302
|
+
const key = (keyEnv ?? '').toUpperCase();
|
|
303
|
+
const id = provider.toLowerCase();
|
|
304
|
+
if (host.includes(DEEPSEEK_BALANCE_HOST) || key.startsWith('DEEPSEEK') || id.startsWith('deepseek')) {
|
|
305
|
+
return 'deepseek';
|
|
306
|
+
}
|
|
307
|
+
if (host.includes(TEAMOROUTER_HOST) || key.includes('TEAMO') || id.includes('teamo')) {
|
|
308
|
+
return 'teamorouter';
|
|
309
|
+
}
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* The balance endpoint for one family. TeamoRouter serves billing from the apex
|
|
314
|
+
* host while its model endpoint lives on the `api.` subdomain, so the host is
|
|
315
|
+
* rewritten rather than concatenated.
|
|
316
|
+
* @param kind - balance family.
|
|
317
|
+
* @param baseURL - the provider's model endpoint base.
|
|
318
|
+
* @returns the absolute balance URL.
|
|
319
|
+
*/
|
|
320
|
+
function balanceURLOf(kind, baseURL) {
|
|
321
|
+
const base = baseURL.replace(/\/+$/, '');
|
|
322
|
+
if (kind === 'teamorouter') {
|
|
323
|
+
return `${base.replace('//api.teamorouter.cn', '//teamorouter.cn')}/billing/balance`;
|
|
324
|
+
}
|
|
325
|
+
return `${base}/user/balance`;
|
|
326
|
+
}
|
|
327
|
+
/** Read a number out of a wire field that may be a string or a number. */
|
|
328
|
+
function balanceNum(value, fallback = 0) {
|
|
329
|
+
const n = typeof value === 'number' ? value
|
|
330
|
+
: typeof value === 'string' && value !== '' ? Number(value)
|
|
331
|
+
: NaN;
|
|
332
|
+
return Number.isFinite(n) ? n : fallback;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* DeepSeek: `{ is_available, balance_infos: [{ currency, total_balance,
|
|
336
|
+
* granted_balance, topped_up_balance }] }`.
|
|
337
|
+
*/
|
|
338
|
+
function parseDeepseekBalance(data) {
|
|
339
|
+
const record = (data ?? {});
|
|
340
|
+
const first = Array.isArray(record.balance_infos)
|
|
341
|
+
? record.balance_infos[0]
|
|
342
|
+
: undefined;
|
|
343
|
+
return {
|
|
344
|
+
currency: typeof first?.currency === 'string' && first.currency !== '' ? first.currency : 'CNY',
|
|
345
|
+
total: balanceNum(first?.total_balance),
|
|
346
|
+
granted: balanceNum(first?.granted_balance),
|
|
347
|
+
toppedUp: balanceNum(first?.topped_up_balance),
|
|
348
|
+
isAvailable: record.is_available !== false,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* TeamoRouter: `{ balance: { value: "85.320000", currency: "USD" } }`. The
|
|
353
|
+
* account is identified by the API key, so there is no availability flag.
|
|
354
|
+
*/
|
|
355
|
+
function parseTeamorouterBalance(data) {
|
|
356
|
+
const record = (data ?? {});
|
|
357
|
+
const balance = record.balance !== null && typeof record.balance === 'object'
|
|
358
|
+
? record.balance
|
|
359
|
+
: undefined;
|
|
360
|
+
return {
|
|
361
|
+
currency: typeof balance?.currency === 'string' && balance.currency !== '' ? balance.currency : 'USD',
|
|
362
|
+
total: balanceNum(balance?.value),
|
|
363
|
+
isAvailable: true,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
284
366
|
export class TokenQuotaService extends Service {
|
|
285
367
|
static Config = z.object({
|
|
286
368
|
storagePath: z.string().default(''),
|
|
369
|
+
...TOKEN_QUOTA_SETTINGS_FIELDS,
|
|
287
370
|
});
|
|
288
371
|
storagePath;
|
|
289
372
|
reset = {
|
|
@@ -296,7 +379,84 @@ export class TokenQuotaService extends Service {
|
|
|
296
379
|
history = {};
|
|
297
380
|
limits = {};
|
|
298
381
|
monitored = undefined;
|
|
299
|
-
|
|
382
|
+
/** Settings resolved from this plugin entry's own config (see applySettings). */
|
|
383
|
+
resolvedSettings = { limits: {}, monitored: [], onFull: 'stop', checkUpdates: true, dimWhenIdle: false, music: { ...TOKEN_QUOTA_DEFAULT_MUSIC }, order: [], notes: [], balance: { ...TOKEN_QUOTA_DEFAULT_BALANCE }, transcribe: { ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE } };
|
|
384
|
+
/** The settings document this instance runs with. */
|
|
385
|
+
settingsSource = () => this.resolvedSettings;
|
|
386
|
+
/**
|
|
387
|
+
* Normalize this entry's config into the plugin's settings shape and apply
|
|
388
|
+
* it. Called once per instantiation: a settings write from the panel reloads
|
|
389
|
+
* the entry, so this is the live-apply path that used to be an onChange
|
|
390
|
+
* callback.
|
|
391
|
+
* @param config - the plugin entry config (Config schema, defaults applied).
|
|
392
|
+
*/
|
|
393
|
+
applySettings(config) {
|
|
394
|
+
const doc = config;
|
|
395
|
+
const settings = {
|
|
396
|
+
limits: doc.limits ?? {},
|
|
397
|
+
monitored: doc.monitored ?? [],
|
|
398
|
+
onFull: doc.onFull === 'switchPriority' ? 'switchAll' : (doc.onFull ?? 'stop'),
|
|
399
|
+
checkUpdates: doc.checkUpdates ?? true,
|
|
400
|
+
dimWhenIdle: doc.dimWhenIdle ?? false,
|
|
401
|
+
order: Array.isArray(doc.order) ? doc.order : [],
|
|
402
|
+
balance: {
|
|
403
|
+
enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
|
|
404
|
+
pollMinutes: typeof doc.balance?.pollMinutes === 'number'
|
|
405
|
+
? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes)))
|
|
406
|
+
: TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes,
|
|
407
|
+
},
|
|
408
|
+
transcribe: {
|
|
409
|
+
enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
|
|
410
|
+
baseURL: typeof doc.transcribe?.baseURL === 'string' && doc.transcribe.baseURL !== ''
|
|
411
|
+
? doc.transcribe.baseURL.replace(/\/+$/, '')
|
|
412
|
+
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
|
|
413
|
+
apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === 'string' && doc.transcribe.apiKeyEnv !== ''
|
|
414
|
+
? doc.transcribe.apiKeyEnv
|
|
415
|
+
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
|
|
416
|
+
model: typeof doc.transcribe?.model === 'string' && doc.transcribe.model !== ''
|
|
417
|
+
? doc.transcribe.model
|
|
418
|
+
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model,
|
|
419
|
+
},
|
|
420
|
+
music: {
|
|
421
|
+
enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
|
|
422
|
+
volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
|
|
423
|
+
style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
|
|
424
|
+
onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession,
|
|
425
|
+
},
|
|
426
|
+
notes: Array.isArray(doc.notes) ? doc.notes.slice(0, TOKEN_QUOTA_MAX_NOTES) : [],
|
|
427
|
+
...doc.reset !== undefined && doc.reset !== null ? { reset: doc.reset } : {},
|
|
428
|
+
};
|
|
429
|
+
this.resolvedSettings = settings;
|
|
430
|
+
// Live-apply the parts the service acts on.
|
|
431
|
+
this.limits = { ...settings.limits };
|
|
432
|
+
this.monitored = settings.monitored.length > 0 ? new Set(settings.monitored) : undefined;
|
|
433
|
+
this.checkUpdates = settings.checkUpdates;
|
|
434
|
+
const balanceEnabled = settings.balance.enabled;
|
|
435
|
+
const turnedOn = balanceEnabled && !this.balanceEnabled;
|
|
436
|
+
this.balanceEnabled = balanceEnabled;
|
|
437
|
+
if (!balanceEnabled)
|
|
438
|
+
this.balances.clear();
|
|
439
|
+
const configured = settings.reset;
|
|
440
|
+
if (configured !== undefined
|
|
441
|
+
&& typeof configured === 'object'
|
|
442
|
+
&& configured !== null
|
|
443
|
+
&& typeof configured.offsetHours === 'number'
|
|
444
|
+
&& typeof configured.hour === 'number'
|
|
445
|
+
&& typeof configured.minute === 'number') {
|
|
446
|
+
this.reset = {
|
|
447
|
+
offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
|
|
448
|
+
hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
|
|
449
|
+
minute: Math.max(0, Math.min(59, Math.round(configured.minute))),
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
this.reset = { offsetHours: localOffsetHours(), hour: 0, minute: 0 };
|
|
454
|
+
}
|
|
455
|
+
this.rollCycleIfNeeded();
|
|
456
|
+
// Turning balance polling on fetches immediately so the panel has numbers.
|
|
457
|
+
if (turnedOn)
|
|
458
|
+
void this.refreshAllBalances();
|
|
459
|
+
}
|
|
300
460
|
/** Whether update checks are enabled (mirrors the settings document). */
|
|
301
461
|
checkUpdates = true;
|
|
302
462
|
/** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
|
|
@@ -351,118 +511,11 @@ export class TokenQuotaService extends Service {
|
|
|
351
511
|
? config.storagePath
|
|
352
512
|
: defaultStoragePath();
|
|
353
513
|
this.load();
|
|
354
|
-
//
|
|
355
|
-
// the
|
|
356
|
-
// the
|
|
357
|
-
//
|
|
358
|
-
|
|
359
|
-
ctx.inject(['settings'], (settingsCtx) => {
|
|
360
|
-
settingsCtx.settings.installSection(ctx, TOKEN_QUOTA_NAMESPACE, TOKEN_QUOTA_SETTINGS_SCHEMA, { limits: {} }, {
|
|
361
|
-
setSource: (current) => {
|
|
362
|
-
// Normalize the resolved (schema-shaped) document into the plugin's
|
|
363
|
-
// required shape: empty monitored = monitor everything, absent onFull
|
|
364
|
-
// falls back to 'stop'.
|
|
365
|
-
this.settingsSource = () => {
|
|
366
|
-
const doc = current();
|
|
367
|
-
return {
|
|
368
|
-
limits: doc.limits ?? {},
|
|
369
|
-
monitored: doc.monitored ?? [],
|
|
370
|
-
// Legacy `switchPriority` (removed in 0.1.7) maps to `switchAll`:
|
|
371
|
-
// capped models first, then uncapped — both monitored-only.
|
|
372
|
-
onFull: doc.onFull === 'switchPriority' ? 'switchAll' : (doc.onFull ?? 'stop'),
|
|
373
|
-
checkUpdates: doc.checkUpdates ?? true,
|
|
374
|
-
dimWhenIdle: doc.dimWhenIdle ?? false,
|
|
375
|
-
order: Array.isArray(doc.order) ? doc.order : [],
|
|
376
|
-
balance: {
|
|
377
|
-
enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
|
|
378
|
-
pollMinutes: typeof doc.balance?.pollMinutes === 'number'
|
|
379
|
-
? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes)))
|
|
380
|
-
: TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes,
|
|
381
|
-
},
|
|
382
|
-
transcribe: {
|
|
383
|
-
enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
|
|
384
|
-
baseURL: typeof doc.transcribe?.baseURL === 'string' && doc.transcribe.baseURL !== ''
|
|
385
|
-
? doc.transcribe.baseURL.replace(/\/+$/, '')
|
|
386
|
-
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
|
|
387
|
-
apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === 'string' && doc.transcribe.apiKeyEnv !== ''
|
|
388
|
-
? doc.transcribe.apiKeyEnv
|
|
389
|
-
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
|
|
390
|
-
model: typeof doc.transcribe?.model === 'string' && doc.transcribe.model !== ''
|
|
391
|
-
? doc.transcribe.model
|
|
392
|
-
: TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model,
|
|
393
|
-
},
|
|
394
|
-
notes: Array.isArray(doc.notes)
|
|
395
|
-
? doc.notes.slice(0, TOKEN_QUOTA_MAX_NOTES).flatMap((note) => {
|
|
396
|
-
if (typeof note.id !== 'string')
|
|
397
|
-
return [];
|
|
398
|
-
return [{
|
|
399
|
-
id: note.id,
|
|
400
|
-
title: note.title ?? '',
|
|
401
|
-
text: note.text ?? '',
|
|
402
|
-
x: note.x ?? 80,
|
|
403
|
-
y: note.y ?? 80,
|
|
404
|
-
width: note.width ?? 220,
|
|
405
|
-
height: note.height ?? 220,
|
|
406
|
-
collapsed: note.collapsed ?? false,
|
|
407
|
-
visible: note.visible ?? true,
|
|
408
|
-
}];
|
|
409
|
-
})
|
|
410
|
-
: [],
|
|
411
|
-
reset: doc.reset ?? undefined,
|
|
412
|
-
music: {
|
|
413
|
-
enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
|
|
414
|
-
volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
|
|
415
|
-
style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
|
|
416
|
-
onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession,
|
|
417
|
-
},
|
|
418
|
-
};
|
|
419
|
-
};
|
|
420
|
-
},
|
|
421
|
-
validate: (value) => {
|
|
422
|
-
for (const [key, limit] of Object.entries(value.limits ?? {})) {
|
|
423
|
-
assertTokenQuotaLimit(limit, key);
|
|
424
|
-
splitTokenQuotaKey(key);
|
|
425
|
-
}
|
|
426
|
-
},
|
|
427
|
-
onChange: () => {
|
|
428
|
-
const doc = this.settingsSource();
|
|
429
|
-
this.limits = { ...doc.limits };
|
|
430
|
-
this.monitored = doc.monitored !== undefined && doc.monitored.length > 0
|
|
431
|
-
? new Set(doc.monitored)
|
|
432
|
-
: undefined;
|
|
433
|
-
this.checkUpdates = doc.checkUpdates;
|
|
434
|
-
this.syncUpdateChecking();
|
|
435
|
-
const balanceEnabled = doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled;
|
|
436
|
-
const turnedOn = balanceEnabled && !this.balanceEnabled;
|
|
437
|
-
this.balanceEnabled = balanceEnabled;
|
|
438
|
-
if (!balanceEnabled)
|
|
439
|
-
this.balances.clear();
|
|
440
|
-
this.syncBalancePolling();
|
|
441
|
-
// Flipping the toggle on: fetch right away so the panel shows numbers.
|
|
442
|
-
if (turnedOn)
|
|
443
|
-
void this.refreshAllBalances();
|
|
444
|
-
if (doc.reset !== undefined
|
|
445
|
-
&& typeof doc.reset === 'object'
|
|
446
|
-
&& doc.reset !== null
|
|
447
|
-
&& typeof doc.reset.offsetHours === 'number'
|
|
448
|
-
&& typeof doc.reset.hour === 'number'
|
|
449
|
-
&& typeof doc.reset.minute === 'number') {
|
|
450
|
-
const configured = doc.reset;
|
|
451
|
-
this.reset = {
|
|
452
|
-
offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
|
|
453
|
-
hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
|
|
454
|
-
minute: Math.max(0, Math.min(59, Math.round(configured.minute))),
|
|
455
|
-
};
|
|
456
|
-
this.rollCycleIfNeeded();
|
|
457
|
-
}
|
|
458
|
-
else {
|
|
459
|
-
// null / malformed (unset) = machine-local midnight — the default.
|
|
460
|
-
this.reset = { offsetHours: localOffsetHours(), hour: 0, minute: 0 };
|
|
461
|
-
this.rollCycleIfNeeded();
|
|
462
|
-
}
|
|
463
|
-
},
|
|
464
|
-
});
|
|
465
|
-
});
|
|
514
|
+
// This Harness version exposes a plugin's Config AS its settings namespace:
|
|
515
|
+
// the panel writes through `remote.settings`, the loader re-applies this
|
|
516
|
+
// entry, and the live-apply work that used to hang off `installSection`'s
|
|
517
|
+
// onChange callback happens once per instantiation instead.
|
|
518
|
+
this.applySettings(config);
|
|
466
519
|
// Snapshot route: optional — only mounted when a webServer service exists
|
|
467
520
|
// (the Web profile); headless deployments keep the enforcement without it.
|
|
468
521
|
this.tryMountRoute();
|
|
@@ -784,20 +837,35 @@ export class TokenQuotaService extends Service {
|
|
|
784
837
|
.map(source => this.refreshProviderBalance(source.provider, source))).then(() => undefined);
|
|
785
838
|
}
|
|
786
839
|
/**
|
|
787
|
-
* Discover every provider in the model directory
|
|
788
|
-
* together with its own credential reference and endpoint base.
|
|
789
|
-
* decides which providers are queried: a provider qualifies when
|
|
790
|
-
*
|
|
791
|
-
*
|
|
840
|
+
* Discover every provider in the model directory whose balance this plugin
|
|
841
|
+
* can query, together with its own credential reference and endpoint base.
|
|
842
|
+
* This is what decides which providers are queried: a provider qualifies when
|
|
843
|
+
* its base URL, credential reference, or route id matches a supported family
|
|
844
|
+
* (see {@link balanceKindOf}), and it must declare an `apiKeyEnv`.
|
|
792
845
|
*/
|
|
793
846
|
discoverBalanceSources() {
|
|
794
847
|
const found = new Map();
|
|
795
848
|
const llm = this.ctx.get('llm');
|
|
796
|
-
|
|
849
|
+
// Provider profiles live in OTHER plugins' entry configs. This Harness
|
|
850
|
+
// version dropped `settings.get(ns)`, so read the composed configuration
|
|
851
|
+
// once from the config editor and index it by profile entry id.
|
|
852
|
+
const configEditor = this.ctx.get('configEditor');
|
|
853
|
+
const liveConfigs = new Map();
|
|
854
|
+
try {
|
|
855
|
+
for (const row of configEditor?.configuration() ?? []) {
|
|
856
|
+
const id = row.entry.options.id;
|
|
857
|
+
if (id !== undefined)
|
|
858
|
+
liveConfigs.set(id, row.entry.options.config);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
catch {
|
|
862
|
+
// No config editor in this deployment: balance discovery falls back.
|
|
863
|
+
}
|
|
797
864
|
const fallback = () => ({
|
|
798
865
|
provider: 'deepseek',
|
|
799
866
|
keyEnv: 'DEEPSEEK_API_KEY',
|
|
800
867
|
baseURL: process.env.DEEPSEEK_BASE_URL ?? `https://${DEEPSEEK_BALANCE_HOST}`,
|
|
868
|
+
kind: 'deepseek',
|
|
801
869
|
});
|
|
802
870
|
if (llm?.listConfigurableProviders === undefined) {
|
|
803
871
|
found.set('deepseek', fallback());
|
|
@@ -805,7 +873,7 @@ export class TokenQuotaService extends Service {
|
|
|
805
873
|
}
|
|
806
874
|
for (const entry of llm.listConfigurableProviders()) {
|
|
807
875
|
try {
|
|
808
|
-
let profile =
|
|
876
|
+
let profile = liveConfigs.get(entry.settingsNs);
|
|
809
877
|
for (const segment of entry.settingsPath ?? []) {
|
|
810
878
|
profile = profile !== null && typeof profile === 'object'
|
|
811
879
|
? profile[segment]
|
|
@@ -820,15 +888,14 @@ export class TokenQuotaService extends Service {
|
|
|
820
888
|
const baseURL = typeof record.baseURL === 'string' && record.baseURL !== ''
|
|
821
889
|
? record.baseURL
|
|
822
890
|
: undefined;
|
|
823
|
-
const
|
|
824
|
-
|
|
825
|
-
|| entry.provider.startsWith('deepseek');
|
|
826
|
-
if (!isDeepSeek || keyEnv === undefined)
|
|
891
|
+
const kind = balanceKindOf(entry.provider, keyEnv, baseURL);
|
|
892
|
+
if (kind === undefined || keyEnv === undefined)
|
|
827
893
|
continue;
|
|
828
894
|
found.set(entry.provider, {
|
|
829
895
|
provider: entry.provider,
|
|
830
896
|
keyEnv,
|
|
831
|
-
baseURL: baseURL ?? `https://${DEEPSEEK_BALANCE_HOST}
|
|
897
|
+
baseURL: baseURL ?? (kind === 'deepseek' ? `https://${DEEPSEEK_BALANCE_HOST}` : `https://${TEAMOROUTER_HOST}`),
|
|
898
|
+
kind,
|
|
832
899
|
});
|
|
833
900
|
}
|
|
834
901
|
catch {
|
|
@@ -870,7 +937,7 @@ export class TokenQuotaService extends Service {
|
|
|
870
937
|
if (key === undefined || key === '') {
|
|
871
938
|
this.balances.set(provider, {
|
|
872
939
|
provider,
|
|
873
|
-
currency:
|
|
940
|
+
currency: BALANCE_DEFAULT_CURRENCY[resolved.kind],
|
|
874
941
|
total: 0,
|
|
875
942
|
isAvailable: false,
|
|
876
943
|
fetchedAt: Date.now(),
|
|
@@ -878,13 +945,12 @@ export class TokenQuotaService extends Service {
|
|
|
878
945
|
});
|
|
879
946
|
return;
|
|
880
947
|
}
|
|
881
|
-
const base = resolved.baseURL;
|
|
882
948
|
try {
|
|
883
949
|
const controller = new AbortController();
|
|
884
950
|
const timer = setTimeout(() => { controller.abort(); }, 10_000);
|
|
885
951
|
let res;
|
|
886
952
|
try {
|
|
887
|
-
res = await fetch(
|
|
953
|
+
res = await fetch(balanceURLOf(resolved.kind, resolved.baseURL), {
|
|
888
954
|
headers: { authorization: `Bearer ${key}`, accept: 'application/json' },
|
|
889
955
|
signal: controller.signal,
|
|
890
956
|
});
|
|
@@ -894,34 +960,30 @@ export class TokenQuotaService extends Service {
|
|
|
894
960
|
}
|
|
895
961
|
if (!res.ok)
|
|
896
962
|
throw new Error(`HTTP ${res.status}`);
|
|
897
|
-
const data =
|
|
898
|
-
const
|
|
899
|
-
? data
|
|
900
|
-
:
|
|
901
|
-
const
|
|
902
|
-
const n = typeof value === 'number' ? value
|
|
903
|
-
: typeof value === 'string' && value !== '' ? Number(value)
|
|
904
|
-
: NaN;
|
|
905
|
-
return Number.isFinite(n) ? n : 0;
|
|
906
|
-
};
|
|
907
|
-
this.balances.set(provider, {
|
|
963
|
+
const data = await res.json();
|
|
964
|
+
const parsed = resolved.kind === 'teamorouter'
|
|
965
|
+
? parseTeamorouterBalance(data)
|
|
966
|
+
: parseDeepseekBalance(data);
|
|
967
|
+
const next = {
|
|
908
968
|
provider,
|
|
909
|
-
currency:
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
total: num(first?.total_balance),
|
|
913
|
-
granted: num(first?.granted_balance),
|
|
914
|
-
toppedUp: num(first?.topped_up_balance),
|
|
915
|
-
isAvailable: data?.is_available !== false,
|
|
969
|
+
currency: parsed.currency,
|
|
970
|
+
total: parsed.total,
|
|
971
|
+
isAvailable: parsed.isAvailable,
|
|
916
972
|
fetchedAt: Date.now(),
|
|
917
973
|
status: 'ok',
|
|
918
|
-
}
|
|
974
|
+
};
|
|
975
|
+
// Only set the optional detail fields when the family reports them.
|
|
976
|
+
if (parsed.granted !== undefined)
|
|
977
|
+
next.granted = parsed.granted;
|
|
978
|
+
if (parsed.toppedUp !== undefined)
|
|
979
|
+
next.toppedUp = parsed.toppedUp;
|
|
980
|
+
this.balances.set(provider, next);
|
|
919
981
|
}
|
|
920
982
|
catch (error) {
|
|
921
983
|
const previous = this.balances.get(provider);
|
|
922
984
|
const next = {
|
|
923
985
|
provider,
|
|
924
|
-
currency: previous?.currency ??
|
|
986
|
+
currency: previous?.currency ?? BALANCE_DEFAULT_CURRENCY[resolved.kind],
|
|
925
987
|
total: previous?.total ?? 0,
|
|
926
988
|
isAvailable: false,
|
|
927
989
|
fetchedAt: previous?.fetchedAt ?? Date.now(),
|
package/lib/types/types.d.ts
CHANGED
|
@@ -246,8 +246,10 @@ export interface TokenQuotaSettings {
|
|
|
246
246
|
*/
|
|
247
247
|
order: string[];
|
|
248
248
|
}
|
|
249
|
-
/** Token-quota plugin configuration. */
|
|
250
|
-
export interface TokenQuotaConfig {
|
|
249
|
+
/** Token-quota plugin configuration (the entry config doubles as the namespace). */
|
|
250
|
+
export interface TokenQuotaConfig extends Partial<Omit<TokenQuotaSettings, 'onFull'>> {
|
|
251
|
+
/** Legacy `switchPriority` stays accepted in the schema; the runtime maps it. */
|
|
252
|
+
onFull?: TokenQuotaFullAction | 'switchPriority';
|
|
251
253
|
/**
|
|
252
254
|
* Counter JSON file path. Defaults to `token-quota.json` under the Harness
|
|
253
255
|
* home (`DSH_HOME` or `~/.dsh`).
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jxgame2020/dsh-token-quota",
|
|
3
3
|
"description": "Daily per-model token quota accounting, enforcement, and a floating quota panel for the DeepSeek Harness — a fully self-contained plugin (no core-Harness wiring, no generated RPC contract)",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.51",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|