@pinkbanana/dsh-balance 0.6.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/lib/index.js CHANGED
@@ -2,20 +2,38 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  //#region src/providers.ts
4
4
  /** Browser-safe provider metadata. Credentials and wire parsers stay on the Host. */
5
- const BALANCE_PROVIDERS = [{
6
- id: "deepseek",
7
- name: "DeepSeek",
8
- apiKeyRef: "DEEPSEEK_API_KEY",
9
- baseUrl: "https://api.deepseek.com"
10
- }, {
11
- id: "stepfun",
12
- name: "StepFun",
13
- apiKeyRef: "STEPFUN_API_KEY",
14
- baseUrl: "https://api.stepfun.com/v1"
15
- }];
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
+ ];
16
27
  function findBalanceProvider(id) {
17
28
  return BALANCE_PROVIDERS.find((provider) => provider.id === id.trim().toLowerCase());
18
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
+ }
19
37
  //#endregion
20
38
  //#region src/balance.ts
21
39
  const DECIMAL = /^-?\d+(?:\.\d+)?$/;
@@ -74,6 +92,28 @@ function parseStepFunBalance(value) {
74
92
  }]
75
93
  };
76
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
+ };
116
+ }
77
117
  /** Add a provider's endpoint and parser here; transport and error handling are shared. */
