@pinkbanana/dsh-balance 0.4.0 → 0.5.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
@@ -75,6 +75,349 @@ async function queryDeepSeekBalance(options) {
75
75
  return parseDeepSeekBalance(payload);
76
76
  }
77
77
  //#endregion
78
+ //#region src/pricing.ts
79
+ /** Shared DeepSeek pricing schedule used by Host billing and the client indicator. */
80
+ const BEIJING_OFFSET_MS = 288e5;
81
+ /** The current V4 schedule became effective at 00:00 Beijing time on 2026-08-17. */
82
+ const PEAK_EFFECTIVE_FROM = Date.parse("2026-08-17T00:00:00+08:00");
83
+ const PEAK_WINDOWS = [[9, 12], [14, 18]];
84
+ /** Hour of day in Beijing time (UTC+8), 0–23. */
85
+ function beijingHour(date) {
86
+ return new Date(date.getTime() + BEIJING_OFFSET_MS).getUTCHours();
87
+ }
88
+ /** Whether the given instant falls inside a DeepSeek peak-pricing window. */
89
+ function isPeakHour(date) {
90
+ if (date.getTime() < PEAK_EFFECTIVE_FROM) return false;
91
+ const hour = beijingHour(date);
92
+ return PEAK_WINDOWS.some(([start, end]) => hour >= start && hour < end);
93
+ }
94
+ //#endregion
95
+ //#region src/billing.ts
96
+ const USAGE_ROUTE = "/dsh-balance/api/usage";
97
+ const BILLING_PRICING_VERSION = "deepseek-v4-2026-08-17";
98
+ const TOKENS_PER_MILLION = 1e6;
99
+ const CURRENT_PRICES = {
100
+ "deepseek-v4-flash": {
101
+ cacheHitUsdPerMillion: .007,
102
+ cacheMissUsdPerMillion: .22,
103
+ outputUsdPerMillion: .66
104
+ },
105
+ "deepseek-v4-pro": {
106
+ cacheHitUsdPerMillion: .022,
107
+ cacheMissUsdPerMillion: .66,
108
+ outputUsdPerMillion: 1.98
109
+ }
110
+ };
111
+ const LEGACY_PRICES = {
112
+ "deepseek-chat": {
113
+ cacheHitUsdPerMillion: .07,
114
+ cacheMissUsdPerMillion: .27,
115
+ outputUsdPerMillion: 1.1
116
+ },
117
+ "deepseek-reasoner": {
118
+ cacheHitUsdPerMillion: .14,
119
+ cacheMissUsdPerMillion: .55,
120
+ outputUsdPerMillion: 2.19
121
+ }
122
+ };
123
+ const BILLING_PRICES = [...Object.entries(LEGACY_PRICES).map(([model, rates]) => ({
124
+ provider: "deepseek",
125
+ model,
126
+ effectiveFrom: (/* @__PURE__ */ new Date(0)).toISOString(),
127
+ pricingVersion: "deepseek-legacy",
128
+ ...rates
129
+ })), ...Object.entries(CURRENT_PRICES).map(([model, rates]) => ({
130
+ provider: "deepseek",
131
+ model,
132
+ effectiveFrom: new Date(PEAK_EFFECTIVE_FROM).toISOString(),
133
+ pricingVersion: BILLING_PRICING_VERSION,
134
+ ...rates
135
+ }))];
136
+ function emptyTotals() {
137
+ return {
138
+ requests: 0,
139
+ pricedRequests: 0,
140
+ unpricedRequests: 0,
141
+ inputTokens: 0,
142
+ outputTokens: 0,
143
+ cacheReadTokens: 0,
144
+ cacheWriteTokens: 0,
145
+ costUsd: 0
146
+ };
147
+ }
148
+ function addTotals(target, record) {
149
+ target.requests += 1;
150
+ if (record.costUsd === null) target.unpricedRequests += 1;
151
+ else {
152
+ target.pricedRequests += 1;
153
+ target.costUsd += record.costUsd;
154
+ }
155
+ target.inputTokens += record.inputTokens;
156
+ target.outputTokens += record.outputTokens;
157
+ target.cacheReadTokens += record.cacheReadTokens;
158
+ target.cacheWriteTokens += record.cacheWriteTokens;
159
+ }
160
+ function toTotals(value, usdToCny) {
161
+ const costUsd = roundMoney(value.costUsd);
162
+ return {
163
+ ...value,
164
+ costUsd,
165
+ costCny: usdToCny === null ? null : roundMoney(costUsd * usdToCny)
166
+ };
167
+ }
168
+ function roundMoney(value) {
169
+ return Math.round(value * 0xe8d4a51000) / 0xe8d4a51000;
170
+ }
171
+ function requiredPositiveInteger(value) {
172
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
173
+ }
174
+ function readUsage(value) {
175
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
176
+ const row = value;
177
+ const inputTokens = requiredPositiveInteger(row.inputTokens);
178
+ const outputTokens = requiredPositiveInteger(row.outputTokens);
179
+ const cacheReadTokens = row.cacheReadTokens === void 0 ? 0 : requiredPositiveInteger(row.cacheReadTokens);
180
+ const cacheWriteTokens = row.cacheWriteTokens === void 0 ? 0 : requiredPositiveInteger(row.cacheWriteTokens);
181
+ if (inputTokens === void 0 || outputTokens === void 0 || cacheReadTokens === void 0 || cacheWriteTokens === void 0) return void 0;
182
+ return {
183
+ inputTokens,
184
+ outputTokens,
185
+ cacheReadTokens,
186
+ cacheWriteTokens
187
+ };
188
+ }
189
+ function readRequestMetadata(event) {
190
+ if (event.type !== "request/header") return void 0;
191
+ const config = event.data.header.config;
192
+ if (typeof config.provider !== "string" || typeof config.model !== "string") return void 0;
193
+ return {
194
+ provider: config.provider,
195
+ model: config.model,
196
+ time: event.time
197
+ };
198
+ }
199
+ function stepKey(turn, step) {
200
+ return `${turn}:${step}`;
201
+ }
202
+ function messageMetadata(event) {
203
+ if (event.type !== "assistant/message") return void 0;
204
+ const source = event.data.message.source;
205
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return void 0;
206
+ const row = source;
207
+ return typeof row.provider === "string" && typeof row.model === "string" ? {
208
+ provider: row.provider,
209
+ model: row.model
210
+ } : void 0;
211
+ }
212
+ /** Resolve the versioned price for one request. */
213
+ function resolveBillingPrice(provider, model, time) {
214
+ if (provider !== "deepseek") return void 0;
215
+ const canonicalModel = model === "deepseek-chat" || model === "deepseek-reasoner" ? time >= PEAK_EFFECTIVE_FROM ? "deepseek-v4-flash" : model : model;
216
+ const rates = time < PEAK_EFFECTIVE_FROM && canonicalModel === model ? LEGACY_PRICES[canonicalModel] : CURRENT_PRICES[canonicalModel];
217
+ if (rates === void 0) return void 0;
218
+ return {
219
+ provider,
220
+ model: canonicalModel,
221
+ effectiveFrom: new Date(time < PEAK_EFFECTIVE_FROM ? 0 : PEAK_EFFECTIVE_FROM).toISOString(),
222
+ pricingVersion: time < PEAK_EFFECTIVE_FROM ? "deepseek-legacy" : BILLING_PRICING_VERSION,
223
+ ...rates
224
+ };
225
+ }
226
+ /** Compute one request charge. Cache writes are billed as cache misses. */
227
+ function calculateRequestCost(usage, price, time) {
228
+ const multiplier = isPeakHour(new Date(time)) ? 2 : 1;
229
+ return roundMoney(((usage.inputTokens + usage.cacheWriteTokens) * price.cacheMissUsdPerMillion + usage.cacheReadTokens * price.cacheHitUsdPerMillion + usage.outputTokens * price.outputUsdPerMillion) / TOKENS_PER_MILLION * multiplier);
230
+ }
231
+ function dateKey(time, timeZone) {
232
+ const parts = new Intl.DateTimeFormat("en-CA", {
233
+ timeZone,
234
+ year: "numeric",
235
+ month: "2-digit",
236
+ day: "2-digit"
237
+ }).formatToParts(new Date(time));
238
+ const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
239
+ return `${values.year ?? "0000"}-${values.month ?? "00"}-${values.day ?? "00"}`;
240
+ }
241
+ function inDateRange(time, timeZone, from, to) {
242
+ const day = dateKey(time, timeZone);
243
+ return (from === void 0 || day >= from) && (to === void 0 || day <= to);
244
+ }
245
+ /** Fold a complete session log into request-level billing records. */
246
+ function extractSessionUsage(sessionId, header, events, options) {
247
+ const seedLength = header.seedLength ?? 0;
248
+ let latestRequest;
249
+ const requests = /* @__PURE__ */ new Map();
250
+ const records = [];
251
+ for (const event of events) {
252
+ const metadata = readRequestMetadata(event);
253
+ if (metadata !== void 0) latestRequest = metadata;
254
+ if (event.type === "step/start") {
255
+ if (latestRequest !== void 0) requests.set(stepKey(event.data.turn, event.data.step), latestRequest);
256
+ continue;
257
+ }
258
+ if (event.type !== "assistant/message" || event.seq < seedLength) continue;
259
+ const request = requests.get(stepKey(event.data.turn, event.data.step)) ?? latestRequest;
260
+ const fallback = messageMetadata(event);
261
+ const provider = request?.provider ?? fallback?.provider ?? null;
262
+ const model = request?.model ?? fallback?.model ?? null;
263
+ const time = request?.time ?? event.time;
264
+ if (!inDateRange(time, options.timeZone, options.from, options.to)) continue;
265
+ const usage = readUsage(event.data.usage);
266
+ const inputTokens = usage?.inputTokens ?? 0;
267
+ const outputTokens = usage?.outputTokens ?? 0;
268
+ const cacheReadTokens = usage?.cacheReadTokens ?? 0;
269
+ const cacheWriteTokens = usage?.cacheWriteTokens ?? 0;
270
+ let costUsd = null;
271
+ let pricingVersion;
272
+ let unknownReason;
273
+ if (usage === void 0) unknownReason = "missing-usage";
274
+ else if (provider === null || model === null) unknownReason = "missing-request-metadata";
275
+ else {
276
+ const price = resolveBillingPrice(provider, model, time);
277
+ if (price === void 0) unknownReason = provider === "deepseek" ? "unknown-model" : "unknown-provider";
278
+ else {
279
+ costUsd = calculateRequestCost(usage, price, time);
280
+ pricingVersion = price.pricingVersion;
281
+ }
282
+ }
283
+ const record = {
284
+ sessionId,
285
+ turn: event.data.turn,
286
+ step: event.data.step,
287
+ time: new Date(time).toISOString(),
288
+ provider,
289
+ model,
290
+ ...usage === void 0 ? {} : { usage },
291
+ inputTokens,
292
+ outputTokens,
293
+ cacheReadTokens,
294
+ cacheWriteTokens,
295
+ costUsd,
296
+ ...pricingVersion === void 0 ? {} : { pricingVersion },
297
+ ...unknownReason === void 0 ? {} : { unknownReason }
298
+ };
299
+ records.push(record);
300
+ }
301
+ return records;
302
+ }
303
+ function aggregateRecords(records, sessionTitles, timeZone, usdToCny) {
304
+ const totals = emptyTotals();
305
+ const models = /* @__PURE__ */ new Map();
306
+ const days = /* @__PURE__ */ new Map();
307
+ const sessions = /* @__PURE__ */ new Map();
308
+ for (const record of records) {
309
+ addTotals(totals, record);
310
+ const provider = record.provider ?? "unknown";
311
+ const model = record.model ?? "unknown";
312
+ const modelKey = `${provider}:${model}`;
313
+ const modelTotal = models.get(modelKey) ?? {
314
+ ...emptyTotals(),
315
+ provider,
316
+ model
317
+ };
318
+ addTotals(modelTotal, record);
319
+ models.set(modelKey, modelTotal);
320
+ const day = dateKey(Date.parse(record.time), timeZone);
321
+ const dayTotal = days.get(day) ?? {
322
+ ...emptyTotals(),
323
+ date: day
324
+ };
325
+ addTotals(dayTotal, record);
326
+ days.set(day, dayTotal);
327
+ const sessionTotal = sessions.get(record.sessionId) ?? {
328
+ ...emptyTotals(),
329
+ sessionId: record.sessionId,
330
+ title: sessionTitles.get(record.sessionId) ?? record.sessionId
331
+ };
332
+ addTotals(sessionTotal, record);
333
+ sessions.set(record.sessionId, sessionTotal);
334
+ }
335
+ const toAggregate = (value) => {
336
+ const { requests, pricedRequests, unpricedRequests, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, costUsd } = value;
337
+ const totals = {
338
+ requests,
339
+ pricedRequests,
340
+ unpricedRequests,
341
+ inputTokens,
342
+ outputTokens,
343
+ cacheReadTokens,
344
+ cacheWriteTokens,
345
+ costUsd: roundMoney(costUsd),
346
+ costCny: usdToCny === null ? null : roundMoney(costUsd * usdToCny)
347
+ };
348
+ const extras = value;
349
+ if (extras.provider !== void 0 && extras.model !== void 0) return {
350
+ ...totals,
351
+ provider: extras.provider,
352
+ model: extras.model
353
+ };
354
+ if (extras.date !== void 0) return {
355
+ ...totals,
356
+ date: extras.date
357
+ };
358
+ return {
359
+ ...totals,
360
+ sessionId: extras.sessionId ?? "",
361
+ title: extras.title ?? ""
362
+ };
363
+ };
364
+ const summary = {
365
+ timeZone,
366
+ usdToCny,
367
+ totals: toTotals(totals, usdToCny),
368
+ byModel: [...models.values()].map((value) => ({
369
+ ...toAggregate(value),
370
+ provider: value.provider,
371
+ model: value.model
372
+ })),
373
+ byDay: [...days.values()].map((value) => ({
374
+ ...toAggregate(value),
375
+ date: value.date
376
+ })),
377
+ bySession: [...sessions.values()].map((value) => ({
378
+ ...toAggregate(value),
379
+ sessionId: value.sessionId,
380
+ title: value.title
381
+ }))
382
+ };
383
+ summary.byModel.sort((a, b) => b.costUsd - a.costUsd || `${a.provider}/${a.model}`.localeCompare(`${b.provider}/${b.model}`));
384
+ summary.byDay.sort((a, b) => b.date.localeCompare(a.date));
385
+ summary.bySession.sort((a, b) => b.costUsd - a.costUsd || a.title.localeCompare(b.title));
386
+ return {
387
+ summary,
388
+ sessionRecords: [...sessions.keys()].map((sessionId) => ({
389
+ session: summary.bySession.find((item) => item.sessionId === sessionId) ?? {
390
+ ...toTotals(emptyTotals(), usdToCny),
391
+ sessionId,
392
+ title: sessionTitles.get(sessionId) ?? sessionId
393
+ },
394
+ records: records.filter((record) => record.sessionId === sessionId)
395
+ }))
396
+ };
397
+ }
398
+ /** Aggregate one or many sessions for the settings page or session view. */
399
+ function aggregateBilling(sources, options) {
400
+ const records = [];
401
+ const titles = /* @__PURE__ */ new Map();
402
+ for (const source of sources) {
403
+ titles.set(source.sessionId, source.title);
404
+ records.push(...extractSessionUsage(source.sessionId, source.header, source.events, options));
405
+ }
406
+ const aggregate = aggregateRecords(records, titles, options.timeZone, options.usdToCny ?? null);
407
+ return {
408
+ summary: aggregate.summary,
409
+ requestsBySession: new Map(aggregate.sessionRecords.map((item) => [item.session.sessionId, item.records]))
410
+ };
411
+ }
412
+ /** Validate an IANA timezone before accepting it at the Host boundary. */
413
+ function assertTimeZone(timeZone) {
414
+ new Intl.DateTimeFormat("en-US", { timeZone }).format();
415
+ }
416
+ /** Convert the configured USD rate into a JSON-safe optional amount. */
417
+ function normalizeUsdToCny(value) {
418
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : void 0;
419
+ }
420
+ //#endregion
78
421
  //#region src/models.ts
