@alexpeng/dsh-custom-plugin 0.9.3 → 0.11.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/CHANGELOG.md +1730 -866
- package/NOTICE +71 -0
- package/README.i18n.yaml +7 -7
- package/README.md +344 -335
- package/README.zh.md +309 -302
- package/lib/client.js +10260 -2063
- package/lib/client.js.map +1 -1
- package/lib/index.js +235 -99
- package/lib/types/balance.d.ts +44 -0
- package/lib/types/client/api.d.ts +13 -8
- package/lib/types/client/bg-ascii.d.ts +405 -0
- package/lib/types/client/bg-field.d.ts +62 -0
- package/lib/types/client/bg-focus.d.ts +63 -0
- package/lib/types/client/bg-jelly.d.ts +53 -0
- package/lib/types/client/bg-layer.d.ts +152 -0
- package/lib/types/client/bg-ocean.d.ts +31 -0
- package/lib/types/client/bg-params.d.ts +142 -0
- package/lib/types/client/bg-pointer.d.ts +107 -0
- package/lib/types/client/bg-shader.d.ts +329 -0
- package/lib/types/client/bg-wake.d.ts +57 -0
- package/lib/types/client/bg-whale.d.ts +56 -0
- package/lib/types/client/custom.d.ts +4 -1
- package/lib/types/client/index.d.ts +1 -1
- package/lib/types/client/palette.d.ts +100 -0
- package/lib/types/client/panel-bounds.d.ts +65 -0
- package/lib/types/client/styles.d.ts +9 -4
- package/lib/types/client/ui/anchor.d.ts +55 -0
- package/lib/types/client/ui/appearance-controls.d.ts +24 -0
- package/lib/types/client/ui/command-model.d.ts +28 -0
- package/lib/types/client/ui/folders-model.d.ts +31 -0
- package/lib/types/client/ui/index-bridge.d.ts +6 -0
- package/lib/types/client/ui/overlays.d.ts +66 -0
- package/lib/types/client/ui/primitives.d.ts +93 -0
- package/lib/types/client/ui/prompt-model.d.ts +37 -0
- package/lib/types/host-service.d.ts +68 -15
- package/lib/types/pricing.d.ts +8 -4
- package/lib/types/protocol.d.ts +48 -2
- package/lib/types/usage.d.ts +8 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +106 -105
package/lib/index.js
CHANGED
|
@@ -90,14 +90,36 @@ 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
|
+
"whale",
|
|
99
|
+
"jelly",
|
|
100
|
+
"starfield",
|
|
101
|
+
"ripple",
|
|
102
|
+
"static"
|
|
103
|
+
];
|
|
104
|
+
/** Shader style ids; keep in sync with `SHADER_STYLES` in `client/bg-shader.ts`. */
|
|
105
|
+
const BG_FX_SHADER_STYLES = ["liquid", "grain"];
|
|
93
106
|
/** Default configuration (also the composition-layer default). */
|
|
94
107
|
const DEFAULT_CONFIG = {
|
|
95
108
|
bg: "天青灰",
|
|
109
|
+
bgFx: "none",
|
|
110
|
+
bgFxPreset: "flow",
|
|
111
|
+
bgStrength: "standard",
|
|
112
|
+
bgDensity: -1,
|
|
113
|
+
bgSpeed: -1,
|
|
114
|
+
bgFps: -1,
|
|
115
|
+
bgFontPx: -1,
|
|
116
|
+
bgOpacity: -1,
|
|
117
|
+
bgIntensity: -1,
|
|
118
|
+
bgFocus: true,
|
|
96
119
|
weather: "none",
|
|
97
120
|
glass: true,
|
|
98
121
|
glassMode: "frost",
|
|
99
122
|
globalGlass: true,
|
|
100
|
-
quote: true,
|
|
101
123
|
antiScroll: false,
|
|
102
124
|
mermaid: true,
|
|
103
125
|
formula: true,
|
|
@@ -209,11 +231,38 @@ function dayKey(time) {
|
|
|
209
231
|
return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
|
|
210
232
|
}
|
|
211
233
|
/** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
|
|
212
|
-
* 14:00-18:00; all weekend hours
|
|
213
|
-
*
|
|
234
|
+
* 14:00-18:00, excluding Chinese statutory holidays; all weekend hours and
|
|
235
|
+
* holidays are off-peak. Evaluated on China Standard Time so the split matches
|
|
236
|
+
* the published schedule on any host timezone. */
|
|
214
237
|
function isPeakHour(time) {
|
|
215
238
|
const { hour, weekday } = cstParts(time);
|
|
216
|
-
return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18);
|
|
239
|
+
return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18) && !isStatutoryHoliday(time);
|
|
240
|
+
}
|
|
241
|
+
/** Chinese statutory holiday ranges (inclusive), checked 2026-11-14 against
|
|
242
|
+
* the State Council notices: 2026 (published 2025-11-04) and 2027 (published
|
|
243
|
+
* 2026-11-05). Weekends are already off-peak; these ranges add the weekday
|
|
244
|
+
* days inside each holiday. Extend this table when the next notice ships —
|
|
245
|
+
* a missing year would charge its weekday holidays at the peak rate. */
|
|
246
|
+
const STATUTORY_HOLIDAYS = [
|
|
247
|
+
["2026-01-01", "2026-01-03"],
|
|
248
|
+
["2026-02-15", "2026-02-23"],
|
|
249
|
+
["2026-04-04", "2026-04-06"],
|
|
250
|
+
["2026-05-01", "2026-05-05"],
|
|
251
|
+
["2026-06-19", "2026-06-21"],
|
|
252
|
+
["2026-09-25", "2026-09-27"],
|
|
253
|
+
["2026-10-01", "2026-10-07"],
|
|
254
|
+
["2027-01-01", "2027-01-03"],
|
|
255
|
+
["2027-02-05", "2027-02-13"],
|
|
256
|
+
["2027-04-03", "2027-04-05"],
|
|
257
|
+
["2027-05-01", "2027-05-05"],
|
|
258
|
+
["2027-06-09", "2027-06-09"],
|
|
259
|
+
["2027-09-15", "2027-09-15"],
|
|
260
|
+
["2027-10-01", "2027-10-07"]
|
|
261
|
+
];
|
|
262
|
+
/** Whether the Beijing calendar day is a Chinese statutory holiday. */
|
|
263
|
+
function isStatutoryHoliday(time) {
|
|
264
|
+
const key = dayKey(time);
|
|
265
|
+
return STATUTORY_HOLIDAYS.some(([start, end]) => key >= start && key <= end);
|
|
217
266
|
}
|
|
218
267
|
/** Remove malformed or expired day buckets from the persisted usage ledger. */
|
|
219
268
|
function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
|
|
@@ -265,10 +314,11 @@ function mergeUsageRow(target, source) {
|
|
|
265
314
|
* `request/context` events anywhere in the log keep the model tracking in
|
|
266
315
|
* order; only `assistant/message` usage events whose own timestamp falls on
|
|
267
316
|
* `day` are folded, so a session crossing midnight contributes exactly the
|
|
268
|
-
* events it produced that day.
|
|
269
|
-
|
|
317
|
+
* events it produced that day. `fallbackModel` covers logs whose first usage
|
|
318
|
+
* event precedes any `request/context` (the live fold has the same rule). */
|
|
319
|
+
function aggregateDayUsage(events, day, fallbackModel = null) {
|
|
270
320
|
const agg = {};
|
|
271
|
-
let model =
|
|
321
|
+
let model = fallbackModel;
|
|
272
322
|
for (const event of events) {
|
|
273
323
|
if (event === void 0 || event === null) continue;
|
|
274
324
|
if (event.type === "request/context") model = event.data.model ?? null;
|
|
@@ -322,6 +372,25 @@ function normalizeCfg(raw) {
|
|
|
322
372
|
if (typeof value === "string") cfg[key] = value;
|
|
323
373
|
}
|
|
324
374
|
}
|
|
375
|
+
if (typeof src.bgFx === "boolean") cfg.bgFx = src.bgFx ? "ascii" : "none";
|
|
376
|
+
if (cfg.bgFx !== "none" && cfg.bgFx !== "ascii" && cfg.bgFx !== "shader") cfg.bgFx = "none";
|
|
377
|
+
const shaderTier = cfg.bgFx === "shader";
|
|
378
|
+
const allowed = shaderTier ? BG_FX_SHADER_STYLES : BG_FX_ASCII_PRESETS;
|
|
379
|
+
const fallback = shaderTier ? "liquid" : "flow";
|
|
380
|
+
const preset = cfg.bgFxPreset;
|
|
381
|
+
if (typeof preset !== "string" || !allowed.includes(preset)) cfg.bgFxPreset = fallback;
|
|
382
|
+
if (cfg.bgStrength !== "soft" && cfg.bgStrength !== "standard" && cfg.bgStrength !== "strong") cfg.bgStrength = "standard";
|
|
383
|
+
for (const key of [
|
|
384
|
+
"bgDensity",
|
|
385
|
+
"bgSpeed",
|
|
386
|
+
"bgFps",
|
|
387
|
+
"bgFontPx",
|
|
388
|
+
"bgOpacity",
|
|
389
|
+
"bgIntensity"
|
|
390
|
+
]) {
|
|
391
|
+
const value = cfg[key];
|
|
392
|
+
cfg[key] = typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : -1;
|
|
393
|
+
}
|
|
325
394
|
cfg.monthlyBudgetCny = Math.max(0, cfg.monthlyBudgetCny ?? 0);
|
|
326
395
|
cfg.budgetWarningPercent = Math.max(1, Math.min(100, cfg.budgetWarningPercent ?? 80));
|
|
327
396
|
if (cfg.bg === "aurora") cfg.bg = "default";
|
|
@@ -561,6 +630,40 @@ const saveQueues = /* @__PURE__ */ new Map();
|
|
|
561
630
|
function tempPathFor(target, pid = process.pid) {
|
|
562
631
|
return `${target}.${pid}.tmp`;
|
|
563
632
|
}
|
|
633
|
+
/** Windows can hold the destination open for a moment (a virus scanner or the
|
|
634
|
+
* other dsh host's read), which makes `rename` fail with EPERM/EBUSY even
|
|
635
|
+
* though the temp file is complete. Retry those codes with backoff, but never
|
|
636
|
+
* retry a directory in the target's place; after the last attempt write the
|
|
637
|
+
* small document in place so the user's change is not lost. */
|
|
638
|
+
const RENAME_RETRY_MS = [
|
|
639
|
+
30,
|
|
640
|
+
60,
|
|
641
|
+
120,
|
|
642
|
+
240,
|
|
643
|
+
480,
|
|
644
|
+
800
|
|
645
|
+
];
|
|
646
|
+
async function replaceStateFile(tmpPath, statePath, doc) {
|
|
647
|
+
let lastError = null;
|
|
648
|
+
for (let attempt = 0; attempt <= RENAME_RETRY_MS.length; attempt++) try {
|
|
649
|
+
await rename(tmpPath, statePath);
|
|
650
|
+
return;
|
|
651
|
+
} catch (error) {
|
|
652
|
+
lastError = error;
|
|
653
|
+
const code = error.code;
|
|
654
|
+
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw error;
|
|
655
|
+
if ((await stat(statePath).catch(() => null))?.isDirectory() === true) throw error;
|
|
656
|
+
if (attempt === RENAME_RETRY_MS.length) break;
|
|
657
|
+
await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_MS[attempt]));
|
|
658
|
+
}
|
|
659
|
+
try {
|
|
660
|
+
await writeFile(statePath, doc, "utf8");
|
|
661
|
+
if (await readFile(statePath, "utf8") !== doc) throw lastError;
|
|
662
|
+
await rm(tmpPath, { force: true }).catch(() => {});
|
|
663
|
+
} catch (error) {
|
|
664
|
+
throw lastError ?? error;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
564
667
|
/** Atomically persist the state document. Saves to the same path are
|
|
565
668
|
* serialized: a caller awaits its own turn's completion, a failed turn never
|
|
566
669
|
* poisons the queue behind it. Before writing, another host's changes since
|
|
@@ -575,7 +678,7 @@ function saveStateFile(state, home = dshHome()) {
|
|
|
575
678
|
const tmpPath = tempPathFor(statePath);
|
|
576
679
|
try {
|
|
577
680
|
await writeFile(tmpPath, doc, "utf8");
|
|
578
|
-
await
|
|
681
|
+
await replaceStateFile(tmpPath, statePath, doc);
|
|
579
682
|
} catch (error) {
|
|
580
683
|
await rm(tmpPath, { force: true }).catch(() => {});
|
|
581
684
|
throw error;
|
|
@@ -1373,6 +1476,26 @@ function resolveMermaidVersion() {
|
|
|
1373
1476
|
} catch {}
|
|
1374
1477
|
return "11.6.0";
|
|
1375
1478
|
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Sum the account's normal (recharge) and bonus wallets into the balance shape
|
|
1481
|
+
* the header card renders. CNY wins when both currencies exist, matching the
|
|
1482
|
+
* balance endpoint's own preference; decimal strings are summed as numbers and
|
|
1483
|
+
* re-quantized to two decimals for display.
|
|
1484
|
+
*/
|
|
1485
|
+
function balanceFromAccountWallets(normal, bonus) {
|
|
1486
|
+
const currencies = [...normal, ...bonus].map((wallet) => wallet.currency);
|
|
1487
|
+
const currency = currencies.includes("CNY") ? "CNY" : currencies.includes("USD") ? "USD" : "";
|
|
1488
|
+
if (currency === "") return null;
|
|
1489
|
+
const sum = (wallets) => wallets.filter((wallet) => wallet.currency === currency).reduce((total, wallet) => total + (Number.isFinite(Number(wallet.balance)) ? Number(wallet.balance) : 0), 0);
|
|
1490
|
+
const toppedUp = sum(normal);
|
|
1491
|
+
const granted = sum(bonus);
|
|
1492
|
+
return {
|
|
1493
|
+
currency,
|
|
1494
|
+
total: (toppedUp + granted).toFixed(2),
|
|
1495
|
+
granted: granted.toFixed(2),
|
|
1496
|
+
toppedUp: toppedUp.toFixed(2)
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1376
1499
|
async function mapConcurrent(items, limit, worker) {
|
|
1377
1500
|
const results = new Array(items.length);
|
|
1378
1501
|
let next = 0;
|
|
@@ -1395,7 +1518,11 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
1395
1518
|
diagReports;
|
|
1396
1519
|
attachments;
|
|
1397
1520
|
credentialStore;
|
|
1521
|
+
accountBalance;
|
|
1398
1522
|
sessionModel = /* @__PURE__ */ new Map();
|
|
1523
|
+
/** Last model seen on any session; attributes events (title generation,
|
|
1524
|
+
* synthetic turns) that arrive before their own `request/context`. */
|
|
1525
|
+
lastKnownModel = null;
|
|
1399
1526
|
stateOperation = Promise.resolve();
|
|
1400
1527
|
stateOperationActive = false;
|
|
1401
1528
|
stateOperationPending = 0;
|
|
@@ -1420,6 +1547,7 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
1420
1547
|
this.diagReports = options.diagReports;
|
|
1421
1548
|
this.attachments = options.attachments;
|
|
1422
1549
|
this.credentialStore = options.credentialStore ?? new SystemCredentialStore();
|
|
1550
|
+
this.accountBalance = options.accountBalance;
|
|
1423
1551
|
this.localMermaidPath = options.localMermaidPath ?? defaultLocalMermaidPath;
|
|
1424
1552
|
this.readCredential = options.readCredential ?? readDeepSeekCredential;
|
|
1425
1553
|
}
|
|
@@ -1489,14 +1617,16 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
1489
1617
|
/** Track the model of each session's latest request. */
|
|
1490
1618
|
rememberModel(sessionId, model) {
|
|
1491
1619
|
this.sessionModel.set(sessionId, model);
|
|
1620
|
+
if (model !== null && model !== "" && model !== "unknown") this.lastKnownModel = model;
|
|
1492
1621
|
}
|
|
1493
1622
|
forgetSession(sessionId) {
|
|
1494
1623
|
this.sessionModel.delete(sessionId);
|
|
1495
1624
|
}
|
|
1496
1625
|
/** Fold one assistant/message usage record into the ledger. The event time
|
|
1497
|
-
* decides
|
|
1626
|
+
* decides the day bucket; the peak counters are legacy telemetry (the
|
|
1627
|
+
* current official tariff is flat). */
|
|
1498
1628
|
foldUsage(sessionId, usage, time, modelOverride) {
|
|
1499
|
-
const model = modelOverride
|
|
1629
|
+
const model = modelOverride ?? this.sessionModel.get(sessionId) ?? this.lastKnownModel ?? "unknown";
|
|
1500
1630
|
if (this.stateOperationActive) {
|
|
1501
1631
|
this.queuedUsage.push({
|
|
1502
1632
|
usage,
|
|
@@ -1917,52 +2047,71 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
1917
2047
|
};
|
|
1918
2048
|
return status;
|
|
1919
2049
|
}
|
|
1920
|
-
/**
|
|
2050
|
+
/**
|
|
2051
|
+
* Balance for the header card and the usage tab. The DSH account service is
|
|
2052
|
+
* the only source — it is the same recharge + bonus wallet query the
|
|
2053
|
+
* Settings 「账号与余额」 page renders, so a signed-in desktop needs no sk- key.
|
|
2054
|
+
* The result distinguishes signed-out / pending / failed so the UI can show
|
|
2055
|
+
* the right hint instead of a generic failure.
|
|
2056
|
+
*/
|
|
1921
2057
|
async balanceGet() {
|
|
1922
2058
|
const usageToday = this.state.usage[dayKey()] ?? {};
|
|
1923
|
-
const
|
|
1924
|
-
if (key === "") return {
|
|
2059
|
+
const unavailable = () => ({
|
|
1925
2060
|
ok: false,
|
|
1926
|
-
|
|
1927
|
-
error: "
|
|
2061
|
+
accountUnavailable: true,
|
|
2062
|
+
error: "当前环境没有 DSH 账号余额服务",
|
|
1928
2063
|
usageToday
|
|
1929
|
-
};
|
|
1930
|
-
|
|
2064
|
+
});
|
|
2065
|
+
if (this.accountBalance === void 0) return unavailable();
|
|
1931
2066
|
try {
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
2067
|
+
const account = await this.accountBalance();
|
|
2068
|
+
if (account === void 0) return unavailable();
|
|
2069
|
+
if (account.status === "signed-out") return {
|
|
2070
|
+
ok: false,
|
|
2071
|
+
accountSignedOut: true,
|
|
2072
|
+
links: account.links,
|
|
2073
|
+
error: "DSH 账号未登录",
|
|
2074
|
+
usageToday
|
|
2075
|
+
};
|
|
2076
|
+
if (account.status === "pending") return {
|
|
2077
|
+
ok: false,
|
|
2078
|
+
accountPending: true,
|
|
2079
|
+
links: account.links,
|
|
2080
|
+
error: "账号余额加载中,正在重试",
|
|
2081
|
+
usageToday
|
|
2082
|
+
};
|
|
2083
|
+
if (account.status === "failed") return {
|
|
2084
|
+
ok: false,
|
|
2085
|
+
accountError: "账号余额读取失败",
|
|
2086
|
+
links: account.links,
|
|
2087
|
+
error: "账号余额读取失败",
|
|
2088
|
+
usageToday
|
|
2089
|
+
};
|
|
2090
|
+
const mapped = balanceFromAccountWallets(account.value, account.bonusWallets);
|
|
2091
|
+
if (mapped === null) return {
|
|
2092
|
+
ok: false,
|
|
2093
|
+
accountError: "账号没有可用的余额信息",
|
|
2094
|
+
links: account.links,
|
|
2095
|
+
error: "账号没有可用的余额信息",
|
|
2096
|
+
usageToday
|
|
2097
|
+
};
|
|
2098
|
+
return {
|
|
2099
|
+
ok: true,
|
|
2100
|
+
source: "account",
|
|
2101
|
+
balance: mapped,
|
|
2102
|
+
links: account.links,
|
|
2103
|
+
error: null,
|
|
2104
|
+
usageToday
|
|
2105
|
+
};
|
|
1936
2106
|
} catch (error) {
|
|
2107
|
+
const message = String(error?.message ?? error);
|
|
1937
2108
|
return {
|
|
1938
2109
|
ok: false,
|
|
1939
|
-
|
|
1940
|
-
error:
|
|
2110
|
+
accountError: message,
|
|
2111
|
+
error: message,
|
|
1941
2112
|
usageToday
|
|
1942
2113
|
};
|
|
1943
2114
|
}
|
|
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
2115
|
}
|
|
1967
2116
|
/** Re-scan the session logs and rebuild today's usage ledger. Every session
|
|
1968
2117
|
* is replayed but only usage events whose own timestamp falls on today are
|
|
@@ -2001,7 +2150,7 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
2001
2150
|
try {
|
|
2002
2151
|
return {
|
|
2003
2152
|
readable: true,
|
|
2004
|
-
usage: aggregateDayUsage((await this.readSessionLog(record.header.id)).events, today)
|
|
2153
|
+
usage: aggregateDayUsage((await this.readSessionLog(record.header.id)).events, today, this.lastKnownModel)
|
|
2005
2154
|
};
|
|
2006
2155
|
} catch {
|
|
2007
2156
|
return {
|
|
@@ -2180,59 +2329,7 @@ var CustomPluginHost = class CustomPluginHost {
|
|
|
2180
2329
|
};
|
|
2181
2330
|
}
|
|
2182
2331
|
}
|
|
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
2332
|
};
|
|
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
2333
|
/** A 200 from a mirror is not proof of the engine: captive portals and
|
|
2237
2334
|
* misconfigured mirrors happily serve an HTML interstitial with status 200.
|
|
2238
2335
|
* The real bundle is a multi-megabyte script that never starts with a
|
|
@@ -2683,6 +2780,11 @@ const inject = [
|
|
|
2683
2780
|
"tools",
|
|
2684
2781
|
"sessionQuery"
|
|
2685
2782
|
];
|
|
2783
|
+
/** Platform client version header. The desktop forwards its build version in
|
|
2784
|
+
* `DSH_CLIENT_VERSION`; the plugin version is a truthful fallback. */
|
|
2785
|
+
function accountClientVersion() {
|
|
2786
|
+
return (globalThis.process?.env)?.DSH_CLIENT_VERSION || "0.9.3";
|
|
2787
|
+
}
|
|
2686
2788
|
const apply = mountOnce("@alexpeng/dsh-custom-plugin", applyImpl);
|
|
2687
2789
|
function applyImpl(ctx) {
|
|
2688
2790
|
const state = defaultState();
|
|
@@ -2716,7 +2818,41 @@ function applyImpl(ctx) {
|
|
|
2716
2818
|
saveNow: () => stateWritable ? saveStateFile(state) : Promise.resolve(),
|
|
2717
2819
|
reportDiag,
|
|
2718
2820
|
diagReports,
|
|
2719
|
-
attachments: ctx.get("attachments")
|
|
2821
|
+
attachments: ctx.get("attachments"),
|
|
2822
|
+
accountBalance: async () => {
|
|
2823
|
+
const account = ctx.get("deepseekAccount");
|
|
2824
|
+
if (account === void 0 || typeof account.getBalance !== "function") return void 0;
|
|
2825
|
+
let links;
|
|
2826
|
+
try {
|
|
2827
|
+
if (typeof account.getState === "function") {
|
|
2828
|
+
const state = await account.getState();
|
|
2829
|
+
links = state.links;
|
|
2830
|
+
if (state.status === "signed-out") return {
|
|
2831
|
+
status: "signed-out",
|
|
2832
|
+
links
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
} catch {
|
|
2836
|
+
return { status: "failed" };
|
|
2837
|
+
}
|
|
2838
|
+
const client = {
|
|
2839
|
+
version: accountClientVersion(),
|
|
2840
|
+
locale: "zh-CN",
|
|
2841
|
+
timezoneOffsetSeconds: -(/* @__PURE__ */ new Date()).getTimezoneOffset() * 60
|
|
2842
|
+
};
|
|
2843
|
+
let balance = await account.getBalance(client);
|
|
2844
|
+
if (balance === null) {
|
|
2845
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
2846
|
+
balance = await account.getBalance(client);
|
|
2847
|
+
}
|
|
2848
|
+
return balance === null ? {
|
|
2849
|
+
status: "pending",
|
|
2850
|
+
links
|
|
2851
|
+
} : {
|
|
2852
|
+
...balance,
|
|
2853
|
+
links
|
|
2854
|
+
};
|
|
2855
|
+
}
|
|
2720
2856
|
});
|
|
2721
2857
|
const stateReady = loadStateFile(state).then(async (path) => {
|
|
2722
2858
|
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
|
|
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<{
|