78
118
  const adapters = {
79
119
  deepseek: {
@@ -83,6 +123,10 @@ const adapters = {
83
123
  stepfun: {
84
124
  path: "accounts",
85
125
  parse: parseStepFunBalance
126
+ },
127
+ tokener: {
128
+ path: "billing/balance",
129
+ parse: parseTokenerBalance
86
130
  }
87
131
  };
88
132
  function upstreamFailure$1(status, provider) {
@@ -267,12 +311,12 @@ function messageMetadata(event) {
267
311
  }
268
312
  /** Resolve the versioned price for one request. */
269
313
  function resolveBillingPrice(provider, model, time) {
270
- if (provider !== "deepseek") return void 0;
314
+ if (findBalanceProvider(provider)?.id !== "deepseek") return void 0;
271
315
  const canonicalModel = model === "deepseek-chat" || model === "deepseek-reasoner" ? time >= PEAK_EFFECTIVE_FROM ? "deepseek-v4-flash" : model : model;
272
316
  const rates = time < PEAK_EFFECTIVE_FROM && canonicalModel === model ? LEGACY_PRICES[canonicalModel] : CURRENT_PRICES[canonicalModel];
273
317
  if (rates === void 0) return void 0;
274
318
  return {
275
- provider,
319
+ provider: "deepseek",
276
320
  model: canonicalModel,
277
321
  effectiveFrom: new Date(time < PEAK_EFFECTIVE_FROM ? 0 : PEAK_EFFECTIVE_FROM).toISOString(),
278
322
  pricingVersion: time < PEAK_EFFECTIVE_FROM ? "deepseek-legacy" : BILLING_PRICING_VERSION,
@@ -281,7 +325,7 @@ function resolveBillingPrice(provider, model, time) {
281
325
  }
282
326
  /** Compute one request charge. Cache writes are billed as cache misses. */
283
327
  function calculateRequestCost(usage, price, time) {
284
- const multiplier = isPeakHour(new Date(time)) ? 2 : 1;
328
+ const multiplier = findBalanceProvider(price.provider)?.id === "deepseek" && isPeakHour(new Date(time)) ? 2 : 1;
285
329
  return roundMoney(((usage.inputTokens + usage.cacheWriteTokens) * price.cacheMissUsdPerMillion + usage.cacheReadTokens * price.cacheHitUsdPerMillion + usage.outputTokens * price.outputUsdPerMillion) / TOKENS_PER_MILLION * multiplier);
286
330
  }
287
331
  function dateKey(time, timeZone) {
@@ -303,20 +347,32 @@ function extractSessionUsage(sessionId, header, events, options) {
303
347
  const seedLength = header.seedLength ?? 0;
304
348
  let latestRequest;
305
349
  const requests = /* @__PURE__ */ new Map();
350
+ let activeStep;
306
351
  const records = [];
307
352
  for (const event of events) {
308
- const metadata = readRequestMetadata(event);
309
- if (metadata !== void 0) latestRequest = metadata;
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
+ }
310
360
  if (event.type === "step/start") {
311
- if (latestRequest !== void 0) requests.set(stepKey(event.data.turn, event.data.step), latestRequest);
361
+ activeStep = stepKey(event.data.turn, event.data.step);
362
+ requests.set(activeStep, {
363
+ metadata: latestRequest,
364
+ time: event.time
365
+ });
312
366
  continue;
313
367
  }
368
+ if (event.type === "step/end") activeStep = void 0;
314
369
  if (event.type !== "assistant/message" || event.seq < seedLength) continue;
315
- const request = requests.get(stepKey(event.data.turn, event.data.step)) ?? latestRequest;
316
- const fallback = messageMetadata(event);
317
- const provider = request?.provider ?? fallback?.provider ?? null;
318
- const model = request?.model ?? fallback?.model ?? null;
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;
319
374
  const time = request?.time ?? event.time;
375
+ if (options.provider !== void 0 && provider !== (findBalanceProvider(options.provider)?.id ?? options.provider)) continue;
320
376
  if (!inDateRange(time, options.timeZone, options.from, options.to)) continue;
321
377
  const usage = readUsage(event.data.usage);
322
378
  const inputTokens = usage?.inputTokens ?? 0;
@@ -330,7 +386,7 @@ function extractSessionUsage(sessionId, header, events, options) {
330
386
  else if (provider === null || model === null) unknownReason = "missing-request-metadata";
331
387
  else {
332
388
  const price = resolveBillingPrice(provider, model, time);
333
- if (price === void 0) unknownReason = provider === "deepseek" ? "unknown-model" : "unknown-provider";
389
+ if (price === void 0) unknownReason = findBalanceProvider(provider) !== void 0 ? "unknown-model" : "unknown-provider";
334
390
  else {
335
391
  costUsd = calculateRequestCost(usage, price, time);
336
392
  pricingVersion = price.pricingVersion;
@@ -365,7 +421,7 @@ function aggregateRecords(records, sessionTitles, timeZone, usdToCny) {
365
421
  addTotals(totals, record);
366
422
  const provider = record.provider ?? "unknown";
367
423
  const model = record.model ?? "unknown";
368
- const modelKey = `${provider}:${model}`;
424
+ const modelKey = JSON.stringify([provider, model]);
369
425
  const modelTotal = models.get(modelKey) ?? {
370
426
  ...emptyTotals(),
371
427
  provider,
@@ -573,7 +629,9 @@ const Config = z.object({
573
629
  providers: z.array(z.object({
574
630
  id: z.string().required(),
575
631
  apiKeyRef: z.string().role("credential-ref").required(false),
576
- baseUrl: z.string().required(false)
632
+ baseUrl: z.string().required(false),
633
+ balanceApiKeyRef: z.string().role("credential-ref").required(false),
634
+ balanceBaseUrl: z.string().required(false)
577
635
  })).required(false),
578
636
  apiKeyRef: z.string().role("credential-ref").default("DEEPSEEK_API_KEY"),
579
637
  baseUrl: z.string().default("https://api.deepseek.com"),
@@ -634,7 +692,8 @@ function parseUsageQuery(requestUrl) {
634
692
  timeZone,
635
693
  ...from === void 0 ? {} : { from },
636
694
  ...to === void 0 ? {} : { to },
637
- refresh: requestUrl.searchParams.get("refresh") === "1"
695
+ refresh: requestUrl.searchParams.get("refresh") === "1",
696
+ ...requestUrl.searchParams.has("provider") ? { provider: requestUrl.searchParams.get("provider").trim() } : {}
638
697
  };
639
698
  }
640
699
  function sessionTitle(events, fallback) {
@@ -663,22 +722,28 @@ async function mapWithConcurrency(items, concurrency, fn) {
663
722
  function apply(ctx, config) {
664
723
  validateBaseUrl(config.baseUrl);
665
724
  credentialRef(config.apiKeyRef);
666
- const providerConfigs = new Map(BALANCE_PROVIDERS.map((provider) => [provider.id, {
667
- apiKeyRef: provider.id === "deepseek" ? config.apiKeyRef : provider.apiKeyRef,
668
- baseUrl: provider.id === "deepseek" ? config.baseUrl : provider.baseUrl
669
- }]));
670
- const configured = /* @__PURE__ */ new Set();
725
+ const providerConfigs = /* @__PURE__ */ new Map();
726
+ const configured = /* @__PURE__ */ new Map();
671
727
  for (const override of config.providers ?? []) {
672
728
  const provider = findBalanceProvider(override.id);
673
729
  if (provider === void 0 || configured.has(provider.id)) throw new Error("dsh-balance: unsupported or duplicate balance provider");
674
- configured.add(provider.id);
675
- const defaults = providerConfigs.get(provider.id);
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);
676
737
  const entry = {
677
- apiKeyRef: override.apiKeyRef ?? defaults.apiKeyRef,
678
- baseUrl: override.baseUrl ?? defaults.baseUrl
738
+ apiKeyRef,
739
+ baseUrl,
740
+ balanceApiKeyRef: override?.balanceApiKeyRef ?? ("balanceApiKeyRef" in provider ? defaults.apiKeyRef : apiKeyRef),
741
+ balanceBaseUrl: override?.balanceBaseUrl ?? ("balanceBaseUrl" in provider ? defaults.baseUrl : baseUrl)
679
742
  };
680
743
  validateBaseUrl(entry.baseUrl);
744
+ validateBaseUrl(entry.balanceBaseUrl);
681
745
  credentialRef(entry.apiKeyRef);
746
+ credentialRef(entry.balanceApiKeyRef);
682
747
  providerConfigs.set(provider.id, entry);
683
748
  }
684
749
  const balanceCache = /* @__PURE__ */ new Map();
@@ -723,12 +788,12 @@ function apply(ctx, config) {
723
788
  return;
724
789
  }
725
790
  try {
726
- const credential = await ctx.credentials.resolve(credentialRef(settings.apiKeyRef));
791
+ const credential = await ctx.credentials.resolve(credentialRef(settings.balanceApiKeyRef));
727
792
  if (credential === void 0) {
728
793
  sendJson(res, 401, {
729
794
  ok: false,
730
795
  code: "MISSING_API_KEY",
731
- message: `未配置 ${settings.apiKeyRef},请先在“模型”设置中保存 ${provider.name} API 密钥`
796
+ message: `未配置 ${settings.balanceApiKeyRef},请配置 ${provider.name} 余额查询凭据`
732
797
  });
733
798
  return;
734
799
  }
@@ -736,7 +801,7 @@ function apply(ctx, config) {
736
801
  ok: true,
737
802
  ...await queryProviderBalance(provider.id, {
738
803
  apiKey: credential.value,
739
- baseUrl: settings.baseUrl,
804
+ baseUrl: settings.balanceBaseUrl,
740
805
  timeoutMs: config.timeoutMs
741
806
  }),
742
807
  provider: provider.id,
@@ -878,6 +943,7 @@ function apply(ctx, config) {
878
943
  });
879
944
  const usdToCny = normalizeUsdToCny(config.usdToCny);
880
945
  const aggregateOptions = { timeZone: query.timeZone };
946
+ if (query.provider !== void 0) aggregateOptions.provider = query.provider;
881
947
  if (query.from !== void 0) aggregateOptions.from = query.from;
882
948
  if (query.to !== void 0) aggregateOptions.to = query.to;
883
949
  if (usdToCny !== void 0) aggregateOptions.usdToCny = usdToCny;
@@ -933,6 +999,6 @@ function apply(ctx, config) {
933
999
  }), `dsh-balance: ${USAGE_ROUTE}`);
934
1000
  }
935
1001
  //#endregion
936
- export { BALANCE_PROVIDERS, BILLING_PRICES, BILLING_PRICING_VERSION, BalanceQueryError, Config, ModelQueryError, USAGE_ROUTE, aggregateBilling, apply, assertTimeZone, calculateRequestCost, extractSessionUsage, findBalanceProvider, inject, name, normalizeUsdToCny, parseDeepSeekBalance, parseDeepSeekModels, parseModel, parseModels, parseStepFunBalance, queryDeepSeekBalance, queryDeepSeekModels, queryProviderBalance, queryProviderModels, queryStepFunBalance, 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 };
937
1003
 
938
1004
  //# sourceMappingURL=index.js.map