79
422
  /** A safe, classified model-list failure suitable for the Host boundary. */
80
423
  var ModelQueryError = class extends Error {
@@ -151,13 +494,18 @@ const MODELS_ROUTE = "/dsh-balance/api/models";
151
494
  //#endregion
152
495
  //#region src/index.ts
153
496
  const name = "dsh-balance";
154
- const inject = ["webServer", "credentials"];
497
+ const inject = [
498
+ "webServer",
499
+ "credentials",
500
+ "sessionPersistence"
501
+ ];
155
502
  const Config = z.object({
156
503
  apiKeyRef: z.string().role("credential-ref").default("DEEPSEEK_API_KEY"),
157
504
  baseUrl: z.string().default("https://api.deepseek.com"),
158
505
  timeoutMs: z.number().step(1).min(1).max(6e4).default(1e4),
159
506
  cacheMs: z.number().step(1).min(0).max(3e5).default(3e4),
160
- allowRemote: z.boolean().default(false)
507
+ allowRemote: z.boolean().default(false),
508
+ usdToCny: z.number().min(1e-6).max(1e6).required(false)
161
509
  });
162
510
  function validateBaseUrl(value) {
163
511
  const url = new URL(value);
@@ -182,12 +530,67 @@ function sendJson(res, status, body) {
182
530
  });
183
531
  res.end(JSON.stringify(body));
184
532
  }
