@alexpeng/dsh-custom-plugin 0.1.4 → 0.1.5

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
@@ -111,6 +111,43 @@ const DEFAULT_CONFIG = {
111
111
  * both defined on this clock, independent of the host's local timezone. */
112
112
  const CST_OFFSET_MS = 8 * 36e5;
113
113
  const DAY_MS = 864e5;
114
+ const PEAK_COUNTER_KEYS = [
115
+ "peakIn",
116
+ "peakCacheIn",
117
+ "peakCacheW",
118
+ "peakOut"
119
+ ];
120
+ /** Create a row whose peak/off-peak split is exact from its first event. */
121
+ function createUsageRow() {
122
+ return {
123
+ in: 0,
124
+ out: 0,
125
+ cacheIn: 0,
126
+ cacheW: 0,
127
+ reason: 0,
128
+ calls: 0,
129
+ peakIn: 0,
130
+ peakCacheIn: 0,
131
+ peakCacheW: 0,
132
+ peakOut: 0,
133
+ peakSplitKnown: true
134
+ };
135
+ }
136
+ function hasAllPeakCounters(row) {
137
+ return PEAK_COUNTER_KEYS.every((key) => typeof row[key] === "number");
138
+ }
139
+ /** Whether a row has enough persisted information for exact tariff math. */
140
+ function hasKnownPeakSplit(row) {
141
+ return row.peakSplitKnown === true || row.peakSplitKnown === void 0 && hasAllPeakCounters(row);
142
+ }
143
+ function ensurePeakCounters(row) {
144
+ const known = hasKnownPeakSplit(row);
145
+ row.peakIn ??= 0;
146
+ row.peakCacheIn ??= 0;
147
+ row.peakCacheW ??= 0;
148
+ row.peakOut ??= 0;
149
+ row.peakSplitKnown = known;
150
+ }
114
151
  function cstParts(time) {
115
152
  const d = new Date(time + CST_OFFSET_MS);
116
153
  return {
@@ -147,6 +184,7 @@ function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
147
184
  }
148
185
  /** Fold one usage record into a ledger row, tracking the peak-hour portion. */
149
186
  function foldUsageRecord(row, usage, peak) {
187
+ ensurePeakCounters(row);
150
188
  row.in += usage.inputTokens ?? 0;
151
189
  row.out += usage.outputTokens ?? 0;
152
190
  row.cacheIn += usage.cacheReadTokens ?? 0;
@@ -162,6 +200,9 @@ function foldUsageRecord(row, usage, peak) {
162
200
  }
163
201
  /** Merge one aggregated row into a target row (scan folds per-session rows). */
164
202
  function mergeUsageRow(target, source) {
203
+ const targetKnown = hasKnownPeakSplit(target);
204
+ const sourceKnown = hasKnownPeakSplit(source);
205
+ ensurePeakCounters(target);
165
206
  target.in += source.in;
166
207
  target.out += source.out;
167
208
  target.cacheIn += source.cacheIn;
@@ -172,6 +213,7 @@ function mergeUsageRow(target, source) {
172
213
  target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
173
214
  target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
174
215
  target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
216
+ target.peakSplitKnown = targetKnown && sourceKnown;
175
217
  }
176
218
  /** Replay a session log and aggregate one day's per-model usage rows.
177
219
  * `request/context` events anywhere in the log keep the model tracking in
@@ -186,14 +228,7 @@ function aggregateDayUsage(events, day) {
186
228
  if (event.type === "request/context") model = event.data.model ?? null;
187
229
  else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
188
230
  const key = model ?? "unknown";
189
- foldUsageRecord(agg[key] ?? (agg[key] = {
190
- in: 0,
191
- out: 0,
192
- cacheIn: 0,
193
- cacheW: 0,
194
- reason: 0,
195
- calls: 0
196
- }), event.data.usage, isPeakHour(event.time));
231
+ foldUsageRecord(agg[key] ?? (agg[key] = createUsageRow()), event.data.usage, isPeakHour(event.time));
197
232
  }
198
233
  }
199
234
  return agg;
@@ -591,11 +626,7 @@ var SystemCredentialStore = class {
591
626
  }
592
627
  async get() {
593
628
  if (this.keytar === null) return "";
594
- try {
595
- return (await this.keytar.getPassword("@alexpeng/dsh-custom-plugin", "deepseek-api-key") ?? "").trim();
596
- } catch {
597
- return "";
598
- }
629
+ return (await this.keytar.getPassword("@alexpeng/dsh-custom-plugin", "deepseek-api-key") ?? "").trim();
599
630
  }
600
631
  async set(value) {
601
632
  if (this.keytar === null) return false;
@@ -643,6 +674,7 @@ var CustomPluginHost = class {
643
674
  credentialStore;
644
675
  sessionModel = /* @__PURE__ */ new Map();
645
676
  usageScanPromise = null;
677
+ usageRevision = 0;
646
678
  lastUsagePruneDay = "";
647
679
  mermaidBytesValue = 0;
648
680
  mermaidJs = "";
@@ -687,14 +719,8 @@ var CustomPluginHost = class {
687
719
  this.lastUsagePruneDay = dayName;
688
720
  }
689
721
  const model = this.sessionModel.get(sessionId) ?? "unknown";
690
- foldUsageRecord(day[model] ?? (day[model] = {
691
- in: 0,
692
- out: 0,
693
- cacheIn: 0,
694
- cacheW: 0,
695
- reason: 0,
696
- calls: 0
697
- }), usage, isPeakHour(at));
722
+ foldUsageRecord(day[model] ?? (day[model] = createUsageRow()), usage, isPeakHour(at));
723
+ this.usageRevision++;
698
724
  }
699
725
  /** Snapshot of browser-safe state; the API key value never crosses this boundary. */
700
726
  async stateView() {
@@ -720,7 +746,8 @@ var CustomPluginHost = class {
720
746
  if (typeof edit.apiKey === "string") {
721
747
  const key = edit.apiKey.trim();
722
748
  if (key === "") {
723
- await this.credentialStore.clear();
749
+ const cleared = await this.credentialStore.clear();
750
+ if (this.credentialStore.available && !cleared) throw new Error("系统凭据清除失败,请重试");
724
751
  this.state.apiKey = "";
725
752
  } else {
726
753
  if (!/^sk-/.test(key)) throw new Error("DeepSeek API Key 必须以 sk- 开头");
@@ -732,6 +759,19 @@ var CustomPluginHost = class {
732
759
  async migrateLegacyApiKey() {
733
760
  const key = (this.state.apiKey ?? "").trim();
734
761
  if (!/^sk-/.test(key) || !this.credentialStore.available) return false;
762
+ let existing = "";
763
+ try {
764
+ existing = (await this.credentialStore.get()).trim();
765
+ } catch {
766
+ return false;
767
+ }
768
+ if (existing !== "") {
769
+ if (/^sk-/.test(existing)) {
770
+ this.state.apiKey = "";
771
+ return true;
772
+ }
773
+ return false;
774
+ }
735
775
  if (!await this.credentialStore.set(key)) return false;
736
776
  this.state.apiKey = "";
737
777
  return true;
@@ -964,6 +1004,7 @@ var CustomPluginHost = class {
964
1004
  }
965
1005
  }
966
1006
  async usageScanImpl() {
1007
+ const revisionAtStart = this.usageRevision;
967
1008
  let records;
968
1009
  try {
969
1010
  records = await this.sessionQuery.listSessions();
@@ -974,7 +1015,6 @@ var CustomPluginHost = class {
974
1015
  };
975
1016
  }
976
1017
  const today = dayKey();
977
- pruneUsage(this.state.usage);
978
1018
  const agg = {};
979
1019
  let scanned = 0;
980
1020
  const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
@@ -990,26 +1030,31 @@ var CustomPluginHost = class {
990
1030
  };
991
1031
  }
992
1032
  });
993
- let readableSessions = 0;
1033
+ let failedSessions = 0;
994
1034
  for (const entry of entries) {
995
- if (!entry.readable) continue;
996
- readableSessions++;
1035
+ if (!entry.readable) {
1036
+ failedSessions++;
1037
+ continue;
1038
+ }
997
1039
  const models = Object.keys(entry.usage);
998
1040
  if (models.length === 0) continue;
999
1041
  scanned++;
1000
- for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = {
1001
- in: 0,
1002
- out: 0,
1003
- cacheIn: 0,
1004
- cacheW: 0,
1005
- reason: 0,
1006
- calls: 0
1007
- }), entry.usage[model]);
1042
+ for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = createUsageRow()), entry.usage[model]);
1008
1043
  }
1009
- if (records.length === 0 || readableSessions > 0) this.state.usage[today] = agg;
1010
- this.persist();
1044
+ if (failedSessions > 0) return {
1045
+ ok: false,
1046
+ error: "部分会话读取失败,未覆盖现有用量,请稍后重试"
1047
+ };
1048
+ if (this.usageRevision !== revisionAtStart) return {
1049
+ ok: false,
1050
+ error: "扫描期间产生了新用量,未覆盖现有用量,请稍后重试"
1051
+ };
1052
+ pruneUsage(this.state.usage);
1053
+ this.state.usage[today] = agg;
1054
+ this.persist().catch((error) => this.pushDiag(`usage scan save failed: ${String(error?.message ?? error)}`));
1011
1055
  return {
1012
1056
  ok: true,
1057
+ day: today,
1013
1058
  usageToday: this.state.usage[today] ?? {},
1014
1059
  scannedSessions: scanned
1015
1060
  };
@@ -67,6 +67,7 @@ export declare function apiBalanceGet(): Promise<BalancePayload>;
67
67
  /** Re-scan today's session logs for usage. */
68
68
  export declare function apiUsageScan(): Promise<{
69
69
  ok: true;
70
+ day: string;
70
71
  usageToday: Record<string, unknown>;
71
72
  scannedSessions: number;
72
73
  } | {
@@ -11,6 +11,7 @@ import type { BalanceInfo, CustomPluginPublicState, CustomPluginState, TimelineI
11
11
  import { type UsageRecord } from './usage.ts';
12
12
  type UsageScanResult = {
13
13
  ok: true;
14
+ day: string;
14
15
  usageToday: unknown;
15
16
  scannedSessions: number;
16
17
  } | {
@@ -50,6 +51,7 @@ export declare class CustomPluginHost {
50
51
  private readonly credentialStore;
51
52
  private readonly sessionModel;
52
53
  private usageScanPromise;
54
+ private usageRevision;
53
55
  private lastUsagePruneDay;
54
56
  private mermaidBytesValue;
55
57
  private mermaidJs;
@@ -18,6 +18,8 @@ export interface DeepSeekUnitPrice {
18
18
  output: number;
19
19
  }
20
20
  export interface UsageCostBreakdown {
21
+ /** False for pre-split rows whose tariff allocation is not recoverable. */
22
+ exact: boolean;
21
23
  peakTokens: number;
22
24
  offPeakTokens: number;
23
25
  peakCostCny: number;
@@ -28,9 +30,8 @@ export interface UsageCostBreakdown {
28
30
  export declare function priceOf(model: string): DeepSeekUnitPrice;
29
31
  /**
30
32
  * Split one row into peak/off-peak token volume and CNY cost. Rows without
31
- * peak counters are treated as
32
- * entirely off-peak for compatibility with state written before peak
33
- * tracking existed; a rescan can rebuild the row with exact split counters.
33
+ * peak counters retain the old all-off-peak numeric fallback for compatibility,
34
+ * but `exact` is false until a rescan rebuilds the row with split counters.
34
35
  */
35
36
  export declare function usageCostBreakdown(row: UsageRow, model: string): UsageCostBreakdown;
36
37
  /** Estimate one row's total CNY cost. */
@@ -73,6 +73,10 @@ export interface UsageRow {
73
73
  peakCacheIn?: number;
74
74
  peakCacheW?: number;
75
75
  peakOut?: number;
76
+ /** True when the complete row was rebuilt or recorded with an exact
77
+ * peak/off-peak split. Omitted/false marks legacy rows whose historical
78
+ * portion cannot be assigned to either tariff from persisted counters. */
79
+ peakSplitKnown?: boolean;
76
80
  }
77
81
  /** Day -> model -> counters. */
78
82
  export type UsageMap = Record<string, Record<string, UsageRow>>;
@@ -14,6 +14,10 @@ export interface UsageRecord {
14
14
  }
15
15
  /** Number of Beijing calendar days retained in the local usage ledger. */
16
16
  export declare const USAGE_RETENTION_DAYS = 90;
17
+ /** Create a row whose peak/off-peak split is exact from its first event. */
18
+ export declare function createUsageRow(): UsageRow;
19
+ /** Whether a row has enough persisted information for exact tariff math. */
20
+ export declare function hasKnownPeakSplit(row: UsageRow): boolean;
17
21
  /** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
18
22
  export declare function dayKey(time?: number): string;
19
23
  /** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alexpeng/dsh-custom-plugin",
3
3
  "description": "Custom convenience suite for the dsh web GUI: background colors with weather FX, liquid glass, a per-user-message timeline rail with stars and branching, multi-level project folders, prompt library, conversation export (JSON / Markdown / PDF-with-images), Mermaid rendering, quote reply, DeepSeek balance and daily token usage; dual-face plugin mounted without dsh source changes.",
4
- "version": "0.1.4",
4
+ "version": "0.1.5",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",