@alexpeng/dsh-custom-plugin 0.1.3 → 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
@@ -105,6 +105,135 @@ 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
+ 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
+ }
151
+ function cstParts(time) {
152
+ const d = new Date(time + CST_OFFSET_MS);
153
+ return {
154
+ year: d.getUTCFullYear(),
155
+ month: d.getUTCMonth() + 1,
156
+ day: d.getUTCDate(),
157
+ hour: d.getUTCHours(),
158
+ minute: d.getUTCMinutes(),
159
+ weekday: d.getUTCDay()
160
+ };
161
+ }
162
+ /** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
163
+ function dayKey(time) {
164
+ const p = cstParts(time === void 0 ? Date.now() : time);
165
+ const pad = (n) => String(n).padStart(2, "0");
166
+ return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
167
+ }
168
+ /** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
169
+ * 14:00-18:00; all weekend hours are off-peak. Evaluated on China Standard
170
+ * Time so the split matches the published schedule on any host timezone. */
171
+ function isPeakHour(time) {
172
+ const { hour, weekday } = cstParts(time);
173
+ return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18);
174
+ }
175
+ /** Remove malformed or expired day buckets from the persisted usage ledger. */
176
+ function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
177
+ const cutoff = dayKey(now - (Math.max(1, Math.floor(retentionDays)) - 1) * DAY_MS);
178
+ let removed = 0;
179
+ for (const key of Object.keys(usage)) if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || key < cutoff) {
180
+ delete usage[key];
181
+ removed++;
182
+ }
183
+ return removed;
184
+ }
185
+ /** Fold one usage record into a ledger row, tracking the peak-hour portion. */
186
+ function foldUsageRecord(row, usage, peak) {
187
+ ensurePeakCounters(row);
188
+ row.in += usage.inputTokens ?? 0;
189
+ row.out += usage.outputTokens ?? 0;
190
+ row.cacheIn += usage.cacheReadTokens ?? 0;
191
+ row.cacheW += usage.cacheWriteTokens ?? 0;
192
+ row.reason += usage.reasoningTokens ?? 0;
193
+ row.calls += 1;
194
+ if (peak) {
195
+ row.peakIn = (row.peakIn ?? 0) + (usage.inputTokens ?? 0);
196
+ row.peakCacheIn = (row.peakCacheIn ?? 0) + (usage.cacheReadTokens ?? 0);
197
+ row.peakCacheW = (row.peakCacheW ?? 0) + (usage.cacheWriteTokens ?? 0);
198
+ row.peakOut = (row.peakOut ?? 0) + (usage.outputTokens ?? 0);
199
+ }
200
+ }
201
+ /** Merge one aggregated row into a target row (scan folds per-session rows). */
202
+ function mergeUsageRow(target, source) {
203
+ const targetKnown = hasKnownPeakSplit(target);
204
+ const sourceKnown = hasKnownPeakSplit(source);
205
+ ensurePeakCounters(target);
206
+ target.in += source.in;
207
+ target.out += source.out;
208
+ target.cacheIn += source.cacheIn;
209
+ target.cacheW += source.cacheW;
210
+ target.reason += source.reason;
211
+ target.calls += source.calls;
212
+ target.peakIn = (target.peakIn ?? 0) + (source.peakIn ?? 0);
213
+ target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
214
+ target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
215
+ target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
216
+ target.peakSplitKnown = targetKnown && sourceKnown;
217
+ }
218
+ /** Replay a session log and aggregate one day's per-model usage rows.
219
+ * `request/context` events anywhere in the log keep the model tracking in
220
+ * order; only `assistant/message` usage events whose own timestamp falls on
221
+ * `day` are folded, so a session crossing midnight contributes exactly the
222
+ * events it produced that day. */
223
+ function aggregateDayUsage(events, day) {
224
+ const agg = {};
225
+ let model = null;
226
+ for (const event of events) {
227
+ if (event === void 0 || event === null) continue;
228
+ if (event.type === "request/context") model = event.data.model ?? null;
229
+ else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
230
+ const key = model ?? "unknown";
231
+ foldUsageRecord(agg[key] ?? (agg[key] = createUsageRow()), event.data.usage, isPeakHour(event.time));
232
+ }
233
+ }
234
+ return agg;
235
+ }
236
+ //#endregion
108
237
  //#region src/state.ts