533
+ function usageFailure(code, message) {
534
+ return {
535
+ ok: false,
536
+ code,
537
+ message
538
+ };
539
+ }
540
+ function parseUsageQuery(requestUrl) {
541
+ const scope = requestUrl.searchParams.get("scope") ?? "all";
542
+ if (scope !== "all" && scope !== "session") return usageFailure("INVALID_REQUEST", "scope 只能是 all 或 session");
543
+ const sessionId = requestUrl.searchParams.get("sessionId") ?? void 0;
544
+ if (scope === "session" && (sessionId === void 0 || sessionId.trim().length === 0)) return usageFailure("INVALID_REQUEST", "session scope 需要 sessionId");
545
+ const timeZone = requestUrl.searchParams.get("timeZone") ?? "UTC";
546
+ try {
547
+ assertTimeZone(timeZone);
548
+ } catch {
549
+ return usageFailure("INVALID_REQUEST", "timeZone 不是有效的 IANA 时区");
550
+ }
551
+ const from = requestUrl.searchParams.get("from") ?? void 0;
552
+ const to = requestUrl.searchParams.get("to") ?? void 0;
553
+ const datePattern = /^\d{4}-\d{2}-\d{2}$/;
554
+ if (from !== void 0 && !datePattern.test(from) || to !== void 0 && !datePattern.test(to)) return usageFailure("INVALID_REQUEST", "from 和 to 必须是 YYYY-MM-DD");
555
+ if (from !== void 0 && to !== void 0 && from > to) return usageFailure("INVALID_REQUEST", "from 不能晚于 to");
556
+ return {
557
+ scope,
558
+ ...sessionId === void 0 ? {} : { sessionId },
559
+ timeZone,
560
+ ...from === void 0 ? {} : { from },
561
+ ...to === void 0 ? {} : { to },
562
+ refresh: requestUrl.searchParams.get("refresh") === "1"
563
+ };
564
+ }
565
+ function sessionTitle(events, fallback) {
566
+ let title = fallback;
567
+ for (const event of events) {
568
+ if (event.type !== "session/title" || typeof event.data !== "object" || event.data === null || Array.isArray(event.data)) continue;
569
+ const value = event.data.title;
570
+ if (typeof value === "string" && value.trim().length > 0) title = value;
571
+ }
572
+ return title;
573
+ }
574
+ async function mapWithConcurrency(items, concurrency, fn) {
575
+ const result = [];
576
+ let next = 0;
577
+ const worker = async () => {
578
+ while (next < items.length) {
579
+ const index = next++;
580
+ const item = items[index];
581
+ if (item !== void 0) result[index] = await fn(item);
582
+ }
583
+ };
584
+ await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(items.length, 1)) }, worker));
585
+ return result;
586
+ }
185
587
  /** Register the Host route that keeps credentials and upstream access out of the browser. */
