@alexpeng/dsh-custom-plugin 0.1.3 → 0.1.4

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
@@ -105,6 +105,100 @@ const DEFAULT_CONFIG = {
105
105
  formula: true
106
106
  };
107
107
  //#endregion
108
+ //#region src/usage.ts
109
+ /** China Standard Time offset: UTC+8, no DST, so fixed-offset arithmetic is
110
+ * exact. The published peak/off-peak schedule and the ledger day buckets are
111
+ * both defined on this clock, independent of the host's local timezone. */
112
+ const CST_OFFSET_MS = 8 * 36e5;
113
+ const DAY_MS = 864e5;
114
+ function cstParts(time) {
115
+ const d = new Date(time + CST_OFFSET_MS);
116
+ return {
117
+ year: d.getUTCFullYear(),
118
+ month: d.getUTCMonth() + 1,
119
+ day: d.getUTCDate(),
120
+ hour: d.getUTCHours(),
121
+ minute: d.getUTCMinutes(),
122
+ weekday: d.getUTCDay()
123
+ };
124
+ }
125
+ /** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
126
+ function dayKey(time) {
127
+ const p = cstParts(time === void 0 ? Date.now() : time);
128
+ const pad = (n) => String(n).padStart(2, "0");
129
+ return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
130
+ }
131
+ /** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
132
+ * 14:00-18:00; all weekend hours are off-peak. Evaluated on China Standard
133
+ * Time so the split matches the published schedule on any host timezone. */
134
+ function isPeakHour(time) {
135
+ const { hour, weekday } = cstParts(time);
136
+ return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18);
137
+ }
138
+ /** Remove malformed or expired day buckets from the persisted usage ledger. */
139
+ function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
140
+ const cutoff = dayKey(now - (Math.max(1, Math.floor(retentionDays)) - 1) * DAY_MS);
141
+ let removed = 0;
142
+ for (const key of Object.keys(usage)) if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || key < cutoff) {
143
+ delete usage[key];
144
+ removed++;
145
+ }
146
+ return removed;
147
+ }
148
+ /** Fold one usage record into a ledger row, tracking the peak-hour portion. */
149
+ function foldUsageRecord(row, usage, peak) {
150
+ row.in += usage.inputTokens ?? 0;
151
+ row.out += usage.outputTokens ?? 0;
152
+ row.cacheIn += usage.cacheReadTokens ?? 0;
153
+ row.cacheW += usage.cacheWriteTokens ?? 0;
154
+ row.reason += usage.reasoningTokens ?? 0;
155
+ row.calls += 1;
156
+ if (peak) {
157
+ row.peakIn = (row.peakIn ?? 0) + (usage.inputTokens ?? 0);
158
+ row.peakCacheIn = (row.peakCacheIn ?? 0) + (usage.cacheReadTokens ?? 0);
159
+ row.peakCacheW = (row.peakCacheW ?? 0) + (usage.cacheWriteTokens ?? 0);
160
+ row.peakOut = (row.peakOut ?? 0) + (usage.outputTokens ?? 0);
161
+ }
162
+ }
163
+ /** Merge one aggregated row into a target row (scan folds per-session rows). */
164
+ function mergeUsageRow(target, source) {
165
+ target.in += source.in;
166
+ target.out += source.out;
167
+ target.cacheIn += source.cacheIn;
168
+ target.cacheW += source.cacheW;
169
+ target.reason += source.reason;
170
+ target.calls += source.calls;
171
+ target.peakIn = (target.peakIn ?? 0) + (source.peakIn ?? 0);
172
+ target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
173
+ target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
174
+ target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
175
+ }
176
+ /** Replay a session log and aggregate one day's per-model usage rows.
177
+ * `request/context` events anywhere in the log keep the model tracking in
178
+ * order; only `assistant/message` usage events whose own timestamp falls on
179
+ * `day` are folded, so a session crossing midnight contributes exactly the
180
+ * events it produced that day. */
181
+ function aggregateDayUsage(events, day) {
182
+ const agg = {};
183
+ let model = null;
184
+ for (const event of events) {
185
+ if (event === void 0 || event === null) continue;
186
+ if (event.type === "request/context") model = event.data.model ?? null;
187
+ else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
188
+ 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));
197
+ }
198
+ }
199
+ return agg;
200
+ }
201
+ //#endregion
108
202
  //#region src/state.ts