109
238
  /**
110
239
  * Host-owned state store for dsh-custom-plugin.
@@ -169,6 +298,7 @@ async function loadStateFile(state, home = dshHome()) {
169
298
  raw = null;
170
299
  }
171
300
  if (raw !== null) mergeState(state, raw);
301
+ pruneUsage(state.usage);
172
302
  return statePath;
173
303
  }
174
304
  /** In-flight save per state path: concurrent saves queue instead of racing
@@ -464,89 +594,75 @@ async function readDeepSeekCredential(home = dshHome()) {
464
594
  return "";
465
595
  }
466
596
  //#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);
597
+ //#region src/system-credentials.ts
598
+ /**
599
+ * Optional OS credential-store adapter.
600
+ *
601
+ * `keytar` is optional so the plugin still works in minimal/headless
602
+ * installations. When present, it delegates storage to the platform keyring
603
+ * (Windows Credential Manager, macOS Keychain, or the Linux Secret Service
604
+ * backend exposed by keytar). The caller owns the legacy state-file fallback.
605
+ * @module @alexpeng/dsh-custom-plugin/system-credentials
606
+ */
607
+ const CREDENTIAL_SERVICE = "@alexpeng/dsh-custom-plugin";
608
+ const CREDENTIAL_ACCOUNT = "deepseek-api-key";
609
+ function loadKeytar() {
610
+ try {
611
+ const required = createRequire(import.meta.url)("keytar");
612
+ const candidate = required !== null && typeof required === "object" && "default" in required ? required.default : required;
613
+ if (candidate === null || typeof candidate !== "object") return null;
614
+ const module = candidate;
615
+ if (typeof module.getPassword !== "function" || typeof module.setPassword !== "function" || typeof module.deletePassword !== "function") return null;
616
+ return module;
617
+ } catch {
618
+ return null;
508
619
  }
509
620
  }
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));
621
+ /** Safe wrapper around the optional keytar dependency. */
622
+ var SystemCredentialStore = class {
623
+ keytar = loadKeytar();
624
+ get available() {
625
+ return this.keytar !== null;
626
+ }
627
+ async get() {
628
+ if (this.keytar === null) return "";
629
+ return (await this.keytar.getPassword("@alexpeng/dsh-custom-plugin", "deepseek-api-key") ?? "").trim();
630
+ }
631
+ async set(value) {
632
+ if (this.keytar === null) return false;
633
+ try {
634
+ await this.keytar.setPassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT, value);
635
+ return true;
636
+ } catch {
637
+ return false;
544
638
  }
545
639
  }
546
- return agg;
547
- }
640
+ async clear() {
641
+ if (this.keytar === null) return false;
642
+ try {
643
+ await this.keytar.deletePassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT);
644
+ return true;
645
+ } catch {
646
+ return false;
647
+ }
648
+ }
649
+ };
548
650
  //#endregion
549
651
  //#region src/host-service.ts
652
+ const USAGE_SCAN_CONCURRENCY = 4;
653
+ async function mapConcurrent(items, limit, worker) {
654
+ const results = new Array(items.length);
655
+ let next = 0;
656
+ const run = async () => {
657
+ while (true) {
658
+ const index = next++;
659
+ if (index >= items.length) return;
660
+ results[index] = await worker(items[index]);
661
+ }
662
+ };
663
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => run()));
664
+ return results;
665
+ }
550
666
  /** Host capabilities behind the routes and the agent tool. */