186
588
  function apply(ctx, config) {
187
589
  validateBaseUrl(config.baseUrl);
188
590
  const ref = credentialRef(config.apiKeyRef);
189
591
  let cached;
190
592
  let cachedModels;
593
+ let cachedUsage;
191
594
  const handler = async (req, res) => {
192
595
  if (req.method !== "GET") {
193
596
  res.setHeader("allow", "GET");
@@ -310,6 +713,90 @@ function apply(ctx, config) {
310
713
  });
311
714
  }
312
715
  };
716
+ const usageHandler = async (req, res) => {
717
+ if (req.method !== "GET") {
718
+ res.setHeader("allow", "GET");
719
+ sendJson(res, 405, usageFailure("METHOD_NOT_ALLOWED", "仅支持 GET 请求"));
720
+ return;
721
+ }
722
+ if (!config.allowRemote && !isLoopbackRequest(req)) {
723
+ sendJson(res, 403, usageFailure("FORBIDDEN", "消费统计仅允许从本机访问"));
724
+ return;
725
+ }
726
+ const parsedQuery = parseUsageQuery(new URL(req.url ?? "/dsh-balance/api/usage", "http://localhost"));
727
+ if ("code" in parsedQuery) {
728
+ sendJson(res, 400, parsedQuery);
729
+ return;
730
+ }
731
+ const query = parsedQuery;
732
+ try {
733
+ const snapshots = query.scope === "session" ? (await ctx.sessionPersistence.listSnapshots()).filter((snapshot) => String(snapshot.header.id) === query.sessionId) : await ctx.sessionPersistence.listSnapshots();
734
+ if (query.scope === "session" && snapshots.length === 0) {
735
+ sendJson(res, 404, usageFailure("SESSION_NOT_FOUND", "找不到指定会话"));
736
+ return;
737
+ }
738
+ const revisionKey = snapshots.map((snapshot) => `${String(snapshot.header.id)}:${JSON.stringify(snapshot.revision)}`).sort().join("|");
739
+ const cacheKey = JSON.stringify({
740
+ revisionKey,
741
+ ...query,
742
+ usdToCny: normalizeUsdToCny(config.usdToCny)
743
+ });
744
+ if (!query.refresh && cachedUsage !== void 0 && cachedUsage.key === cacheKey && cachedUsage.expiresAt > Date.now()) {
745
+ sendJson(res, 200, {
746
+ ...cachedUsage.value,
747
+ source: "cache"
748
+ });
749
+ return;
750
+ }
751
+ const sources = await mapWithConcurrency(snapshots, 4, async (snapshot) => {
752
+ const inspection = await ctx.sessionPersistence.inspect(snapshot.header.id);
753
+ return {
754
+ sessionId: String(inspection.meta.id),
755
+ title: sessionTitle(inspection.events, String(inspection.meta.id)),
756
+ header: inspection.meta,
757
+ events: inspection.events
758
+ };
759
+ });
760
+ const usdToCny = normalizeUsdToCny(config.usdToCny);
761
+ const aggregateOptions = { timeZone: query.timeZone };
762
+ if (query.from !== void 0) aggregateOptions.from = query.from;
763
+ if (query.to !== void 0) aggregateOptions.to = query.to;
764
+ if (usdToCny !== void 0) aggregateOptions.usdToCny = usdToCny;
765
+ const aggregate = aggregateBilling(sources, aggregateOptions);
766
+ const fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
767
+ const value = query.scope === "session" ? (() => {
768
+ const selected = aggregate.summary.bySession.find((item) => item.sessionId === query.sessionId) ?? {
769
+ ...aggregate.summary.totals,
770
+ sessionId: query.sessionId ?? "",
771
+ title: query.sessionId ?? ""
772
+ };
773
+ return {
774
+ ok: true,
775
+ scope: "session",
776
+ fetchedAt,
777
+ source: "live",
778
+ session: selected,
779
+ summary: aggregate.summary,
780
+ requests: [...aggregate.requestsBySession.get(query.sessionId ?? "") ?? []]
781
+ };
782
+ })() : {
783
+ ok: true,
784
+ scope: "all",
785
+ fetchedAt,
786
+ source: "live",
787
+ summary: aggregate.summary
788
+ };
789
+ cachedUsage = {
790
+ key: cacheKey,
791
+ expiresAt: Date.now() + config.cacheMs,
792
+ value
793
+ };
794
+ sendJson(res, 200, value);
795
+ } catch (error) {
796
+ ctx.logger.warn(error);
797
+ sendJson(res, 503, usageFailure("UPSTREAM_UNAVAILABLE", "读取会话消费记录失败,请稍后重试"));
798
+ }
799
+ };
313
800
  ctx.effect(() => ctx.webServer.register({
314
801
  kind: "exact",
315
802
  path: BALANCE_ROUTE,
@@ -320,8 +807,13 @@ function apply(ctx, config) {
320
807
  path: MODELS_ROUTE,
321
808
  handler: modelsHandler
322
809
  }), `dsh-balance: ${MODELS_ROUTE}`);
810
+ ctx.effect(() => ctx.webServer.register({
811
+ kind: "exact",
812
+ path: USAGE_ROUTE,
813
+ handler: usageHandler
814
+ }), `dsh-balance: ${USAGE_ROUTE}`);
323
815
  }
324
816
  //#endregion
325
- export { BalanceQueryError, Config, ModelQueryError, apply, inject, name, parseDeepSeekBalance, parseDeepSeekModels, queryDeepSeekBalance, queryDeepSeekModels };
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 };
326
818
 
327
819
  //# sourceMappingURL=index.js.map