@alexpeng/dsh-custom-plugin 0.1.5 → 0.4.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
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
- import { homedir } from "node:os";
4
3
  import { dirname, isAbsolute, join } from "node:path";
4
+ import { homedir } from "node:os";
5
5
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
6
6
  import { readFileSync } from "node:fs";
7
7
  //#region src/dsh-home.ts
@@ -102,7 +102,9 @@ const DEFAULT_CONFIG = {
102
102
  quote: true,
103
103
  antiScroll: false,
104
104
  mermaid: true,
105
- formula: true
105
+ formula: true,
106
+ monthlyBudgetCny: 0,
107
+ budgetWarningPercent: 80
106
108
  };
107
109
  //#endregion
108
110
  //#region src/usage.ts
@@ -117,6 +119,9 @@ const PEAK_COUNTER_KEYS = [
117
119
  "peakCacheW",
118
120
  "peakOut"
119
121
  ];
122
+ function isCounter(value) {
123
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
124
+ }
120
125
  /** Create a row whose peak/off-peak split is exact from its first event. */
121
126
  function createUsageRow() {
122
127
  return {
@@ -134,18 +139,18 @@ function createUsageRow() {
134
139
  };
135
140
  }
136
141
  function hasAllPeakCounters(row) {
137
- return PEAK_COUNTER_KEYS.every((key) => typeof row[key] === "number");
142
+ return PEAK_COUNTER_KEYS.every((key) => isCounter(row[key]));
138
143
  }
139
144
  /** Whether a row has enough persisted information for exact tariff math. */
140
145
  function hasKnownPeakSplit(row) {
141
- return row.peakSplitKnown === true || row.peakSplitKnown === void 0 && hasAllPeakCounters(row);
146
+ if (!isCounter(row.in) || !isCounter(row.out) || !isCounter(row.cacheIn) || !isCounter(row.cacheW) || !isCounter(row.reason) || !isCounter(row.calls)) return false;
147
+ if (!hasAllPeakCounters(row)) return false;
148
+ if (row.peakIn > row.in || row.peakCacheIn > row.cacheIn || row.peakCacheW > row.cacheW || row.peakOut > row.out) return false;
149
+ return row.peakSplitKnown === true || row.peakSplitKnown === void 0;
142
150
  }
143
151
  function ensurePeakCounters(row) {
144
152
  const known = hasKnownPeakSplit(row);
145
- row.peakIn ??= 0;
146
- row.peakCacheIn ??= 0;
147
- row.peakCacheW ??= 0;
148
- row.peakOut ??= 0;
153
+ for (const key of PEAK_COUNTER_KEYS) if (!isCounter(row[key])) row[key] = 0;
149
154
  row.peakSplitKnown = known;
150
155
  }
151
156
  function cstParts(time) {
@@ -176,7 +181,10 @@ function isPeakHour(time) {
176
181
  function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
177
182
  const cutoff = dayKey(now - (Math.max(1, Math.floor(retentionDays)) - 1) * DAY_MS);
178
183
  let removed = 0;
179
- for (const key of Object.keys(usage)) if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || key < cutoff) {
184
+ for (const key of Object.keys(usage)) if (!(/^\d{4}-\d{2}-\d{2}$/.test(key) && (() => {
185
+ const parsed = /* @__PURE__ */ new Date(`${key}T00:00:00.000Z`);
186
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === key;
187
+ })()) || key < cutoff) {
180
188
  delete usage[key];
181
189
  removed++;
182
190
  }
@@ -270,19 +278,38 @@ function normalizeCfg(raw) {
270
278
  const current = cfg[key];
271
279
  if (typeof current === "boolean") {
272
280
  if (typeof value === "boolean") cfg[key] = value;
281
+ } else if (typeof current === "number") {
282
+ if (typeof value === "number" && Number.isFinite(value)) cfg[key] = value;
273
283
  } else if (typeof current === "string") {
274
284
  if (typeof value === "string") cfg[key] = value;
275
285
  }
276
286
  }
287
+ cfg.monthlyBudgetCny = Math.max(0, cfg.monthlyBudgetCny ?? 0);
288
+ cfg.budgetWarningPercent = Math.max(1, Math.min(100, cfg.budgetWarningPercent ?? 80));
277
289
  return cfg;
278
290
  }
291
+ /** Normalize one prompt while retaining its stable identity and order. */
292
+ function normalizePrompt(raw) {
293
+ if (raw === null || typeof raw !== "object") return null;
294
+ const src = raw;
295
+ if (typeof src.id !== "string" || src.id === "" || typeof src.name !== "string" || typeof src.text !== "string") return null;
296
+ return {
297
+ id: src.id,
298
+ name: src.name,
299
+ text: src.text,
300
+ tags: Array.isArray(src.tags) ? [...new Set(src.tags.filter((tag) => typeof tag === "string").map((tag) => tag.trim()).filter(Boolean))] : [],
301
+ favorite: src.favorite === true,
302
+ useCount: typeof src.useCount === "number" && Number.isFinite(src.useCount) && src.useCount >= 0 ? Math.floor(src.useCount) : 0,
303
+ lastUsedAt: typeof src.lastUsedAt === "number" && Number.isFinite(src.lastUsedAt) && src.lastUsedAt > 0 ? src.lastUsedAt : void 0
304
+ };
305
+ }
279
306
  /** Merge a persisted document into the default state, ignoring unknown shapes. */
280
307
  function mergeState(target, raw) {
281
308
  if (raw === null || typeof raw !== "object") return;
282
309
  const src = raw;
283
310
  if (src.cfg !== void 0) target.cfg = normalizeCfg(src.cfg);
284
311
  if (Array.isArray(src.folders)) target.folders = src.folders;
285
- if (Array.isArray(src.prompts)) target.prompts = src.prompts;
312
+ if (Array.isArray(src.prompts)) target.prompts = src.prompts.map(normalizePrompt).filter((item) => item !== null);
286
313
  if (src.stars !== null && typeof src.stars === "object" && !Array.isArray(src.stars)) target.stars = src.stars;
287
314
  if (typeof src.apiKey === "string") target.apiKey = src.apiKey;
288
315
  if (src.usage !== null && typeof src.usage === "object" && !Array.isArray(src.usage)) target.usage = src.usage;
@@ -648,6 +675,297 @@ var SystemCredentialStore = class {
648
675
  }
649
676
  };
650
677
  //#endregion
678
+ //#region src/backup.ts
679
+ /** Validation and merge rules for versioned, secret-free local backups. */
680
+ const BACKUP_FORMAT = "dsh-custom-plugin-backup";
681
+ function clone(value) {
682
+ return JSON.parse(JSON.stringify(value));
683
+ }
684
+ function counter(value) {
685
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
686
+ }
687
+ function validDayKey(value) {
688
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
689
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
690
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
691
+ }
692
+ function strictCfg(raw) {
693
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error("配置数据无效");
694
+ const src = raw;
695
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
696
+ const value = src[key];
697
+ if (value === void 0) continue;
698
+ const expected = DEFAULT_CONFIG[key];
699
+ if (typeof value !== typeof expected) throw new Error("配置数据无效");
700
+ if (typeof expected === "number") {
701
+ const numericValue = value;
702
+ if (!Number.isFinite(numericValue) || key === "monthlyBudgetCny" && numericValue < 0 || key === "budgetWarningPercent" && (numericValue < 1 || numericValue > 100)) throw new Error("配置数据无效");
703
+ }
704
+ }
705
+ return normalizeCfg(raw);
706
+ }
707
+ function safeKey(value) {
708
+ return value !== "__proto__" && value !== "constructor" && value !== "prototype";
709
+ }
710
+ function folder(raw, seen) {
711
+ if (raw === null || typeof raw !== "object") return null;
712
+ const src = raw;
713
+ if (typeof src.id !== "string" || src.id === "" || seen.has(src.id) || typeof src.name !== "string") return null;
714
+ seen.add(src.id);
715
+ if (!Array.isArray(src.children) || !Array.isArray(src.sessionIds) || !Array.isArray(src.workspaceIds) || !Array.isArray(src.prompts)) return null;
716
+ const children = src.children.map((item) => folder(item, seen));
717
+ if (children.some((item) => item === null)) return null;
718
+ const strings = (value) => value.every((item) => typeof item === "string") ? [...new Set(value)] : null;
719
+ const sessionIds = strings(src.sessionIds);
720
+ const workspaceIds = strings(src.workspaceIds);
721
+ const prompts = strings(src.prompts);
722
+ if (sessionIds === null || workspaceIds === null || prompts === null) return null;
723
+ return {
724
+ id: src.id,
725
+ name: src.name,
726
+ children,
727
+ sessionIds,
728
+ workspaceIds,
729
+ prompts
730
+ };
731
+ }
732
+ function usageRow(raw) {
733
+ if (raw === null || typeof raw !== "object") return null;
734
+ const src = raw;
735
+ for (const key of [
736
+ "in",
737
+ "out",
738
+ "cacheIn",
739
+ "cacheW",
740
+ "reason",
741
+ "calls"
742
+ ]) if (!counter(src[key])) return null;
743
+ const row = {
744
+ in: src.in,
745
+ out: src.out,
746
+ cacheIn: src.cacheIn,
747
+ cacheW: src.cacheW,
748
+ reason: src.reason,
749
+ calls: src.calls
750
+ };
751
+ let providedPeakCounters = 0;
752
+ for (const key of [
753
+ "peakIn",
754
+ "peakCacheIn",
755
+ "peakCacheW",
756
+ "peakOut"
757
+ ]) {
758
+ if (src[key] !== void 0) {
759
+ if (!counter(src[key])) return null;
760
+ providedPeakCounters++;
761
+ }
762
+ if (typeof src[key] === "number") row[key] = src[key];
763
+ }
764
+ if (providedPeakCounters !== 0 && providedPeakCounters !== 4) return null;
765
+ if (src.peakSplitKnown !== void 0 && typeof src.peakSplitKnown !== "boolean") return null;
766
+ const hasPeakCounters = providedPeakCounters === 4;
767
+ if (src.peakSplitKnown === true && !hasPeakCounters) return null;
768
+ if (hasPeakCounters && (row.peakIn > row.in || row.peakCacheIn > row.cacheIn || row.peakCacheW > row.cacheW || row.peakOut > row.out)) return null;
769
+ row.peakSplitKnown = src.peakSplitKnown === false ? false : hasPeakCounters;
770
+ return row;
771
+ }
772
+ function createBackup(state) {
773
+ const seen = /* @__PURE__ */ new Set();
774
+ const folders = (Array.isArray(state.folders) ? state.folders : []).map((item) => folder(item, seen)).filter((item) => item !== null);
775
+ const prompts = (Array.isArray(state.prompts) ? state.prompts : []).map(normalizePrompt).filter((item) => item !== null);
776
+ const stars = {};
777
+ if (state.stars !== null && typeof state.stars === "object") for (const [sessionId, entries] of Object.entries(state.stars)) {
778
+ if (!safeKey(sessionId) || entries === null || typeof entries !== "object" || Array.isArray(entries)) continue;
779
+ const clean = {};
780
+ for (const [seq, value] of Object.entries(entries)) if (value === true && /^\d+$/.test(seq)) clean[seq] = true;
781
+ if (Object.keys(clean).length > 0) stars[sessionId] = clean;
782
+ }
783
+ const usage = {};
784
+ if (state.usage !== null && typeof state.usage === "object") for (const [day, models] of Object.entries(state.usage)) {
785
+ if (!validDayKey(day) || models === null || typeof models !== "object" || Array.isArray(models)) continue;
786
+ const clean = {};
787
+ for (const [model, rawRow] of Object.entries(models)) {
788
+ if (!safeKey(model)) continue;
789
+ const row = usageRow(rawRow);
790
+ if (model !== "" && row !== null) clean[model] = row;
791
+ }
792
+ if (Object.keys(clean).length > 0) usage[day] = clean;
793
+ }
794
+ return clone({
795
+ format: BACKUP_FORMAT,
796
+ version: 1,
797
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
798
+ data: {
799
+ cfg: normalizeCfg(state.cfg),
800
+ folders,
801
+ prompts,
802
+ stars,
803
+ usage
804
+ }
805
+ });
806
+ }
807
+ function parseBackup(raw) {
808
+ if (raw === null || typeof raw !== "object") throw new Error("备份文件不是 JSON 对象");
809
+ const src = raw;
810
+ if (src.format !== "dsh-custom-plugin-backup" || src.version !== 1) throw new Error("不支持的备份格式或版本");
811
+ if (typeof src.exportedAt !== "string" || Number.isNaN(Date.parse(src.exportedAt))) throw new Error("备份时间无效");
812
+ if (src.data === null || typeof src.data !== "object") throw new Error("备份数据缺失");
813
+ const data = src.data;
814
+ if (data.cfg === null || typeof data.cfg !== "object" || Array.isArray(data.cfg) || !Array.isArray(data.folders) || !Array.isArray(data.prompts) || data.stars === null || typeof data.stars !== "object" || Array.isArray(data.stars) || data.usage === null || typeof data.usage !== "object" || Array.isArray(data.usage)) throw new Error("备份数据结构无效");
815
+ const seen = /* @__PURE__ */ new Set();
816
+ const folders = data.folders.map((item) => folder(item, seen));
817
+ if (folders.some((item) => item === null)) throw new Error("文件夹数据无效");
818
+ const prompts = data.prompts.map(normalizePrompt);
819
+ if (prompts.some((item) => item === null)) throw new Error("提示词数据无效");
820
+ const stars = {};
821
+ for (const [sessionId, entries] of Object.entries(data.stars)) {
822
+ if (!safeKey(sessionId)) throw new Error("星标数据无效");
823
+ if (entries === null || typeof entries !== "object" || Array.isArray(entries)) throw new Error("星标数据无效");
824
+ stars[sessionId] = {};
825
+ for (const [seq, value] of Object.entries(entries)) {
826
+ if (value !== true || !/^\d+$/.test(seq)) throw new Error("星标数据无效");
827
+ stars[sessionId][seq] = true;
828
+ }
829
+ }
830
+ const usage = {};
831
+ for (const [day, models] of Object.entries(data.usage)) {
832
+ if (!validDayKey(day) || models === null || typeof models !== "object" || Array.isArray(models)) throw new Error("用量数据无效");
833
+ usage[day] = {};
834
+ for (const [model, rawRow] of Object.entries(models)) {
835
+ if (!safeKey(model)) throw new Error("用量数据无效");
836
+ const row = usageRow(rawRow);
837
+ if (model === "" || row === null) throw new Error("用量数据无效");
838
+ usage[day][model] = row;
839
+ }
840
+ }
841
+ pruneUsage(usage);
842
+ return {
843
+ format: BACKUP_FORMAT,
844
+ version: 1,
845
+ exportedAt: src.exportedAt,
846
+ data: {
847
+ cfg: strictCfg(data.cfg),
848
+ folders,
849
+ prompts,
850
+ stars,
851
+ usage
852
+ }
853
+ };
854
+ }
855
+ function folderIds(nodes, out = /* @__PURE__ */ new Set()) {
856
+ for (const node of nodes) {
857
+ out.add(node.id);
858
+ folderIds(node.children, out);
859
+ }
860
+ return out;
861
+ }
862
+ function backupPreview(current, backup) {
863
+ const currentFolders = folderIds(current.folders);
864
+ const incomingFolders = folderIds(backup.data.folders);
865
+ const currentPrompts = new Set(current.prompts.map((item) => item.id));
866
+ return {
867
+ folders: incomingFolders.size,
868
+ prompts: backup.data.prompts.length,
869
+ starredSessions: Object.keys(backup.data.stars).length,
870
+ usageDays: Object.keys(backup.data.usage).length,
871
+ conflicts: {
872
+ folders: [...incomingFolders].filter((id) => currentFolders.has(id)).length,
873
+ prompts: backup.data.prompts.filter((item) => currentPrompts.has(item.id)).length,
874
+ usageDays: Object.keys(backup.data.usage).filter((day) => current.usage[day] !== void 0).length
875
+ }
876
+ };
877
+ }
878
+ function mergeById(current, incoming) {
879
+ const replacements = new Map(incoming.map((item) => [item.id, clone(item)]));
880
+ const out = current.map((item) => replacements.get(item.id) ?? item);
881
+ for (const item of incoming) if (!current.some((old) => old.id === item.id)) out.push(clone(item));
882
+ return out;
883
+ }
884
+ /** Merge a folder tree by stable node id. Imported parents and sibling order
885
+ * win for nodes present in the document; current nodes absent from it remain
886
+ * in their existing order. This also moves a duplicate node when its parent
887
+ * changed in the imported tree, instead of leaving a stale root copy behind. */
888
+ function mergeFolders(current, incoming) {
889
+ const incomingIds = folderIds(incoming);
890
+ const index = /* @__PURE__ */ new Map();
891
+ const indexTree = (nodes) => {
892
+ for (const node of nodes) {
893
+ index.set(node.id, node);
894
+ indexTree(node.children);
895
+ }
896
+ };
897
+ indexTree(current);
898
+ const retain = (node) => {
899
+ if (incomingIds.has(node.id)) return null;
900
+ const children = node.children.map(retain).filter((item) => item !== null);
901
+ return {
902
+ id: node.id,
903
+ name: node.name,
904
+ children,
905
+ sessionIds: clone(node.sessionIds),
906
+ workspaceIds: clone(node.workspaceIds),
907
+ prompts: clone(node.prompts)
908
+ };
909
+ };
910
+ const imported = (source) => {
911
+ const children = (index.get(source.id)?.children ?? []).map(retain).filter((item) => item !== null).concat(source.children.map(imported));
912
+ return {
913
+ id: source.id,
914
+ name: source.name,
915
+ children,
916
+ sessionIds: clone(source.sessionIds),
917
+ workspaceIds: clone(source.workspaceIds),
918
+ prompts: clone(source.prompts)
919
+ };
920
+ };
921
+ const out = incoming.map(imported);
922
+ for (const node of current) if (!incomingIds.has(node.id)) {
923
+ const kept = retain(node);
924
+ if (kept !== null) out.push(kept);
925
+ }
926
+ return out;
927
+ }
928
+ function importedState(current, backup, mode) {
929
+ const data = backup.data;
930
+ if (mode === "replace") return {
931
+ cfg: clone(data.cfg),
932
+ folders: clone(data.folders),
933
+ prompts: clone(data.prompts),
934
+ stars: clone(data.stars),
935
+ usage: clone(data.usage),
936
+ apiKey: current.apiKey
937
+ };
938
+ const stars = clone(current.stars);
939
+ for (const [sessionId, values] of Object.entries(data.stars)) stars[sessionId] = {
940
+ ...stars[sessionId] ?? {},
941
+ ...clone(values)
942
+ };
943
+ const usage = clone(current.usage);
944
+ for (const [day, models] of Object.entries(data.usage)) usage[day] = {
945
+ ...usage[day] ?? {},
946
+ ...clone(models)
947
+ };
948
+ pruneUsage(usage);
949
+ return {
950
+ cfg: normalizeCfg({
951
+ ...current.cfg,
952
+ ...clone(data.cfg)
953
+ }),
954
+ folders: mergeFolders(current.folders, data.folders),
955
+ prompts: mergeById(current.prompts, data.prompts),
956
+ stars,
957
+ usage,
958
+ apiKey: current.apiKey
959
+ };
960
+ }
961
+ async function writeRecoveryBackup(path, state) {
962
+ const target = path + ".backup.json";
963
+ const temporary = target + ".tmp";
964
+ await writeFile(temporary, JSON.stringify(createBackup(state), null, 2), "utf8");
965
+ await rename(temporary, target);
966
+ return target;
967
+ }
968
+ //#endregion
651
969
  //#region src/host-service.ts
652
970
  const USAGE_SCAN_CONCURRENCY = 4;
653
971
  async function mapConcurrent(items, limit, worker) {
@@ -673,9 +991,14 @@ var CustomPluginHost = class {
673
991
  attachments;
674
992
  credentialStore;
675
993
  sessionModel = /* @__PURE__ */ new Map();
994
+ stateOperation = Promise.resolve();
995
+ stateOperationActive = false;
996
+ stateOperationPending = 0;
997
+ queuedUsage = [];
676
998
  usageScanPromise = null;
677
999
  usageRevision = 0;
678
1000
  lastUsagePruneDay = "";
1001
+ mermaidFetchPromise = null;
679
1002
  mermaidBytesValue = 0;
680
1003
  mermaidJs = "";
681
1004
  mermaidSource = "";
@@ -696,6 +1019,33 @@ var CustomPluginHost = class {
696
1019
  async persist() {
697
1020
  await this.persistNow();
698
1021
  }
1022
+ /** Persist after all queued state mutations have reached a stable point. */
1023
+ async persistWhenIdle() {
1024
+ await this.runStateOperation(() => this.persist());
1025
+ }
1026
+ runStateOperation(operation) {
1027
+ this.stateOperationPending++;
1028
+ this.stateOperationActive = true;
1029
+ const run = this.stateOperation.catch(() => {}).then(async () => {
1030
+ try {
1031
+ return await operation();
1032
+ } finally {
1033
+ while (this.queuedUsage.length > 0) {
1034
+ const pending = this.queuedUsage.splice(0);
1035
+ for (const item of pending) this.foldUsageNow(item.usage, item.time, item.model);
1036
+ try {
1037
+ await this.persist();
1038
+ } catch (error) {
1039
+ this.pushDiag(`queued usage save failed: ${String(error?.message ?? error)}`);
1040
+ }
1041
+ }
1042
+ this.stateOperationPending--;
1043
+ if (this.stateOperationPending === 0) this.stateOperationActive = false;
1044
+ }
1045
+ });
1046
+ this.stateOperation = run.then(() => {}, () => {});
1047
+ return run;
1048
+ }
699
1049
  /** Record a bounded client diagnostic line. */
700
1050
  pushDiag(message) {
701
1051
  this.diagReports.push(String(message ?? "").slice(0, 400));
@@ -710,7 +1060,20 @@ var CustomPluginHost = class {
710
1060
  }
711
1061
  /** Fold one assistant/message usage record into the ledger. The event time
712
1062
  * decides both the day bucket and the peak/off-peak portion. */
713
- foldUsage(sessionId, usage, time) {
1063
+ foldUsage(sessionId, usage, time, modelOverride) {
1064
+ const model = modelOverride !== void 0 ? modelOverride ?? "unknown" : this.sessionModel.get(sessionId) ?? "unknown";
1065
+ if (this.stateOperationActive) {
1066
+ this.queuedUsage.push({
1067
+ usage,
1068
+ time,
1069
+ model
1070
+ });
1071
+ this.usageRevision++;
1072
+ return;
1073
+ }
1074
+ this.foldUsageNow(usage, time, model);
1075
+ }
1076
+ foldUsageNow(usage, time, model) {
714
1077
  const at = time ?? Date.now();
715
1078
  const dayName = dayKey(at);
716
1079
  const day = this.state.usage[dayName] ?? (this.state.usage[dayName] = {});
@@ -718,7 +1081,6 @@ var CustomPluginHost = class {
718
1081
  pruneUsage(this.state.usage, at);
719
1082
  this.lastUsagePruneDay = dayName;
720
1083
  }
721
- const model = this.sessionModel.get(sessionId) ?? "unknown";
722
1084
  foldUsageRecord(day[model] ?? (day[model] = createUsageRow()), usage, isPeakHour(at));
723
1085
  this.usageRevision++;
724
1086
  }
@@ -736,12 +1098,23 @@ var CustomPluginHost = class {
736
1098
  }
737
1099
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
738
1100
  async applyEdit(edit) {
739
- if (edit.cfg !== void 0 && edit.cfg !== null && typeof edit.cfg === "object") this.state.cfg = {
1101
+ await this.runStateOperation(async () => {
1102
+ const previous = JSON.parse(JSON.stringify(this.state));
1103
+ try {
1104
+ await this.applyEditNow(edit);
1105
+ } catch (error) {
1106
+ Object.assign(this.state, previous);
1107
+ throw error;
1108
+ }
1109
+ });
1110
+ }
1111
+ async applyEditNow(edit) {
1112
+ if (edit.cfg !== void 0 && edit.cfg !== null && typeof edit.cfg === "object") this.state.cfg = normalizeCfg({
740
1113
  ...this.state.cfg,
741
1114
  ...edit.cfg
742
- };
1115
+ });
743
1116
  if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
744
- if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts;
1117
+ if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts.map(normalizePrompt).filter((item) => item !== null);
745
1118
  if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
746
1119
  if (typeof edit.apiKey === "string") {
747
1120
  const key = edit.apiKey.trim();
@@ -755,6 +1128,48 @@ var CustomPluginHost = class {
755
1128
  }
756
1129
  }
757
1130
  }
1131
+ /** Build the portable backup projection; credentials never enter it. */
1132
+ backupExport() {
1133
+ return createBackup(this.state);
1134
+ }
1135
+ /** Validate/preview or atomically apply a portable backup. */
1136
+ async backupImport(raw, mode, dryRun) {
1137
+ return await this.runStateOperation(() => this.backupImportNow(raw, mode, dryRun));
1138
+ }
1139
+ async backupImportNow(raw, mode, dryRun) {
1140
+ try {
1141
+ if (mode !== "merge" && mode !== "replace") return {
1142
+ ok: false,
1143
+ error: "导入模式无效"
1144
+ };
1145
+ const backup = parseBackup(raw);
1146
+ const preview = backupPreview(this.state, backup);
1147
+ if (dryRun) return {
1148
+ ok: true,
1149
+ preview
1150
+ };
1151
+ const previous = JSON.parse(JSON.stringify(this.state));
1152
+ const recoveryPath = await writeRecoveryBackup(this.statePath(), previous);
1153
+ const next = importedState(previous, backup, mode);
1154
+ Object.assign(this.state, next);
1155
+ try {
1156
+ await this.persist();
1157
+ } catch (error) {
1158
+ Object.assign(this.state, previous);
1159
+ throw error;
1160
+ }
1161
+ return {
1162
+ ok: true,
1163
+ preview,
1164
+ recoveryPath
1165
+ };
1166
+ } catch (error) {
1167
+ return {
1168
+ ok: false,
1169
+ error: String(error?.message ?? error)
1170
+ };
1171
+ }
1172
+ }
758
1173
  /** Move a legacy plaintext state key into the OS store when available. */
759
1174
  async migrateLegacyApiKey() {
760
1175
  const key = (this.state.apiKey ?? "").trim();
@@ -931,6 +1346,57 @@ var CustomPluginHost = class {
931
1346
  source: "none"
932
1347
  };
933
1348
  }
1349
+ /** Search one session using DSH's indexed event search and bind hits to a user-turn anchor. */
1350
+ async conversationSearch(sessionId, query, kinds) {
1351
+ const wanted = new Set(kinds.length > 0 ? kinds : [
1352
+ "user",
1353
+ "assistant",
1354
+ "tool"
1355
+ ]);
1356
+ try {
1357
+ const eventTypes = kinds.length > 0 ? kinds.flatMap((kind) => kind === "user" ? ["user/message"] : kind === "assistant" ? ["assistant/message"] : ["tool/call", "tool/result"]) : [];
1358
+ const [page, snapshot] = await Promise.all([this.sessionQuery.searchEvents({
1359
+ sessionId,
1360
+ query,
1361
+ limit: 100,
1362
+ ...eventTypes.length > 0 ? { filters: [{
1363
+ kind: "type",
1364
+ values: eventTypes
1365
+ }] } : {}
1366
+ }), this.sessionQuery.readSession(sessionId)]);
1367
+ const anchors = /* @__PURE__ */ new Map();
1368
+ let anchor;
1369
+ for (const event of snapshot.events) {
1370
+ if (event.type === "user/message") anchor = event.seq;
1371
+ if (anchor !== void 0) anchors.set(event.seq, anchor);
1372
+ }
1373
+ const items = [];
1374
+ for (const hit of page.items) {
1375
+ const kind = hit.type === "user/message" ? "user" : hit.type === "assistant/message" ? "assistant" : hit.type.startsWith("tool/") ? "tool" : null;
1376
+ if (kind === null || !wanted.has(kind)) continue;
1377
+ const anchorSeq = anchors.get(hit.seq);
1378
+ if (anchorSeq === void 0) continue;
1379
+ items.push({
1380
+ sessionId,
1381
+ seq: hit.seq,
1382
+ anchorSeq,
1383
+ kind,
1384
+ time: hit.time,
1385
+ snippet: hit.snippet.slice(0, 500)
1386
+ });
1387
+ }
1388
+ return {
1389
+ ok: true,
1390
+ items,
1391
+ hasMore: page.nextCursor !== void 0
1392
+ };
1393
+ } catch (error) {
1394
+ return {
1395
+ ok: false,
1396
+ error: String(error?.message ?? error)
1397
+ };
1398
+ }
1399
+ }
934
1400
  async resolveApiKey() {
935
1401
  return (await this.resolveApiKeyWithSource()).key;
936
1402
  }
@@ -995,7 +1461,7 @@ var CustomPluginHost = class {
995
1461
  * they produced today. */
996
1462
  async usageScan() {
997
1463
  if (this.usageScanPromise !== null) return await this.usageScanPromise;
998
- const run = this.usageScanImpl();
1464
+ const run = this.runStateOperation(() => this.usageScanImpl());
999
1465
  this.usageScanPromise = run;
1000
1466
  try {
1001
1467
  return await run;
@@ -1049,9 +1515,18 @@ var CustomPluginHost = class {
1049
1515
  ok: false,
1050
1516
  error: "扫描期间产生了新用量,未覆盖现有用量,请稍后重试"
1051
1517
  };
1518
+ const previousUsage = JSON.parse(JSON.stringify(this.state.usage));
1052
1519
  pruneUsage(this.state.usage);
1053
1520
  this.state.usage[today] = agg;
1054
- this.persist().catch((error) => this.pushDiag(`usage scan save failed: ${String(error?.message ?? error)}`));
1521
+ try {
1522
+ await this.persist();
1523
+ } catch (error) {
1524
+ this.state.usage = previousUsage;
1525
+ return {
1526
+ ok: false,
1527
+ error: `用量保存失败: ${String(error?.message ?? error)}`
1528
+ };
1529
+ }
1055
1530
  return {
1056
1531
  ok: true,
1057
1532
  day: today,
@@ -1067,6 +1542,16 @@ var CustomPluginHost = class {
1067
1542
  ok: true,
1068
1543
  bytes: this.mermaidBytesValue
1069
1544
  };
1545
+ if (this.mermaidFetchPromise !== null) return await this.mermaidFetchPromise;
1546
+ const run = this.mermaidFetchImpl();
1547
+ this.mermaidFetchPromise = run;
1548
+ try {
1549
+ return await run;
1550
+ } finally {
1551
+ if (this.mermaidFetchPromise === run) this.mermaidFetchPromise = null;
1552
+ }
1553
+ }
1554
+ async mermaidFetchImpl() {
1070
1555
  const localPath = this.localMermaidPath();
1071
1556
  if (localPath !== null && localPath !== "") try {
1072
1557
  const text = readFileSync(localPath, "utf8");
@@ -1260,6 +1745,7 @@ function isLoopbackRequest(request) {
1260
1745
  //#region src/routes.ts
1261
1746
  const BODY_LIMIT = 256 * 1024;
1262
1747
  const TIMELINE_LIMIT = 64 * 1024;
1748
+ const BACKUP_REQUEST_LIMIT = 5308416;
1263
1749
  function json(res, status, body) {
1264
1750
  res.writeHead(status, {
1265
1751
  "content-type": "application/json; charset=utf-8",
@@ -1299,13 +1785,14 @@ function isMethod(req, method, res) {
1299
1785
  return false;
1300
1786
  }
1301
1787
  /** Build the plugin's route set. */
1302
- function makeCustomPluginRoutes(host) {
1788
+ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
1303
1789
  return [
1304
1790
  {
1305
1791
  kind: "exact",
1306
1792
  path: `${CUSTOM_PLUGIN_API_PREFIX}/state`,
1307
1793
  handler: async (req, res) => {
1308
1794
  if (!guard(req, res)) return;
1795
+ await ready;
1309
1796
  if (req.method === "GET") {
1310
1797
  json(res, 200, {
1311
1798
  ok: true,
@@ -1329,7 +1816,7 @@ function makeCustomPluginRoutes(host) {
1329
1816
  stars: body.stars,
1330
1817
  apiKey: typeof body.apiKey === "string" ? body.apiKey : void 0
1331
1818
  });
1332
- await host.persist();
1819
+ await host.persistWhenIdle();
1333
1820
  json(res, 200, {
1334
1821
  ok: true,
1335
1822
  ...await host.credentialStatus()
@@ -1361,6 +1848,123 @@ function makeCustomPluginRoutes(host) {
1361
1848
  json(res, result.ok ? 200 : 500, result);
1362
1849
  }
1363
1850
  },
1851
+ {
1852
+ kind: "exact",
1853
+ path: `${CUSTOM_PLUGIN_API_PREFIX}/backup`,
1854
+ handler: async (req, res) => {
1855
+ if (!guard(req, res)) return;
1856
+ await ready;
1857
+ if (req.method === "GET") {
1858
+ json(res, 200, {
1859
+ ok: true,
1860
+ data: host.backupExport()
1861
+ });
1862
+ return;
1863
+ }
1864
+ if (!isMethod(req, "POST", res)) return;
1865
+ try {
1866
+ const rawBody = await readBody(req, BACKUP_REQUEST_LIMIT);
1867
+ if (rawBody === null || typeof rawBody !== "object" || Array.isArray(rawBody)) {
1868
+ json(res, 400, {
1869
+ ok: false,
1870
+ error: "备份请求结构无效"
1871
+ });
1872
+ return;
1873
+ }
1874
+ const body = rawBody;
1875
+ if (body.mode !== "merge" && body.mode !== "replace") {
1876
+ json(res, 400, {
1877
+ ok: false,
1878
+ error: "导入模式无效"
1879
+ });
1880
+ return;
1881
+ }
1882
+ if (!Object.prototype.hasOwnProperty.call(body, "document")) {
1883
+ json(res, 400, {
1884
+ ok: false,
1885
+ error: "备份文档缺失"
1886
+ });
1887
+ return;
1888
+ }
1889
+ if (body.dryRun !== void 0 && typeof body.dryRun !== "boolean") {
1890
+ json(res, 400, {
1891
+ ok: false,
1892
+ error: "dryRun 字段无效"
1893
+ });
1894
+ return;
1895
+ }
1896
+ const encodedDocument = JSON.stringify(body.document);
1897
+ if (encodedDocument === void 0) {
1898
+ json(res, 400, {
1899
+ ok: false,
1900
+ error: "备份文档无效"
1901
+ });
1902
+ return;
1903
+ }
1904
+ if (Buffer.byteLength(encodedDocument, "utf8") > 5242880) {
1905
+ json(res, 413, {
1906
+ ok: false,
1907
+ error: "备份文档不能超过 5 MB"
1908
+ });
1909
+ return;
1910
+ }
1911
+ const result = await host.backupImport(body.document, body.mode, body.dryRun === true);
1912
+ json(res, result.ok ? 200 : 400, result);
1913
+ } catch (error) {
1914
+ const message = error instanceof Error ? error.message : String(error);
1915
+ json(res, message === "body-too-large" ? 413 : 400, {
1916
+ ok: false,
1917
+ error: message
1918
+ });
1919
+ }
1920
+ }
1921
+ },
1922
+ {
1923
+ kind: "exact",
1924
+ path: `${CUSTOM_PLUGIN_API_PREFIX}/search`,
1925
+ handler: async (req, res) => {
1926
+ if (!guard(req, res)) return;
1927
+ if (!isMethod(req, "POST", res)) return;
1928
+ try {
1929
+ const body = await readBody(req, TIMELINE_LIMIT);
1930
+ if (typeof body.sessionId !== "string" || body.sessionId === "" || typeof body.query !== "string" || body.query.trim() === "") {
1931
+ json(res, 400, {
1932
+ ok: false,
1933
+ error: "会话或搜索词为空"
1934
+ });
1935
+ return;
1936
+ }
1937
+ const allowed = /* @__PURE__ */ new Set([
1938
+ "user",
1939
+ "assistant",
1940
+ "tool"
1941
+ ]);
1942
+ if (body.kinds !== void 0 && !Array.isArray(body.kinds)) {
1943
+ json(res, 400, {
1944
+ ok: false,
1945
+ error: "角色筛选无效"
1946
+ });
1947
+ return;
1948
+ }
1949
+ if (Array.isArray(body.kinds) && body.kinds.some((kind) => typeof kind !== "string" || !allowed.has(kind))) {
1950
+ json(res, 400, {
1951
+ ok: false,
1952
+ error: "角色筛选无效"
1953
+ });
1954
+ return;
1955
+ }
1956
+ const kinds = Array.isArray(body.kinds) ? body.kinds : [];
1957
+ const result = await host.conversationSearch(body.sessionId, body.query.trim(), kinds);
1958
+ json(res, result.ok ? 200 : 500, result);
1959
+ } catch (error) {
1960
+ const message = error instanceof Error ? error.message : String(error);
1961
+ json(res, message === "body-too-large" ? 413 : 400, {
1962
+ ok: false,
1963
+ error: message
1964
+ });
1965
+ }
1966
+ }
1967
+ },
1364
1968
  {
1365
1969
  kind: "exact",
1366
1970
  path: `${CUSTOM_PLUGIN_API_PREFIX}/export`,
@@ -1392,6 +1996,7 @@ function makeCustomPluginRoutes(host) {
1392
1996
  path: `${CUSTOM_PLUGIN_API_PREFIX}/balance`,
1393
1997
  handler: async (req, res) => {
1394
1998
  if (!guard(req, res)) return;
1999
+ await ready;
1395
2000
  if (!isMethod(req, "GET", res)) return;
1396
2001
  json(res, 200, await host.balanceGet());
1397
2002
  }
@@ -1401,6 +2006,7 @@ function makeCustomPluginRoutes(host) {
1401
2006
  path: `${CUSTOM_PLUGIN_API_PREFIX}/usage-scan`,
1402
2007
  handler: async (req, res) => {
1403
2008
  if (!guard(req, res)) return;
2009
+ await ready;
1404
2010
  if (!isMethod(req, "POST", res)) return;
1405
2011
  const result = await host.usageScan();
1406
2012
  json(res, result.ok ? 200 : 500, result);
@@ -1452,7 +2058,7 @@ function makeCustomPluginRoutes(host) {
1452
2058
  handler: (req, res) => {
1453
2059
  if (!guard(req, res)) return;
1454
2060
  if (!isMethod(req, "GET", res)) return;
1455
- host.debugInfo().then((info) => {
2061
+ ready.then(() => host.debugInfo()).then((info) => {
1456
2062
  json(res, 200, {
1457
2063
  ok: true,
1458
2064
  ...info
@@ -1477,7 +2083,10 @@ const inject = [
1477
2083
  const apply = mountOnce("@alexpeng/dsh-custom-plugin", applyImpl);
1478
2084
  function applyImpl(ctx) {
1479
2085
  const state = defaultState();
1480
- let statePath = dshHome();
2086
+ let statePath = join(dshHome(), STATE_FILE);
2087
+ let stateLoaded = false;
2088
+ const sessionModels = /* @__PURE__ */ new Map();
2089
+ const pendingUsage = [];
1481
2090
  const diagReports = [];
1482
2091
  const reportDiag = (message) => {
1483
2092
  diagReports.push(String(message ?? "").slice(0, 400));
@@ -1489,7 +2098,7 @@ function applyImpl(ctx) {
1489
2098
  if (timer !== void 0) clearTimeout(timer);
1490
2099
  timer = setTimeout(() => {
1491
2100
  timer = void 0;
1492
- saveStateFile(state).catch((error) => {
2101
+ host.persistWhenIdle().catch((error) => {
1493
2102
  reportDiag(`state save failed: ${String(error?.message ?? error)}`);
1494
2103
  });
1495
2104
  }, 500);
@@ -1504,19 +2113,32 @@ function applyImpl(ctx) {
1504
2113
  diagReports,
1505
2114
  attachments: ctx.get("attachments")
1506
2115
  });
1507
- loadStateFile(state).then(async (path) => {
2116
+ const stateReady = loadStateFile(state).then(async (path) => {
1508
2117
  statePath = path;
1509
2118
  if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
2119
+ stateLoaded = true;
2120
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
1510
2121
  return saveStateFile(state);
1511
2122
  }).catch((error) => {
1512
2123
  reportDiag(`state load failed: ${String(error?.message ?? error)}`);
2124
+ stateLoaded = true;
2125
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
1513
2126
  });
1514
2127
  ctx.on("session/event", (session, event) => {
1515
2128
  try {
1516
2129
  if (event === void 0 || event === null) return;
1517
2130
  const sessionId = String(session.id);
1518
- if (event.type === "request/context") host.rememberModel(sessionId, event.data.model ?? null);
1519
- else if (event.type === "assistant/message" && event.data.usage !== void 0) {
2131
+ if (event.type === "request/context") {
2132
+ const model = event.data.model ?? null;
2133
+ sessionModels.set(sessionId, model);
2134
+ host.rememberModel(sessionId, model);
2135
+ } else if (event.type === "assistant/message" && event.data.usage !== void 0) if (!stateLoaded) pendingUsage.push({
2136
+ sessionId,
2137
+ usage: event.data.usage,
2138
+ time: event.time,
2139
+ model: sessionModels.get(sessionId) ?? null
2140
+ });
2141
+ else {
1520
2142
  host.foldUsage(sessionId, event.data.usage, event.time);
1521
2143
  saveSoon();
1522
2144
  }
@@ -1525,10 +2147,12 @@ function applyImpl(ctx) {
1525
2147
  }
1526
2148
  });
1527
2149
  ctx.on("session/disposed", (session) => {
1528
- host.forgetSession(String(session.id));
2150
+ const sessionId = String(session.id);
2151
+ sessionModels.delete(sessionId);
2152
+ host.forgetSession(sessionId);
1529
2153
  });
1530
2154
  const routeDisposers = [];
1531
- for (const route of makeCustomPluginRoutes(host)) routeDisposers.push(ctx.webServer.register(route));
2155
+ for (const route of makeCustomPluginRoutes(host, stateReady)) routeDisposers.push(ctx.webServer.register(route));
1532
2156
  host.mermaidFetch().then((result) => {
1533
2157
  reportDiag(result.ok ? `mermaid engine ready (${result.bytes} bytes, ${host.mermaidLoadedSource()})` : `mermaid engine failed: ${result.error}`);
1534
2158
  });
@@ -1562,6 +2186,7 @@ function applyImpl(ctx) {
1562
2186
  }
1563
2187
  },
1564
2188
  async execute() {
2189
+ await stateReady;
1565
2190
  const out = {
1566
2191
  today: dayKey(),
1567
2192
  cfg: state.cfg,