109
203
  /**
110
204
  * Host-owned state store for dsh-custom-plugin.
@@ -169,6 +263,7 @@ async function loadStateFile(state, home = dshHome()) {
169
263
  raw = null;
170
264
  }
171
265
  if (raw !== null) mergeState(state, raw);
266
+ pruneUsage(state.usage);
172
267
  return statePath;
173
268
  }
174
269
  /** In-flight save per state path: concurrent saves queue instead of racing
@@ -464,89 +559,79 @@ async function readDeepSeekCredential(home = dshHome()) {
464
559
  return "";
465
560
  }
466
561
  //#endregion
467
- //#region src/usage.ts
468
- /** China Standard Time offset: UTC+8, no DST, so fixed-offset arithmetic is
469
- * exact. The published peak/off-peak schedule and the ledger day buckets are
470
- * both defined on this clock, independent of the host's local timezone. */
471
- const CST_OFFSET_MS = 8 * 36e5;
472
- function cstParts(time) {
473
- const d = new Date(time + CST_OFFSET_MS);
474
- return {
475
- year: d.getUTCFullYear(),
476
- month: d.getUTCMonth() + 1,
477
- day: d.getUTCDate(),
478
- hour: d.getUTCHours(),
479
- minute: d.getUTCMinutes()
480
- };
481
- }
482
- /** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
483
- function dayKey(time) {
484
- const p = cstParts(time === void 0 ? Date.now() : time);
485
- const pad = (n) => String(n).padStart(2, "0");
486
- return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
487
- }
488
- /** DeepSeek peak billing window: Beijing 09:00-12:00 / 14:00-18:00, off-peak is
489
- * the remainder at half price. Evaluated on China Standard Time so the split
490
- * matches the published schedule on any host timezone. */
491
- function isPeakHour(time) {
492
- const { hour } = cstParts(time);
493
- return hour >= 9 && hour < 12 || hour >= 14 && hour < 18;
494
- }
495
- /** Fold one usage record into a ledger row, tracking the peak-hour portion. */
496
- function foldUsageRecord(row, usage, peak) {
497
- row.in += usage.inputTokens ?? 0;
498
- row.out += usage.outputTokens ?? 0;
499
- row.cacheIn += usage.cacheReadTokens ?? 0;
500
- row.cacheW += usage.cacheWriteTokens ?? 0;
501
- row.reason += usage.reasoningTokens ?? 0;
502
- row.calls += 1;
503
- if (peak) {
504
- row.peakIn = (row.peakIn ?? 0) + (usage.inputTokens ?? 0);
505
- row.peakCacheIn = (row.peakCacheIn ?? 0) + (usage.cacheReadTokens ?? 0);
506
- row.peakCacheW = (row.peakCacheW ?? 0) + (usage.cacheWriteTokens ?? 0);
507
- row.peakOut = (row.peakOut ?? 0) + (usage.outputTokens ?? 0);
562
+ //#region src/system-credentials.ts
563
+ /**
564
+ * Optional OS credential-store adapter.
565
+ *
566
+ * `keytar` is optional so the plugin still works in minimal/headless
567
+ * installations. When present, it delegates storage to the platform keyring
568
+ * (Windows Credential Manager, macOS Keychain, or the Linux Secret Service
569
+ * backend exposed by keytar). The caller owns the legacy state-file fallback.
570
+ * @module @alexpeng/dsh-custom-plugin/system-credentials
571
+ */
572
+ const CREDENTIAL_SERVICE = "@alexpeng/dsh-custom-plugin";
573
+ const CREDENTIAL_ACCOUNT = "deepseek-api-key";
574
+ function loadKeytar() {
575
+ try {
576
+ const required = createRequire(import.meta.url)("keytar");
577
+ const candidate = required !== null && typeof required === "object" && "default" in required ? required.default : required;
578
+ if (candidate === null || typeof candidate !== "object") return null;
579
+ const module = candidate;
580
+ if (typeof module.getPassword !== "function" || typeof module.setPassword !== "function" || typeof module.deletePassword !== "function") return null;
581
+ return module;
582
+ } catch {
583
+ return null;
508
584
  }
509
585
  }
510
- /** Merge one aggregated row into a target row (scan folds per-session rows). */
511
- function mergeUsageRow(target, source) {
512
- target.in += source.in;
513
- target.out += source.out;
514
- target.cacheIn += source.cacheIn;
515
- target.cacheW += source.cacheW;
516
- target.reason += source.reason;
517
- target.calls += source.calls;
518
- target.peakIn = (target.peakIn ?? 0) + (source.peakIn ?? 0);
519
- target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
520
- target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
521
- target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
522
- }
523
- /** Replay a session log and aggregate one day's per-model usage rows.
524
- * `request/context` events anywhere in the log keep the model tracking in
525
- * order; only `assistant/message` usage events whose own timestamp falls on
526
- * `day` are folded, so a session crossing midnight contributes exactly the
527
- * events it produced that day. */
528
- function aggregateDayUsage(events, day) {
529
- const agg = {};
530
- let model = null;
531
- for (const event of events) {
532
- if (event === void 0 || event === null) continue;
533
- if (event.type === "request/context") model = event.data.model ?? null;
534
- else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
535
- const key = model ?? "unknown";
536
- foldUsageRecord(agg[key] ?? (agg[key] = {
537
- in: 0,
538
- out: 0,
539
- cacheIn: 0,
540
- cacheW: 0,
541
- reason: 0,
542
- calls: 0
543
- }), event.data.usage, isPeakHour(event.time));
586
+ /** Safe wrapper around the optional keytar dependency. */
587
+ var SystemCredentialStore = class {
588
+ keytar = loadKeytar();
589
+ get available() {
590
+ return this.keytar !== null;
591
+ }
592
+ async get() {
593
+ 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 "";
544
598
  }
545
599
  }
546
- return agg;
547
- }
600
+ async set(value) {
601
+ if (this.keytar === null) return false;
602
+ try {
603
+ await this.keytar.setPassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT, value);
604
+ return true;
605
+ } catch {
606
+ return false;
607
+ }
608
+ }
609
+ async clear() {
610
+ if (this.keytar === null) return false;
611
+ try {
612
+ await this.keytar.deletePassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT);
613
+ return true;
614
+ } catch {
615
+ return false;
616
+ }
617
+ }
618
+ };
548
619
  //#endregion
