@alexpeng/dsh-custom-plugin 0.7.0 → 0.8.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
@@ -2,8 +2,9 @@ import { createRequire } from "node:module";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import { dirname, isAbsolute, join } from "node:path";
4
4
  import { homedir } from "node:os";
5
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import { readFileSync } from "node:fs";
7
+ import { createHash } from "node:crypto";
7
8
  //#region src/dsh-home.ts
8
9
  /**
9
10
  * DSH_HOME resolution for the plugin's Host half: the environment override
@@ -116,9 +117,49 @@ const PEAK_COUNTER_KEYS = [
116
117
  "peakCacheW",
117
118
  "peakOut"
118
119
  ];
120
+ const COUNTER_KEYS = [
121
+ "in",
122
+ "out",
123
+ "cacheIn",
124
+ "cacheW",
125
+ "reason",
126
+ "calls",
127
+ ...PEAK_COUNTER_KEYS
128
+ ];
119
129
  function isCounter(value) {
120
130
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
121
131
  }
132
+ function counterOf$1(value) {
133
+ return isCounter(value) ? value : 0;
134
+ }
135
+ /**
136
+ * Rebuild a persisted usage ledger from untrusted JSON: keep day buckets and
137
+ * model rows that are objects, coerce every counter to a finite non-negative
138
+ * number, and drop prototype-polluting model keys. This is the load-side
139
+ * counterpart of the browser shape gates; without it a hand-edited or
140
+ * half-written document could make later folds throw (or concatenate a string
141
+ * into a counter) while every save kept succeeding.
142
+ */
143
+ function normalizeUsageMap(raw) {
144
+ const out = {};
145
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return out;
146
+ for (const [day, modelsRaw] of Object.entries(raw)) {
147
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) continue;
148
+ if (modelsRaw === null || typeof modelsRaw !== "object" || Array.isArray(modelsRaw)) continue;
149
+ const clean = {};
150
+ for (const [model, rowRaw] of Object.entries(modelsRaw)) {
151
+ if (model === "__proto__" || model === "constructor" || model === "prototype") continue;
152
+ if (rowRaw === null || typeof rowRaw !== "object" || Array.isArray(rowRaw)) continue;
153
+ const src = rowRaw;
154
+ const row = createUsageRow();
155
+ for (const key of COUNTER_KEYS) row[key] = counterOf$1(src[key]);
156
+ row.peakSplitKnown = src.peakSplitKnown !== false;
157
+ clean[model] = row;
158
+ }
159
+ if (Object.keys(clean).length > 0) out[day] = clean;
160
+ }
161
+ return out;
162
+ }
122
163
  /** Create a row whose peak/off-peak split is exact from its first event. */
