@alexpeng/dsh-custom-plugin 0.1.6 → 0.4.1

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,6 +991,10 @@ 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 = "";
@@ -697,6 +1019,33 @@ var CustomPluginHost = class {
697
1019
  async persist() {
698
1020
  await this.persistNow();
699
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
+ }
700
1049
  /** Record a bounded client diagnostic line. */
701
1050
  pushDiag(message) {
702
1051
  this.diagReports.push(String(message ?? "").slice(0, 400));
@@ -711,7 +1060,20 @@ var CustomPluginHost = class {
711
1060
  }
712
1061
  /** Fold one assistant/message usage record into the ledger. The event time
713
1062
  * decides both the day bucket and the peak/off-peak portion. */
714
- 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) {
715
1077
  const at = time ?? Date.now();
716
1078
  const dayName = dayKey(at);
717
1079
  const day = this.state.usage[dayName] ?? (this.state.usage[dayName] = {});
@@ -719,7 +1081,6 @@ var CustomPluginHost = class {
719
1081
  pruneUsage(this.state.usage, at);
720
1082
  this.lastUsagePruneDay = dayName;
721
1083
  }
722
- const model = this.sessionModel.get(sessionId) ?? "unknown";
723
1084
  foldUsageRecord(day[model] ?? (day[model] = createUsageRow()), usage, isPeakHour(at));
724
1085
  this.usageRevision++;
725
1086
  }
@@ -737,12 +1098,23 @@ var CustomPluginHost = class {
737
1098
  }
738
1099
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
739
1100
  async applyEdit(edit) {
740
- 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({
741
1113
  ...this.state.cfg,
742
1114
  ...edit.cfg
743
- };
1115
+ });
744
1116
  if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
745
- 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);
746
1118
  if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
747
1119
  if (typeof edit.apiKey === "string") {
748
1120
  const key = edit.apiKey.trim();
@@ -756,6 +1128,48 @@ var CustomPluginHost = class {
756
1128
  }
757
1129
  }
758
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
+ }
759
1173
  /** Move a legacy plaintext state key into the OS store when available. */
760
1174
  async migrateLegacyApiKey() {
761
1175
  const key = (this.state.apiKey ?? "").trim();
@@ -932,6 +1346,57 @@ var CustomPluginHost = class {
932
1346
  source: "none"
933
1347
  };
934
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
+ }
935
1400
  async resolveApiKey() {
936
1401
  return (await this.resolveApiKeyWithSource()).key;
937
1402
  }
