@alexpeng/dsh-custom-plugin 0.9.3 → 0.10.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +1687 -866
  2. package/NOTICE +71 -0
  3. package/README.i18n.yaml +7 -7
  4. package/README.md +344 -335
  5. package/README.zh.md +309 -302
  6. package/lib/client.js +9458 -2063
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +233 -99
  9. package/lib/types/balance.d.ts +44 -0
  10. package/lib/types/client/api.d.ts +13 -8
  11. package/lib/types/client/bg-ascii.d.ts +397 -0
  12. package/lib/types/client/bg-field.d.ts +60 -0
  13. package/lib/types/client/bg-focus.d.ts +63 -0
  14. package/lib/types/client/bg-layer.d.ts +152 -0
  15. package/lib/types/client/bg-ocean.d.ts +31 -0
  16. package/lib/types/client/bg-params.d.ts +142 -0
  17. package/lib/types/client/bg-pointer.d.ts +107 -0
  18. package/lib/types/client/bg-shader.d.ts +329 -0
  19. package/lib/types/client/bg-wake.d.ts +57 -0
  20. package/lib/types/client/custom.d.ts +4 -1
  21. package/lib/types/client/index.d.ts +1 -1
  22. package/lib/types/client/palette.d.ts +100 -0
  23. package/lib/types/client/panel-bounds.d.ts +65 -0
  24. package/lib/types/client/styles.d.ts +9 -4
  25. package/lib/types/client/ui/anchor.d.ts +55 -0
  26. package/lib/types/client/ui/appearance-controls.d.ts +24 -0
  27. package/lib/types/client/ui/command-model.d.ts +28 -0
  28. package/lib/types/client/ui/folders-model.d.ts +31 -0
  29. package/lib/types/client/ui/index-bridge.d.ts +6 -0
  30. package/lib/types/client/ui/overlays.d.ts +66 -0
  31. package/lib/types/client/ui/primitives.d.ts +93 -0
  32. package/lib/types/client/ui/prompt-model.d.ts +37 -0
  33. package/lib/types/host-service.d.ts +68 -15
  34. package/lib/types/pricing.d.ts +8 -4
  35. package/lib/types/protocol.d.ts +48 -2
  36. package/lib/types/usage.d.ts +8 -4
  37. package/locale/en.json +1 -1
  38. package/locale/zh.json +1 -1
  39. package/package.json +106 -105
package/lib/index.js CHANGED
@@ -90,14 +90,34 @@ function mountOnce(packageName, fn) {
90
90
  const CUSTOM_PLUGIN_API_PREFIX = "/api/custom-plugin";
91
91
  /** Path the host serves the fetched Mermaid engine at (script src). */
92
92
  const MERMAID_SCRIPT_PATH = "/custom-plugin/mermaid.js";
93
+ /** ASCII preset ids; keep in sync with `ASCII_PRESETS` in `client/bg-ascii.ts`. */
94
+ const BG_FX_ASCII_PRESETS = [
95
+ "flow",
96
+ "rain",
97
+ "ocean",
98
+ "starfield",
99
+ "ripple",
100
+ "static"
101
+ ];
102
+ /** Shader style ids; keep in sync with `SHADER_STYLES` in `client/bg-shader.ts`. */
103
+ const BG_FX_SHADER_STYLES = ["liquid", "grain"];
93
104
  /** Default configuration (also the composition-layer default). */
94
105
  const DEFAULT_CONFIG = {
95
106
  bg: "天青灰",
107
+ bgFx: "none",
108
+ bgFxPreset: "flow",
109
+ bgStrength: "standard",
110
+ bgDensity: -1,
111
+ bgSpeed: -1,
112
+ bgFps: -1,
113
+ bgFontPx: -1,
114
+ bgOpacity: -1,
115
+ bgIntensity: -1,
116
+ bgFocus: true,
96
117
  weather: "none",
97
118
  glass: true,
98
119
  glassMode: "frost",
99
120
  globalGlass: true,
100
- quote: true,
101
121
  antiScroll: false,
102
122
  mermaid: true,
103
123
  formula: true,
@@ -209,11 +229,38 @@ function dayKey(time) {
209
229
  return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
210
230
  }
211
231
  /** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
212
- * 14:00-18:00; all weekend hours are off-peak. Evaluated on China Standard
213
- * Time so the split matches the published schedule on any host timezone. */
232
+ * 14:00-18:00, excluding Chinese statutory holidays; all weekend hours and
233
+ * holidays are off-peak. Evaluated on China Standard Time so the split matches
234
+ * the published schedule on any host timezone. */
214
235
  function isPeakHour(time) {
215
236
  const { hour, weekday } = cstParts(time);
216
- return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18);
237
+ return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18) && !isStatutoryHoliday(time);
238
+ }
239
+ /** Chinese statutory holiday ranges (inclusive), checked 2026-11-14 against
240
+ * the State Council notices: 2026 (published 2025-11-04) and 2027 (published
241
+ * 2026-11-05). Weekends are already off-peak; these ranges add the weekday
242
+ * days inside each holiday. Extend this table when the next notice ships —
243
+ * a missing year would charge its weekday holidays at the peak rate. */
244
+ const STATUTORY_HOLIDAYS = [
245
+ ["2026-01-01", "2026-01-03"],
246
+ ["2026-02-15", "2026-02-23"],
247
+ ["2026-04-04", "2026-04-06"],
248
+ ["2026-05-01", "2026-05-05"],
249
+ ["2026-06-19", "2026-06-21"],
250
+ ["2026-09-25", "2026-09-27"],
251
+ ["2026-10-01", "2026-10-07"],
252
+ ["2027-01-01", "2027-01-03"],
253
+ ["2027-02-05", "2027-02-13"],
254
+ ["2027-04-03", "2027-04-05"],
255
+ ["2027-05-01", "2027-05-05"],
256
+ ["2027-06-09", "2027-06-09"],
257
+ ["2027-09-15", "2027-09-15"],
258
+ ["2027-10-01", "2027-10-07"]
259
+ ];
260
+ /** Whether the Beijing calendar day is a Chinese statutory holiday. */
261
+ function isStatutoryHoliday(time) {
262
+ const key = dayKey(time);
263
+ return STATUTORY_HOLIDAYS.some(([start, end]) => key >= start && key <= end);
217
264
  }