123
164
  function createUsageRow() {
124
165
  return {
@@ -306,26 +347,204 @@ function mergeState(target, raw) {
306
347
  if (raw === null || typeof raw !== "object") return;
307
348
  const src = raw;
308
349
  if (src.cfg !== void 0) target.cfg = normalizeCfg(src.cfg);
309
- if (Array.isArray(src.folders)) target.folders = src.folders;
350
+ if (Array.isArray(src.folders)) {
351
+ const folders = normalizeFolders(src.folders);
352
+ if (folders !== null) target.folders = folders;
353
+ }
310
354
  if (Array.isArray(src.prompts)) target.prompts = src.prompts.map(normalizePrompt).filter((item) => item !== null);
311
- if (src.stars !== null && typeof src.stars === "object" && !Array.isArray(src.stars)) target.stars = src.stars;
355
+ if (src.stars !== null && typeof src.stars === "object" && !Array.isArray(src.stars)) {
356
+ const stars = normalizeStars(src.stars);
357
+ if (stars !== null) target.stars = stars;
358
+ }
312
359
  if (typeof src.apiKey === "string") target.apiKey = src.apiKey;
313
- if (src.usage !== null && typeof src.usage === "object" && !Array.isArray(src.usage)) target.usage = src.usage;
360
+ if (src.usage !== null && typeof src.usage === "object" && !Array.isArray(src.usage)) target.usage = normalizeUsageMap(src.usage);
361
+ }
362
+ /** Rejection caps for browser-supplied documents. A shape beyond them is
363
+ * rejected outright — never truncated — because the client owns the whole
364
+ * document and a partial accept would silently drop the rest. The depth cap
365
+ * is what keeps a hostile edit from making `JSON.stringify` throw
366
+ * `RangeError` on every later save. */
367
+ const MAX_FOLDER_DEPTH = 32;
368
+ const MAX_FOLDER_NODES = 2e3;
369
+ const MAX_STAR_ENTRIES = 1e4;
370
+ function safeKeyPart(value) {
371
+ return value !== "__proto__" && value !== "constructor" && value !== "prototype";
314
372
  }
315
- /** Load and merge the persisted document into `state`. */
316
- async function loadStateFile(state, home = dshHome()) {
373
+ /**
374
+ * Validate a folder tree from the browser against the persisted shape:
375
+ * unique non-empty ids, string name, and string-only id lists, bounded in
376
+ * depth and node count. Null on any violation — the caller rejects the edit.
377
+ */
378
+ function normalizeFolders(raw) {
379
+ if (!Array.isArray(raw)) return null;
380
+ const seen = /* @__PURE__ */ new Set();
381
+ let count = 0;
382
+ const walk = (node, depth) => {
383
+ if (node === null || typeof node !== "object") return null;
384
+ const src = node;
385
+ if (typeof src.id !== "string" || src.id === "" || seen.has(src.id)) return null;
386
+ if (typeof src.name !== "string") return null;
387
+ if (!Array.isArray(src.children) || !Array.isArray(src.sessionIds) || !Array.isArray(src.workspaceIds) || !Array.isArray(src.prompts)) return null;
388
+ const strings = (value) => value.every((item) => typeof item === "string") ? [...new Set(value)] : null;
389
+ const sessionIds = strings(src.sessionIds);
390
+ const workspaceIds = strings(src.workspaceIds);
391
+ const prompts = strings(src.prompts);
392
+ if (sessionIds === null || workspaceIds === null || prompts === null) return null;
393
+ if (depth >= MAX_FOLDER_DEPTH) return null;
394
+ if (++count > MAX_FOLDER_NODES) return null;
395
+ seen.add(src.id);
396
+ const children = [];
397
+ for (const child of src.children) {
398
+ const parsed = walk(child, depth + 1);
399
+ if (parsed === null) return null;
400
+ children.push(parsed);
401
+ }
402
+ return {
403
+ id: src.id,
404
+ name: src.name,
405
+ children,
406
+ sessionIds,
407
+ workspaceIds,
408
+ prompts
409
+ };
410
+ };
411
+ const out = [];
412
+ for (const node of raw) {
413
+ const parsed = walk(node, 0);
414
+ if (parsed === null) return null;
415
+ out.push(parsed);
416
+ }
417
+ return out;
418
+ }
419
+ /**
420
+ * Validate a star map from the browser: session ids as safe object keys,
421
+ * digit-string sequence keys, `true` values only, bounded total. Null on any
422
+ * violation.
423
+ */
424
+ function normalizeStars(raw) {
425
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
426
+ const out = {};
427
+ let total = 0;
428
+ for (const [sessionId, entries] of Object.entries(raw)) {
429
+ if (!safeKeyPart(sessionId)) return null;
430
+ if (entries === null || typeof entries !== "object" || Array.isArray(entries)) return null;
431
+ const clean = {};
432
+ for (const [seq, value] of Object.entries(entries)) {
433
+ if (value !== true || !/^\d+$/.test(seq)) return null;
434
+ if (++total > MAX_STAR_ENTRIES) return null;
435
+ clean[seq] = true;
436
+ }
437
+ out[sessionId] = clean;
438
+ }
439
+ return out;
440
+ }
441
+ /** Retry ladder for a transiently unreadable state file (AV scan, sync
442
+ * client, a sharing violation racing the Desktop host's rename). Same
443
+ * cadence as the browser half's load retries, so a slow-locking file heals
444
+ * inside the window the client is still retrying its first read. */
445
+ const LOAD_RETRY_DELAYS = [
446
+ 1500,
447
+ 3e3,
448
+ 6e3
449
+ ];
450
+ /**
451
+ * Reject a syntactically valid document whose collections cannot be persisted
452
+ * safely. Browser edits already pass the same gates; a hand-edited or
453
+ * half-written file must not bypass them, or one malformed tree makes every
454
+ * later `JSON.stringify` throw while the plugin keeps "loading" it.
455
+ * @returns a human-readable reason, or null when the shape is safe.
456
+ */
457
+ function validateLoadedShape(raw) {
458
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return "state document is not a JSON object";
459
+ const src = raw;
460
+ if (src.folders !== void 0 && normalizeFolders(src.folders) === null) return "folders tree fails the shape gate";
461
+ if (src.stars !== void 0 && normalizeStars(src.stars) === null) return "stars map fails the shape gate";
462
+ return null;
463
+ }
464
+ /**
465
+ * Load and merge the persisted document into `state`.
466
+ *
467
+ * A missing file (ENOENT) is a fresh install and resolves with defaults. A
468
+ * corrupt or permanently unreadable file is renamed aside before defaults
469
+ * are adopted, so the caller's immediate save cannot destroy the previous
470
+ * bytes. Only when the file is unreadable AND cannot be moved aside does
471
+ * this reject — the caller must then suppress saves, because persisting
472
+ * never-loaded defaults would clobber a document that may be intact.
473
+ */
474
+ async function loadStateFile(state, home = dshHome(), retryDelays = LOAD_RETRY_DELAYS) {
317
475
  const statePath = join(home, STATE_FILE);
318
- let raw = null;
476
+ let text;
477
+ let mtimeMs = 0;
478
+ let size = 0;
479
+ for (let attempt = 0;; attempt++) try {
480
+ const handle = await open(statePath, "r");
481
+ try {
482
+ const st = await handle.stat();
483
+ text = await handle.readFile("utf8");
484
+ mtimeMs = st.mtimeMs;
485
+ size = st.size;
486
+ } finally {
487
+ await handle.close();
488
+ }
489
+ break;
490
+ } catch (error) {
491
+ if (error?.code === "ENOENT") {
492
+ syncBaselines.set(statePath, null);
493
+ return statePath;
494
+ }
495
+ if (attempt < retryDelays.length) {
496
+ await new Promise((resolve) => {
497
+ setTimeout(resolve, retryDelays[attempt]);
498
+ });
499
+ continue;
500
+ }
501
+ await quarantineStateFile(statePath, error);
502
+ syncBaselines.set(statePath, null);
503
+ return statePath;
504
+ }
505
+ let raw;
319
506
  try {
320
- const text = await readFile(statePath, "utf8");
321
507
  raw = JSON.parse(text);
322
- } catch {
508
+ } catch (error) {
509
+ await quarantineStateFile(statePath, error);
510
+ syncBaselines.set(statePath, null);
323
511
  raw = null;
324
512
  }
325
- if (raw !== null) mergeState(state, raw);
513
+ if (raw !== null) {
514
+ const shapeError = validateLoadedShape(raw);
515
+ if (shapeError !== null) {
516
+ await quarantineStateFile(statePath, new Error(shapeError));
517
+ syncBaselines.set(statePath, null);
518
+ raw = null;
519
+ }
520
+ }
521
+ if (raw !== null) {
522
+ mergeState(state, raw);
523
+ syncBaselines.set(statePath, {
524
+ mtimeMs,
525
+ size,
526
+ doc: text
527
+ });
528
+ }
326
529
  pruneUsage(state.usage);
327
530
  return statePath;
328
531
  }
532
+ /**
533
+ * Rename an unusable state document aside, pid-qualified like the atomic
534
+ * save temp: `$DSH_HOME` is shared by every host under it, so two hosts
535
+ * quarantining must not fight over one recovery name. A file that vanished
536
+ * between the failed read and this rename needs no recovery copy; any other
537
+ * rename failure propagates so the caller knows not to save defaults over a
538
+ * document it could neither read nor preserve.
539
+ */
540
+ async function quarantineStateFile(statePath, cause) {
541
+ try {
542
+ await rename(statePath, `${statePath}.corrupt-${process.pid}`);
543
+ } catch (error) {
544
+ if (error?.code === "ENOENT") return;
545
+ throw new Error(`state file unreadable and could not be quarantined (read: ${String(cause?.message ?? cause)}; rename: ${String(error?.message ?? error)})`, { cause: error });
546
+ }
547
+ }
329
548
  /** In-flight save per state path: concurrent saves queue instead of racing on
330
549
  * the rename order. Two writers renaming one temp file is the Windows
331
550
  * EPERM/EBUSY source; queuing also coalesces naturally, because each turn
@@ -344,25 +563,138 @@ function tempPathFor(target, pid = process.pid) {
344
563
  }
345
564
  /** Atomically persist the state document. Saves to the same path are
346
565
  * serialized: a caller awaits its own turn's completion, a failed turn never
347
- * poisons the queue behind it. */
566
+ * poisons the queue behind it. Before writing, another host's changes since
567
+ * this process last loaded or saved the file are merged back in (see
568
+ * `mergeExternalChanges`). */
348
569
  function saveStateFile(state, home = dshHome()) {
349
570
  const statePath = join(home, STATE_FILE);
350
571
  const turn = (saveQueues.get(statePath) ?? Promise.resolve()).catch(() => {}).then(async () => {
572
+ await mergeExternalChanges(state, statePath);
351
573
  await mkdir(dirname(statePath), { recursive: true });
574
+ const doc = JSON.stringify(state);
352
575
  const tmpPath = tempPathFor(statePath);
353
576
  try {
354
- await writeFile(tmpPath, JSON.stringify(state), "utf8");
577
+ await writeFile(tmpPath, doc, "utf8");
355
578
  await rename(tmpPath, statePath);
356
579
  } catch (error) {
357
580
  await rm(tmpPath, { force: true }).catch(() => {});
358
581
  throw error;
359
582
  }
583
+ const st = await stat(statePath).catch(() => null);
584
+ syncBaselines.set(statePath, st !== null ? {
585
+ mtimeMs: st.mtimeMs,
586
+ size: st.size,
587
+ doc
588
+ } : null);
360
589
  });
361
590
  saveQueues.set(statePath, turn);
362
591
  return turn.finally(() => {
363
592
  if (saveQueues.get(statePath) === turn) saveQueues.delete(statePath);
364
593
  });
365
594
  }
595
+ /** Per-path view of the on-disk document this process last saw: its stat
596
+ * identity and its serialized bytes. `$DSH_HOME` is shared by every dsh host
597
+ * under it (Web + Desktop), so a save must first notice whether another host
598
+ * wrote the file since. `null` marks "believed absent"; no entry at all marks
599
+ * "never loaded through this module", where a direct save keeps the plain
600
+ * last-writer-wins behavior. */
601
+ const syncBaselines = /* @__PURE__ */ new Map();
602
+ /**
603
+ * Fold another host's writes back in before this process saves over them.
604
+ *
605
+ * Each host holds the whole document in memory, so an unchecked save is
606
+ * last-writer-wins and silently discards the other host's usage folds and
607
+ * config edits. When the file's stat identity no longer matches what this
608
+ * process last wrote or loaded, the current bytes are re-read and three-way
609
+ * merged against the last-saved snapshot: sections this process has not
610
+ * touched adopt the external version, the usage ledger unions arithmetically
611
+ * (`theirs + ours − base` per counter — exact for two hosts that both
612
+ * started from `base`), and locally-dirty sections keep the local version.
613
+ *
614
+ * The stat fast path misses only a same-instant, same-length rewrite by
615
+ * another host. An unreadable or undecodable external document falls back to
616
+ * the plain overwrite — the boot-time quarantine remains the backstop for
617
+ * the destructive case.
618
+ */
619
+ async function mergeExternalChanges(state, statePath) {
620
+ const baseline = syncBaselines.get(statePath);
621
+ if (baseline === void 0) return;
622
+ const st = await stat(statePath).catch(() => null);
623
+ if (st === null) return;
624
+ if (baseline !== null && st.mtimeMs === baseline.mtimeMs && st.size === baseline.size) return;
625
+ const text = await readFile(statePath, "utf8").catch(() => null);
626
+ if (text === null) return;
627
+ let theirs;
628
+ try {
629
+ theirs = JSON.parse(text);
630
+ } catch {
631
+ return;
632
+ }
633
+ if (theirs === null || typeof theirs !== "object") return;
634
+ mergeThreeWay(state, baseline !== null ? safeParse(baseline.doc) : null, theirs);
635
+ }
636
+ function safeParse(text) {
637
+ try {
638
+ return JSON.parse(text);
639
+ } catch {
640
+ return null;
641
+ }
642
+ }
643
+ function sameJson(a, b) {
644
+ return JSON.stringify(a) === JSON.stringify(b);
645
+ }
646
+ function mergeThreeWay(state, base, theirs) {
647
+ const t = theirs;
648
+ const b = base ?? {};
649
+ if (sameJson(state.cfg, b.cfg)) state.cfg = normalizeCfg(t.cfg);
650
+ if (sameJson(state.folders, b.folders) && Array.isArray(t.folders)) state.folders = t.folders;
651
+ if (sameJson(state.prompts, b.prompts) && Array.isArray(t.prompts)) state.prompts = t.prompts.map(normalizePrompt).filter((item) => item !== null);
652
+ if (sameJson(state.stars, b.stars) && t.stars !== null && typeof t.stars === "object" && !Array.isArray(t.stars)) state.stars = t.stars;
653
+ if (sameJson(state.apiKey, b.apiKey) && typeof t.apiKey === "string") state.apiKey = t.apiKey;
654
+ state.usage = mergeUsageThreeWay(state.usage, base?.usage ?? {}, t.usage);
655
+ }
656
+ const USAGE_COUNTER_KEYS = [
657
+ "in",
658
+ "out",
659
+ "cacheIn",
660
+ "cacheW",
661
+ "reason",
662
+ "calls",
663
+ "peakIn",
664
+ "peakCacheIn",
665
+ "peakCacheW",
666
+ "peakOut"
667
+ ];
668
+ function counterOf(row, key) {
669
+ const value = row?.[key];
670
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
671
+ }
672
+ /** Union two hosts' ledgers given the snapshot both last saved. For every
673
+ * counter `theirs + ours − base` is exactly the combined progress when both
674
+ * hosts started from `base` (their session streams are disjoint: separate
675
+ * dsh profiles under one `$DSH_HOME`); clamped at zero so a tampered base
676
+ * cannot drive a row negative. */
677
+ function mergeUsageThreeWay(ours, base, theirsRaw) {
678
+ const theirs = theirsRaw !== null && typeof theirsRaw === "object" && !Array.isArray(theirsRaw) ? theirsRaw : {};
679
+ const merged = {};
680
+ for (const day of /* @__PURE__ */ new Set([...Object.keys(ours), ...Object.keys(theirs)])) {
681
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) continue;
682
+ const mergedDay = {};
683
+ for (const model of /* @__PURE__ */ new Set([...Object.keys(ours[day] ?? {}), ...Object.keys(theirs[day] ?? {})])) {
684
+ if (model === "__proto__" || model === "constructor" || model === "prototype") continue;
685
+ const om = ours[day]?.[model];
686
+ const tm = theirs[day]?.[model];
687
+ if (om === void 0 && tm === void 0) continue;
688
+ const row = createUsageRow();
689
+ for (const key of USAGE_COUNTER_KEYS) row[key] = Math.max(0, counterOf(tm, key) + counterOf(om, key) - counterOf(base[day]?.[model], key));
690
+ row.peakSplitKnown = !(om?.peakSplitKnown === false || tm?.peakSplitKnown === false);
691
+ mergedDay[model] = row;
692
+ }
693
+ if (Object.keys(mergedDay).length > 0) merged[day] = mergedDay;
694
+ }
695
+ pruneUsage(merged);
696
+ return merged;
697
+ }
366
698
  //#endregion
367
699
  //#region src/extract.ts
368
700
  /** Base64 encode bytes without relying on Buffer (browser-host parity). */
@@ -1029,6 +1361,18 @@ async function writeRecoveryBackup(path, state) {
1029
1361
  //#endregion
1030
1362
  //#region src/host-service.ts
1031
1363
  const USAGE_SCAN_CONCURRENCY = 4;
1364
+ /** CDN fallback version: the exact package this build ships. A hardcoded
1365
+ * `mermaid@11.6.0` while the local dependency resolved 11.17.x made the
1366
+ * offline and fallback engines diverge in behavior. */
1367
+ const MERMAID_CDN_VERSION = resolveMermaidVersion();
1368
+ function resolveMermaidVersion() {
1369
+ try {
1370
+ const require = createRequire(import.meta.url);
1371
+ const pkg = JSON.parse(readFileSync(require.resolve("mermaid/package.json"), "utf8"));
1372
+ if (typeof pkg.version === "string" && /^\d+\.\d+\.\d+/.test(pkg.version)) return pkg.version;
1373
+ } catch {}
1374
+ return "11.6.0";
1375
+ }
1032
1376
  async function mapConcurrent(items, limit, worker) {
1033
1377
  const results = new Array(items.length);
1034
1378
  let next = 0;
@@ -1043,7 +1387,7 @@ async function mapConcurrent(items, limit, worker) {
1043
1387
  return results;
1044
1388
  }
1045
1389
  /** Host capabilities behind the routes and the agent tool. */
1046
- var CustomPluginHost = class {
1390
+ var CustomPluginHost = class CustomPluginHost {
1047
1391
  sessionQuery;
1048
1392
  state;
1049
1393
  statePath;
@@ -1063,8 +1407,11 @@ var CustomPluginHost = class {
1063
1407
  mermaidBytesValue = 0;
1064
1408
  mermaidJs = "";
1065
1409
  mermaidSource = "";
1410
+ mermaidEtagValue = "";
1066
1411
  localMermaidPath;
1067
1412
  readCredential;
1413
+ credentialCache = null;
1414
+ static CREDENTIAL_CACHE_TTL_MS = 5e3;
1068
1415
  constructor(options) {
1069
1416
  this.sessionQuery = options.sessionQuery;
1070
1417
  this.state = options.state;
@@ -1186,8 +1533,15 @@ var CustomPluginHost = class {
1186
1533
  }
1187
1534
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
1188
1535
  async applyEdit(edit) {
1536
+ this.credentialCache = null;
1189
1537
  await this.runStateOperation(async () => {
1190
- const previous = JSON.parse(JSON.stringify(this.state));
1538
+ const previous = {
1539
+ cfg: this.state.cfg,
1540
+ folders: this.state.folders,
1541
+ prompts: this.state.prompts,
1542
+ stars: this.state.stars,
1543
+ apiKey: this.state.apiKey
1544
+ };
1191
1545
  try {
1192
1546
  await this.applyEditNow(edit);
1193
1547
  } catch (error) {
@@ -1201,9 +1555,17 @@ var CustomPluginHost = class {
1201
1555
  ...this.state.cfg,
1202
1556
  ...edit.cfg
1203
1557
  });
1204
- if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
1558
+ if (Array.isArray(edit.folders)) {
1559
+ const folders = normalizeFolders(edit.folders);
1560
+ if (folders === null) throw new Error("文件夹数据无效");
1561
+ this.state.folders = folders;
1562
+ }
1205
1563
  if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts.map(normalizePrompt).filter((item) => item !== null);
1206
- if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
1564
+ if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") {
1565
+ const stars = normalizeStars(edit.stars);
1566
+ if (stars === null) throw new Error("星标数据无效");
1567
+ this.state.stars = stars;
1568
+ }
1207
1569
  if (typeof edit.apiKey === "string") {
1208
1570
  const key = edit.apiKey.trim();
1209
1571
  if (key === "") {
@@ -1236,7 +1598,14 @@ var CustomPluginHost = class {
1236
1598
  ok: true,
1237
1599
  preview
1238
1600
  };
1239
- const previous = JSON.parse(JSON.stringify(this.state));
1601
+ const previous = {
1602
+ cfg: this.state.cfg,
1603
+ folders: this.state.folders,
1604
+ prompts: this.state.prompts,
1605
+ stars: this.state.stars,
1606
+ usage: this.state.usage,
1607
+ apiKey: this.state.apiKey
1608
+ };
1240
1609
  const recoveryPath = await writeRecoveryBackup(this.statePath(), previous);
1241
1610
  const next = importedState(previous, backup, mode);
1242
1611
  Object.assign(this.state, next);
@@ -1260,6 +1629,7 @@ var CustomPluginHost = class {
1260
1629
  }
1261
1630
  /** Move a legacy plaintext state key into the OS store when available. */
1262
1631
  async migrateLegacyApiKey() {
1632
+ this.credentialCache = null;
1263
1633
  const key = (this.state.apiKey ?? "").trim();
1264
1634
  if (!/^sk-/.test(key) || !this.credentialStore.available) return false;
1265
1635
  let existing = "";
@@ -1534,11 +1904,18 @@ var CustomPluginHost = class {
1534
1904
  }
1535
1905
  /** Browser-safe credential status used by state and save responses. */
1536
1906
  async credentialStatus() {
1907
+ const now = Date.now();
1908
+ if (this.credentialCache !== null && now - this.credentialCache.at < CustomPluginHost.CREDENTIAL_CACHE_TTL_MS) return this.credentialCache.status;
1537
1909
  const resolved = await this.resolveApiKeyWithSource();
1538
- return {
1910
+ const status = {
1539
1911
  apiKeyConfigured: resolved.key !== "",
1540
1912
  credentialStorage: resolved.source
1541
1913
  };
1914
+ this.credentialCache = {
1915
+ at: now,
1916
+ status
1917
+ };
1918
+ return status;
1542
1919
  }
1543
1920
  /** Query the DeepSeek balance endpoint (15s timeout). */
1544
1921
  async balanceGet() {
@@ -1616,6 +1993,11 @@ var CustomPluginHost = class {
1616
1993
  const agg = {};
1617
1994
  let scanned = 0;
1618
1995
  const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
1996
+ if (this.usageRevision !== revisionAtStart) return {
1997
+ readable: false,
1998
+ stale: true,
1999
+ usage: {}
2000
+ };
1619
2001
  try {
1620
2002
  return {
1621
2003
  readable: true,
@@ -1630,6 +2012,7 @@ var CustomPluginHost = class {
1630
2012
  });
1631
2013
  let failedSessions = 0;
1632
2014
  for (const entry of entries) {
2015
+ if (entry.stale === true) continue;
1633
2016
  if (!entry.readable) {
1634
2017
  failedSessions++;
1635
2018
  continue;
@@ -1686,29 +2069,31 @@ var CustomPluginHost = class {
1686
2069
  async mermaidFetchImpl() {
1687
2070
  const localPath = this.localMermaidPath();
1688
2071
  if (localPath !== null && localPath !== "") try {
1689
- const text = readFileSync(localPath, "utf8");
2072
+ const text = await readFile(localPath, "utf8");
1690
2073
  if (text.length > 0) {
1691
- this.mermaidJs = text;
1692
- this.mermaidBytesValue = text.length;
1693
- this.mermaidSource = "local";
2074
+ this.cacheMermaid(text, "local");
1694
2075
  return {
1695
2076
  ok: true,
1696
- bytes: text.length
2077
+ bytes: this.mermaidBytesValue
1697
2078
  };
1698
2079
  }
1699
2080
  } catch {}
1700
2081
  const urls = [
1701
- "https://cdn.jsdelivr.net/npm/mermaid@11.6.0/dist/mermaid.min.js",
1702
- "https://fastly.jsdelivr.net/npm/mermaid@11.6.0/dist/mermaid.min.js",
1703
- "https://unpkg.com/mermaid@11.6.0/dist/mermaid.min.js"
2082
+ `https://cdn.jsdelivr.net/npm/mermaid@${MERMAID_CDN_VERSION}/dist/mermaid.min.js`,
2083
+ `https://fastly.jsdelivr.net/npm/mermaid@${MERMAID_CDN_VERSION}/dist/mermaid.min.js`,
2084
+ `https://unpkg.com/mermaid@${MERMAID_CDN_VERSION}/dist/mermaid.min.js`
1704
2085
  ];
1705
2086
  let text = "";
1706
2087
  let lastError = "";
1707
2088
  for (const url of urls) try {
1708
2089
  const result = await this.httpText(url);
1709
2090
  if (result.ok) {
1710
- text = result.text;
1711
- break;
2091
+ if (looksLikeMermaidBundle(result.text)) {
2092
+ text = result.text;
2093
+ break;
2094
+ }
2095
+ lastError = `镜像返回了非脚本内容 (${result.text.length} bytes)`;
2096
+ continue;
1712
2097
  }
1713
2098
  lastError = result.error ?? "";
1714
2099
  } catch (error) {
@@ -1718,14 +2103,21 @@ var CustomPluginHost = class {
1718
2103
  ok: false,
1719
2104
  error: `无法获取 Mermaid 引擎: ${lastError}`
1720
2105
  };
1721
- this.mermaidJs = text;
1722
- this.mermaidBytesValue = text.length;
1723
- this.mermaidSource = "cdn";
2106
+ this.cacheMermaid(text, "cdn");
1724
2107
  return {
1725
2108
  ok: true,
1726
- bytes: text.length
2109
+ bytes: this.mermaidBytesValue
1727
2110
  };
1728
2111
  }
2112
+ /** Cache the engine and its validators. `bytes` is UTF-8 length, not the
2113
+ * JavaScript string length: the status/debug payloads call it bytes, and a
2114
+ * non-ASCII bundle would otherwise under-report the transfer size. */
2115
+ cacheMermaid(text, source) {
2116
+ this.mermaidJs = text;
2117
+ this.mermaidBytesValue = Buffer.byteLength(text, "utf8");
2118
+ this.mermaidSource = source;
2119
+ this.mermaidEtagValue = createHash("sha256").update(text).digest("hex").slice(0, 32);
2120
+ }
1729
2121
  /** The cached Mermaid engine script (served at the script path). */
1730
2122
  mermaidScript() {
1731
2123
  return this.mermaidJs;
@@ -1734,14 +2126,20 @@ var CustomPluginHost = class {
1734
2126
  mermaidBytes() {
1735
2127
  return this.mermaidBytesValue;
1736
2128
  }
2129
+ /** Cache validator for the engine script ('' while unloaded). */
2130
+ mermaidEtag() {
2131
+ return this.mermaidEtagValue;
2132
+ }
1737
2133
  /** Where the engine came from: 'local', 'cdn', or '' while unloaded. */
1738
2134
  mermaidLoadedSource() {
1739
2135
  return this.mermaidSource;
1740
2136
  }
1741
2137
  /** Whether any DeepSeek key source resolves (state, environment, credential
1742
- * file) — the honest answer behind the panel's "key configured" badge. */
2138
+ * file) — the honest answer behind the panel's "key configured" badge.
2139
+ * Goes through the 5s source cache: the status tool and About tab call this
2140
+ * independently of `/state`, and each miss hits the OS keychain plus a file. */
1743
2141
  async hasApiKey() {
1744
- return await this.resolveApiKey() !== "";
2142
+ return (await this.credentialStatus()).apiKeyConfigured;
1745
2143
  }
1746
2144
  /** Diagnostics snapshot for the status tool and the About tab. */
1747
2145
  async debugInfo() {
@@ -1835,6 +2233,14 @@ function readableFetchError(error) {
1835
2233
  const message = String(cause?.message ?? error?.message ?? error);
1836
2234
  return message === "fetch failed" ? "网络请求失败:请检查本机网络与代理配置" : message;
1837
2235
  }
2236
+ /** A 200 from a mirror is not proof of the engine: captive portals and
2237
+ * misconfigured mirrors happily serve an HTML interstitial with status 200.
2238
+ * The real bundle is a multi-megabyte script that never starts with a
2239
+ * document tag; anything else must not poison the host-lifetime cache. */
2240
+ function looksLikeMermaidBundle(text) {
2241
+ const head = text.slice(0, 64).replace(/^\uFEFF/, "").trimStart();
2242
+ return text.length >= 1e3 && !head.startsWith("<");
2243
+ }
1838
2244
  /** Resolve `mermaid/dist/mermaid.min.js` from the package's own dependency
1839
2245
  * tree (works for `link:` checkouts and registry installs alike); null when
1840
2246
  * the dependency is absent, which falls mermaidFetch back to the CDN. */
@@ -1894,7 +2300,7 @@ function isLoopbackRequest(request) {
1894
2300
  }
1895
2301
  //#endregion
1896
2302
  //#region src/routes.ts
1897
- const BODY_LIMIT = 256 * 1024;
2303
+ const STATE_BODY_LIMIT = 1024 * 1024;
1898
2304
  const TIMELINE_LIMIT = 64 * 1024;
1899
2305
  const BACKUP_REQUEST_LIMIT = 5308416;
1900
2306
  function json(res, status, body) {
@@ -1966,7 +2372,15 @@ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
1966
2372
  return;
1967
2373
  }
1968
2374
  try {
1969
- const body = await readBody(req, BODY_LIMIT);
2375
+ const rawBody = await readBody(req, STATE_BODY_LIMIT);
2376
+ if (rawBody === null || typeof rawBody !== "object" || Array.isArray(rawBody)) {
2377
+ json(res, 400, {
2378
+ ok: false,
2379
+ error: "状态请求结构无效"
2380
+ });
2381
+ return;
2382
+ }
2383
+ const body = rawBody;
1970
2384
  await host.applyEdit({
1971
2385
  cfg: body.cfg,
1972
2386
  folders: Array.isArray(body.folders) ? body.folders : void 0,
@@ -2156,7 +2570,15 @@ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
2156
2570
  if (!guard(req, res)) return;
2157
2571
  await ready;
2158
2572
  if (!isMethod(req, "GET", res)) return;
2159
- json(res, 200, await host.balanceGet());
2573
+ try {
2574
+ json(res, 200, await host.balanceGet());
2575
+ } catch (error) {
2576
+ json(res, 500, {
2577
+ ok: false,
2578
+ keyConfigured: false,
2579
+ error: String(error?.message ?? error)
2580
+ });
2581
+ }
2160
2582
  }
2161
2583
  },
2162
2584
  {
@@ -2166,8 +2588,15 @@ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
2166
2588
  if (!guard(req, res)) return;
2167
2589
  await ready;
2168
2590
  if (!isMethod(req, "POST", res)) return;
2169
- const result = await host.usageScan();
2170
- json(res, result.ok ? 200 : 500, result);
2591
+ try {
2592
+ const result = await host.usageScan();
2593
+ json(res, result.ok ? 200 : 500, result);
2594
+ } catch (error) {
2595
+ json(res, 500, {
2596
+ ok: false,
2597
+ error: String(error?.message ?? error)
2598
+ });
2599
+ }
2171
2600
  }
2172
2601
  },
2173
2602
  {
@@ -2176,8 +2605,15 @@ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
2176
2605
  handler: async (req, res) => {
2177
2606
  if (!guard(req, res)) return;
2178
2607
  if (!isMethod(req, "POST", res)) return;
2179
- const result = await host.mermaidFetch();
2180
- json(res, result.ok ? 200 : 502, result);
2608
+ try {
2609
+ const result = await host.mermaidFetch();
2610
+ json(res, result.ok ? 200 : 502, result);
2611
+ } catch (error) {
2612
+ json(res, 502, {
2613
+ ok: false,
2614
+ error: String(error?.message ?? error)
2615
+ });
2616
+ }
2181
2617
  }
2182
2618
  },
2183
2619
  {
@@ -2191,9 +2627,18 @@ function makeCustomPluginRoutes(host, ready = Promise.resolve()) {
2191
2627
  res.end("mermaid bundle not ready");
2192
2628
  return;
2193
2629
  }
2630
+ const etag = `"${host.mermaidEtag()}"`;
2631
+ res.setHeader("ETag", etag);
2632
+ res.setHeader("Cache-Control", "no-cache");
2633
+ const ifNoneMatch = req.headers["if-none-match"];
2634
+ if (typeof ifNoneMatch === "string" && ifNoneMatch.split(",").some((value) => value.trim() === etag)) {
2635
+ res.statusCode = 304;
2636
+ res.end();
2637
+ return;
2638
+ }
2194
2639
  res.statusCode = 200;
2195
2640
  res.setHeader("Content-Type", "text/javascript; charset=utf-8");
2196
- res.setHeader("Cache-Control", "no-store");
2641
+ res.setHeader("Content-Length", String(Buffer.byteLength(script, "utf8")));
2197
2642
  res.end(script);
2198
2643
  }
2199
2644
  },
@@ -2243,6 +2688,7 @@ function applyImpl(ctx) {
2243
2688
  const state = defaultState();
2244
2689
  let statePath = join(dshHome(), STATE_FILE);
2245
2690
  let stateLoaded = false;
2691
+ let stateWritable = true;
2246
2692
  const sessionModels = /* @__PURE__ */ new Map();
2247
2693
  const pendingUsage = [];
2248
2694
  const diagReports = [];
@@ -2253,6 +2699,7 @@ function applyImpl(ctx) {
2253
2699
  const saveSoon = (() => {
2254
2700
  let timer;
2255
2701
  return () => {
2702
+ if (!stateWritable) return;
2256
2703
  if (timer !== void 0) clearTimeout(timer);
2257
2704
  timer = setTimeout(() => {
2258
2705
  timer = void 0;
@@ -2266,7 +2713,7 @@ function applyImpl(ctx) {
2266
2713
  sessionQuery: ctx.sessionQuery,
2267
2714
  state,
2268
2715
  statePath: () => statePath,
2269
- saveNow: () => saveStateFile(state),
2716
+ saveNow: () => stateWritable ? saveStateFile(state) : Promise.resolve(),
2270
2717
  reportDiag,
2271
2718
  diagReports,
2272
2719
  attachments: ctx.get("attachments")
@@ -2275,12 +2722,17 @@ function applyImpl(ctx) {
2275
2722
  statePath = path;
2276
2723
  if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
2277
2724
  stateLoaded = true;
2278
- for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
2279
- return saveStateFile(state);
2725
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model ?? void 0);
2726
+ try {
2727
+ await saveStateFile(state);
2728
+ } catch (error) {
2729
+ reportDiag(`state save failed: ${String(error?.message ?? error)}`);
2730
+ }
2280
2731
  }).catch((error) => {
2281
- reportDiag(`state load failed: ${String(error?.message ?? error)}`);
2732
+ reportDiag(`state file unreadable, running read-only: ${String(error?.message ?? error)}`);
2733
+ stateWritable = false;
2282
2734
  stateLoaded = true;
2283
- for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
2735
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model ?? void 0);
2284
2736
  });
2285
2737
  ctx.on("session/event", (session, event) => {
2286
2738
  try {
@@ -2313,6 +2765,8 @@ function applyImpl(ctx) {
2313
2765
  for (const route of makeCustomPluginRoutes(host, stateReady)) routeDisposers.push(ctx.webServer.register(route));
2314
2766
  host.mermaidFetch().then((result) => {
2315
2767
  reportDiag(result.ok ? `mermaid engine ready (${result.bytes} bytes, ${host.mermaidLoadedSource()})` : `mermaid engine failed: ${result.error}`);
2768
+ }).catch((error) => {
2769
+ reportDiag(`mermaid preheat failed: ${String(error?.message ?? error)}`);
2316
2770
  });
2317
2771
  const disposeTool = ctx.tools.register(defineTool({
2318
2772
  name: "custom_plugin_status",