@@ -996,7 +1461,7 @@ var CustomPluginHost = class {
996
1461
  * they produced today. */
997
1462
  async usageScan() {
998
1463
  if (this.usageScanPromise !== null) return await this.usageScanPromise;
999
- const run = this.usageScanImpl();
1464
+ const run = this.runStateOperation(() => this.usageScanImpl());
1000
1465
  this.usageScanPromise = run;
1001
1466
  try {
1002
1467
  return await run;
@@ -1050,9 +1515,18 @@ var CustomPluginHost = class {
1050
1515
  ok: false,
1051
1516
  error: "扫描期间产生了新用量,未覆盖现有用量,请稍后重试"
1052
1517
  };
1518
+ const previousUsage = JSON.parse(JSON.stringify(this.state.usage));
1053
1519
  pruneUsage(this.state.usage);
1054
1520
  this.state.usage[today] = agg;
1055
- 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
+ }
1056
1530
  return {
1057
1531
  ok: true,
1058
1532
  day: today,
@@ -1271,6 +1745,7 @@ function isLoopbackRequest(request) {
1271
1745
  //#region src/routes.ts
1272
1746
  const BODY_LIMIT = 256 * 1024;
1273
1747
  const TIMELINE_LIMIT = 64 * 1024;
1748
+ const BACKUP_REQUEST_LIMIT = 5308416;
1274
1749
  function json(res, status, body) {
1275
1750
  res.writeHead(status, {
1276
1751
  "content-type": "application/json; charset=utf-8",
@@ -1310,13 +1785,14 @@ function isMethod(req, method, res) {
1310
1785
  return false;
1311
1786
  }
1312
1787
  /** Build the plugin's route set. */
1313
- function makeCustomPluginRoutes(host) {
1788
+ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
1314
1789
  return [
1315
1790
  {
1316
1791
  kind: "exact",
1317
1792
  path: `${CUSTOM_PLUGIN_API_PREFIX}/state`,
1318
1793
  handler: async (req, res) => {
1319
1794
  if (!guard(req, res)) return;
1795
+ await ready;
1320
1796
  if (req.method === "GET") {
1321
1797
  json(res, 200, {
1322
1798
  ok: true,
@@ -1340,7 +1816,7 @@ function makeCustomPluginRoutes(host) {
1340
1816
  stars: body.stars,
1341
1817
  apiKey: typeof body.apiKey === "string" ? body.apiKey : void 0
1342
1818
  });
1343
- await host.persist();
1819
+ await host.persistWhenIdle();
1344
1820
  json(res, 200, {
1345
1821
  ok: true,
1346
1822
  ...await host.credentialStatus()
@@ -1372,6 +1848,123 @@ function makeCustomPluginRoutes(host) {
1372
1848
  json(res, result.ok ? 200 : 500, result);
1373
1849
  }
1374
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
+ },
1375
1968
  {
1376
1969
  kind: "exact",
1377
1970
  path: `${CUSTOM_PLUGIN_API_PREFIX}/export`,
@@ -1403,6 +1996,7 @@ function makeCustomPluginRoutes(host) {
1403
1996
  path: `${CUSTOM_PLUGIN_API_PREFIX}/balance`,
1404
1997
  handler: async (req, res) => {
1405
1998
  if (!guard(req, res)) return;
1999
+ await ready;
1406
2000
  if (!isMethod(req, "GET", res)) return;
1407
2001
  json(res, 200, await host.balanceGet());
1408
2002
  }
@@ -1412,6 +2006,7 @@ function makeCustomPluginRoutes(host) {
1412
2006
  path: `${CUSTOM_PLUGIN_API_PREFIX}/usage-scan`,
1413
2007
  handler: async (req, res) => {
1414
2008
  if (!guard(req, res)) return;
2009
+ await ready;
1415
2010
  if (!isMethod(req, "POST", res)) return;
1416
2011
  const result = await host.usageScan();
1417
2012
  json(res, result.ok ? 200 : 500, result);
@@ -1463,7 +2058,7 @@ function makeCustomPluginRoutes(host) {
1463
2058
  handler: (req, res) => {
1464
2059
  if (!guard(req, res)) return;
1465
2060
  if (!isMethod(req, "GET", res)) return;
1466
- host.debugInfo().then((info) => {
2061
+ ready.then(() => host.debugInfo()).then((info) => {
1467
2062
  json(res, 200, {
1468
2063
  ok: true,
1469
2064
  ...info
@@ -1488,7 +2083,10 @@ const inject = [
1488
2083
  const apply = mountOnce("@alexpeng/dsh-custom-plugin", applyImpl);
1489
2084
  function applyImpl(ctx) {
1490
2085
  const state = defaultState();
1491
- let statePath = dshHome();
2086
+ let statePath = join(dshHome(), STATE_FILE);
2087
+ let stateLoaded = false;
2088
+ const sessionModels = /* @__PURE__ */ new Map();
2089
+ const pendingUsage = [];
1492
2090
  const diagReports = [];
1493
2091
  const reportDiag = (message) => {
1494
2092
  diagReports.push(String(message ?? "").slice(0, 400));
@@ -1500,7 +2098,7 @@ function applyImpl(ctx) {
1500
2098
  if (timer !== void 0) clearTimeout(timer);
1501
2099
  timer = setTimeout(() => {
1502
2100
  timer = void 0;
1503
- saveStateFile(state).catch((error) => {
2101
+ host.persistWhenIdle().catch((error) => {
1504
2102
  reportDiag(`state save failed: ${String(error?.message ?? error)}`);
1505
2103
  });
1506
2104
  }, 500);
@@ -1515,19 +2113,32 @@ function applyImpl(ctx) {
1515
2113
  diagReports,
1516
2114
  attachments: ctx.get("attachments")
1517
2115
  });
1518
- loadStateFile(state).then(async (path) => {
2116
+ const stateReady = loadStateFile(state).then(async (path) => {
1519
2117
  statePath = path;
1520
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);
1521
2121
  return saveStateFile(state);
1522
2122
  }).catch((error) => {
1523
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);
1524
2126
  });
1525
2127
  ctx.on("session/event", (session, event) => {
1526
2128
  try {
1527
2129
  if (event === void 0 || event === null) return;
1528
2130
  const sessionId = String(session.id);
1529
- if (event.type === "request/context") host.rememberModel(sessionId, event.data.model ?? null);
1530
- 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 {
1531
2142
  host.foldUsage(sessionId, event.data.usage, event.time);
1532
2143
  saveSoon();
1533
2144
  }
@@ -1536,10 +2147,12 @@ function applyImpl(ctx) {
1536
2147
  }
1537
2148
  });
1538
2149
  ctx.on("session/disposed", (session) => {
1539
- host.forgetSession(String(session.id));
2150
+ const sessionId = String(session.id);
2151
+ sessionModels.delete(sessionId);
2152
+ host.forgetSession(sessionId);
1540
2153
  });
1541
2154
  const routeDisposers = [];
1542
- 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));
1543
2156
  host.mermaidFetch().then((result) => {
1544
2157
  reportDiag(result.ok ? `mermaid engine ready (${result.bytes} bytes, ${host.mermaidLoadedSource()})` : `mermaid engine failed: ${result.error}`);
1545
2158
  });
@@ -1573,6 +2186,7 @@ function applyImpl(ctx) {
1573
2186
  }
1574
2187
  },
1575
2188
  async execute() {
2189
+ await stateReady;
1576
2190
  const out = {
1577
2191
  today: dayKey(),
1578
2192
  cfg: state.cfg,