@alexpeng/dsh-custom-plugin 0.6.0 → 0.7.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
@@ -2,7 +2,7 @@ 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
7
  //#region src/dsh-home.ts
8
8
  /**
@@ -96,9 +96,6 @@ const DEFAULT_CONFIG = {
96
96
  glass: true,
97
97
  glassMode: "frost",
98
98
  globalGlass: true,
99
- timeline: true,
100
- timelineLeft: false,
101
- starsOnly: false,
102
99
  quote: true,
103
100
  antiScroll: false,
104
101
  mermaid: true,
@@ -286,6 +283,7 @@ function normalizeCfg(raw) {
286
283
  }
287
284
  cfg.monthlyBudgetCny = Math.max(0, cfg.monthlyBudgetCny ?? 0);
288
285
  cfg.budgetWarningPercent = Math.max(1, Math.min(100, cfg.budgetWarningPercent ?? 80));
286
+ if (cfg.bg === "aurora") cfg.bg = "default";
289
287
  return cfg;
290
288
  }
291
289
  /** Normalize one prompt while retaining its stable identity and order. */
@@ -314,20 +312,170 @@ function mergeState(target, raw) {
314
312
  if (typeof src.apiKey === "string") target.apiKey = src.apiKey;
315
313
  if (src.usage !== null && typeof src.usage === "object" && !Array.isArray(src.usage)) target.usage = src.usage;
316
314
  }
