@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/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { splitTokenQuotaKey } from "./invariant.js";
|
|
2
2
|
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
@@ -7,20 +7,6 @@ import z from "@deepseek-ai/schemastery";
|
|
|
7
7
|
import "@deepseek-ai/dsh-agent";
|
|
8
8
|
import { LlmError } from "@deepseek-ai/dsh-llm";
|
|
9
9
|
//#region lib/types/types.js
|
|
10
|
-
/**
|
|
11
|
-
* Shared wire/type vocabulary for the daily token-quota plugin.
|
|
12
|
-
*
|
|
13
|
-
* The Host half owns the durable per-model daily counter and the enforcement
|
|
14
|
-
* gate; the browser half renders a floating panel from the snapshot it pulls
|
|
15
|
-
* over a plugin-owned HTTP route, and writes per-model limits and panel
|
|
16
|
-
* preferences through the settings document. This module is the one meeting
|
|
17
|
-
* point of the two planes: it carries strings and shapes only, never a
|
|
18
|
-
* runtime import from the other half.
|
|
19
|
-
*
|
|
20
|
-
* @module @jxgame2020/dsh-token-quota/types
|
|
21
|
-
*/
|
|
22
|
-
/** Settings namespace owning the per-model daily limits document. */
|
|
23
|
-
const TOKEN_QUOTA_NAMESPACE = "token-quota";
|
|
24
10
|
/** Stable machine code thrown from `agent/request` when a model is over its daily cap. */
|
|
25
11
|
const TOKEN_QUOTA_EXCEEDED_CODE = "TOKEN_QUOTA_EXCEEDED";
|
|
26
12
|
const TOKEN_QUOTA_DEFAULT_BALANCE = {
|
|
@@ -213,7 +199,7 @@ function isNewer(latest, current) {
|
|
|
213
199
|
return false;
|
|
214
200
|
}
|
|
215
201
|
/** Settings schema resolving the per-model daily caps document. */
|
|
216
|
-
const
|
|
202
|
+
const TOKEN_QUOTA_SETTINGS_FIELDS = {
|
|
217
203
|
limits: z.dict(z.number().step(1).min(0)).default({}),
|
|
218
204
|
monitored: z.array(z.string()).default([]),
|
|
219
205
|
onFull: z.union([
|
|
@@ -257,7 +243,7 @@ const TOKEN_QUOTA_SETTINGS_SCHEMA = z.object({
|
|
|
257
243
|
apiKeyEnv: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv),
|
|
258
244
|
model: z.string().default(TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model)
|
|
259
245
|
}).default({ ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE })
|
|
260
|
-
}
|
|
246
|
+
};
|
|
261
247
|
/** Two-digit zero-pad helper. */
|
|
262
248
|
function pad2(value) {
|
|
263
249
|
return String(value).padStart(2, "0");
|
|
@@ -290,8 +276,80 @@ function usageTokens(usage) {
|
|
|
290
276
|
}
|
|
291
277
|
/** DeepSeek's public API host; used to recognise DeepSeek-family providers. */
|
|
292
278
|
const DEEPSEEK_BALANCE_HOST = "api.deepseek.com";
|
|
279
|
+
/** TeamoRouter's host; its model and billing endpoints share this domain. */
|
|
280
|
+
const TEAMOROUTER_HOST = "teamorouter.cn";
|
|
281
|
+
/** Fallback currency per family, used before the first successful fetch. */
|
|
282
|
+
const BALANCE_DEFAULT_CURRENCY = {
|
|
283
|
+
deepseek: "CNY",
|
|
284
|
+
teamorouter: "USD"
|
|
285
|
+
};
|
|
286
|
+
/**
|
|
287
|
+
* Recognise which balance family a provider belongs to, from its endpoint, its
|
|
288
|
+
* credential reference, or its route id. Returns undefined for providers whose
|
|
289
|
+
* balance this plugin cannot query.
|
|
290
|
+
* @param provider - registered provider route id.
|
|
291
|
+
* @param keyEnv - the provider's declared `apiKeyEnv`, when it has one.
|
|
292
|
+
* @param baseURL - the provider's endpoint base, when it declares one.
|
|
293
|
+
* @returns the matching family, or undefined.
|
|
294
|
+
*/
|
|
295
|
+
function balanceKindOf(provider, keyEnv, baseURL) {
|
|
296
|
+
const host = (baseURL ?? "").toLowerCase();
|
|
297
|
+
const key = (keyEnv ?? "").toUpperCase();
|
|
298
|
+
const id = provider.toLowerCase();
|
|
299
|
+
if (host.includes(DEEPSEEK_BALANCE_HOST) || key.startsWith("DEEPSEEK") || id.startsWith("deepseek")) return "deepseek";
|
|
300
|
+
if (host.includes(TEAMOROUTER_HOST) || key.includes("TEAMO") || id.includes("teamo")) return "teamorouter";
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* The balance endpoint for one family. TeamoRouter serves billing from the apex
|
|
304
|
+
* host while its model endpoint lives on the `api.` subdomain, so the host is
|
|
305
|
+
* rewritten rather than concatenated.
|
|
306
|
+
* @param kind - balance family.
|
|
307
|
+
* @param baseURL - the provider's model endpoint base.
|
|
308
|
+
* @returns the absolute balance URL.
|
|
309
|
+
*/
|
|
310
|
+
function balanceURLOf(kind, baseURL) {
|
|
311
|
+
const base = baseURL.replace(/\/+$/, "");
|
|
312
|
+
if (kind === "teamorouter") return `${base.replace("//api.teamorouter.cn", "//teamorouter.cn")}/billing/balance`;
|
|
313
|
+
return `${base}/user/balance`;
|
|
314
|
+
}
|
|
315
|
+
/** Read a number out of a wire field that may be a string or a number. */
|
|
316
|
+
function balanceNum(value, fallback = 0) {
|
|
317
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value !== "" ? Number(value) : NaN;
|
|
318
|
+
return Number.isFinite(n) ? n : fallback;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* DeepSeek: `{ is_available, balance_infos: [{ currency, total_balance,
|
|
322
|
+
* granted_balance, topped_up_balance }] }`.
|
|
323
|
+
*/
|
|
324
|
+
function parseDeepseekBalance(data) {
|
|
325
|
+
const record = data ?? {};
|
|
326
|
+
const first = Array.isArray(record.balance_infos) ? record.balance_infos[0] : void 0;
|
|
327
|
+
return {
|
|
328
|
+
currency: typeof first?.currency === "string" && first.currency !== "" ? first.currency : "CNY",
|
|
329
|
+
total: balanceNum(first?.total_balance),
|
|
330
|
+
granted: balanceNum(first?.granted_balance),
|
|
331
|
+
toppedUp: balanceNum(first?.topped_up_balance),
|
|
332
|
+
isAvailable: record.is_available !== false
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* TeamoRouter: `{ balance: { value: "85.320000", currency: "USD" } }`. The
|
|
337
|
+
* account is identified by the API key, so there is no availability flag.
|
|
338
|
+
*/
|
|
339
|
+
function parseTeamorouterBalance(data) {
|
|
340
|
+
const record = data ?? {};
|
|
341
|
+
const balance = record.balance !== null && typeof record.balance === "object" ? record.balance : void 0;
|
|
342
|
+
return {
|
|
343
|
+
currency: typeof balance?.currency === "string" && balance.currency !== "" ? balance.currency : "USD",
|
|
344
|
+
total: balanceNum(balance?.value),
|
|
345
|
+
isAvailable: true
|
|
346
|
+
};
|
|
347
|
+
}
|
|
293
348
|
var TokenQuotaService = class TokenQuotaService extends Service {
|
|
294
|
-
static Config = z.object({
|
|
349
|
+
static Config = z.object({
|
|
350
|
+
storagePath: z.string().default(""),
|
|
351
|
+
...TOKEN_QUOTA_SETTINGS_FIELDS
|
|
352
|
+
});
|
|
295
353
|
storagePath;
|
|
296
354
|
reset = {
|
|
297
355
|
offsetHours: localOffsetHours(),
|
|
@@ -303,7 +361,8 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
303
361
|
history = {};
|
|
304
362
|
limits = {};
|
|
305
363
|
monitored = void 0;
|
|
306
|
-
|
|
364
|
+
/** Settings resolved from this plugin entry's own config (see applySettings). */
|
|
365
|
+
resolvedSettings = {
|
|
307
366
|
limits: {},
|
|
308
367
|
monitored: [],
|
|
309
368
|
onFull: "stop",
|
|
@@ -314,7 +373,66 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
314
373
|
notes: [],
|
|
315
374
|
balance: { ...TOKEN_QUOTA_DEFAULT_BALANCE },
|
|
316
375
|
transcribe: { ...TOKEN_QUOTA_DEFAULT_TRANSCRIBE }
|
|
317
|
-
}
|
|
376
|
+
};
|
|
377
|
+
/** The settings document this instance runs with. */
|
|
378
|
+
settingsSource = () => this.resolvedSettings;
|
|
379
|
+
/**
|
|
380
|
+
* Normalize this entry's config into the plugin's settings shape and apply
|
|
381
|
+
* it. Called once per instantiation: a settings write from the panel reloads
|
|
382
|
+
* the entry, so this is the live-apply path that used to be an onChange
|
|
383
|
+
* callback.
|
|
384
|
+
* @param config - the plugin entry config (Config schema, defaults applied).
|
|
385
|
+
*/
|
|
386
|
+
applySettings(config) {
|
|
387
|
+
const doc = config;
|
|
388
|
+
const settings = {
|
|
389
|
+
limits: doc.limits ?? {},
|
|
390
|
+
monitored: doc.monitored ?? [],
|
|
391
|
+
onFull: doc.onFull === "switchPriority" ? "switchAll" : doc.onFull ?? "stop",
|
|
392
|
+
checkUpdates: doc.checkUpdates ?? true,
|
|
393
|
+
dimWhenIdle: doc.dimWhenIdle ?? false,
|
|
394
|
+
order: Array.isArray(doc.order) ? doc.order : [],
|
|
395
|
+
balance: {
|
|
396
|
+
enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
|
|
397
|
+
pollMinutes: typeof doc.balance?.pollMinutes === "number" ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes))) : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes
|
|
398
|
+
},
|
|
399
|
+
transcribe: {
|
|
400
|
+
enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
|
|
401
|
+
baseURL: typeof doc.transcribe?.baseURL === "string" && doc.transcribe.baseURL !== "" ? doc.transcribe.baseURL.replace(/\/+$/, "") : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
|
|
402
|
+
apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === "string" && doc.transcribe.apiKeyEnv !== "" ? doc.transcribe.apiKeyEnv : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
|
|
403
|
+
model: typeof doc.transcribe?.model === "string" && doc.transcribe.model !== "" ? doc.transcribe.model : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model
|
|
404
|
+
},
|
|
405
|
+
music: {
|
|
406
|
+
enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
|
|
407
|
+
volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
|
|
408
|
+
style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
|
|
409
|
+
onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession
|
|
410
|
+
},
|
|
411
|
+
notes: Array.isArray(doc.notes) ? doc.notes.slice(0, 5) : [],
|
|
412
|
+
...doc.reset !== void 0 && doc.reset !== null ? { reset: doc.reset } : {}
|
|
413
|
+
};
|
|
414
|
+
this.resolvedSettings = settings;
|
|
415
|
+
this.limits = { ...settings.limits };
|
|
416
|
+
this.monitored = settings.monitored.length > 0 ? new Set(settings.monitored) : void 0;
|
|
417
|
+
this.checkUpdates = settings.checkUpdates;
|
|
418
|
+
const balanceEnabled = settings.balance.enabled;
|
|
419
|
+
const turnedOn = balanceEnabled && !this.balanceEnabled;
|
|
420
|
+
this.balanceEnabled = balanceEnabled;
|
|
421
|
+
if (!balanceEnabled) this.balances.clear();
|
|
422
|
+
const configured = settings.reset;
|
|
423
|
+
if (configured !== void 0 && typeof configured === "object" && configured !== null && typeof configured.offsetHours === "number" && typeof configured.hour === "number" && typeof configured.minute === "number") this.reset = {
|
|
424
|
+
offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
|
|
425
|
+
hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
|
|
426
|
+
minute: Math.max(0, Math.min(59, Math.round(configured.minute)))
|
|
427
|
+
};
|
|
428
|
+
else this.reset = {
|
|
429
|
+
offsetHours: localOffsetHours(),
|
|
430
|
+
hour: 0,
|
|
431
|
+
minute: 0
|
|
432
|
+
};
|
|
433
|
+
this.rollCycleIfNeeded();
|
|
434
|
+
if (turnedOn) this.refreshAllBalances();
|
|
435
|
+
}
|
|
318
436
|
/** Whether update checks are enabled (mirrors the settings document). */
|
|
319
437
|
checkUpdates = true;
|
|
320
438
|
/** Cached upgrade availability; recomputed by {@link refreshUpgrade}. */
|
|
@@ -367,89 +485,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
367
485
|
super(ctx, "tokenQuota");
|
|
368
486
|
this.storagePath = config.storagePath !== void 0 && config.storagePath.length > 0 ? config.storagePath : defaultStoragePath();
|
|
369
487
|
this.load();
|
|
370
|
-
|
|
371
|
-
settingsCtx.settings.installSection(ctx, TOKEN_QUOTA_NAMESPACE, TOKEN_QUOTA_SETTINGS_SCHEMA, { limits: {} }, {
|
|
372
|
-
setSource: (current) => {
|
|
373
|
-
this.settingsSource = () => {
|
|
374
|
-
const doc = current();
|
|
375
|
-
return {
|
|
376
|
-
limits: doc.limits ?? {},
|
|
377
|
-
monitored: doc.monitored ?? [],
|
|
378
|
-
onFull: doc.onFull === "switchPriority" ? "switchAll" : doc.onFull ?? "stop",
|
|
379
|
-
checkUpdates: doc.checkUpdates ?? true,
|
|
380
|
-
dimWhenIdle: doc.dimWhenIdle ?? false,
|
|
381
|
-
order: Array.isArray(doc.order) ? doc.order : [],
|
|
382
|
-
balance: {
|
|
383
|
-
enabled: doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled,
|
|
384
|
-
pollMinutes: typeof doc.balance?.pollMinutes === "number" ? Math.max(1, Math.min(120, Math.round(doc.balance.pollMinutes))) : TOKEN_QUOTA_DEFAULT_BALANCE.pollMinutes
|
|
385
|
-
},
|
|
386
|
-
transcribe: {
|
|
387
|
-
enabled: doc.transcribe?.enabled ?? TOKEN_QUOTA_DEFAULT_TRANSCRIBE.enabled,
|
|
388
|
-
baseURL: typeof doc.transcribe?.baseURL === "string" && doc.transcribe.baseURL !== "" ? doc.transcribe.baseURL.replace(/\/+$/, "") : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.baseURL,
|
|
389
|
-
apiKeyEnv: typeof doc.transcribe?.apiKeyEnv === "string" && doc.transcribe.apiKeyEnv !== "" ? doc.transcribe.apiKeyEnv : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.apiKeyEnv,
|
|
390
|
-
model: typeof doc.transcribe?.model === "string" && doc.transcribe.model !== "" ? doc.transcribe.model : TOKEN_QUOTA_DEFAULT_TRANSCRIBE.model
|
|
391
|
-
},
|
|
392
|
-
notes: Array.isArray(doc.notes) ? doc.notes.slice(0, 5).flatMap((note) => {
|
|
393
|
-
if (typeof note.id !== "string") return [];
|
|
394
|
-
return [{
|
|
395
|
-
id: note.id,
|
|
396
|
-
title: note.title ?? "",
|
|
397
|
-
text: note.text ?? "",
|
|
398
|
-
x: note.x ?? 80,
|
|
399
|
-
y: note.y ?? 80,
|
|
400
|
-
width: note.width ?? 220,
|
|
401
|
-
height: note.height ?? 220,
|
|
402
|
-
collapsed: note.collapsed ?? false,
|
|
403
|
-
visible: note.visible ?? true
|
|
404
|
-
}];
|
|
405
|
-
}) : [],
|
|
406
|
-
reset: doc.reset ?? void 0,
|
|
407
|
-
music: {
|
|
408
|
-
enabled: doc.music?.enabled ?? TOKEN_QUOTA_DEFAULT_MUSIC.enabled,
|
|
409
|
-
volume: doc.music?.volume ?? TOKEN_QUOTA_DEFAULT_MUSIC.volume,
|
|
410
|
-
style: doc.music?.style ?? TOKEN_QUOTA_DEFAULT_MUSIC.style,
|
|
411
|
-
onlyCurrentSession: doc.music?.onlyCurrentSession ?? TOKEN_QUOTA_DEFAULT_MUSIC.onlyCurrentSession
|
|
412
|
-
}
|
|
413
|
-
};
|
|
414
|
-
};
|
|
415
|
-
},
|
|
416
|
-
validate: (value) => {
|
|
417
|
-
for (const [key, limit] of Object.entries(value.limits ?? {})) {
|
|
418
|
-
assertTokenQuotaLimit(limit, key);
|
|
419
|
-
splitTokenQuotaKey(key);
|
|
420
|
-
}
|
|
421
|
-
},
|
|
422
|
-
onChange: () => {
|
|
423
|
-
const doc = this.settingsSource();
|
|
424
|
-
this.limits = { ...doc.limits };
|
|
425
|
-
this.monitored = doc.monitored !== void 0 && doc.monitored.length > 0 ? new Set(doc.monitored) : void 0;
|
|
426
|
-
this.checkUpdates = doc.checkUpdates;
|
|
427
|
-
this.syncUpdateChecking();
|
|
428
|
-
const balanceEnabled = doc.balance?.enabled ?? TOKEN_QUOTA_DEFAULT_BALANCE.enabled;
|
|
429
|
-
const turnedOn = balanceEnabled && !this.balanceEnabled;
|
|
430
|
-
this.balanceEnabled = balanceEnabled;
|
|
431
|
-
if (!balanceEnabled) this.balances.clear();
|
|
432
|
-
this.syncBalancePolling();
|
|
433
|
-
if (turnedOn) this.refreshAllBalances();
|
|
434
|
-
if (doc.reset !== void 0 && typeof doc.reset === "object" && doc.reset !== null && typeof doc.reset.offsetHours === "number" && typeof doc.reset.hour === "number" && typeof doc.reset.minute === "number") {
|
|
435
|
-
const configured = doc.reset;
|
|
436
|
-
this.reset = {
|
|
437
|
-
offsetHours: Math.max(-12, Math.min(14, Math.round(configured.offsetHours))),
|
|
438
|
-
hour: Math.max(0, Math.min(23, Math.round(configured.hour))),
|
|
439
|
-
minute: Math.max(0, Math.min(59, Math.round(configured.minute)))
|
|
440
|
-
};
|
|
441
|
-
this.rollCycleIfNeeded();
|
|
442
|
-
} else {
|
|
443
|
-
this.reset = {
|
|
444
|
-
offsetHours: localOffsetHours(),
|
|
445
|
-
hour: 0,
|
|
446
|
-
minute: 0
|
|
447
|
-
};
|
|
448
|
-
this.rollCycleIfNeeded();
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
});
|
|
452
|
-
});
|
|
488
|
+
this.applySettings(config);
|
|
453
489
|
this.tryMountRoute();
|
|
454
490
|
if (this.disposeRoute === void 0) this.disposeRouteWatcher = ctx.on("internal/service", (name) => {
|
|
455
491
|
if (name === "webServer") this.tryMountRoute();
|
|
@@ -651,7 +687,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
651
687
|
return this.upgradeCheck;
|
|
652
688
|
}
|
|
653
689
|
async doRefreshUpgrade() {
|
|
654
|
-
const current = "0.1.
|
|
690
|
+
const current = "0.1.51";
|
|
655
691
|
let latest;
|
|
656
692
|
try {
|
|
657
693
|
const response = await fetch(REGISTRY_LATEST_URL, {
|
|
@@ -729,37 +765,47 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
729
765
|
return Promise.all([...this.discoverBalanceSources().values()].map((source) => this.refreshProviderBalance(source.provider, source))).then(() => void 0);
|
|
730
766
|
}
|
|
731
767
|
/**
|
|
732
|
-
* Discover every provider in the model directory
|
|
733
|
-
* together with its own credential reference and endpoint base.
|
|
734
|
-
* decides which providers are queried: a provider qualifies when
|
|
735
|
-
*
|
|
736
|
-
*
|
|
768
|
+
* Discover every provider in the model directory whose balance this plugin
|
|
769
|
+
* can query, together with its own credential reference and endpoint base.
|
|
770
|
+
* This is what decides which providers are queried: a provider qualifies when
|
|
771
|
+
* its base URL, credential reference, or route id matches a supported family
|
|
772
|
+
* (see {@link balanceKindOf}), and it must declare an `apiKeyEnv`.
|
|
737
773
|
*/
|
|
738
774
|
discoverBalanceSources() {
|
|
739
775
|
const found = /* @__PURE__ */ new Map();
|
|
740
776
|
const llm = this.ctx.get("llm");
|
|
741
|
-
const
|
|
777
|
+
const configEditor = this.ctx.get("configEditor");
|
|
778
|
+
const liveConfigs = /* @__PURE__ */ new Map();
|
|
779
|
+
try {
|
|
780
|
+
for (const row of configEditor?.configuration() ?? []) {
|
|
781
|
+
const id = row.entry.options.id;
|
|
782
|
+
if (id !== void 0) liveConfigs.set(id, row.entry.options.config);
|
|
783
|
+
}
|
|
784
|
+
} catch {}
|
|
742
785
|
const fallback = () => ({
|
|
743
786
|
provider: "deepseek",
|
|
744
787
|
keyEnv: "DEEPSEEK_API_KEY",
|
|
745
|
-
baseURL: process.env.DEEPSEEK_BASE_URL ?? `https://${DEEPSEEK_BALANCE_HOST}
|
|
788
|
+
baseURL: process.env.DEEPSEEK_BASE_URL ?? `https://${DEEPSEEK_BALANCE_HOST}`,
|
|
789
|
+
kind: "deepseek"
|
|
746
790
|
});
|
|
747
791
|
if (llm?.listConfigurableProviders === void 0) {
|
|
748
792
|
found.set("deepseek", fallback());
|
|
749
793
|
return found;
|
|
750
794
|
}
|
|
751
795
|
for (const entry of llm.listConfigurableProviders()) try {
|
|
752
|
-
let profile =
|
|
796
|
+
let profile = liveConfigs.get(entry.settingsNs);
|
|
753
797
|
for (const segment of entry.settingsPath ?? []) profile = profile !== null && typeof profile === "object" ? profile[segment] : void 0;
|
|
754
798
|
if (profile === null || typeof profile !== "object") continue;
|
|
755
799
|
const record = profile;
|
|
756
800
|
const keyEnv = typeof record.apiKeyEnv === "string" && record.apiKeyEnv !== "" ? record.apiKeyEnv : void 0;
|
|
757
801
|
const baseURL = typeof record.baseURL === "string" && record.baseURL !== "" ? record.baseURL : void 0;
|
|
758
|
-
|
|
802
|
+
const kind = balanceKindOf(entry.provider, keyEnv, baseURL);
|
|
803
|
+
if (kind === void 0 || keyEnv === void 0) continue;
|
|
759
804
|
found.set(entry.provider, {
|
|
760
805
|
provider: entry.provider,
|
|
761
806
|
keyEnv,
|
|
762
|
-
baseURL: baseURL ?? `https://${DEEPSEEK_BALANCE_HOST}`
|
|
807
|
+
baseURL: baseURL ?? (kind === "deepseek" ? `https://${DEEPSEEK_BALANCE_HOST}` : `https://${TEAMOROUTER_HOST}`),
|
|
808
|
+
kind
|
|
763
809
|
});
|
|
764
810
|
} catch {}
|
|
765
811
|
if (found.size === 0) found.set("deepseek", fallback());
|
|
@@ -787,7 +833,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
787
833
|
if (key === void 0 || key === "") {
|
|
788
834
|
this.balances.set(provider, {
|
|
789
835
|
provider,
|
|
790
|
-
currency:
|
|
836
|
+
currency: BALANCE_DEFAULT_CURRENCY[resolved.kind],
|
|
791
837
|
total: 0,
|
|
792
838
|
isAvailable: false,
|
|
793
839
|
fetchedAt: Date.now(),
|
|
@@ -795,7 +841,6 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
795
841
|
});
|
|
796
842
|
return;
|
|
797
843
|
}
|
|
798
|
-
const base = resolved.baseURL;
|
|
799
844
|
try {
|
|
800
845
|
const controller = new AbortController();
|
|
801
846
|
const timer = setTimeout(() => {
|
|
@@ -803,7 +848,7 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
803
848
|
}, 1e4);
|
|
804
849
|
let res;
|
|
805
850
|
try {
|
|
806
|
-
res = await fetch(
|
|
851
|
+
res = await fetch(balanceURLOf(resolved.kind, resolved.baseURL), {
|
|
807
852
|
headers: {
|
|
808
853
|
authorization: `Bearer ${key}`,
|
|
809
854
|
accept: "application/json"
|
|
@@ -815,26 +860,23 @@ var TokenQuotaService = class TokenQuotaService extends Service {
|
|
|
815
860
|
}
|
|
816
861
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
817
862
|
const data = await res.json();
|
|
818
|
-
const
|
|
819
|
-
const
|
|
820
|
-
const n = typeof value === "number" ? value : typeof value === "string" && value !== "" ? Number(value) : NaN;
|
|
821
|
-
return Number.isFinite(n) ? n : 0;
|
|
822
|
-
};
|
|
823
|
-
this.balances.set(provider, {
|
|
863
|
+
const parsed = resolved.kind === "teamorouter" ? parseTeamorouterBalance(data) : parseDeepseekBalance(data);
|
|
864
|
+
const next = {
|
|
824
865
|
provider,
|
|
825
|
-
currency:
|
|
826
|
-
total:
|
|
827
|
-
|
|
828
|
-
toppedUp: num(first?.topped_up_balance),
|
|
829
|
-
isAvailable: data?.is_available !== false,
|
|
866
|
+
currency: parsed.currency,
|
|
867
|
+
total: parsed.total,
|
|
868
|
+
isAvailable: parsed.isAvailable,
|
|
830
869
|
fetchedAt: Date.now(),
|
|
831
870
|
status: "ok"
|
|
832
|
-
}
|
|
871
|
+
};
|
|
872
|
+
if (parsed.granted !== void 0) next.granted = parsed.granted;
|
|
873
|
+
if (parsed.toppedUp !== void 0) next.toppedUp = parsed.toppedUp;
|
|
874
|
+
this.balances.set(provider, next);
|
|
833
875
|
} catch (error) {
|
|
834
876
|
const previous = this.balances.get(provider);
|
|
835
877
|
const next = {
|
|
836
878
|
provider,
|
|
837
|
-
currency: previous?.currency ??
|
|
879
|
+
currency: previous?.currency ?? BALANCE_DEFAULT_CURRENCY[resolved.kind],
|
|
838
880
|
total: previous?.total ?? 0,
|
|
839
881
|
isAvailable: false,
|
|
840
882
|
fetchedAt: previous?.fetchedAt ?? Date.now(),
|
|
@@ -348,7 +348,15 @@ export function TokenQuotaPanel({ t, load, setLimit, selectModel, setMonitored,
|
|
|
348
348
|
// Storage unavailable: the position still applies for this session.
|
|
349
349
|
}
|
|
350
350
|
};
|
|
351
|
-
|
|
351
|
+
// This Harness version dropped the list's `current` field: the visible
|
|
352
|
+
// conversation is the session the main view retains.
|
|
353
|
+
const sessionId = useSessions((state) => {
|
|
354
|
+
for (const session of Object.values(state.byId)) {
|
|
355
|
+
if ((session.retainedBy.mainView ?? 0) > 0)
|
|
356
|
+
return session.id;
|
|
357
|
+
}
|
|
358
|
+
return undefined;
|
|
359
|
+
});
|
|
352
360
|
const snapshot = useStore(s => s.snapshot);
|
|
353
361
|
const groups = useStore(s => s.groups);
|
|
354
362
|
const current = useStore(s => s.current);
|
|
@@ -431,15 +439,45 @@ export function TokenQuotaPanel({ t, load, setLimit, selectModel, setMonitored,
|
|
|
431
439
|
};
|
|
432
440
|
// Track whether any text input (composer, search, dialogs) currently has
|
|
433
441
|
// focus, so the panel can dim while the user types elsewhere.
|
|
442
|
+
// Track whether the user is typing in a text field OUTSIDE this plugin's own
|
|
443
|
+
// surfaces, so the panel can dim while the chat behind it needs to stay
|
|
444
|
+
// readable.
|
|
445
|
+
//
|
|
446
|
+
// `focusout` matters as much as `focusin`: an earlier version observed only
|
|
447
|
+
// focusin, so once any field had ever received focus the flag stayed true for
|
|
448
|
+
// the rest of the session and the panel sat at 30% opacity — which reads as
|
|
449
|
+
// "the panel disappeared" until a reload reset the state. Recompute from
|
|
450
|
+
// document.activeElement rather than trusting the event, and also settle on
|
|
451
|
+
// pointer-down and window blur so a removed focused node cannot strand it.
|
|
434
452
|
useEffect(() => {
|
|
435
|
-
const
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
453
|
+
const isEditable = (el) => el !== null && (el.matches('input, textarea, [contenteditable="true"]')
|
|
454
|
+
|| el.closest('input, textarea, [contenteditable="true"]') !== null);
|
|
455
|
+
const isOwnSurface = (el) => {
|
|
456
|
+
if (el === null)
|
|
457
|
+
return false;
|
|
458
|
+
for (const node of [panelRef.current, settingsRef.current, logRef.current]) {
|
|
459
|
+
if (node !== null && node.contains(el))
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
return false;
|
|
463
|
+
};
|
|
464
|
+
const sync = () => {
|
|
465
|
+
const active = document.activeElement;
|
|
466
|
+
setInputActive(!isOwnSurface(active) && isEditable(active));
|
|
467
|
+
};
|
|
468
|
+
// focusout/pointerdown run before the next element gains focus: settle next tick.
|
|
469
|
+
const deferredSync = () => { window.setTimeout(sync, 0); };
|
|
470
|
+
document.addEventListener('focusin', sync);
|
|
471
|
+
document.addEventListener('focusout', deferredSync);
|
|
472
|
+
document.addEventListener('pointerdown', deferredSync, true);
|
|
473
|
+
window.addEventListener('blur', sync);
|
|
474
|
+
sync();
|
|
475
|
+
return () => {
|
|
476
|
+
document.removeEventListener('focusin', sync);
|
|
477
|
+
document.removeEventListener('focusout', deferredSync);
|
|
478
|
+
document.removeEventListener('pointerdown', deferredSync, true);
|
|
479
|
+
window.removeEventListener('blur', sync);
|
|
440
480
|
};
|
|
441
|
-
window.addEventListener('focusin', onFocusIn);
|
|
442
|
-
return () => { window.removeEventListener('focusin', onFocusIn); };
|
|
443
481
|
}, []);
|
|
444
482
|
// When a NEW latest version appears (manual check or periodic poll):
|
|
445
483
|
// expand the panel (it may be collapsed), force it opaque, and flash the
|
|
@@ -552,14 +590,6 @@ export function TokenQuotaPanel({ t, load, setLimit, selectModel, setMonitored,
|
|
|
552
590
|
});
|
|
553
591
|
return () => { cancelled = true; };
|
|
554
592
|
}, [logOpen, actions]);
|
|
555
|
-
if (collapsed) {
|
|
556
|
-
return (_jsxs("div", { className: css.tab, role: "button", tabIndex: 0, title: t('expandHint'), "aria-label": t('expandHint'), onClick: () => { setCollapsed(false); }, onKeyDown: (event) => {
|
|
557
|
-
if (event.key === 'Enter' || event.key === ' ') {
|
|
558
|
-
event.preventDefault();
|
|
559
|
-
setCollapsed(false);
|
|
560
|
-
}
|
|
561
|
-
}, children: [_jsx("span", { className: css.tabIcon, "aria-hidden": "true", children: "\u25B8" }), _jsx("span", { className: css.tabLabel, children: t('expand') })] }));
|
|
562
|
-
}
|
|
563
593
|
const openSettings = () => {
|
|
564
594
|
actions.setDialogOpen(true);
|
|
565
595
|
};
|
|
@@ -775,7 +805,20 @@ export function TokenQuotaPanel({ t, load, setLimit, selectModel, setMonitored,
|
|
|
775
805
|
const panelDimClass = dimWhenIdle
|
|
776
806
|
? (hovered || upgradeFlash ? '' : inputActive ? css.panelDimStrong : css.panelDim)
|
|
777
807
|
: '';
|
|
778
|
-
|
|
808
|
+
// Collapsed tab. This early return MUST sit below every hook: React requires
|
|
809
|
+
// the hook count to be identical across renders, and returning above the
|
|
810
|
+
// balance/timestamp memos made it drop on collapse — React threw "Rendered
|
|
811
|
+
// fewer hooks than expected", the slot error boundary swallowed the entry,
|
|
812
|
+
// and the panel simply vanished until a page reload reset `collapsed`.
|
|
813
|
+
if (collapsed) {
|
|
814
|
+
return (_jsxs("div", { className: css.tab, role: "button", tabIndex: 0, title: t('expandHint'), "aria-label": t('expandHint'), onClick: () => { setCollapsed(false); }, onKeyDown: (event) => {
|
|
815
|
+
if (event.key === 'Enter' || event.key === ' ') {
|
|
816
|
+
event.preventDefault();
|
|
817
|
+
setCollapsed(false);
|
|
818
|
+
}
|
|
819
|
+
}, children: [_jsx("span", { className: css.tabIcon, "aria-hidden": "true", children: "\u25B8" }), _jsx("span", { className: css.tabLabel, children: t('expand') })] }));
|
|
820
|
+
}
|
|
821
|
+
return (_jsxs(_Fragment, { children: [_jsxs("div", { ref: panelRef, "data-token-quota-panel": "", className: `${css.panel}${panelDimClass !== '' ? ` ${panelDimClass}` : ''}`, style: panelPos !== null ? { left: panelPos.x, top: panelPos.y, right: 'auto' } : undefined, onPointerEnter: () => { setHovered(true); }, onPointerLeave: () => { setHovered(false); }, children: [_jsxs("div", { className: css.header, onPointerDown: (event) => { beginDrag(event, panelRef.current, applyPanelPos); }, children: [_jsx("div", { className: css.headerText, children: _jsxs("div", { className: css.title, children: [t('title'), __TOKEN_QUOTA_VERSION__ !== undefined && __TOKEN_QUOTA_VERSION__ !== '' && (upgrade !== null
|
|
779
822
|
? (_jsxs("span", { className: `${css.version} ${css.versionNew}`, title: t('upgradeAvailableHint'), children: ["v", __TOKEN_QUOTA_VERSION__, " \u2192 v", upgrade.latestVersion] }))
|
|
780
823
|
: (_jsxs("span", { className: css.version, children: ["v", __TOKEN_QUOTA_VERSION__] })))] }) }), _jsxs("div", { className: css.headerActions, onPointerDown: (event) => { event.stopPropagation(); }, children: [_jsx("button", { type: "button", "aria-pressed": musicEnabled, className: `${css.settingsBtn}${musicEnabled ? ` ${css.settingsBtnActive}` : ''}`, title: `${t('musicLabel')}:${musicEnabled ? t('musicOn') : t('musicOff')}`, onClick: () => { setMusicEnabled(!musicEnabled); }, children: "\u266A" }), _jsx("button", { type: "button", className: css.settingsBtn, onClick: () => { actions.setLogOpen(true); }, children: t('logs') }), _jsx("button", { type: "button", className: css.settingsBtn, onClick: openSettings, children: t('settings') }), _jsx("button", { type: "button", className: css.collapse, onClick: () => { setCollapsed(true); }, children: t('collapse') })] }), _jsxs("div", { className: css.notesBar, onPointerDown: (event) => { event.stopPropagation(); }, children: [notes.map((note) => {
|
|
781
824
|
const open = note.visible && !note.collapsed;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots';
|
|
2
|
+
import { TOKEN_QUOTA_NAMESPACE } from '@jxgame2020/dsh-token-quota/types';
|
|
3
|
+
import type { createTokenQuotaStashStore } from './stash.ts';
|
|
4
|
+
/** Full component props: runtime + per-session stash store + locale. */
|
|
5
|
+
export type TokenQuotaStashComponentProps = PropsRuntime<'conversation.input.overlay'> & PropsStore<ReturnType<typeof createTokenQuotaStashStore>> & PropsLocale<typeof TOKEN_QUOTA_NAMESPACE>;
|
|
6
|
+
/**
|
|
7
|
+
* Numbered stash chips plus the capture popup, rendered inside the composer.
|
|
8
|
+
*/
|
|
9
|
+
export declare function TokenQuotaStash({ t, useStore, actions }: TokenQuotaStashComponentProps): JSX.Element;
|
|
10
|
+
//# sourceMappingURL=TokenQuotaStash.d.ts.map
|