551
667
  var CustomPluginHost = class {
552
668
  sessionQuery;
@@ -555,7 +671,11 @@ var CustomPluginHost = class {
555
671
  persistNow;
556
672
  diagReports;
557
673
  attachments;
674
+ credentialStore;
558
675
  sessionModel = /* @__PURE__ */ new Map();
676
+ usageScanPromise = null;
677
+ usageRevision = 0;
678
+ lastUsagePruneDay = "";
559
679
  mermaidBytesValue = 0;
560
680
  mermaidJs = "";
561
681
  mermaidSource = "";
@@ -568,6 +688,7 @@ var CustomPluginHost = class {
568
688
  this.persistNow = options.saveNow;
569
689
  this.diagReports = options.diagReports;
570
690
  this.attachments = options.attachments;
691
+ this.credentialStore = options.credentialStore ?? new SystemCredentialStore();
571
692
  this.localMermaidPath = options.localMermaidPath ?? defaultLocalMermaidPath;
572
693
  this.readCredential = options.readCredential ?? readDeepSeekCredential;
573
694
  }
@@ -591,30 +712,30 @@ var CustomPluginHost = class {
591
712
  * decides both the day bucket and the peak/off-peak portion. */
592
713
  foldUsage(sessionId, usage, time) {
593
714
  const at = time ?? Date.now();
594
- const day = this.state.usage[dayKey(at)] ?? (this.state.usage[dayKey(at)] = {});
715
+ const dayName = dayKey(at);
716
+ const day = this.state.usage[dayName] ?? (this.state.usage[dayName] = {});
717
+ if (this.lastUsagePruneDay !== dayName) {
718
+ pruneUsage(this.state.usage, at);
719
+ this.lastUsagePruneDay = dayName;
720
+ }
595
721
  const model = this.sessionModel.get(sessionId) ?? "unknown";
596
- foldUsageRecord(day[model] ?? (day[model] = {
597
- in: 0,
598
- out: 0,
599
- cacheIn: 0,
600
- cacheW: 0,
601
- reason: 0,
602
- calls: 0
603
- }), usage, isPeakHour(at));
722
+ foldUsageRecord(day[model] ?? (day[model] = createUsageRow()), usage, isPeakHour(at));
723
+ this.usageRevision++;
604
724
  }
605
- /** Snapshot of the whole state document for the browser. */
606
- stateView() {
725
+ /** Snapshot of browser-safe state; the API key value never crosses this boundary. */
726
+ async stateView() {
727
+ const credential = await this.credentialStatus();
607
728
  return {
608
729
  cfg: this.state.cfg,
609
730
  folders: this.state.folders,
610
731
  prompts: this.state.prompts,
611
732
  stars: this.state.stars,
612
- apiKey: this.state.apiKey,
613
- usage: this.state.usage
733
+ usage: this.state.usage,
734
+ ...credential
614
735
  };
615
736
  }
616
737
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
617
- applyEdit(edit) {
738
+ async applyEdit(edit) {
618
739
  if (edit.cfg !== void 0 && edit.cfg !== null && typeof edit.cfg === "object") this.state.cfg = {
619
740
  ...this.state.cfg,
620
741
  ...edit.cfg
@@ -622,7 +743,38 @@ var CustomPluginHost = class {
622
743
  if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
623
744
  if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts;
624
745
  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;
746
+ if (typeof edit.apiKey === "string") {
747
+ const key = edit.apiKey.trim();
748
+ if (key === "") {
749
+ const cleared = await this.credentialStore.clear();
750
+ if (this.credentialStore.available && !cleared) throw new Error("系统凭据清除失败,请重试");
751
+ this.state.apiKey = "";
752
+ } else {
753
+ if (!/^sk-/.test(key)) throw new Error("DeepSeek API Key 必须以 sk- 开头");
754
+ this.state.apiKey = await this.credentialStore.set(key) ? "" : key;
755
+ }
756
+ }
757
+ }
758
+ /** Move a legacy plaintext state key into the OS store when available. */
759
+ async migrateLegacyApiKey() {
760
+ const key = (this.state.apiKey ?? "").trim();
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
+ }
775
+ if (!await this.credentialStore.set(key)) return false;
776
+ this.state.apiKey = "";
777
+ return true;
626
778
  }
627
779
  /** Timeline nodes for one session, capped to the 400-node tail. The tail cap
628
780
  * bounds the payload (each item carries up to 4k of preview text); 400 keeps
@@ -739,10 +891,20 @@ var CustomPluginHost = class {
739
891
  };
740
892
  }
741
893
  }
742
- /** Resolve the DeepSeek balance API key: state value first, then environment, then DSH credential refs. */
743
- async resolveApiKey() {
894
+ /** Resolve the key and its source without returning either value to the browser. */
895
+ async resolveApiKeyWithSource() {
896
+ try {
897
+ const system = (await this.credentialStore.get()).trim();
898
+ if (/^sk-/.test(system)) return {
899
+ key: system,
900
+ source: "system"
901
+ };
902
+ } catch {}
744
903
  const key = (this.state.apiKey ?? "").trim();
745
- if (key !== "") return key;
904
+ if (/^sk-/.test(key)) return {
905
+ key,
906
+ source: "legacy-state"
907
+ };
746
908
  try {
747
909
  const env = globalThis.process?.env;
748
910
  for (const name of [
@@ -751,14 +913,34 @@ var CustomPluginHost = class {
751
913
  "DEEPSEEK_TOKEN"
752
914
  ]) {
753
915
  const value = env?.[name];
754
- if (typeof value === "string" && /^sk-/.test(value.trim())) return value.trim();
916
+ if (typeof value === "string" && /^sk-/.test(value.trim())) return {
917
+ key: value.trim(),
918
+ source: "environment"
919
+ };
755
920
  }
756
921
  } catch {}
757
922
  try {
758
923
  const candidate = await this.readCredential();
759
- if (/^sk-/.test(candidate)) return candidate;
924
+ if (/^sk-/.test(candidate)) return {
925
+ key: candidate.trim(),
926
+ source: "dsh"
927
+ };
760
928
  } catch {}
761
- return "";
929
+ return {
930
+ key: "",
931
+ source: "none"
932
+ };
933
+ }
934
+ async resolveApiKey() {
935
+ return (await this.resolveApiKeyWithSource()).key;
936
+ }
937
+ /** Browser-safe credential status used by state and save responses. */
938
+ async credentialStatus() {
939
+ const resolved = await this.resolveApiKeyWithSource();
940
+ return {
941
+ apiKeyConfigured: resolved.key !== "",
942
+ credentialStorage: resolved.source
943
+ };
762
944
  }
763
945
  /** Query the DeepSeek balance endpoint (15s timeout). */
764
946
  async balanceGet() {
@@ -812,6 +994,17 @@ var CustomPluginHost = class {
812
994
  * folded, so sessions created before midnight keep contributing the usage
813
995
  * they produced today. */
814
996
  async usageScan() {
997
+ if (this.usageScanPromise !== null) return await this.usageScanPromise;
998
+ const run = this.usageScanImpl();
999
+ this.usageScanPromise = run;
1000
+ try {
1001
+ return await run;
1002
+ } finally {
1003
+ if (this.usageScanPromise === run) this.usageScanPromise = null;
1004
+ }
1005
+ }
1006
+ async usageScanImpl() {
1007
+ const revisionAtStart = this.usageRevision;
815
1008
  let records;
816
1009
  try {
817
1010
  records = await this.sessionQuery.listSessions();
@@ -824,24 +1017,44 @@ var CustomPluginHost = class {
824
1017
  const today = dayKey();
825
1018
  const agg = {};
826
1019
  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);
1020
+ const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
1021
+ try {
1022
+ return {
1023
+ readable: true,
1024
+ usage: aggregateDayUsage((await this.sessionQuery.readSession(record.header.id)).events, today)
1025
+ };
1026
+ } catch {
1027
+ return {
1028
+ readable: false,
1029
+ usage: {}
1030
+ };
1031
+ }
1032
+ });
1033
+ let failedSessions = 0;
1034
+ for (const entry of entries) {
1035
+ if (!entry.readable) {
1036
+ failedSessions++;
1037
+ continue;
1038
+ }
1039
+ const models = Object.keys(entry.usage);
830
1040
  if (models.length === 0) continue;
831
1041
  scanned++;
832
- for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = {
833
- in: 0,
834
- out: 0,
835
- cacheIn: 0,
836
- cacheW: 0,
837
- reason: 0,
838
- calls: 0
839
- }), dayUsage[model]);
840
- } catch {}
841
- if (scanned > 0) this.state.usage[today] = agg;
842
- this.persist();
1042
+ for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = createUsageRow()), entry.usage[model]);
1043
+ }
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)}`));
843
1055
  return {
844
1056
  ok: true,
1057
+ day: today,
845
1058
  usageToday: this.state.usage[today] ?? {},
846
1059
  scannedSessions: scanned
847
1060
  };
@@ -1096,7 +1309,7 @@ function makeCustomPluginRoutes(host) {
1096
1309
  if (req.method === "GET") {
1097
1310
  json(res, 200, {
1098
1311
  ok: true,
1099
- data: host.stateView()
1312
+ data: await host.stateView()
1100
1313
  });
1101
1314
  return;
1102
1315
  }
@@ -1109,7 +1322,7 @@ function makeCustomPluginRoutes(host) {
1109
1322
  }
1110
1323
  try {
1111
1324
  const body = await readBody(req, BODY_LIMIT);
1112
- host.applyEdit({
1325
+ await host.applyEdit({
1113
1326
  cfg: body.cfg,
1114
1327
  folders: Array.isArray(body.folders) ? body.folders : void 0,
1115
1328
  prompts: Array.isArray(body.prompts) ? body.prompts : void 0,
@@ -1117,7 +1330,10 @@ function makeCustomPluginRoutes(host) {
1117
1330
  apiKey: typeof body.apiKey === "string" ? body.apiKey : void 0
1118
1331
  });
1119
1332
  await host.persist();
1120
- json(res, 200, { ok: true });
1333
+ json(res, 200, {
1334
+ ok: true,
1335
+ ...await host.credentialStatus()
1336
+ });
1121
1337
  } catch (error) {
1122
1338
  const message = error instanceof Error ? error.message : String(error);
1123
1339
  json(res, message === "body-too-large" ? 413 : 400, {
@@ -1267,12 +1483,6 @@ function applyImpl(ctx) {
1267
1483
  diagReports.push(String(message ?? "").slice(0, 400));
1268
1484
  if (diagReports.length > 20) diagReports.splice(0, diagReports.length - 20);
1269
1485
  };
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
1486
  const saveSoon = (() => {
1277
1487
  let timer;
1278
1488
  return () => {
@@ -1294,6 +1504,13 @@ function applyImpl(ctx) {
1294
1504
  diagReports,
1295
1505
  attachments: ctx.get("attachments")
1296
1506
  });
1507
+ loadStateFile(state).then(async (path) => {
1508
+ statePath = path;
1509
+ if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
1510
+ return saveStateFile(state);
1511
+ }).catch((error) => {
1512
+ reportDiag(`state load failed: ${String(error?.message ?? error)}`);
1513
+ });
1297
1514
  ctx.on("session/event", (session, event) => {
1298
1515
  try {
1299
1516
  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;
@@ -65,6 +67,7 @@ export declare function apiBalanceGet(): Promise<BalancePayload>;
65
67
  /** Re-scan today's session logs for usage. */
66
68
  export declare function apiUsageScan(): Promise<{
67
69
  ok: true;
70
+ day: string;
68
71
  usageToday: Record<string, unknown>;
69
72
  scannedSessions: number;
70
73
  } | {