317
- /** Load and merge the persisted document into `state`. */
318
- async function loadStateFile(state, home = dshHome()) {
315
+ /** Rejection caps for browser-supplied documents. A shape beyond them is
316
+ * rejected outright — never truncated — because the client owns the whole
317
+ * document and a partial accept would silently drop the rest. The depth cap
318
+ * is what keeps a hostile edit from making `JSON.stringify` throw
319
+ * `RangeError` on every later save. */
320
+ const MAX_FOLDER_DEPTH = 32;
321
+ const MAX_FOLDER_NODES = 2e3;
322
+ const MAX_STAR_ENTRIES = 1e4;
323
+ function safeKeyPart(value) {
324
+ return value !== "__proto__" && value !== "constructor" && value !== "prototype";
325
+ }
326
+ /**
327
+ * Validate a folder tree from the browser against the persisted shape:
328
+ * unique non-empty ids, string name, and string-only id lists, bounded in
329
+ * depth and node count. Null on any violation — the caller rejects the edit.
330
+ */
331
+ function normalizeFolders(raw) {
332
+ if (!Array.isArray(raw)) return null;
333
+ const seen = /* @__PURE__ */ new Set();
334
+ let count = 0;
335
+ const walk = (node, depth) => {
336
+ if (node === null || typeof node !== "object") return null;
337
+ const src = node;
338
+ if (typeof src.id !== "string" || src.id === "" || seen.has(src.id)) return null;
339
+ if (typeof src.name !== "string") return null;
340
+ if (!Array.isArray(src.children) || !Array.isArray(src.sessionIds) || !Array.isArray(src.workspaceIds) || !Array.isArray(src.prompts)) return null;
341
+ const strings = (value) => value.every((item) => typeof item === "string") ? [...new Set(value)] : null;
342
+ const sessionIds = strings(src.sessionIds);
343
+ const workspaceIds = strings(src.workspaceIds);
344
+ const prompts = strings(src.prompts);
345
+ if (sessionIds === null || workspaceIds === null || prompts === null) return null;
346
+ if (depth >= MAX_FOLDER_DEPTH) return null;
347
+ if (++count > MAX_FOLDER_NODES) return null;
348
+ seen.add(src.id);
349
+ const children = [];
350
+ for (const child of src.children) {
351
+ const parsed = walk(child, depth + 1);
352
+ if (parsed === null) return null;
353
+ children.push(parsed);
354
+ }
355
+ return {
356
+ id: src.id,
357
+ name: src.name,
358
+ children,
359
+ sessionIds,
360
+ workspaceIds,
361
+ prompts
362
+ };
363
+ };
364
+ const out = [];
365
+ for (const node of raw) {
366
+ const parsed = walk(node, 0);
367
+ if (parsed === null) return null;
368
+ out.push(parsed);
369
+ }
370
+ return out;
371
+ }
372
+ /**
373
+ * Validate a star map from the browser: session ids as safe object keys,
374
+ * digit-string sequence keys, `true` values only, bounded total. Null on any
375
+ * violation.
376
+ */
377
+ function normalizeStars(raw) {
378
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
379
+ const out = {};
380
+ let total = 0;
381
+ for (const [sessionId, entries] of Object.entries(raw)) {
382
+ if (!safeKeyPart(sessionId)) return null;
383
+ if (entries === null || typeof entries !== "object" || Array.isArray(entries)) return null;
384
+ const clean = {};
385
+ for (const [seq, value] of Object.entries(entries)) {
386
+ if (value !== true || !/^\d+$/.test(seq)) return null;
387
+ if (++total > MAX_STAR_ENTRIES) return null;
388
+ clean[seq] = true;
389
+ }
390
+ out[sessionId] = clean;
391
+ }
392
+ return out;
393
+ }
394
+ /** Retry ladder for a transiently unreadable state file (AV scan, sync
395
+ * client, a sharing violation racing the Desktop host's rename). Same
396
+ * cadence as the browser half's load retries, so a slow-locking file heals
397
+ * inside the window the client is still retrying its first read. */
398
+ const LOAD_RETRY_DELAYS = [
399
+ 1500,
400
+ 3e3,
401
+ 6e3
402
+ ];
403
+ /**
404
+ * Load and merge the persisted document into `state`.
405
+ *
406
+ * A missing file (ENOENT) is a fresh install and resolves with defaults. A
407
+ * corrupt or permanently unreadable file is renamed aside before defaults
408
+ * are adopted, so the caller's immediate save cannot destroy the previous
409
+ * bytes. Only when the file is unreadable AND cannot be moved aside does
410
+ * this reject — the caller must then suppress saves, because persisting
411
+ * never-loaded defaults would clobber a document that may be intact.
412
+ */
413
+ async function loadStateFile(state, home = dshHome(), retryDelays = LOAD_RETRY_DELAYS) {
319
414
  const statePath = join(home, STATE_FILE);
320
- let raw = null;
415
+ let text;
416
+ let mtimeMs = 0;
417
+ let size = 0;
418
+ for (let attempt = 0;; attempt++) try {
419
+ const handle = await open(statePath, "r");
420
+ try {
421
+ const st = await handle.stat();
422
+ text = await handle.readFile("utf8");
423
+ mtimeMs = st.mtimeMs;
424
+ size = st.size;
425
+ } finally {
426
+ await handle.close();
427
+ }
428
+ break;
429
+ } catch (error) {
430
+ if (error?.code === "ENOENT") {
431
+ syncBaselines.set(statePath, null);
432
+ return statePath;
433
+ }
434
+ if (attempt < retryDelays.length) {
435
+ await new Promise((resolve) => {
436
+ setTimeout(resolve, retryDelays[attempt]);
437
+ });
438
+ continue;
439
+ }
440
+ await quarantineStateFile(statePath, error);
441
+ syncBaselines.set(statePath, null);
442
+ return statePath;
443
+ }
444
+ let raw;
321
445
  try {
322
- const text = await readFile(statePath, "utf8");
323
446
  raw = JSON.parse(text);
324
- } catch {
447
+ } catch (error) {
448
+ await quarantineStateFile(statePath, error);
449
+ syncBaselines.set(statePath, null);
325
450
  raw = null;
326
451
  }
327
- if (raw !== null) mergeState(state, raw);
452
+ if (raw !== null) {
453
+ mergeState(state, raw);
454
+ syncBaselines.set(statePath, {
455
+ mtimeMs,
456
+ size,
457
+ doc: text
458
+ });
459
+ }
328
460
  pruneUsage(state.usage);
329
461
  return statePath;
330
462
  }
463
+ /**
464
+ * Rename an unusable state document aside, pid-qualified like the atomic
465
+ * save temp: `$DSH_HOME` is shared by every host under it, so two hosts
466
+ * quarantining must not fight over one recovery name. A file that vanished
467
+ * between the failed read and this rename needs no recovery copy; any other
468
+ * rename failure propagates so the caller knows not to save defaults over a
469
+ * document it could neither read nor preserve.
470
+ */
471
+ async function quarantineStateFile(statePath, cause) {
472
+ try {
473
+ await rename(statePath, `${statePath}.corrupt-${process.pid}`);
474
+ } catch (error) {
475
+ if (error?.code === "ENOENT") return;
476
+ throw new Error(`state file unreadable and could not be quarantined (read: ${String(cause?.message ?? cause)}; rename: ${String(error?.message ?? error)})`, { cause: error });
477
+ }
478
+ }
331
479
  /** In-flight save per state path: concurrent saves queue instead of racing on
332
480
  * the rename order. Two writers renaming one temp file is the Windows
333
481
  * EPERM/EBUSY source; queuing also coalesces naturally, because each turn
@@ -346,25 +494,136 @@ function tempPathFor(target, pid = process.pid) {
346
494
  }
347
495
  /** Atomically persist the state document. Saves to the same path are
348
496
  * serialized: a caller awaits its own turn's completion, a failed turn never
349
- * poisons the queue behind it. */
497
+ * poisons the queue behind it. Before writing, another host's changes since
498
+ * this process last loaded or saved the file are merged back in (see
499
+ * `mergeExternalChanges`). */
350
500
  function saveStateFile(state, home = dshHome()) {
351
501
  const statePath = join(home, STATE_FILE);
352
502
  const turn = (saveQueues.get(statePath) ?? Promise.resolve()).catch(() => {}).then(async () => {
503
+ await mergeExternalChanges(state, statePath);
353
504
  await mkdir(dirname(statePath), { recursive: true });
505
+ const doc = JSON.stringify(state);
354
506
  const tmpPath = tempPathFor(statePath);
355
507
  try {
356
- await writeFile(tmpPath, JSON.stringify(state), "utf8");
508
+ await writeFile(tmpPath, doc, "utf8");
357
509
  await rename(tmpPath, statePath);
358
510
  } catch (error) {
359
511
  await rm(tmpPath, { force: true }).catch(() => {});
360
512
  throw error;
361
513
  }
514
+ const st = await stat(statePath).catch(() => null);
515
+ syncBaselines.set(statePath, st !== null ? {
516
+ mtimeMs: st.mtimeMs,
517
+ size: st.size,
518
+ doc
519
+ } : null);
362
520
  });
363
521
  saveQueues.set(statePath, turn);
364
522
  return turn.finally(() => {
365
523
  if (saveQueues.get(statePath) === turn) saveQueues.delete(statePath);
366
524
  });
367
525
  }
526
+ /** Per-path view of the on-disk document this process last saw: its stat
527
+ * identity and its serialized bytes. `$DSH_HOME` is shared by every dsh host
528
+ * under it (Web + Desktop), so a save must first notice whether another host
529
+ * wrote the file since. `null` marks "believed absent"; no entry at all marks
530
+ * "never loaded through this module", where a direct save keeps the plain
531
+ * last-writer-wins behavior. */
532
+ const syncBaselines = /* @__PURE__ */ new Map();
533
+ /**
534
+ * Fold another host's writes back in before this process saves over them.
535
+ *
536
+ * Each host holds the whole document in memory, so an unchecked save is
537
+ * last-writer-wins and silently discards the other host's usage folds and
538
+ * config edits. When the file's stat identity no longer matches what this
539
+ * process last wrote or loaded, the current bytes are re-read and three-way
540
+ * merged against the last-saved snapshot: sections this process has not
541
+ * touched adopt the external version, the usage ledger unions arithmetically
542
+ * (`theirs + ours − base` per counter — exact for two hosts that both
543
+ * started from `base`), and locally-dirty sections keep the local version.
544
+ *
545
+ * The stat fast path misses only a same-instant, same-length rewrite by
546
+ * another host. An unreadable or undecodable external document falls back to
547
+ * the plain overwrite — the boot-time quarantine remains the backstop for
548
+ * the destructive case.
549
+ */
550
+ async function mergeExternalChanges(state, statePath) {
551
+ const baseline = syncBaselines.get(statePath);
552
+ if (baseline === void 0) return;
553
+ const st = await stat(statePath).catch(() => null);
554
+ if (st === null) return;
555
+ if (baseline !== null && st.mtimeMs === baseline.mtimeMs && st.size === baseline.size) return;
556
+ const text = await readFile(statePath, "utf8").catch(() => null);
557
+ if (text === null) return;
558
+ let theirs;
559
+ try {
560
+ theirs = JSON.parse(text);
561
+ } catch {
562
+ return;
563
+ }
564
+ if (theirs === null || typeof theirs !== "object") return;
565
+ mergeThreeWay(state, baseline !== null ? safeParse(baseline.doc) : null, theirs);
566
+ }
567
+ function safeParse(text) {
568
+ try {
569
+ return JSON.parse(text);
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+ function sameJson(a, b) {
575
+ return JSON.stringify(a) === JSON.stringify(b);
576
+ }
577
+ function mergeThreeWay(state, base, theirs) {
578
+ const t = theirs;
579
+ const b = base ?? {};
580
+ if (sameJson(state.cfg, b.cfg)) state.cfg = normalizeCfg(t.cfg);
581
+ if (sameJson(state.folders, b.folders) && Array.isArray(t.folders)) state.folders = t.folders;
582
+ if (sameJson(state.prompts, b.prompts) && Array.isArray(t.prompts)) state.prompts = t.prompts.map(normalizePrompt).filter((item) => item !== null);
583
+ if (sameJson(state.stars, b.stars) && t.stars !== null && typeof t.stars === "object" && !Array.isArray(t.stars)) state.stars = t.stars;
584
+ if (sameJson(state.apiKey, b.apiKey) && typeof t.apiKey === "string") state.apiKey = t.apiKey;
585
+ state.usage = mergeUsageThreeWay(state.usage, base?.usage ?? {}, t.usage);
586
+ }
587
+ const USAGE_COUNTER_KEYS = [
588
+ "in",
589
+ "out",
590
+ "cacheIn",
591
+ "cacheW",
592
+ "reason",
593
+ "calls",
594
+ "peakIn",
595
+ "peakCacheIn",
596
+ "peakCacheW",
597
+ "peakOut"
598
+ ];
599
+ function counterOf(row, key) {
600
+ const value = row?.[key];
601
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
602
+ }
603
+ /** Union two hosts' ledgers given the snapshot both last saved. For every
604
+ * counter `theirs + ours − base` is exactly the combined progress when both
605
+ * hosts started from `base` (their session streams are disjoint: separate
606
+ * dsh profiles under one `$DSH_HOME`); clamped at zero so a tampered base
607
+ * cannot drive a row negative. */
608
+ function mergeUsageThreeWay(ours, base, theirsRaw) {
609
+ const theirs = theirsRaw !== null && typeof theirsRaw === "object" && !Array.isArray(theirsRaw) ? theirsRaw : {};
610
+ const merged = {};
611
+ for (const day of /* @__PURE__ */ new Set([...Object.keys(ours), ...Object.keys(theirs)])) {
612
+ const mergedDay = {};
613
+ for (const model of /* @__PURE__ */ new Set([...Object.keys(ours[day] ?? {}), ...Object.keys(theirs[day] ?? {})])) {
614
+ const om = ours[day]?.[model];
615
+ const tm = theirs[day]?.[model];
616
+ if (om === void 0 && tm === void 0) continue;
617
+ const row = createUsageRow();
618
+ for (const key of USAGE_COUNTER_KEYS) row[key] = Math.max(0, counterOf(tm, key) + counterOf(om, key) - counterOf(base[day]?.[model], key));
619
+ row.peakSplitKnown = !(om?.peakSplitKnown === false || tm?.peakSplitKnown === false);
620
+ mergedDay[model] = row;
621
+ }
622
+ if (Object.keys(mergedDay).length > 0) merged[day] = mergedDay;
623
+ }
624
+ pruneUsage(merged);
625
+ return merged;
626
+ }
368
627
  //#endregion
369
628
  //#region src/extract.ts
370
629
  /** Base64 encode bytes without relying on Buffer (browser-host parity). */
@@ -1045,7 +1304,7 @@ async function mapConcurrent(items, limit, worker) {
1045
1304
  return results;
1046
1305
  }
1047
1306
  /** Host capabilities behind the routes and the agent tool. */
1048
- var CustomPluginHost = class {
1307
+ var CustomPluginHost = class CustomPluginHost {
1049
1308
  sessionQuery;
1050
1309
  state;
1051
1310
  statePath;
@@ -1067,6 +1326,8 @@ var CustomPluginHost = class {
1067
1326
  mermaidSource = "";
1068
1327
  localMermaidPath;
1069
1328
  readCredential;
1329
+ credentialCache = null;
1330
+ static CREDENTIAL_CACHE_TTL_MS = 5e3;
1070
1331
  constructor(options) {
1071
1332
  this.sessionQuery = options.sessionQuery;
1072
1333
  this.state = options.state;
@@ -1188,6 +1449,7 @@ var CustomPluginHost = class {
1188
1449
  }
1189
1450
  /** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
1190
1451
  async applyEdit(edit) {
1452
+ this.credentialCache = null;
1191
1453
  await this.runStateOperation(async () => {
1192
1454
  const previous = JSON.parse(JSON.stringify(this.state));
1193
1455
  try {
@@ -1203,9 +1465,17 @@ var CustomPluginHost = class {
1203
1465
  ...this.state.cfg,
1204
1466
  ...edit.cfg
1205
1467
  });
1206
- if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
1468
+ if (Array.isArray(edit.folders)) {
1469
+ const folders = normalizeFolders(edit.folders);
1470
+ if (folders === null) throw new Error("文件夹数据无效");
1471
+ this.state.folders = folders;
1472
+ }
1207
1473
  if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts.map(normalizePrompt).filter((item) => item !== null);
1208
- if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
1474
+ if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") {
1475
+ const stars = normalizeStars(edit.stars);
1476
+ if (stars === null) throw new Error("星标数据无效");
1477
+ this.state.stars = stars;
1478
+ }
1209
1479
  if (typeof edit.apiKey === "string") {
1210
1480
  const key = edit.apiKey.trim();
1211
1481
  if (key === "") {
@@ -1262,6 +1532,7 @@ var CustomPluginHost = class {
1262
1532
  }
1263
1533
  /** Move a legacy plaintext state key into the OS store when available. */
1264
1534
  async migrateLegacyApiKey() {
1535
+ this.credentialCache = null;
1265
1536
  const key = (this.state.apiKey ?? "").trim();
1266
1537
  if (!/^sk-/.test(key) || !this.credentialStore.available) return false;
1267
1538
  let existing = "";
@@ -1536,11 +1807,18 @@ var CustomPluginHost = class {
1536
1807
  }
1537
1808
  /** Browser-safe credential status used by state and save responses. */
1538
1809
  async credentialStatus() {
1810
+ const now = Date.now();
1811
+ if (this.credentialCache !== null && now - this.credentialCache.at < CustomPluginHost.CREDENTIAL_CACHE_TTL_MS) return this.credentialCache.status;
1539
1812
  const resolved = await this.resolveApiKeyWithSource();
1540
- return {
1813
+ const status = {
1541
1814
  apiKeyConfigured: resolved.key !== "",
1542
1815
  credentialStorage: resolved.source
1543
1816
  };
1817
+ this.credentialCache = {
1818
+ at: now,
1819
+ status
1820
+ };
1821
+ return status;
1544
1822
  }
1545
1823
  /** Query the DeepSeek balance endpoint (15s timeout). */
1546
1824
  async balanceGet() {
@@ -1618,6 +1896,11 @@ var CustomPluginHost = class {
1618
1896
  const agg = {};
1619
1897
  let scanned = 0;
1620
1898
  const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
1899
+ if (this.usageRevision !== revisionAtStart) return {
1900
+ readable: false,
1901
+ stale: true,
1902
+ usage: {}
1903
+ };
1621
1904
  try {
1622
1905
  return {
1623
1906
  readable: true,
@@ -1632,6 +1915,7 @@ var CustomPluginHost = class {
1632
1915
  });
1633
1916
  let failedSessions = 0;
1634
1917
  for (const entry of entries) {
1918
+ if (entry.stale === true) continue;
1635
1919
  if (!entry.readable) {
1636
1920
  failedSessions++;
1637
1921
  continue;
@@ -1709,8 +1993,12 @@ var CustomPluginHost = class {
1709
1993
  for (const url of urls) try {
1710
1994
  const result = await this.httpText(url);
1711
1995
  if (result.ok) {
1712
- text = result.text;
1713
- break;
1996
+ if (looksLikeMermaidBundle(result.text)) {
1997
+ text = result.text;
1998
+ break;
1999
+ }
2000
+ lastError = `镜像返回了非脚本内容 (${result.text.length} bytes)`;
2001
+ continue;
1714
2002
  }
1715
2003
  lastError = result.error ?? "";
1716
2004
  } catch (error) {
@@ -1815,11 +2103,36 @@ var CustomPluginHost = class {
1815
2103
  } catch (error) {
1816
2104
  return {
1817
2105
  ok: false,
1818
- error: String(error?.message ?? error)
2106
+ error: readableFetchError(error)
1819
2107
  };
1820
2108
  }
1821
2109
  }
1822
2110
  };
2111
+ /**
2112
+ * Translate a Node `fetch` connection-level failure into a message a user can
2113
+ * act on. Node reports "fetch failed" with the real reason in `error.cause`
2114
+ * (e.g. `SELF_SIGNED_CERT_IN_CHAIN` — a local TLS-intercepting proxy or
2115
+ * security suite, which makes outbound calls fail *intermittently* whenever
2116
+ * the interceptor takes the connection), and passing the bare TypeError
2117
+ * through once read as a mysterious network that "sometimes does not exist".
2118
+ */
2119
+ function readableFetchError(error) {
2120
+ const cause = error?.cause;
2121
+ const code = cause?.code ?? "";
2122
+ if (code === "SELF_SIGNED_CERT_IN_CHAIN" || code === "DEPTH_ZERO_SELF_SIGNED_CERT" || code === "UNABLE_TO_GET_ISSUER_CERT_LOCALLY" || code === "UNABLE_TO_VERIFY_LEAF_SIGNATURE") return "TLS 证书校验失败:本机代理或安全软件可能正在解密 HTTPS——请对 api.deepseek.com 放行直连,或将该软件的根证书装入系统信任";
2123
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "DNS 解析失败:请检查本机网络与代理配置";
2124
+ if (code === "ETIMEDOUT" || code === "ECONNRESET" || code === "ECONNREFUSED" || code === "EHOSTUNREACH" || code === "ENETUNREACH") return `连接失败(${code}):请检查本机网络与代理配置`;
2125
+ const message = String(cause?.message ?? error?.message ?? error);
2126
+ return message === "fetch failed" ? "网络请求失败:请检查本机网络与代理配置" : message;
2127
+ }
2128
+ /** A 200 from a mirror is not proof of the engine: captive portals and
2129
+ * misconfigured mirrors happily serve an HTML interstitial with status 200.
2130
+ * The real bundle is a multi-megabyte script that never starts with a
2131
+ * document tag; anything else must not poison the host-lifetime cache. */
2132
+ function looksLikeMermaidBundle(text) {
2133
+ const head = text.slice(0, 64).replace(/^\uFEFF/, "").trimStart();
2134
+ return text.length >= 1e3 && !head.startsWith("<");
2135
+ }
1823
2136
  /** Resolve `mermaid/dist/mermaid.min.js` from the package's own dependency
1824
2137
  * tree (works for `link:` checkouts and registry installs alike); null when
1825
2138
  * the dependency is absent, which falls mermaidFetch back to the CDN. */
@@ -1851,9 +2164,11 @@ function isLoopbackHostname(hostname) {
1851
2164
  return isIPv4Loopback(hostname);
1852
2165
  }
1853
2166
  /**
1854
- * Request-level trust fence: a loopback socket address AND a loopback Host
1855
- * header, plus browser same-origin markers. The socket address is
1856
- * authoritative; X-Forwarded-For is never trusted.
2167
+ * Request-level trust fence, mirroring the platform fence's semantics: a
2168
+ * loopback socket address AND a loopback Host header, non-`cross-site` fetch
2169
+ * marker, and an Origin that is absent (trusted — the dsh Desktop forward
2170
+ * shape) or matches the Host authority. The socket address is authoritative;
2171
+ * X-Forwarded-For is never trusted.
1857
2172
  */
1858
2173
  function isLoopbackRequest(request) {
1859
2174
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
@@ -1887,11 +2202,18 @@ function json(res, status, body) {
1887
2202
  });
1888
2203
  res.end(JSON.stringify(body));
1889
2204
  }
1890
- function browserSameOriginMarker(req) {
1891
- return req.headers["sec-fetch-site"] === "same-origin" || typeof req.headers.origin === "string";
1892
- }
2205
+ /**
2206
+ * The request fence. Trust is decided by `isLoopbackRequest` alone: a loopback
2207
+ * socket with a loopback Host, a non-`cross-site` fetch marker, and an Origin
2208
+ * that is absent or matches the Host authority. Absent markers are *accepted*
2209
+ * — that is the exact header shape dsh Desktop's shell produces when it
2210
+ * forwards renderer requests to its own Host (it deletes `host`, `origin`,
2211
+ * `sec-fetch-site` and `cookie` first), and the same shape the platform fence
2212
+ * treats as trusted. A foreign origin, a cross-site marker, or a non-loopback
2213
+ * peer is rejected.
2214
+ */
1893
2215
  function guard(req, res) {
1894
- if (browserSameOriginMarker(req) && isLoopbackRequest(req)) return true;
2216
+ if (isLoopbackRequest(req)) return true;
1895
2217
  json(res, 403, {
1896
2218
  ok: false,
1897
2219
  error: "forbidden"
@@ -2219,6 +2541,7 @@ function applyImpl(ctx) {
2219
2541
  const state = defaultState();
2220
2542
  let statePath = join(dshHome(), STATE_FILE);
2221
2543
  let stateLoaded = false;
2544
+ let stateWritable = true;
2222
2545
  const sessionModels = /* @__PURE__ */ new Map();
2223
2546
  const pendingUsage = [];
2224
2547
  const diagReports = [];
@@ -2229,6 +2552,7 @@ function applyImpl(ctx) {
2229
2552
  const saveSoon = (() => {
2230
2553
  let timer;
2231
2554
  return () => {
2555
+ if (!stateWritable) return;
2232
2556
  if (timer !== void 0) clearTimeout(timer);
2233
2557
  timer = setTimeout(() => {
2234
2558
  timer = void 0;
@@ -2242,7 +2566,7 @@ function applyImpl(ctx) {
2242
2566
  sessionQuery: ctx.sessionQuery,
2243
2567
  state,
2244
2568
  statePath: () => statePath,
2245
- saveNow: () => saveStateFile(state),
2569
+ saveNow: () => stateWritable ? saveStateFile(state) : Promise.resolve(),
2246
2570
  reportDiag,
2247
2571
  diagReports,
2248
2572
  attachments: ctx.get("attachments")
@@ -2251,12 +2575,17 @@ function applyImpl(ctx) {
2251
2575
  statePath = path;
2252
2576
  if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
2253
2577
  stateLoaded = true;
2254
- for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
2255
- return saveStateFile(state);
2578
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model ?? void 0);
2579
+ try {
2580
+ await saveStateFile(state);
2581
+ } catch (error) {
2582
+ reportDiag(`state save failed: ${String(error?.message ?? error)}`);
2583
+ }
2256
2584
  }).catch((error) => {
2257
- reportDiag(`state load failed: ${String(error?.message ?? error)}`);
2585
+ reportDiag(`state file unreadable, running read-only: ${String(error?.message ?? error)}`);
2586
+ stateWritable = false;
2258
2587
  stateLoaded = true;
2259
- for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model);
2588
+ for (const item of pendingUsage.splice(0)) host.foldUsage(item.sessionId, item.usage, item.time, item.model ?? void 0);
2260
2589
  });
2261
2590
  ctx.on("session/event", (session, event) => {
2262
2591
  try {
@@ -2289,6 +2618,8 @@ function applyImpl(ctx) {
2289
2618
  for (const route of makeCustomPluginRoutes(host, stateReady)) routeDisposers.push(ctx.webServer.register(route));
2290
2619
  host.mermaidFetch().then((result) => {
2291
2620
  reportDiag(result.ok ? `mermaid engine ready (${result.bytes} bytes, ${host.mermaidLoadedSource()})` : `mermaid engine failed: ${result.error}`);
2621
+ }).catch((error) => {
2622
+ reportDiag(`mermaid preheat failed: ${String(error?.message ?? error)}`);
2292
2623
  });
2293
2624
  const disposeTool = ctx.tools.register(defineTool({
2294
2625
  name: "custom_plugin_status",
@@ -5,7 +5,7 @@
5
5
  * listener set; components re-render on `setS`. The file ports the earlier
6
6
  * dynamic-plugin implementation: React is a platform import, static styles
7
7
  * are injected through one owned style element (styles.ts), dynamic body
8
- * styles (background / aurora / global glass) extend it, and host calls go
8
+ * styles (background / global glass) extend it, and host calls go
9
9
  * over `/api/custom-plugin` fetch routes.
10
10
  * @module @alexpeng/dsh-custom-plugin/client/custom
11
11
  */
@@ -58,10 +58,6 @@ interface TurnLocationLike {
58
58
  interface SessionScopedProps {
59
59
  readonly sessionId?: string | null;
60
60
  }
61
- /** Palette of 20 muted low-saturation backgrounds (with matching tab colors).
62
- * 天青灰 leads the list: it is the install default and renders first among
63
- * the palette swatches, right after 无颜色 / 极光. */
64
- export declare const PALETTE: Array<[string, string, string]>;
65
61
  /** Public component props (the product slot system injects these). */
66
62
  export interface OverlayProps {
67
63
  useSessions: SnapshotSelectorHook<SessionListLike>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Background palette and the dark-mode derivation shared by the appearance
3
+ * panel and the body/token painting.
4
+ *
5
+ * The 20 families are tuned as light pastels. Dark mode reuses the same hue
6
+ * family instead of disabling them: {@link toDarkRamp} keeps hue and
7
+ * saturation and drops lightness onto a dark-ramp target, so 雾蓝 reads as a
8
+ * dark blue-gray, 裸桃 as a warm dark gray, and so on — the canvas stays
9
+ * readable while the palette's character survives.
10
+ * @module @alexpeng/dsh-custom-plugin/client/palette
11
+ */
12
+ /** Palette of 20 muted low-saturation backgrounds (with matching tab colors).
13
+ * 天青灰 leads the list: it is the install default and renders first among
14
+ * the palette swatches, right after 无颜色. */
15
+ export declare const PALETTE: Array<[string, string, string]>;
16
+ /** Parse a #rrggbb (or bare rrggbb) hex color; malformed input yields the
17
+ * palette's neutral gray rather than throwing. */
18
+ export declare function hexToRgb(hex: string): [number, number, number];
19
+ /**
20
+ * Map a palette color onto the dark ramp: hue is kept, saturation is
21
+ * compressed by {@link DARK_SATURATION_SCALE}, and lightness is clamped to
22
+ * `lightness`. The compression is not optional polish: HSL saturation at dark
23
+ * lightness reads far stronger for warm hues (gold / rose / peach) than for
24
+ * blue-grays on a dark canvas, so the raw values made most families glare.
25
+ * Invalid input degrades to a neutral gray at the same lightness.
26
+ */
27
+ export declare function toDarkRamp(hex: string, lightness: number): string;
28
+ /** Body-canvas lightness for the dark variant of a palette family. */
29
+ export declare const DARK_CANVAS_LIGHTNESS = 0.12;
30
+ /** How much of a family's HSL saturation survives on the dark ramp. 0.55
31
+ * keeps the families clearly distinguishable while pulling the warm hues
32
+ * (gold / rose / peach) down from "eye-catching" to "ambient" on the dark
33
+ * canvas; 0.4 turned them into mud, 0.7 still glared. */
34
+ export declare const DARK_SATURATION_SCALE = 0.55;