549
620
  //#region src/host-service.ts
621
+ const USAGE_SCAN_CONCURRENCY = 4;
622
+ async function mapConcurrent(items, limit, worker) {
623
+ const results = new Array(items.length);
624
+ let next = 0;
625
+ const run = async () => {
626
+ while (true) {
627
+ const index = next++;
628
+ if (index >= items.length) return;
629
+ results[index] = await worker(items[index]);
630
+ }
631
+ };
632
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => run()));
633
+ return results;
634
+ }
550
635
  /** Host capabilities behind the routes and the agent tool. */
551
636
  var CustomPluginHost = class {
552
637
  sessionQuery;
@@ -555,7 +640,10 @@ var CustomPluginHost = class {
555
640
  persistNow;
556
641
  diagReports;
557
642
  attachments;
643
+ credentialStore;
558
644
  sessionModel = /* @__PURE__ */ new Map();
645
+ usageScanPromise = null;
646
+ lastUsagePruneDay = "";
559
647
  mermaidBytesValue = 0;
560
648
  mermaidJs = "";
561
649
  mermaidSource = "";
@@ -568,6 +656,7 @@ var CustomPluginHost = class {
568
656
  this.persistNow = options.saveNow;
569
657
  this.diagReports = options.diagReports;
570
658
  this.attachments = options.attachments;
659
+ this.credentialStore = options.credentialStore ?? new SystemCredentialStore();
571
660
  this.localMermaidPath = options.localMermaidPath ?? defaultLocalMermaidPath;
572
661
  this.readCredential = options.readCredential ?? readDeepSeekCredential;
573
662
  }
@@ -591,7 +680,12 @@ var CustomPluginHost = class {
591
680
  * decides both the day bucket and the peak/off-peak portion. */
592
681
  foldUsage(sessionId, usage, time) {
593
682
  const at = time ?? Date.now();
594
- const day = this.state.usage[dayKey(at)] ?? (this.state.usage[dayKey(at)] = {});
683
+ const dayName = dayKey(at);
684
+ const day = this.state.usage[dayName] ?? (this.state.usage[dayName] = {});
685
+ if (this.lastUsagePruneDay !== dayName) {
686
+ pruneUsage(this.state.usage, at);
687
+ this.lastUsagePruneDay = dayName;
688
+ }
595
689
  const model = this.sessionModel.get(sessionId) ?? "unknown";
596
690
  foldUsageRecord(day[model] ?? (day[model] = {
597
691
  in: 0,
@@ -602,19 +696,20 @@ var CustomPluginHost = class {
602
696
  calls: 0
603
697
  }), usage, isPeakHour(at));
604
698
  }
605
- /** Snapshot of the whole state document for the browser. */
606
- stateView() {
699
+ /** Snapshot of browser-safe state; the API key value never crosses this boundary. */
700
+ async stateView() {
701
+ const credential = await this.credentialStatus();
607
702
  return {
608
703
  cfg: this.state.cfg,
609
704
  folders: this.state.folders,
610
705
  prompts: this.state.prompts,
611
706
  stars: this.state.stars,
612
- apiKey: this.state.apiKey,
613
- usage: this.state.usage
707
+ usage: this.state.usage,
708
+ ...credential
614
709
  };
615
710
  }
616
711
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
617
- applyEdit(edit) {
712
+ async applyEdit(edit) {
618
713
  if (edit.cfg !== void 0 && edit.cfg !== null && typeof edit.cfg === "object") this.state.cfg = {
619
714
  ...this.state.cfg,
620
715
  ...edit.cfg
@@ -622,7 +717,24 @@ var CustomPluginHost = class {
622
717
  if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
623
718
  if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts;
624
719
  if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
625
- if (typeof edit.apiKey === "string") this.state.apiKey = edit.apiKey;
720
+ if (typeof edit.apiKey === "string") {
721
+ const key = edit.apiKey.trim();
722
+ if (key === "") {
723
+ await this.credentialStore.clear();
724
+ this.state.apiKey = "";
725
+ } else {
726
+ if (!/^sk-/.test(key)) throw new Error("DeepSeek API Key 必须以 sk- 开头");
727
+ this.state.apiKey = await this.credentialStore.set(key) ? "" : key;
728
+ }
729
+ }
730
+ }
731
+ /** Move a legacy plaintext state key into the OS store when available. */
732
+ async migrateLegacyApiKey() {
733
+ const key = (this.state.apiKey ?? "").trim();
734
+ if (!/^sk-/.test(key) || !this.credentialStore.available) return false;
735
+ if (!await this.credentialStore.set(key)) return false;
736
+ this.state.apiKey = "";
737
+ return true;
626
738
  }
627
739
  /** Timeline nodes for one session, capped to the 400-node tail. The tail cap
628
740
  * bounds the payload (each item carries up to 4k of preview text); 400 keeps
@@ -739,10 +851,20 @@ var CustomPluginHost = class {
739
851
  };
740
852
  }
741
853
  }
742
- /** Resolve the DeepSeek balance API key: state value first, then environment, then DSH credential refs. */
743
- async resolveApiKey() {
854
+ /** Resolve the key and its source without returning either value to the browser. */
855
+ async resolveApiKeyWithSource() {
856
+ try {
857
+ const system = (await this.credentialStore.get()).trim();
858
+ if (/^sk-/.test(system)) return {
859
+ key: system,
860
+ source: "system"
861
+ };
862
+ } catch {}
744
863
  const key = (this.state.apiKey ?? "").trim();
745
- if (key !== "") return key;
864
+ if (/^sk-/.test(key)) return {
865
+ key,
866
+ source: "legacy-state"
867
+ };
746
868
  try {
747
869
  const env = globalThis.process?.env;
748
870
  for (const name of [
@@ -751,14 +873,34 @@ var CustomPluginHost = class {
751
873
  "DEEPSEEK_TOKEN"
752
874
  ]) {
753
875
  const value = env?.[name];
754
- if (typeof value === "string" && /^sk-/.test(value.trim())) return value.trim();
876
+ if (typeof value === "string" && /^sk-/.test(value.trim())) return {
877
+ key: value.trim(),
878
+ source: "environment"
879
+ };
755
880
  }
756
881
  } catch {}
757
882
  try {
758
883
  const candidate = await this.readCredential();
759
- if (/^sk-/.test(candidate)) return candidate;
884
+ if (/^sk-/.test(candidate)) return {
885
+ key: candidate.trim(),
886
+ source: "dsh"
887
+ };
760
888
  } catch {}
761
- return "";
889
+ return {
890
+ key: "",
891
+ source: "none"
892
+ };
893
+ }
894
+ async resolveApiKey() {
895
+ return (await this.resolveApiKeyWithSource()).key;
896
+ }
897
+ /** Browser-safe credential status used by state and save responses. */
898
+ async credentialStatus() {
899
+ const resolved = await this.resolveApiKeyWithSource();
900
+ return {
901
+ apiKeyConfigured: resolved.key !== "",
902
+ credentialStorage: resolved.source
903
+ };
762
904
  }
763
905
  /** Query the DeepSeek balance endpoint (15s timeout). */
764
906
  async balanceGet() {
@@ -812,6 +954,16 @@ var CustomPluginHost = class {
812
954
  * folded, so sessions created before midnight keep contributing the usage
813
955
  * they produced today. */
814
956
  async usageScan() {
957
+ if (this.usageScanPromise !== null) return await this.usageScanPromise;
958
+ const run = this.usageScanImpl();
959
+ this.usageScanPromise = run;
960
+ try {
961
+ return await run;
962
+ } finally {
963
+ if (this.usageScanPromise === run) this.usageScanPromise = null;
964
+ }
965
+ }
966
+ async usageScanImpl() {
815
967
  let records;
816
968
  try {
817
969
  records = await this.sessionQuery.listSessions();
@@ -822,11 +974,27 @@ var CustomPluginHost = class {
822
974
  };
823
975
  }
824
976
  const today = dayKey();
977
+ pruneUsage(this.state.usage);
825
978
  const agg = {};
826
979
  let scanned = 0;
827
- for (const record of records) try {
828
- const dayUsage = aggregateDayUsage((await this.sessionQuery.readSession(record.header.id)).events, today);
829
- const models = Object.keys(dayUsage);
980
+ const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
981
+ try {
982
+ return {
983
+ readable: true,
984
+ usage: aggregateDayUsage((await this.sessionQuery.readSession(record.header.id)).events, today)
985
+ };
986
+ } catch {
987
+ return {
988
+ readable: false,
989
+ usage: {}
990
+ };
991
+ }
992
+ });
993
+ let readableSessions = 0;
994
+ for (const entry of entries) {
995
+ if (!entry.readable) continue;
996
+ readableSessions++;
997
+ const models = Object.keys(entry.usage);
830
998
  if (models.length === 0) continue;
831
999
  scanned++;
832
1000
  for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = {
@@ -836,9 +1004,9 @@ var CustomPluginHost = class {
836
1004
  cacheW: 0,
837
1005
  reason: 0,
838
1006
  calls: 0
839
- }), dayUsage[model]);
840
- } catch {}
841
- if (scanned > 0) this.state.usage[today] = agg;
1007
+ }), entry.usage[model]);
1008
+ }
1009
+ if (records.length === 0 || readableSessions > 0) this.state.usage[today] = agg;
842
1010
  this.persist();
843
1011
  return {
844
1012
  ok: true,
@@ -1096,7 +1264,7 @@ function makeCustomPluginRoutes(host) {
1096
1264
  if (req.method === "GET") {
1097
1265
  json(res, 200, {
1098
1266
  ok: true,
1099
- data: host.stateView()
1267
+ data: await host.stateView()
1100
1268
  });
1101
1269
  return;
1102
1270
  }
@@ -1109,7 +1277,7 @@ function makeCustomPluginRoutes(host) {
1109
1277
  }
1110
1278
  try {
1111
1279
  const body = await readBody(req, BODY_LIMIT);
1112
- host.applyEdit({
1280
+ await host.applyEdit({
1113
1281
  cfg: body.cfg,
1114
1282
  folders: Array.isArray(body.folders) ? body.folders : void 0,
1115
1283
  prompts: Array.isArray(body.prompts) ? body.prompts : void 0,
@@ -1117,7 +1285,10 @@ function makeCustomPluginRoutes(host) {
1117
1285
  apiKey: typeof body.apiKey === "string" ? body.apiKey : void 0
1118
1286
  });
1119
1287
  await host.persist();
1120
- json(res, 200, { ok: true });
1288
+ json(res, 200, {
1289
+ ok: true,
1290
+ ...await host.credentialStatus()
1291
+ });
1121
1292
  } catch (error) {
1122
1293
  const message = error instanceof Error ? error.message : String(error);
1123
1294
  json(res, message === "body-too-large" ? 413 : 400, {
@@ -1267,12 +1438,6 @@ function applyImpl(ctx) {
1267
1438
  diagReports.push(String(message ?? "").slice(0, 400));
1268
1439
  if (diagReports.length > 20) diagReports.splice(0, diagReports.length - 20);
1269
1440
  };
1270
- loadStateFile(state).then((path) => {
1271
- statePath = path;
1272
- return saveStateFile(state);
1273
- }).catch((error) => {
1274
- reportDiag(`state load failed: ${String(error?.message ?? error)}`);
1275
- });
1276
1441
  const saveSoon = (() => {
1277
1442
  let timer;
1278
1443
  return () => {
@@ -1294,6 +1459,13 @@ function applyImpl(ctx) {
1294
1459
  diagReports,
1295
1460
  attachments: ctx.get("attachments")
1296
1461
  });
1462
+ loadStateFile(state).then(async (path) => {
1463
+ statePath = path;
1464
+ if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
1465
+ return saveStateFile(state);
1466
+ }).catch((error) => {
1467
+ reportDiag(`state load failed: ${String(error?.message ?? error)}`);
1468
+ });
1297
1469
  ctx.on("session/event", (session, event) => {
1298
1470
  try {
1299
1471
  if (event === void 0 || event === null) return;
@@ -4,7 +4,7 @@
4
4
  * failures surface as `{ ok: false, error }` instead of throwing.
5
5
  * @module @alexpeng/dsh-custom-plugin/client/api
6
6
  */
7
- import { type CustomPluginConfig, type CustomPluginState, type TimelineItem } from '../protocol.ts';
7
+ import { type CredentialStorage, type CustomPluginConfig, type CustomPluginPublicState, type CustomPluginState, type TimelineItem } from '../protocol.ts';
8
8
  /** State edit the browser sends to the host. */
9
9
  export interface StateEdit {
10
10
  cfg?: Partial<CustomPluginConfig>;
@@ -29,7 +29,7 @@ export interface BalancePayload {
29
29
  /** Read the whole state document. */
30
30
  export declare function apiStateGet(): Promise<{
31
31
  ok: true;
32
- data: CustomPluginState;
32
+ data: CustomPluginPublicState;
33
33
  } | {
34
34
  ok: false;
35
35
  error?: string;
@@ -37,6 +37,8 @@ export declare function apiStateGet(): Promise<{
37
37
  /** Persist a state edit. */
38
38
  export declare function apiStateSave(edit: StateEdit): Promise<{
39
39
  ok: true;
40
+ apiKeyConfigured?: boolean;
41
+ credentialStorage?: CredentialStorage;
40
42
  } | {
41
43
  ok: false;
42
44
  error?: string;
@@ -6,8 +6,17 @@
6
6
  */
7
7
  import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
8
8
  import type { SessionQueryEngine } from '@deepseek-ai/dsh-session-query';
9
- import type { BalanceInfo, CustomPluginState, TimelineItem } from './protocol.ts';
9
+ import { type CredentialStore } from './system-credentials.ts';
10
+ import type { BalanceInfo, CustomPluginPublicState, CustomPluginState, TimelineItem } from './protocol.ts';
10
11
  import { type UsageRecord } from './usage.ts';
12
+ type UsageScanResult = {
13
+ ok: true;
14
+ usageToday: unknown;
15
+ scannedSessions: number;
16
+ } | {
17
+ ok: false;
18
+ error: string;
19
+ };
11
20
  /** Options the loader entry supplies to the host service. */
12
21
  export interface CustomPluginHostOptions {
13
22
  sessionQuery: SessionQueryEngine;
@@ -27,6 +36,8 @@ export interface CustomPluginHostOptions {
27
36
  localMermaidPath?: () => string | null;
28
37
  /** Test seam: read the DeepSeek credential from DSH's credentials file. */
29
38
  readCredential?: () => Promise<string>;
39
+ /** Test seam and optional platform adapter for OS credential storage. */
40
+ credentialStore?: CredentialStore;
30
41
  }
31
42
  /** Host capabilities behind the routes and the agent tool. */
32
43
  export declare class CustomPluginHost {
@@ -36,7 +47,10 @@ export declare class CustomPluginHost {
36
47
  private readonly persistNow;
37
48
  private readonly diagReports;
38
49
  private readonly attachments;
50
+ private readonly credentialStore;
39
51
  private readonly sessionModel;
52
+ private usageScanPromise;
53
+ private lastUsagePruneDay;
40
54
  private mermaidBytesValue;
41
55
  private mermaidJs;
42
56
  private mermaidSource;
@@ -53,8 +67,8 @@ export declare class CustomPluginHost {
53
67
  /** Fold one assistant/message usage record into the ledger. The event time
54
68
  * decides both the day bucket and the peak/off-peak portion. */
55
69
  foldUsage(sessionId: string, usage: UsageRecord, time?: number): void;
56
- /** Snapshot of the whole state document for the browser. */
57
- stateView(): Pick<CustomPluginState, 'cfg' | 'folders' | 'prompts' | 'stars' | 'apiKey' | 'usage'>;
70
+ /** Snapshot of browser-safe state; the API key value never crosses this boundary. */
71
+ stateView(): Promise<CustomPluginPublicState>;
58
72
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
59
73
  applyEdit(edit: {
60
74
  cfg?: Partial<CustomPluginState['cfg']>;
@@ -62,7 +76,9 @@ export declare class CustomPluginHost {
62
76
  prompts?: CustomPluginState['prompts'];
63
77
  stars?: CustomPluginState['stars'];
64
78
  apiKey?: string;
65
- }): void;
79
+ }): Promise<void>;
80
+ /** Move a legacy plaintext state key into the OS store when available. */
81
+ migrateLegacyApiKey(): Promise<boolean>;
66
82
  /** Timeline nodes for one session, capped to the 400-node tail. The tail cap
67
83
  * bounds the payload (each item carries up to 4k of preview text); 400 keeps
68
84
  * dots available when the GUI deep-loads history. */
@@ -84,8 +100,11 @@ export declare class CustomPluginHost {
84
100
  ok: false;
85
101
  error: string;
86
102
  }>;
87
- /** Resolve the DeepSeek balance API key: state value first, then environment, then DSH credential refs. */
103
+ /** Resolve the key and its source without returning either value to the browser. */
104
+ private resolveApiKeyWithSource;
88
105
  private resolveApiKey;
106
+ /** Browser-safe credential status used by state and save responses. */
107
+ credentialStatus(): Promise<Pick<CustomPluginPublicState, 'apiKeyConfigured' | 'credentialStorage'>>;
89
108
  /** Query the DeepSeek balance endpoint (15s timeout). */
90
109
  balanceGet(): Promise<{
91
110
  ok: boolean;
@@ -99,14 +118,8 @@ export declare class CustomPluginHost {
99
118
  * is replayed but only usage events whose own timestamp falls on today are
100
119
  * folded, so sessions created before midnight keep contributing the usage
101
120
  * they produced today. */
102
- usageScan(): Promise<{
103
- ok: true;
104
- usageToday: unknown;
105
- scannedSessions: number;
106
- } | {
107
- ok: false;
108
- error: string;
109
- }>;
121
+ usageScan(): Promise<UsageScanResult>;
122
+ private usageScanImpl;
110
123
  /** Resolve the Mermaid engine: the bundled `mermaid` dependency on disk
111
124
  * first (no runtime network), CDN mirrors only as a fallback (cached for
112
125
  * the host lifetime). */
@@ -143,3 +156,4 @@ export declare class CustomPluginHost {
143
156
  * tree (works for `link:` checkouts and registry installs alike); null when
144
157
  * the dependency is absent, which falls mermaidFetch back to the CDN. */
145
158
  export declare function defaultLocalMermaidPath(): string | null;
159
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * DeepSeek cost-estimation helpers shared by the host-facing usage model and
3
+ * the browser panel. Prices are CNY per 1M tokens at peak rate; off-peak is
4
+ * applied to the portion without a peak counter.
5
+ * @module @alexpeng/dsh-custom-plugin/pricing
6
+ */
7
+ import type { UsageRow } from './protocol.ts';
8
+ /** Official source used for the built-in estimate and shown in the panel. */
9
+ export declare const DEEPSEEK_PRICING_SOURCE_URL = "https://api-docs.deepseek.com/zh-cn/quick_start/pricing/";
10
+ /** Date on which the built-in rule was checked against the official page. */
11
+ export declare const DEEPSEEK_PRICING_CHECKED_ON = "2026-08-26";
12
+ export interface DeepSeekUnitPrice {
13
+ /** Uncached input / cache-miss input price. */
14
+ input: number;
15
+ /** Cache-hit input price. */
16
+ cacheHit: number;
17
+ /** Output price; reasoning is an output subdivision in DSH usage. */
18
+ output: number;
19
+ }
20
+ export interface UsageCostBreakdown {
21
+ peakTokens: number;
22
+ offPeakTokens: number;
23
+ peakCostCny: number;
24
+ offPeakCostCny: number;
25
+ totalCostCny: number;
26
+ }
27
+ /** Resolve a model's peak price, falling back to Flash for unknown/legacy rows. */
28
+ export declare function priceOf(model: string): DeepSeekUnitPrice;
29
+ /**
30
+ * 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.
34
+ */
35
+ export declare function usageCostBreakdown(row: UsageRow, model: string): UsageCostBreakdown;
36
+ /** Estimate one row's total CNY cost. */
37
+ export declare function estimateUsageCostCny(row: UsageRow, model: string): number;