218
265
  /** Remove malformed or expired day buckets from the persisted usage ledger. */
219
266
  function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
@@ -265,10 +312,11 @@ function mergeUsageRow(target, source) {
265
312
  * `request/context` events anywhere in the log keep the model tracking in
266
313
  * order; only `assistant/message` usage events whose own timestamp falls on
267
314
  * `day` are folded, so a session crossing midnight contributes exactly the
268
- * events it produced that day. */
269
- function aggregateDayUsage(events, day) {
315
+ * events it produced that day. `fallbackModel` covers logs whose first usage
316
+ * event precedes any `request/context` (the live fold has the same rule). */
317
+ function aggregateDayUsage(events, day, fallbackModel = null) {
270
318
  const agg = {};
271
- let model = null;
319
+ let model = fallbackModel;
272
320
  for (const event of events) {
273
321
  if (event === void 0 || event === null) continue;
274
322
  if (event.type === "request/context") model = event.data.model ?? null;
@@ -322,6 +370,25 @@ function normalizeCfg(raw) {
322
370
  if (typeof value === "string") cfg[key] = value;
323
371
  }
324
372
  }
373
+ if (typeof src.bgFx === "boolean") cfg.bgFx = src.bgFx ? "ascii" : "none";
374
+ if (cfg.bgFx !== "none" && cfg.bgFx !== "ascii" && cfg.bgFx !== "shader") cfg.bgFx = "none";
375
+ const shaderTier = cfg.bgFx === "shader";
376
+ const allowed = shaderTier ? BG_FX_SHADER_STYLES : BG_FX_ASCII_PRESETS;
377
+ const fallback = shaderTier ? "liquid" : "flow";
378
+ const preset = cfg.bgFxPreset;
379
+ if (typeof preset !== "string" || !allowed.includes(preset)) cfg.bgFxPreset = fallback;
380
+ if (cfg.bgStrength !== "soft" && cfg.bgStrength !== "standard" && cfg.bgStrength !== "strong") cfg.bgStrength = "standard";
381
+ for (const key of [
382
+ "bgDensity",
383
+ "bgSpeed",
384
+ "bgFps",
385
+ "bgFontPx",
386
+ "bgOpacity",
387
+ "bgIntensity"
388
+ ]) {
389
+ const value = cfg[key];
390
+ cfg[key] = typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : -1;
391
+ }
325
392
  cfg.monthlyBudgetCny = Math.max(0, cfg.monthlyBudgetCny ?? 0);
326
393
  cfg.budgetWarningPercent = Math.max(1, Math.min(100, cfg.budgetWarningPercent ?? 80));
327
394
  if (cfg.bg === "aurora") cfg.bg = "default";
@@ -561,6 +628,40 @@ const saveQueues = /* @__PURE__ */ new Map();
561
628
  function tempPathFor(target, pid = process.pid) {
562
629
  return `${target}.${pid}.tmp`;
563
630
  }
631
+ /** Windows can hold the destination open for a moment (a virus scanner or the
632
+ * other dsh host's read), which makes `rename` fail with EPERM/EBUSY even
633
+ * though the temp file is complete. Retry those codes with backoff, but never
634
+ * retry a directory in the target's place; after the last attempt write the
635
+ * small document in place so the user's change is not lost. */
636
+ const RENAME_RETRY_MS = [
637
+ 30,
638
+ 60,
639
+ 120,
640
+ 240,
641
+ 480,
642
+ 800
643
+ ];
644
+ async function replaceStateFile(tmpPath, statePath, doc) {
645
+ let lastError = null;
646
+ for (let attempt = 0; attempt <= RENAME_RETRY_MS.length; attempt++) try {
647
+ await rename(tmpPath, statePath);
648
+ return;
649
+ } catch (error) {
650
+ lastError = error;
651
+ const code = error.code;
652
+ if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw error;
653
+ if ((await stat(statePath).catch(() => null))?.isDirectory() === true) throw error;
654
+ if (attempt === RENAME_RETRY_MS.length) break;
655
+ await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_MS[attempt]));
656
+ }
657
+ try {
658
+ await writeFile(statePath, doc, "utf8");
659
+ if (await readFile(statePath, "utf8") !== doc) throw lastError;
660
+ await rm(tmpPath, { force: true }).catch(() => {});
661
+ } catch (error) {
662
+ throw lastError ?? error;
663
+ }
664
+ }
564
665
  /** Atomically persist the state document. Saves to the same path are
565
666
  * serialized: a caller awaits its own turn's completion, a failed turn never
566
667
  * poisons the queue behind it. Before writing, another host's changes since
@@ -575,7 +676,7 @@ function saveStateFile(state, home = dshHome()) {
575
676
  const tmpPath = tempPathFor(statePath);
576
677
  try {
577
678
  await writeFile(tmpPath, doc, "utf8");
578
- await rename(tmpPath, statePath);
679
+ await replaceStateFile(tmpPath, statePath, doc);
579
680
  } catch (error) {
580
681
  await rm(tmpPath, { force: true }).catch(() => {});
581
682
  throw error;
@@ -1373,6 +1474,26 @@ function resolveMermaidVersion() {
1373
1474
  } catch {}
1374
1475
  return "11.6.0";
1375
1476
  }
1477
+ /**
1478
+ * Sum the account's normal (recharge) and bonus wallets into the balance shape
1479
+ * the header card renders. CNY wins when both currencies exist, matching the
1480
+ * balance endpoint's own preference; decimal strings are summed as numbers and
1481
+ * re-quantized to two decimals for display.
1482
+ */
1483
+ function balanceFromAccountWallets(normal, bonus) {
1484
+ const currencies = [...normal, ...bonus].map((wallet) => wallet.currency);
1485
+ const currency = currencies.includes("CNY") ? "CNY" : currencies.includes("USD") ? "USD" : "";
1486
+ if (currency === "") return null;
1487
+ const sum = (wallets) => wallets.filter((wallet) => wallet.currency === currency).reduce((total, wallet) => total + (Number.isFinite(Number(wallet.balance)) ? Number(wallet.balance) : 0), 0);
1488
+ const toppedUp = sum(normal);
1489
+ const granted = sum(bonus);
1490
+ return {
1491
+ currency,
1492
+ total: (toppedUp + granted).toFixed(2),
1493
+ granted: granted.toFixed(2),
1494
+ toppedUp: toppedUp.toFixed(2)
1495
+ };
1496
+ }
1376
1497
  async function mapConcurrent(items, limit, worker) {
1377
1498
  const results = new Array(items.length);
1378
1499
  let next = 0;
@@ -1395,7 +1516,11 @@ var CustomPluginHost = class CustomPluginHost {
1395
1516
  diagReports;
1396
1517
  attachments;
1397
1518
  credentialStore;
1519
+ accountBalance;
1398
1520
  sessionModel = /* @__PURE__ */ new Map();
1521
+ /** Last model seen on any session; attributes events (title generation,
1522
+ * synthetic turns) that arrive before their own `request/context`. */
1523
+ lastKnownModel = null;
1399
1524
  stateOperation = Promise.resolve();
1400
1525
  stateOperationActive = false;
1401
1526
  stateOperationPending = 0;
@@ -1420,6 +1545,7 @@ var CustomPluginHost = class CustomPluginHost {
1420
1545
  this.diagReports = options.diagReports;
1421
1546
  this.attachments = options.attachments;
1422
1547
  this.credentialStore = options.credentialStore ?? new SystemCredentialStore();
1548
+ this.accountBalance = options.accountBalance;
1423
1549
  this.localMermaidPath = options.localMermaidPath ?? defaultLocalMermaidPath;
1424
1550
  this.readCredential = options.readCredential ?? readDeepSeekCredential;
1425
1551
  }
@@ -1489,14 +1615,16 @@ var CustomPluginHost = class CustomPluginHost {
1489
1615
  /** Track the model of each session's latest request. */
1490
1616
  rememberModel(sessionId, model) {
1491
1617
  this.sessionModel.set(sessionId, model);
1618
+ if (model !== null && model !== "" && model !== "unknown") this.lastKnownModel = model;
1492
1619
  }
1493
1620
  forgetSession(sessionId) {
1494
1621
  this.sessionModel.delete(sessionId);
1495
1622
  }
1496
1623
  /** Fold one assistant/message usage record into the ledger. The event time
1497
- * decides both the day bucket and the peak/off-peak portion. */
1624
+ * decides the day bucket; the peak counters are legacy telemetry (the
1625
+ * current official tariff is flat). */
1498
1626
  foldUsage(sessionId, usage, time, modelOverride) {
1499
- const model = modelOverride !== void 0 ? modelOverride ?? "unknown" : this.sessionModel.get(sessionId) ?? "unknown";
1627
+ const model = modelOverride ?? this.sessionModel.get(sessionId) ?? this.lastKnownModel ?? "unknown";
1500
1628
  if (this.stateOperationActive) {
1501
1629
  this.queuedUsage.push({
1502
1630
  usage,
@@ -1917,52 +2045,71 @@ var CustomPluginHost = class CustomPluginHost {
1917
2045
  };
1918
2046
  return status;
1919
2047
  }
1920
- /** Query the DeepSeek balance endpoint (15s timeout). */
2048
+ /**
2049
+ * Balance for the header card and the usage tab. The DSH account service is
2050
+ * the only source — it is the same recharge + bonus wallet query the
2051
+ * Settings 「账号与余额」 page renders, so a signed-in desktop needs no sk- key.
2052
+ * The result distinguishes signed-out / pending / failed so the UI can show
2053
+ * the right hint instead of a generic failure.
2054
+ */
1921
2055
  async balanceGet() {
1922
2056
  const usageToday = this.state.usage[dayKey()] ?? {};
1923
- const key = await this.resolveApiKey();
1924
- if (key === "") return {
2057
+ const unavailable = () => ({
1925
2058
  ok: false,
1926
- keyConfigured: false,
1927
- error: "未配置 DeepSeek API Key(请在额度面板粘贴 sk- 开头的密钥)",
2059
+ accountUnavailable: true,
2060
+ error: "当前环境没有 DSH 账号余额服务",
1928
2061
  usageToday
1929
- };
1930
- let response;
2062
+ });
2063
+ if (this.accountBalance === void 0) return unavailable();
1931
2064
  try {
1932
- response = await this.httpJson("https://api.deepseek.com/user/balance", {
1933
- Authorization: `Bearer ${key}`,
1934
- Accept: "application/json"
1935
- });
2065
+ const account = await this.accountBalance();
2066
+ if (account === void 0) return unavailable();
2067
+ if (account.status === "signed-out") return {
2068
+ ok: false,
2069
+ accountSignedOut: true,
2070
+ links: account.links,
2071
+ error: "DSH 账号未登录",
2072
+ usageToday
2073
+ };
2074
+ if (account.status === "pending") return {
2075
+ ok: false,
2076
+ accountPending: true,
2077
+ links: account.links,
2078
+ error: "账号余额加载中,正在重试",
2079
+ usageToday
2080
+ };
2081
+ if (account.status === "failed") return {
2082
+ ok: false,
2083
+ accountError: "账号余额读取失败",
2084
+ links: account.links,
2085
+ error: "账号余额读取失败",
2086
+ usageToday
2087
+ };
2088
+ const mapped = balanceFromAccountWallets(account.value, account.bonusWallets);
2089
+ if (mapped === null) return {
2090
+ ok: false,
2091
+ accountError: "账号没有可用的余额信息",
2092
+ links: account.links,
2093
+ error: "账号没有可用的余额信息",
2094
+ usageToday
2095
+ };
2096
+ return {
2097
+ ok: true,
2098
+ source: "account",
2099
+ balance: mapped,
2100
+ links: account.links,
2101
+ error: null,
2102
+ usageToday
2103
+ };
1936
2104
  } catch (error) {
2105
+ const message = String(error?.message ?? error);
1937
2106
  return {
1938
2107
  ok: false,
1939
- keyConfigured: true,
1940
- error: String(error?.message ?? error),
2108
+ accountError: message,
2109
+ error: message,
1941
2110
  usageToday
1942
2111
  };
1943
2112
  }
1944
- if (!response.ok) return {
1945
- ok: false,
1946
- keyConfigured: true,
1947
- error: response.error ?? "请求失败",
1948
- usageToday
1949
- };
1950
- const json = response.json ?? {};
1951
- const infos = json.balance_infos ?? [];
1952
- const info = infos.find((item) => item.currency === "CNY") ?? infos[0];
1953
- return {
1954
- ok: true,
1955
- keyConfigured: true,
1956
- available: json.is_available !== false,
1957
- balance: info !== void 0 ? {
1958
- currency: info.currency ?? "",
1959
- total: info.total_balance ?? "0",
1960
- granted: info.granted_balance ?? "0",
1961
- toppedUp: info.topped_up_balance ?? "0"
1962
- } : null,
1963
- error: infos.length > 0 ? null : "响应中无余额信息",
1964
- usageToday
1965
- };
1966
2113
  }
1967
2114
  /** Re-scan the session logs and rebuild today's usage ledger. Every session
1968
2115
  * is replayed but only usage events whose own timestamp falls on today are
@@ -2001,7 +2148,7 @@ var CustomPluginHost = class CustomPluginHost {
2001
2148
  try {
2002
2149
  return {
2003
2150
  readable: true,
2004
- usage: aggregateDayUsage((await this.readSessionLog(record.header.id)).events, today)
2151
+ usage: aggregateDayUsage((await this.readSessionLog(record.header.id)).events, today, this.lastKnownModel)
2005
2152
  };
2006
2153
  } catch {
2007
2154
  return {
@@ -2180,59 +2327,7 @@ var CustomPluginHost = class CustomPluginHost {
2180
2327
  };
2181
2328
  }
2182
2329
  }
2183
- async httpJson(url, headers) {
2184
- try {
2185
- const response = await fetch(url, {
2186
- method: "GET",
2187
- headers,
2188
- signal: AbortSignal.timeout(15e3)
2189
- });
2190
- if (!response.ok) {
2191
- if (response.status === 401 || response.status === 403) return {
2192
- ok: false,
2193
- error: "认证失败 (HTTP " + response.status + "),请检查 API Key 是否正确"
2194
- };
2195
- return {
2196
- ok: false,
2197
- error: `HTTP ${response.status}`
2198
- };
2199
- }
2200
- try {
2201
- return {
2202
- ok: true,
2203
- json: await response.json()
2204
- };
2205
- } catch {
2206
- return {
2207
- ok: false,
2208
- error: "非 JSON 响应"
2209
- };
2210
- }
2211
- } catch (error) {
2212
- return {
2213
- ok: false,
2214
- error: readableFetchError(error)
2215
- };
2216
- }
2217
- }
2218
2330
  };
2219
- /**
2220
- * Translate a Node `fetch` connection-level failure into a message a user can
2221
- * act on. Node reports "fetch failed" with the real reason in `error.cause`
2222
- * (e.g. `SELF_SIGNED_CERT_IN_CHAIN` — a local TLS-intercepting proxy or
2223
- * security suite, which makes outbound calls fail *intermittently* whenever
2224
- * the interceptor takes the connection), and passing the bare TypeError
2225
- * through once read as a mysterious network that "sometimes does not exist".
2226
- */
2227
- function readableFetchError(error) {
2228
- const cause = error?.cause;
2229
- const code = cause?.code ?? "";
2230
- 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 放行直连,或将该软件的根证书装入系统信任";
2231
- if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "DNS 解析失败:请检查本机网络与代理配置";
2232
- if (code === "ETIMEDOUT" || code === "ECONNRESET" || code === "ECONNREFUSED" || code === "EHOSTUNREACH" || code === "ENETUNREACH") return `连接失败(${code}):请检查本机网络与代理配置`;
2233
- const message = String(cause?.message ?? error?.message ?? error);
2234
- return message === "fetch failed" ? "网络请求失败:请检查本机网络与代理配置" : message;
2235
- }
2236
2331
  /** A 200 from a mirror is not proof of the engine: captive portals and
2237
2332
  * misconfigured mirrors happily serve an HTML interstitial with status 200.
2238
2333
  * The real bundle is a multi-megabyte script that never starts with a
@@ -2683,6 +2778,11 @@ const inject = [
2683
2778
  "tools",
2684
2779
  "sessionQuery"
2685
2780
  ];
2781
+ /** Platform client version header. The desktop forwards its build version in
2782
+ * `DSH_CLIENT_VERSION`; the plugin version is a truthful fallback. */
2783
+ function accountClientVersion() {
2784
+ return (globalThis.process?.env)?.DSH_CLIENT_VERSION || "0.9.3";
2785
+ }
2686
2786
  const apply = mountOnce("@alexpeng/dsh-custom-plugin", applyImpl);
2687
2787
  function applyImpl(ctx) {
2688
2788
  const state = defaultState();
@@ -2716,7 +2816,41 @@ function applyImpl(ctx) {
2716
2816
  saveNow: () => stateWritable ? saveStateFile(state) : Promise.resolve(),
2717
2817
  reportDiag,
2718
2818
  diagReports,
2719
- attachments: ctx.get("attachments")
2819
+ attachments: ctx.get("attachments"),
2820
+ accountBalance: async () => {
2821
+ const account = ctx.get("deepseekAccount");
2822
+ if (account === void 0 || typeof account.getBalance !== "function") return void 0;
2823
+ let links;
2824
+ try {
2825
+ if (typeof account.getState === "function") {
2826
+ const state = await account.getState();
2827
+ links = state.links;
2828
+ if (state.status === "signed-out") return {
2829
+ status: "signed-out",
2830
+ links
2831
+ };
2832
+ }
2833
+ } catch {
2834
+ return { status: "failed" };
2835
+ }
2836
+ const client = {
2837
+ version: accountClientVersion(),
2838
+ locale: "zh-CN",
2839
+ timezoneOffsetSeconds: -(/* @__PURE__ */ new Date()).getTimezoneOffset() * 60
2840
+ };
2841
+ let balance = await account.getBalance(client);
2842
+ if (balance === null) {
2843
+ await new Promise((resolve) => setTimeout(resolve, 800));
2844
+ balance = await account.getBalance(client);
2845
+ }
2846
+ return balance === null ? {
2847
+ status: "pending",
2848
+ links
2849
+ } : {
2850
+ ...balance,
2851
+ links
2852
+ };
2853
+ }
2720
2854
  });
2721
2855
  const stateReady = loadStateFile(state).then(async (path) => {
2722
2856
  statePath = path;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Balance transport for the DeepSeek account endpoint.
3
+ *
4
+ * Node's bundled fetch verifies TLS against its own CA set, which does not
5
+ * include roots installed in the Windows store by proxy/security software.
6
+ * On such machines every balance call dies with `SELF_SIGNED_CERT_IN_CHAIN`
7
+ * even though the browser, PowerShell and curl reach the endpoint fine. The
8
+ * primary path stays Node fetch; certificate failures fall back to the
9
+ * platform curl, which verifies against the system trust store. The API key
10
+ * travels through curl's stdin config so it never appears in the process
11
+ * command line.
12
+ * @module @alexpeng/dsh-custom-plugin/balance
13
+ */
14
+ export declare const BALANCE_URL = "https://api.deepseek.com/user/balance";
15
+ export interface BalanceHttpResult {
16
+ /** True only for a 2xx response with a parsed JSON body. */
17
+ ok: boolean;
18
+ status: number;
19
+ json?: unknown;
20
+ /** Human-readable failure; the caller may replace it with a key-aware hint. */
21
+ error?: string;
22
+ transport: 'node' | 'curl';
23
+ /** Node/curl error code, for diagnostics. */
24
+ causeCode?: string;
25
+ }
26
+ /** Extract the `cause.code` (or a cert-looking message) from a failed fetch. */
27
+ export declare function certificateErrorCode(error: unknown): string;
28
+ /** Whether the machine declares an outbound proxy we can only honour via curl. */
29
+ export declare function proxyFromEnv(env?: Record<string, string | undefined>): string;
30
+ /** Curl config passed on stdin; keeps the bearer token out of argv. */
31
+ export declare function curlConfig(url: string, key: string): string;
32
+ /** Split curl's `-w` trailer from the response body. */
33
+ export declare function parseCurlOutput(stdout: string): {
34
+ status: number;
35
+ body: string;
36
+ };
37
+ /**
38
+ * Query the balance endpoint. `certificateRetry: false` keeps unit tests and
39
+ * callers that must not spawn a process on the Node path.
40
+ */
41
+ export declare function fetchBalance(key: string, options?: {
42
+ timeoutMs?: number;
43
+ certificateRetry?: boolean;
44
+ }): Promise<BalanceHttpResult>;
@@ -4,32 +4,37 @@
4
4
  * failures surface as `{ ok: false, error }` instead of throwing.
5
5
  * @module @alexpeng/dsh-custom-plugin/client/api
6
6
  */
7
- import { type BackupImportMode, type BackupImportPreview, type ConversationSearchKind, type ConversationSearchResult, type CredentialStorage, type CustomPluginBackupV1, type CustomPluginConfig, type CustomPluginPublicState, type CustomPluginState, type TimelineItem } from '../protocol.ts';
7
+ import { type BackupImportMode, type BackupImportPreview, type ConversationSearchKind, type ConversationSearchResult, type CustomPluginBackupV1, type CustomPluginConfig, type CustomPluginPublicState, type CustomPluginState, type TimelineItem } from '../protocol.ts';
8
8
  /** State edit the browser sends to the host. */
9
9
  export interface StateEdit {
10
10
  cfg?: Partial<CustomPluginConfig>;
11
11
  folders?: CustomPluginState['folders'];
12
12
  prompts?: CustomPluginState['prompts'];
13
13
  stars?: CustomPluginState['stars'];
14
- apiKey?: string;
15
14
  }
16
- /** Balance payload as the host reports it. */
15
+ /** Balance payload as the host reports it (DSH account wallets only). */
17
16
  export interface BalancePayload {
18
17
  ok: boolean;
19
- keyConfigured: boolean;
20
18
  balance?: {
21
19
  currency: string;
22
20
  total: string;
23
21
  granted: string;
24
22
  toppedUp: string;
25
23
  } | null;
24
+ links?: {
25
+ usageUrl: string;
26
+ topUpUrl: string;
27
+ };
26
28
  error?: string | null;
27
29
  usageToday?: Record<string, unknown>;
30
+ source?: 'account';
31
+ accountError?: string | null;
32
+ accountSignedOut?: boolean;
33
+ accountPending?: boolean;
34
+ accountUnavailable?: boolean;
28
35
  }
29
36
  type StateSaveResult = {
30
37
  ok: true;
31
- apiKeyConfigured?: boolean;
32
- credentialStorage?: CredentialStorage;
33
38
  } | {
34
39
  ok: false;
35
40
  error?: string;
@@ -75,7 +80,7 @@ export declare function apiConversationSearch(sessionId: string, query: string,
75
80
  error?: string;
76
81
  }>;
77
82
  /** Export one session in the given format. */
78
- export declare function apiExportRun(sessionId: string, format: string): Promise<{
83
+ export declare function apiExportRun(sessionId: string, format: string, signal?: AbortSignal): Promise<{
79
84
  ok: true;
80
85
  content: string;
81
86
  fileName: string;
@@ -84,7 +89,7 @@ export declare function apiExportRun(sessionId: string, format: string): Promise
84
89
  ok: false;
85
90
  error?: string;
86
91
  }>;
87
- /** DeepSeek balance. */
92
+ /** DeepSeek balance from the DSH account service. */
88
93
  export declare function apiBalanceGet(): Promise<BalancePayload>;
89
94
  /** Re-scan today's session logs for usage. */
90
95
  export declare function apiUsageScan(): Promise<{