@pinkbanana/dsh-balance 0.5.0 → 0.7.0
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/README.md +64 -8
- package/README_EN.md +64 -8
- package/lib/client.js +511 -246
- package/lib/client.js.map +1 -1
- package/lib/index.js +280 -95
- package/lib/index.js.map +1 -1
- package/lib/types/balance.d.ts +9 -8
- package/lib/types/billing.d.ts +3 -2
- package/lib/types/client/BalanceDock.d.ts +9 -2
- package/lib/types/client/BalanceTab.d.ts +6 -3
- package/lib/types/client/BillingTab.d.ts +5 -2
- package/lib/types/client/DeepSeekPanel.d.ts +1 -1
- package/lib/types/client/ModelsTab.d.ts +7 -4
- package/lib/types/client/locales.d.ts +39 -16
- package/lib/types/client/styles.d.ts +1 -1
- package/lib/types/index.d.ts +13 -3
- package/lib/types/models.d.ts +11 -6
- package/lib/types/providers.d.ts +43 -0
- package/lib/types/types.d.ts +23 -12
- package/package.json +15 -5
package/lib/index.js
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
//#region src/providers.ts
|
|
4
|
+
/** Browser-safe provider metadata. Credentials and wire parsers stay on the Host. */
|
|
5
|
+
const BALANCE_PROVIDERS = [
|
|
6
|
+
{
|
|
7
|
+
id: "deepseek",
|
|
8
|
+
name: "DeepSeek",
|
|
9
|
+
apiKeyRef: "DEEPSEEK_API_KEY",
|
|
10
|
+
baseUrl: "https://api.deepseek.com"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
id: "stepfun",
|
|
14
|
+
name: "StepFun",
|
|
15
|
+
apiKeyRef: "STEPFUN_API_KEY",
|
|
16
|
+
baseUrl: "https://api.stepfun.com/v1"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
id: "tokener",
|
|
20
|
+
name: "Tokener",
|
|
21
|
+
apiKeyRef: "TOKENER_API_KEY",
|
|
22
|
+
baseUrl: "https://api.tokener.ai/v1",
|
|
23
|
+
balanceApiKeyRef: "TOKENER_MANAGEMENT_TOKEN",
|
|
24
|
+
balanceBaseUrl: "https://console.tokener.ai/api/v1"
|
|
25
|
+
}
|
|
26
|
+
];
|
|
27
|
+
function findBalanceProvider(id) {
|
|
28
|
+
return BALANCE_PROVIDERS.find((provider) => provider.id === id.trim().toLowerCase());
|
|
29
|
+
}
|
|
30
|
+
/** Management APIs may use a separate credential and origin from inference APIs. */
|
|
31
|
+
function balanceDefaults(provider) {
|
|
32
|
+
return {
|
|
33
|
+
apiKeyRef: "balanceApiKeyRef" in provider ? provider.balanceApiKeyRef : provider.apiKeyRef,
|
|
34
|
+
baseUrl: "balanceBaseUrl" in provider ? provider.balanceBaseUrl : provider.baseUrl
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
3
38
|
//#region src/balance.ts
|
|
4
39
|
const DECIMAL = /^-?\d+(?:\.\d+)?$/;
|
|
5
40
|
/** A safe, classified failure suitable for translation at the Host boundary. */
|
|
@@ -38,23 +73,80 @@ function parseDeepSeekBalance(value) {
|
|
|
38
73
|
balanceInfos
|
|
39
74
|
};
|
|
40
75
|
}
|
|
41
|
-
function
|
|
42
|
-
const
|
|
43
|
-
|
|
76
|
+
function numberField(row, key) {
|
|
77
|
+
const value = row[key];
|
|
78
|
+
if (typeof value !== "number" || !Number.isFinite(value)) throw new BalanceQueryError("INVALID_RESPONSE", `StepFun account response has an invalid ${key}`, 502);
|
|
79
|
+
return String(value);
|
|
80
|
+
}
|
|
81
|
+
/** StepFun totals are cumulative amounts, not components of the available balance. */
|
|
82
|
+
function parseStepFunBalance(value) {
|
|
83
|
+
if (!isRecord$1(value) || value.object !== "account" || value.type !== "prepaid" && value.type !== "postpaid") throw new BalanceQueryError("INVALID_RESPONSE", "StepFun returned an invalid account response", 502);
|
|
84
|
+
return {
|
|
85
|
+
isAvailable: null,
|
|
86
|
+
accountType: value.type,
|
|
87
|
+
balanceInfos: [{
|
|
88
|
+
currency: "CNY",
|
|
89
|
+
totalBalance: numberField(value, "balance"),
|
|
90
|
+
totalCashBalance: numberField(value, "total_cash_balance"),
|
|
91
|
+
totalVoucherBalance: numberField(value, "total_voucher_balance")
|
|
92
|
+
}]
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** Tokener encodes USD as integer millionths; keep monetary values exact. */
|
|
96
|
+
function usdMicroField(row, key) {
|
|
97
|
+
const value = row[key];
|
|
98
|
+
if (typeof value !== "string" || !/^-?\d+$/.test(value)) throw new BalanceQueryError("INVALID_RESPONSE", `Tokener balance response has an invalid ${key}`, 502);
|
|
99
|
+
const micro = BigInt(value);
|
|
100
|
+
const absolute = micro < 0n ? -micro : micro;
|
|
101
|
+
const fraction = String(absolute % 1000000n).padStart(6, "0");
|
|
102
|
+
return `${micro < 0n ? "-" : ""}${absolute / 1000000n}.${fraction}`;
|
|
103
|
+
}
|
|
104
|
+
function parseTokenerBalance(value) {
|
|
105
|
+
if (!isRecord$1(value) || value.status !== "active" && value.status !== "suspended") throw new BalanceQueryError("INVALID_RESPONSE", "Tokener returned an invalid balance response", 502);
|
|
106
|
+
const totalBalance = usdMicroField(value, "availableUsdMicro");
|
|
107
|
+
return {
|
|
108
|
+
isAvailable: value.status === "active" && BigInt(value.availableUsdMicro) > 0n,
|
|
109
|
+
balanceInfos: [{
|
|
110
|
+
currency: "USD",
|
|
111
|
+
totalBalance,
|
|
112
|
+
toppedUpBalance: usdMicroField(value, "purchasedAvailableUsdMicro"),
|
|
113
|
+
grantedBalance: usdMicroField(value, "grantedAvailableUsdMicro")
|
|
114
|
+
}]
|
|
115
|
+
};
|
|
44
116
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
117
|
+
/** Add a provider's endpoint and parser here; transport and error handling are shared. */
|
|
118
|
+
const adapters = {
|
|
119
|
+
deepseek: {
|
|
120
|
+
path: "user/balance",
|
|
121
|
+
parse: parseDeepSeekBalance
|
|
122
|
+
},
|
|
123
|
+
stepfun: {
|
|
124
|
+
path: "accounts",
|
|
125
|
+
parse: parseStepFunBalance
|
|
126
|
+
},
|
|
127
|
+
tokener: {
|
|
128
|
+
path: "billing/balance",
|
|
129
|
+
parse: parseTokenerBalance
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
function upstreamFailure$1(status, provider) {
|
|
133
|
+
if (status === 401 || status === 403) return new BalanceQueryError("INVALID_API_KEY", `${provider} API 密钥无效或无权查询余额`, 401);
|
|
134
|
+
if (status === 429) return new BalanceQueryError("RATE_LIMITED", `${provider} API 请求过于频繁,请稍后重试`, 429);
|
|
135
|
+
if (status >= 500) return new BalanceQueryError("UPSTREAM_UNAVAILABLE", `${provider} API 暂时不可用,请稍后重试`, 502);
|
|
136
|
+
return new BalanceQueryError("UPSTREAM_ERROR", `${provider} API 返回了 HTTP ${status}`, 502);
|
|
50
137
|
}
|
|
51
138
|
/** Query the official endpoint with Bearer authentication and strict response validation. */
|
|
52
|
-
async function
|
|
139
|
+
async function queryProviderBalance(providerId, options) {
|
|
140
|
+
const provider = findBalanceProvider(providerId);
|
|
141
|
+
if (provider === void 0) throw new BalanceQueryError("UNSUPPORTED_PROVIDER", "不支持此提供方的余额查询", 400);
|
|
142
|
+
const adapter = adapters[provider.id];
|
|
143
|
+
const baseUrl = options.baseUrl.endsWith("/") ? options.baseUrl : `${options.baseUrl}/`;
|
|
53
144
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
54
145
|
let response;
|
|
55
146
|
try {
|
|
56
|
-
response = await fetchImpl(
|
|
147
|
+
response = await fetchImpl(new URL(adapter.path, baseUrl), {
|
|
57
148
|
method: "GET",
|
|
149
|
+
redirect: "error",
|
|
58
150
|
headers: {
|
|
59
151
|
accept: "application/json",
|
|
60
152
|
authorization: `Bearer ${options.apiKey}`
|
|
@@ -62,17 +154,25 @@ async function queryDeepSeekBalance(options) {
|
|
|
62
154
|
signal: AbortSignal.timeout(options.timeoutMs)
|
|
63
155
|
});
|
|
64
156
|
} catch (error) {
|
|
65
|
-
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new BalanceQueryError("UPSTREAM_TIMEOUT",
|
|
66
|
-
throw new BalanceQueryError("UPSTREAM_UNAVAILABLE",
|
|
157
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new BalanceQueryError("UPSTREAM_TIMEOUT", `查询 ${provider.name} 余额超时`, 504, { cause: error });
|
|
158
|
+
throw new BalanceQueryError("UPSTREAM_UNAVAILABLE", `无法连接到 ${provider.name} API`, 502, { cause: error });
|
|
67
159
|
}
|
|
68
|
-
if (!response.ok) throw upstreamFailure$1(response.status);
|
|
160
|
+
if (!response.ok) throw upstreamFailure$1(response.status, provider.name);
|
|
69
161
|
let payload;
|
|
70
162
|
try {
|
|
71
163
|
payload = await response.json();
|
|
72
164
|
} catch (error) {
|
|
73
|
-
throw new BalanceQueryError("
|
|
165
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new BalanceQueryError("UPSTREAM_TIMEOUT", `查询 ${provider.name} 余额超时`, 504, { cause: error });
|
|
166
|
+
throw new BalanceQueryError("INVALID_RESPONSE", `${provider.name} 返回了无法解析的余额响应`, 502, { cause: error });
|
|
74
167
|
}
|
|
75
|
-
return
|
|
168
|
+
return adapter.parse(payload);
|
|
169
|
+
}
|
|
170
|
+
/** Backward-compatible DeepSeek entry point. */
|
|
171
|
+
function queryDeepSeekBalance(options) {
|
|
172
|
+
return queryProviderBalance("deepseek", options);
|
|
173
|
+
}
|
|
174
|
+
function queryStepFunBalance(options) {
|
|
175
|
+
return queryProviderBalance("stepfun", options);
|
|
76
176
|
}
|
|
77
177
|
//#endregion
|
|
78
178
|
//#region src/pricing.ts
|
|
@@ -211,12 +311,12 @@ function messageMetadata(event) {
|
|
|
211
311
|
}
|
|
212
312
|
/** Resolve the versioned price for one request. */
|
|
213
313
|
function resolveBillingPrice(provider, model, time) {
|
|
214
|
-
if (provider !== "deepseek") return void 0;
|
|
314
|
+
if (findBalanceProvider(provider)?.id !== "deepseek") return void 0;
|
|
215
315
|
const canonicalModel = model === "deepseek-chat" || model === "deepseek-reasoner" ? time >= PEAK_EFFECTIVE_FROM ? "deepseek-v4-flash" : model : model;
|
|
216
316
|
const rates = time < PEAK_EFFECTIVE_FROM && canonicalModel === model ? LEGACY_PRICES[canonicalModel] : CURRENT_PRICES[canonicalModel];
|
|
217
317
|
if (rates === void 0) return void 0;
|
|
218
318
|
return {
|
|
219
|
-
provider,
|
|
319
|
+
provider: "deepseek",
|
|
220
320
|
model: canonicalModel,
|
|
221
321
|
effectiveFrom: new Date(time < PEAK_EFFECTIVE_FROM ? 0 : PEAK_EFFECTIVE_FROM).toISOString(),
|
|
222
322
|
pricingVersion: time < PEAK_EFFECTIVE_FROM ? "deepseek-legacy" : BILLING_PRICING_VERSION,
|
|
@@ -225,7 +325,7 @@ function resolveBillingPrice(provider, model, time) {
|
|
|
225
325
|
}
|
|
226
326
|
/** Compute one request charge. Cache writes are billed as cache misses. */
|
|
227
327
|
function calculateRequestCost(usage, price, time) {
|
|
228
|
-
const multiplier = isPeakHour(new Date(time)) ? 2 : 1;
|
|
328
|
+
const multiplier = findBalanceProvider(price.provider)?.id === "deepseek" && isPeakHour(new Date(time)) ? 2 : 1;
|
|
229
329
|
return roundMoney(((usage.inputTokens + usage.cacheWriteTokens) * price.cacheMissUsdPerMillion + usage.cacheReadTokens * price.cacheHitUsdPerMillion + usage.outputTokens * price.outputUsdPerMillion) / TOKENS_PER_MILLION * multiplier);
|
|
230
330
|
}
|
|
231
331
|
function dateKey(time, timeZone) {
|
|
@@ -247,20 +347,32 @@ function extractSessionUsage(sessionId, header, events, options) {
|
|
|
247
347
|
const seedLength = header.seedLength ?? 0;
|
|
248
348
|
let latestRequest;
|
|
249
349
|
const requests = /* @__PURE__ */ new Map();
|
|
350
|
+
let activeStep;
|
|
250
351
|
const records = [];
|
|
251
352
|
for (const event of events) {
|
|
252
|
-
|
|
253
|
-
|
|
353
|
+
if (event.type === "request/header") {
|
|
354
|
+
latestRequest = readRequestMetadata(event);
|
|
355
|
+
if (activeStep !== void 0) requests.set(activeStep, {
|
|
356
|
+
metadata: latestRequest,
|
|
357
|
+
time: event.time
|
|
358
|
+
});
|
|
359
|
+
}
|
|
254
360
|
if (event.type === "step/start") {
|
|
255
|
-
|
|
361
|
+
activeStep = stepKey(event.data.turn, event.data.step);
|
|
362
|
+
requests.set(activeStep, {
|
|
363
|
+
metadata: latestRequest,
|
|
364
|
+
time: event.time
|
|
365
|
+
});
|
|
256
366
|
continue;
|
|
257
367
|
}
|
|
368
|
+
if (event.type === "step/end") activeStep = void 0;
|
|
258
369
|
if (event.type !== "assistant/message" || event.seq < seedLength) continue;
|
|
259
|
-
const request = requests.get(stepKey(event.data.turn, event.data.step))
|
|
260
|
-
const
|
|
261
|
-
const provider =
|
|
262
|
-
const model =
|
|
370
|
+
const request = requests.get(stepKey(event.data.turn, event.data.step));
|
|
371
|
+
const metadata = messageMetadata(event) ?? request?.metadata ?? latestRequest;
|
|
372
|
+
const provider = metadata === void 0 ? null : findBalanceProvider(metadata.provider)?.id ?? metadata.provider;
|
|
373
|
+
const model = metadata?.model ?? null;
|
|
263
374
|
const time = request?.time ?? event.time;
|
|
375
|
+
if (options.provider !== void 0 && provider !== (findBalanceProvider(options.provider)?.id ?? options.provider)) continue;
|
|
264
376
|
if (!inDateRange(time, options.timeZone, options.from, options.to)) continue;
|
|
265
377
|
const usage = readUsage(event.data.usage);
|
|
266
378
|
const inputTokens = usage?.inputTokens ?? 0;
|
|
@@ -274,7 +386,7 @@ function extractSessionUsage(sessionId, header, events, options) {
|
|
|
274
386
|
else if (provider === null || model === null) unknownReason = "missing-request-metadata";
|
|
275
387
|
else {
|
|
276
388
|
const price = resolveBillingPrice(provider, model, time);
|
|
277
|
-
if (price === void 0) unknownReason = provider
|
|
389
|
+
if (price === void 0) unknownReason = findBalanceProvider(provider) !== void 0 ? "unknown-model" : "unknown-provider";
|
|
278
390
|
else {
|
|
279
391
|
costUsd = calculateRequestCost(usage, price, time);
|
|
280
392
|
pricingVersion = price.pricingVersion;
|
|
@@ -309,7 +421,7 @@ function aggregateRecords(records, sessionTitles, timeZone, usdToCny) {
|
|
|
309
421
|
addTotals(totals, record);
|
|
310
422
|
const provider = record.provider ?? "unknown";
|
|
311
423
|
const model = record.model ?? "unknown";
|
|
312
|
-
const modelKey =
|
|
424
|
+
const modelKey = JSON.stringify([provider, model]);
|
|
313
425
|
const modelTotal = models.get(modelKey) ?? {
|
|
314
426
|
...emptyTotals(),
|
|
315
427
|
provider,
|
|
@@ -435,37 +547,45 @@ function isRecord(value) {
|
|
|
435
547
|
}
|
|
436
548
|
function requiredString(row, key) {
|
|
437
549
|
const value = row[key];
|
|
438
|
-
if (typeof value !== "string" || value.trim().length === 0) throw new ModelQueryError("INVALID_RESPONSE", `
|
|
550
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new ModelQueryError("INVALID_RESPONSE", `Model response has an invalid ${key}`, 502);
|
|
439
551
|
return value;
|
|
440
552
|
}
|
|
553
|
+
/** Shared Model object returned by both list and retrieve APIs. */
|
|
554
|
+
function parseModel(value) {
|
|
555
|
+
if (!isRecord(value) || value.object !== "model") throw new ModelQueryError("INVALID_RESPONSE", "提供方返回了无效的模型条目", 502);
|
|
556
|
+
const created = value.created;
|
|
557
|
+
if (created !== void 0 && (typeof created !== "number" || !Number.isSafeInteger(created) || created < 0 || created > 864e10)) throw new ModelQueryError("INVALID_RESPONSE", "提供方返回了无效的模型创建时间", 502);
|
|
558
|
+
return {
|
|
559
|
+
id: requiredString(value, "id"),
|
|
560
|
+
ownedBy: requiredString(value, "owned_by"),
|
|
561
|
+
...created === void 0 ? {} : { created }
|
|
562
|
+
};
|
|
563
|
+
}
|
|
441
564
|
/** Parse the documented `{ object: "list", data: Model[] }` response. */
|
|
442
|
-
function
|
|
443
|
-
if (!isRecord(value) || value.object !== "list" || !Array.isArray(value.data)) throw new ModelQueryError("INVALID_RESPONSE", "
|
|
444
|
-
return { models: value.data.map(
|
|
445
|
-
if (!isRecord(item) || item.object !== "model") throw new ModelQueryError("INVALID_RESPONSE", "DeepSeek 返回了无效的模型条目", 502);
|
|
446
|
-
return {
|
|
447
|
-
id: requiredString(item, "id"),
|
|
448
|
-
ownedBy: requiredString(item, "owned_by")
|
|
449
|
-
};
|
|
450
|
-
}) };
|
|
565
|
+
function parseModels(value) {
|
|
566
|
+
if (!isRecord(value) || value.object !== "list" || !Array.isArray(value.data)) throw new ModelQueryError("INVALID_RESPONSE", "提供方返回了无效的模型列表", 502);
|
|
567
|
+
return { models: value.data.map(parseModel) };
|
|
451
568
|
}
|
|
452
569
|
function modelsEndpoint(baseUrl) {
|
|
453
570
|
const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
|
|
454
571
|
return new URL("models", normalized);
|
|
455
572
|
}
|
|
456
|
-
function upstreamFailure(status) {
|
|
457
|
-
if (status === 401 || status === 403) return new ModelQueryError("INVALID_API_KEY",
|
|
458
|
-
if (status === 429) return new ModelQueryError("RATE_LIMITED",
|
|
459
|
-
if (status >= 500) return new ModelQueryError("UPSTREAM_UNAVAILABLE",
|
|
460
|
-
return new ModelQueryError("UPSTREAM_ERROR",
|
|
573
|
+
function upstreamFailure(status, provider) {
|
|
574
|
+
if (status === 401 || status === 403) return new ModelQueryError("INVALID_API_KEY", `${provider} API 密钥无效或无权查询模型`, 401);
|
|
575
|
+
if (status === 429) return new ModelQueryError("RATE_LIMITED", `${provider} API 请求过于频繁,请稍后重试`, 429);
|
|
576
|
+
if (status >= 500) return new ModelQueryError("UPSTREAM_UNAVAILABLE", `${provider} API 暂时不可用,请稍后重试`, 502);
|
|
577
|
+
return new ModelQueryError("UPSTREAM_ERROR", `${provider} API 返回了 HTTP ${status}`, 502);
|
|
461
578
|
}
|
|
462
579
|
/** Query the official `/models` endpoint with Bearer authentication and strict validation. */
|
|
463
|
-
async function
|
|
580
|
+
async function queryProviderModels(providerId, options) {
|
|
581
|
+
const provider = findBalanceProvider(providerId);
|
|
582
|
+
if (provider === void 0) throw new ModelQueryError("UNSUPPORTED_PROVIDER", "不支持此提供方的模型查询", 400);
|
|
464
583
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
465
584
|
let response;
|
|
466
585
|
try {
|
|
467
586
|
response = await fetchImpl(modelsEndpoint(options.baseUrl), {
|
|
468
587
|
method: "GET",
|
|
588
|
+
redirect: "error",
|
|
469
589
|
headers: {
|
|
470
590
|
accept: "application/json",
|
|
471
591
|
authorization: `Bearer ${options.apiKey}`
|
|
@@ -473,23 +593,29 @@ async function queryDeepSeekModels(options) {
|
|
|
473
593
|
signal: AbortSignal.timeout(options.timeoutMs)
|
|
474
594
|
});
|
|
475
595
|
} catch (error) {
|
|
476
|
-
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new ModelQueryError("UPSTREAM_TIMEOUT",
|
|
477
|
-
throw new ModelQueryError("UPSTREAM_UNAVAILABLE",
|
|
596
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new ModelQueryError("UPSTREAM_TIMEOUT", `查询 ${provider.name} 模型列表超时`, 504, { cause: error });
|
|
597
|
+
throw new ModelQueryError("UPSTREAM_UNAVAILABLE", `无法连接到 ${provider.name} API`, 502, { cause: error });
|
|
478
598
|
}
|
|
479
|
-
if (!response.ok) throw upstreamFailure(response.status);
|
|
599
|
+
if (!response.ok) throw upstreamFailure(response.status, provider.name);
|
|
480
600
|
let payload;
|
|
481
601
|
try {
|
|
482
602
|
payload = await response.json();
|
|
483
603
|
} catch (error) {
|
|
484
|
-
throw new ModelQueryError("
|
|
604
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new ModelQueryError("UPSTREAM_TIMEOUT", `查询 ${provider.name} 模型列表超时`, 504, { cause: error });
|
|
605
|
+
throw new ModelQueryError("INVALID_RESPONSE", `${provider.name} 返回了无法解析的模型列表`, 502, { cause: error });
|
|
485
606
|
}
|
|
486
|
-
return
|
|
607
|
+
return parseModels(payload);
|
|
608
|
+
}
|
|
609
|
+
/** Backward-compatible entry points for DeepSeek consumers. */
|
|
610
|
+
const parseDeepSeekModels = parseModels;
|
|
611
|
+
function queryDeepSeekModels(options) {
|
|
612
|
+
return queryProviderModels("deepseek", options);
|
|
487
613
|
}
|
|
488
614
|
//#endregion
|
|
489
615
|
//#region src/types.ts
|
|
490
616
|
/** The same-origin endpoint exposed by the plugin's Host half. */
|
|
491
617
|
const BALANCE_ROUTE = "/dsh-balance/api/balance";
|
|
492
|
-
/** The same-origin endpoint that proxies
|
|
618
|
+
/** The same-origin endpoint that proxies the selected provider’s `/models` API. */
|
|
493
619
|
const MODELS_ROUTE = "/dsh-balance/api/models";
|
|
494
620
|
//#endregion
|
|
495
621
|
//#region src/index.ts
|
|
@@ -500,6 +626,13 @@ const inject = [
|
|
|
500
626
|
"sessionPersistence"
|
|
501
627
|
];
|
|
502
628
|
const Config = z.object({
|
|
629
|
+
providers: z.array(z.object({
|
|
630
|
+
id: z.string().required(),
|
|
631
|
+
apiKeyRef: z.string().role("credential-ref").required(false),
|
|
632
|
+
baseUrl: z.string().required(false),
|
|
633
|
+
balanceApiKeyRef: z.string().role("credential-ref").required(false),
|
|
634
|
+
balanceBaseUrl: z.string().required(false)
|
|
635
|
+
})).required(false),
|
|
503
636
|
apiKeyRef: z.string().role("credential-ref").default("DEEPSEEK_API_KEY"),
|
|
504
637
|
baseUrl: z.string().default("https://api.deepseek.com"),
|
|
505
638
|
timeoutMs: z.number().step(1).min(1).max(6e4).default(1e4),
|
|
@@ -509,7 +642,7 @@ const Config = z.object({
|
|
|
509
642
|
});
|
|
510
643
|
function validateBaseUrl(value) {
|
|
511
644
|
const url = new URL(value);
|
|
512
|
-
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
|
|
645
|
+
const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
|
|
513
646
|
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) throw new Error("dsh-balance: baseUrl must use HTTPS (HTTP is accepted only for a loopback test server)");
|
|
514
647
|
}
|
|
515
648
|
function isLoopbackRequest(req) {
|
|
@@ -559,7 +692,8 @@ function parseUsageQuery(requestUrl) {
|
|
|
559
692
|
timeZone,
|
|
560
693
|
...from === void 0 ? {} : { from },
|
|
561
694
|
...to === void 0 ? {} : { to },
|
|
562
|
-
refresh: requestUrl.searchParams.get("refresh") === "1"
|
|
695
|
+
refresh: requestUrl.searchParams.get("refresh") === "1",
|
|
696
|
+
...requestUrl.searchParams.has("provider") ? { provider: requestUrl.searchParams.get("provider").trim() } : {}
|
|
563
697
|
};
|
|
564
698
|
}
|
|
565
699
|
function sessionTitle(events, fallback) {
|
|
@@ -587,9 +721,33 @@ async function mapWithConcurrency(items, concurrency, fn) {
|
|
|
587
721
|
/** Register the Host route that keeps credentials and upstream access out of the browser. */
|
|
588
722
|
function apply(ctx, config) {
|
|
589
723
|
validateBaseUrl(config.baseUrl);
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
724
|
+
credentialRef(config.apiKeyRef);
|
|
725
|
+
const providerConfigs = /* @__PURE__ */ new Map();
|
|
726
|
+
const configured = /* @__PURE__ */ new Map();
|
|
727
|
+
for (const override of config.providers ?? []) {
|
|
728
|
+
const provider = findBalanceProvider(override.id);
|
|
729
|
+
if (provider === void 0 || configured.has(provider.id)) throw new Error("dsh-balance: unsupported or duplicate balance provider");
|
|
730
|
+
configured.set(provider.id, override);
|
|
731
|
+
}
|
|
732
|
+
for (const provider of BALANCE_PROVIDERS) {
|
|
733
|
+
const override = configured.get(provider.id);
|
|
734
|
+
const apiKeyRef = override?.apiKeyRef ?? (provider.id === "deepseek" ? config.apiKeyRef : provider.apiKeyRef);
|
|
735
|
+
const baseUrl = override?.baseUrl ?? (provider.id === "deepseek" ? config.baseUrl : provider.baseUrl);
|
|
736
|
+
const defaults = balanceDefaults(provider);
|
|
737
|
+
const entry = {
|
|
738
|
+
apiKeyRef,
|
|
739
|
+
baseUrl,
|
|
740
|
+
balanceApiKeyRef: override?.balanceApiKeyRef ?? ("balanceApiKeyRef" in provider ? defaults.apiKeyRef : apiKeyRef),
|
|
741
|
+
balanceBaseUrl: override?.balanceBaseUrl ?? ("balanceBaseUrl" in provider ? defaults.baseUrl : baseUrl)
|
|
742
|
+
};
|
|
743
|
+
validateBaseUrl(entry.baseUrl);
|
|
744
|
+
validateBaseUrl(entry.balanceBaseUrl);
|
|
745
|
+
credentialRef(entry.apiKeyRef);
|
|
746
|
+
credentialRef(entry.balanceApiKeyRef);
|
|
747
|
+
providerConfigs.set(provider.id, entry);
|
|
748
|
+
}
|
|
749
|
+
const balanceCache = /* @__PURE__ */ new Map();
|
|
750
|
+
const modelsCache = /* @__PURE__ */ new Map();
|
|
593
751
|
let cachedUsage;
|
|
594
752
|
const handler = async (req, res) => {
|
|
595
753
|
if (req.method !== "GET") {
|
|
@@ -609,43 +767,55 @@ function apply(ctx, config) {
|
|
|
609
767
|
});
|
|
610
768
|
return;
|
|
611
769
|
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
770
|
+
const requestUrl = new URL(req.url ?? "/dsh-balance/api/balance", "http://localhost");
|
|
771
|
+
const provider = findBalanceProvider(requestUrl.searchParams.get("provider") ?? "deepseek");
|
|
772
|
+
if (provider === void 0) {
|
|
773
|
+
sendJson(res, 400, {
|
|
774
|
+
ok: false,
|
|
775
|
+
code: "UNSUPPORTED_PROVIDER",
|
|
776
|
+
message: "不支持此提供方的余额查询"
|
|
616
777
|
});
|
|
617
778
|
return;
|
|
618
779
|
}
|
|
619
|
-
const
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
780
|
+
const settings = providerConfigs.get(provider.id);
|
|
781
|
+
const forceRefresh = requestUrl.searchParams.get("refresh") === "1";
|
|
782
|
+
const cached = balanceCache.get(provider.id);
|
|
783
|
+
if (!forceRefresh && cached !== void 0 && cached.expiresAt > Date.now()) {
|
|
784
|
+
sendJson(res, 200, {
|
|
785
|
+
...cached.value,
|
|
786
|
+
source: "cache"
|
|
625
787
|
});
|
|
626
788
|
return;
|
|
627
789
|
}
|
|
628
790
|
try {
|
|
629
|
-
const
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
791
|
+
const credential = await ctx.credentials.resolve(credentialRef(settings.balanceApiKeyRef));
|
|
792
|
+
if (credential === void 0) {
|
|
793
|
+
sendJson(res, 401, {
|
|
794
|
+
ok: false,
|
|
795
|
+
code: "MISSING_API_KEY",
|
|
796
|
+
message: `未配置 ${settings.balanceApiKeyRef},请配置 ${provider.name} 余额查询凭据`
|
|
797
|
+
});
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
634
800
|
const value = {
|
|
635
801
|
ok: true,
|
|
636
|
-
|
|
637
|
-
|
|
802
|
+
...await queryProviderBalance(provider.id, {
|
|
803
|
+
apiKey: credential.value,
|
|
804
|
+
baseUrl: settings.balanceBaseUrl,
|
|
805
|
+
timeoutMs: config.timeoutMs
|
|
806
|
+
}),
|
|
807
|
+
provider: provider.id,
|
|
638
808
|
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
639
809
|
source: "live"
|
|
640
810
|
};
|
|
641
|
-
|
|
811
|
+
balanceCache.set(provider.id, {
|
|
642
812
|
expiresAt: Date.now() + config.cacheMs,
|
|
643
813
|
value
|
|
644
|
-
};
|
|
814
|
+
});
|
|
645
815
|
sendJson(res, 200, value);
|
|
646
816
|
} catch (error) {
|
|
647
|
-
const failure = error instanceof BalanceQueryError ? error : new BalanceQueryError("UPSTREAM_ERROR", "查询余额时发生未知错误", 502
|
|
648
|
-
ctx.logger.warn(failure);
|
|
817
|
+
const failure = error instanceof BalanceQueryError ? error : new BalanceQueryError("UPSTREAM_ERROR", "查询余额时发生未知错误", 502);
|
|
818
|
+
ctx.logger.warn(`Balance query failed: ${provider.id} ${failure.code}`);
|
|
649
819
|
sendJson(res, failure.httpStatus, {
|
|
650
820
|
ok: false,
|
|
651
821
|
code: failure.code,
|
|
@@ -671,41 +841,55 @@ function apply(ctx, config) {
|
|
|
671
841
|
});
|
|
672
842
|
return;
|
|
673
843
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
844
|
+
const requestUrl = new URL(req.url ?? "/dsh-balance/api/models", "http://localhost");
|
|
845
|
+
const provider = findBalanceProvider(requestUrl.searchParams.get("provider") ?? "deepseek");
|
|
846
|
+
if (provider === void 0) {
|
|
847
|
+
sendJson(res, 400, {
|
|
848
|
+
ok: false,
|
|
849
|
+
code: "UNSUPPORTED_PROVIDER",
|
|
850
|
+
message: "不支持此提供方的模型查询"
|
|
678
851
|
});
|
|
679
852
|
return;
|
|
680
853
|
}
|
|
681
|
-
const
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
854
|
+
const settings = providerConfigs.get(provider.id);
|
|
855
|
+
const cachedModels = modelsCache.get(provider.id);
|
|
856
|
+
if (!(requestUrl.searchParams.get("refresh") === "1") && cachedModels !== void 0 && cachedModels.expiresAt > Date.now()) {
|
|
857
|
+
sendJson(res, 200, {
|
|
858
|
+
...cachedModels.value,
|
|
859
|
+
source: "cache"
|
|
687
860
|
});
|
|
688
861
|
return;
|
|
689
862
|
}
|
|
690
863
|
try {
|
|
864
|
+
const credential = await ctx.credentials.resolve(credentialRef(settings.apiKeyRef));
|
|
865
|
+
if (credential === void 0) {
|
|
866
|
+
sendJson(res, 401, {
|
|
867
|
+
ok: false,
|
|
868
|
+
code: "MISSING_API_KEY",
|
|
869
|
+
message: `未配置 ${settings.apiKeyRef},请先在“模型”设置中保存 ${provider.name} API 密钥`
|
|
870
|
+
});
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
const result = await queryProviderModels(provider.id, {
|
|
874
|
+
apiKey: credential.value,
|
|
875
|
+
baseUrl: settings.baseUrl,
|
|
876
|
+
timeoutMs: config.timeoutMs
|
|
877
|
+
});
|
|
691
878
|
const value = {
|
|
692
879
|
ok: true,
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
baseUrl: config.baseUrl,
|
|
696
|
-
timeoutMs: config.timeoutMs
|
|
697
|
-
})).models,
|
|
880
|
+
provider: provider.id,
|
|
881
|
+
models: result.models,
|
|
698
882
|
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
699
883
|
source: "live"
|
|
700
884
|
};
|
|
701
|
-
|
|
885
|
+
modelsCache.set(provider.id, {
|
|
702
886
|
expiresAt: Date.now() + config.cacheMs,
|
|
703
887
|
value
|
|
704
|
-
};
|
|
888
|
+
});
|
|
705
889
|
sendJson(res, 200, value);
|
|
706
890
|
} catch (error) {
|
|
707
|
-
const failure = error instanceof ModelQueryError ? error : new ModelQueryError("UPSTREAM_ERROR", "查询模型时发生未知错误", 502
|
|
708
|
-
ctx.logger.warn(failure);
|
|
891
|
+
const failure = error instanceof ModelQueryError ? error : new ModelQueryError("UPSTREAM_ERROR", "查询模型时发生未知错误", 502);
|
|
892
|
+
ctx.logger.warn(`Model query failed: ${provider.id} ${failure.code}`);
|
|
709
893
|
sendJson(res, failure.httpStatus, {
|
|
710
894
|
ok: false,
|
|
711
895
|
code: failure.code,
|
|
@@ -759,6 +943,7 @@ function apply(ctx, config) {
|
|
|
759
943
|
});
|
|
760
944
|
const usdToCny = normalizeUsdToCny(config.usdToCny);
|
|
761
945
|
const aggregateOptions = { timeZone: query.timeZone };
|
|
946
|
+
if (query.provider !== void 0) aggregateOptions.provider = query.provider;
|
|
762
947
|
if (query.from !== void 0) aggregateOptions.from = query.from;
|
|
763
948
|
if (query.to !== void 0) aggregateOptions.to = query.to;
|
|
764
949
|
if (usdToCny !== void 0) aggregateOptions.usdToCny = usdToCny;
|
|
@@ -814,6 +999,6 @@ function apply(ctx, config) {
|
|
|
814
999
|
}), `dsh-balance: ${USAGE_ROUTE}`);
|
|
815
1000
|
}
|
|
816
1001
|
//#endregion
|
|
817
|
-
export { BILLING_PRICES, BILLING_PRICING_VERSION, BalanceQueryError, Config, ModelQueryError, USAGE_ROUTE, aggregateBilling, apply, assertTimeZone, calculateRequestCost, extractSessionUsage, inject, name, normalizeUsdToCny, parseDeepSeekBalance, parseDeepSeekModels, queryDeepSeekBalance, queryDeepSeekModels, resolveBillingPrice };
|
|
1002
|
+
export { BALANCE_PROVIDERS, BILLING_PRICES, BILLING_PRICING_VERSION, BalanceQueryError, Config, ModelQueryError, USAGE_ROUTE, aggregateBilling, apply, assertTimeZone, balanceDefaults, calculateRequestCost, extractSessionUsage, findBalanceProvider, inject, name, normalizeUsdToCny, parseDeepSeekBalance, parseDeepSeekModels, parseModel, parseModels, parseStepFunBalance, parseTokenerBalance, queryDeepSeekBalance, queryDeepSeekModels, queryProviderBalance, queryProviderModels, queryStepFunBalance, resolveBillingPrice };
|
|
818
1003
|
|
|
819
1004
|
//# sourceMappingURL=index.js.map
|