dsh-dpharness 0.4.4 → 0.6.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
@@ -1,10 +1,13 @@
1
1
  /**
2
- * dsh-dpharness — host half (v0.4.4).
2
+ * dsh-dpharness — host half (v0.5.2).
3
3
  *
4
4
  * Catalog routes, a write-only telemetry relay and a one-click installer:
5
5
  *
6
- * GET /api/dpharness/search?q=<kw>&take=<n>&sort=stars
6
+ * GET /api/dpharness/search?q=<kw>&take=<n>&sort=stars → { count, total, plugins[] }
7
+ * `count` = 本次返回条数,`total` = 该筛选下的真实命中总数(两者常不等)
7
8
  * GET /api/dpharness/meta
9
+ * GET /api/dpharness/changelog
10
+ * GET /api/dpharness/updates
8
11
  * GET /api/dpharness/postinstall?pkg=<pkg>&via=<local|market>&at=<epochMs>
9
12
  * POST /api/dpharness/event → relayed to https://dpharness.com/api/track/event
10
13
  * POST /api/dpharness/install → spawns `dsh plugin --profile <p> add <pkg>`
@@ -20,9 +23,11 @@
20
23
  * and a keyword *length* are relayed. Telemetry can be switched off in the UI.
21
24
  *
22
25
  * Upstream contracts (all read from source / measured 2026-09-17):
23
- * - GET https://dpharness.com/api/plugins → { count, plugins[] }; `q` covers the
24
- * whole catalog; `take` is clamped at 500; `sort=stars` is a strictly
25
- * descending star order; item.installCheck = { status, pkgName }
26
+ * - GET https://dpharness.com/api/plugins → { count, total, plugins[] }; `q` covers
27
+ * the whole catalog; `take` is clamped at 500; `sort=stars` is a strictly
28
+ * descending star order; `count` is this page's size while `total` is the real
29
+ * hit count under the filter (measured 2026-09-30: q=统计 → count=3/30, total=106);
30
+ * item.installCheck = { status, pkgName }
26
31
  * - POST https://dpharness.com/api/track/event → { type, value, path, visitorId }
27
32
  * (`path` is truncated at "?", so detail belongs in `value`)
28
33
  * - POST /dsh-market/install (dshmarket, when installed) → body { url }, same-origin
@@ -33,13 +38,33 @@ import { spawn } from "node:child_process";
33
38
  import fs from "node:fs";
34
39
  import os from "node:os";
35
40
  import path from "node:path";
41
+ import { CHANGELOG, RELEASES_URL, REPO, compareVersions, mergeChangelog, npmLatestUrl } from "./changelog.js";
42
+ import { classifyUsage, getUsageReport } from "./usage.js";
36
43
 
37
44
  export const name = "dpharness";
38
45
 
39
46
  /** The dsh web server service used to register HTTP routes. */
40
47
  export const inject = ["webServer"];
41
48
 
42
- export const VERSION = "0.4.4";
49
+ export const VERSION = "0.6.0";
50
+
51
+ /**
52
+ * 本插件在 npm 上的包名 —— 与 dsh 的插件 id(上面的 `name = "dpharness"`)**不是一回事**,
53
+ * 别互相替代:前者用于 registry 查询与升级命令,后者用于 profile 加载清单。
54
+ */
55
+ export const PKG_NAME = "dsh-dpharness";
56
+
57
+ /**
58
+ * 接口负载的**形状版本**。改动 /updates、/changelog 返回的字段时**必须 +1**。
59
+ *
60
+ * 为什么需要它:desktop profile 里本插件是指向工作区的符号链接 —— 客户端刷新页面即生效,
61
+ * 而宿主的路由与字段要**重启 dsh** 才会更新。这个窗口期里界面会缺字段(实测已误导过两次),
62
+ * 客户端据此显式提示「宿主进程是旧版本」,而不是让用户以为功能坏了。
63
+ *
64
+ * ⚠️ 客户端侧有一份同名常量(两个半边同包但不同运行时,没法 import),
65
+ * test-local.mjs **双向断言两者相等** —— 改一处忘了另一处会当场变红。
66
+ */
67
+ export const SHAPE_REV = 4;
43
68
 
44
69
  /**
45
70
  * Wall-clock time this dsh process started.
@@ -61,11 +86,42 @@ const STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
61
86
  const PROFILE = (() => {
62
87
  const flag = process.argv.indexOf("--profile");
63
88
  if (flag >= 0 && process.argv[flag + 1]) return process.argv[flag + 1];
64
- return process.env.DSH_DPHARNESS_PROFILE || "web";
89
+ if (process.env.DSH_DPHARNESS_PROFILE) return process.env.DSH_DPHARNESS_PROFILE;
90
+ return profileFromArgv() || "web";
65
91
  })();
66
92
 
93
+ /**
94
+ * Recover the profile name from the desktop shell's positional arguments.
95
+ *
96
+ * The Electron shell boots this host as
97
+ * …/MacOS/DeepSeek Harness --expose-internals <…>/dsh-desktop-host/lib/index.js \
98
+ * <…>/app.asar/dsh <…>/.dsh/profiles/<profile> <…>/runtime/primary-runtime
99
+ * so neither `--profile` nor DSH_DPHARNESS_PROFILE exists and the plain
100
+ * fallback ("web") names the WRONG profile: the user is looking at `desktop`
101
+ * while the install would land in `web` (measured 2026-09-30 against
102
+ * @deepseek-ai/dsh-desktop 0.2.0-rc.2, where argv held …/profiles/desktop).
103
+ *
104
+ * A candidate is accepted only when a package.json really sits there, so an
105
+ * unrelated path that merely contains "profiles" cannot be mistaken for it.
106
+ */
107
+ export function profileFromArgv(argv = process.argv) {
108
+ for (const arg of argv) {
109
+ if (typeof arg !== "string") continue;
110
+ const normalized = arg.replace(/[\\/]+$/, "");
111
+ const match = /[\\/]profiles[\\/]([^\\/]+)$/.exec(normalized);
112
+ if (!match) continue;
113
+ try {
114
+ if (fs.statSync(path.join(normalized, "package.json")).isFile()) return match[1];
115
+ } catch (error) {
116
+ /* not a profile directory — keep looking */
117
+ }
118
+ }
119
+ return null;
120
+ }
121
+
67
122
  const UPSTREAM = "https://dpharness.com/api/plugins";
68
123
  const BEST_UPSTREAM = "https://dpharness.com/api/best";
124
+ const SETS_UPSTREAM = "https://dpharness.com/api/sets";
69
125
  const SITE = "https://dpharness.com";
70
126
  const TRACK = "https://dpharness.com/api/track/event";
71
127
  const DEFAULT_TAKE = 30;
@@ -94,6 +150,15 @@ const EVENT_MAX_PER_WINDOW = 120;
94
150
  */
95
151
  const TARGET_RE = /^[A-Za-z0-9@:./_#+~^=-]+$/;
96
152
  const INSTALL_TIMEOUT_MS = 180 * 1000;
153
+ /**
154
+ * 超时之后的收尾宽限。
155
+ *
156
+ * SIGKILL 已经发出,退出事件通常毫秒级就到 —— 这段时间只用来等 close 收尾,
157
+ * 不改变任何结论;到点仍未收敛就**强制解锁**(见 forceUnlock)。它存在的理由是:
158
+ * close 是 active 的**唯一**复位点,而 close 会缺席(2026-10-14 实测宿主因此
159
+ * 彻底装不了任何插件,见 forceUnlock 的注释)。
160
+ */
161
+ const INSTALL_SETTLE_MS = 5 * 1000;
97
162
 
98
163
  /**
99
164
  * Re-invoke the dsh CLI that launched this host, instead of looking for `dsh`
@@ -103,25 +168,85 @@ const INSTALL_TIMEOUT_MS = 180 * 1000;
103
168
  *
104
169
  * Spawning through the managed node's bin directory also puts `pnpm` on PATH,
105
170
  * because the dsh web process is started by that same node.
171
+ *
172
+ * ⚠️ Under the Electron desktop shell argv[1] is a **flag**, not a path —
173
+ * measured 2026-09-30 on @deepseek-ai/dsh-desktop 0.2.0-rc.2:
174
+ * argv = [ …/MacOS/DeepSeek Harness, "--expose-internals",
175
+ * …/app.asar/dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/index.js,
176
+ * …/app.asar/dsh, ~/.dsh/profiles/desktop, …/runtime/primary-runtime ]
177
+ * The old single branch therefore returned null and **every** install died with
178
+ * "cannot locate the dsh entry point (process.argv[1])" — the failure the user
179
+ * sees in the panel. The shell ships its own CLI wrapper, so reuse that.
106
180
  */
107
181
  function dshInvocation() {
108
182
  const entry = process.argv[1];
109
- if (typeof entry !== "string" || !/[\\/](?:bin\.(?:js|ts)|dsh)$/.test(entry)) return null;
110
- const abs = path.resolve(entry);
111
- return { file: process.execPath, args: [...process.execArgv, abs], cwd: path.dirname(abs) };
183
+ if (typeof entry === "string" && /[\\/](?:bin\.(?:js|ts)|dsh)$/.test(entry)) {
184
+ const abs = path.resolve(entry);
185
+ return { file: process.execPath, args: [...process.execArgv, abs], cwd: path.dirname(abs) };
186
+ }
187
+ const shellCli = desktopShellCli();
188
+ /* cwd 取用户主目录:桌面版 CLI 位于 .app 包内(只读),任何意外写盘都会失败。
189
+ CLI 自己会切到 profile 目录再跑 pnpm(实测错误信息
190
+ "dsh: pnpm failed in profile directory …" 即由此而来),cwd 只作兜底。 */
191
+ if (shellCli !== null) return { file: shellCli, args: [], cwd: os.homedir() };
192
+ return null;
193
+ }
194
+
195
+ /**
196
+ * The Electron desktop shell ships a CLI wrapper inside its own bundle:
197
+ * <Contents>/Resources/runtime/cli/bin/dsh
198
+ * It is the only entry that can drive the shell's embedded dsh — a bare
199
+ * `node <asar>/…/bin.js` cannot read asar, and process.execPath there is the
200
+ * Electron binary rather than node. The wrapper itself sets
201
+ * ELECTRON_RUN_AS_NODE=1 and points at dsh-desktop-host/lib/cli.js (read from
202
+ * the file, not guessed).
203
+ *
204
+ * Path derived from the standard macOS bundle layout (…/Contents/MacOS/<App> →
205
+ * …/Contents) and `accessSync`-checked before use, so an unexpected layout
206
+ * degrades to the previous behaviour instead of spawning something wrong.
207
+ */
208
+ export function desktopShellCli(execPath = process.execPath, isElectron = typeof process.versions?.electron === "string") {
209
+ if (!isElectron) return null;
210
+ const contents = path.resolve(path.dirname(execPath), "..");
211
+ const candidates = [
212
+ path.join(contents, "Resources", "runtime", "cli", "bin", "dsh"),
213
+ path.join(contents, "Resources", "runtime", "cli", "bin", "dsh.cmd"),
214
+ ];
215
+ for (const candidate of candidates) {
216
+ try {
217
+ fs.accessSync(candidate, fs.constants.X_OK);
218
+ return candidate;
219
+ } catch (error) {
220
+ /* try the next candidate */
221
+ }
222
+ }
223
+ return null;
112
224
  }
113
225
 
114
226
  const installJob = {
115
227
  active: false,
116
228
  stage: "idle",
229
+ /* add(安装/升级)| remove(卸载)—— 同一条通道,界面按它决定措辞 */
230
+ verb: "add",
117
231
  target: "",
118
232
  startedAt: 0,
119
233
  finishedAt: 0,
120
234
  code: null,
121
235
  output: [],
122
236
  error: null,
237
+ /* "incompatible" = dsh 自带的兼容性闸门拒绝(见 incompatibleFrom) */
238
+ why: null,
239
+ reject: null,
240
+ /* "changed" / "same"(本来就是目标版本)/ "none"(真的什么都没发生) */
241
+ outcome: null,
123
242
  };
124
243
 
244
+ /* 当前在跑的安装子进程与它的序号。
245
+ 序号是给**延迟收尾**用的:超时兜底计时器可能在下一个任务开始之后才到点,
246
+ 没有序号就会把新任务误判成"卡死的老任务"解锁掉。 */
247
+ let installChild = null;
248
+ let installSeq = 0;
249
+
125
250
  /**
126
251
  * Build a clean environment for the child process.
127
252
  *
@@ -152,7 +277,80 @@ function sanitizedEnv(binDir) {
152
277
  return env;
153
278
  }
154
279
 
155
- function startInstall(target) {
280
+ /**
281
+ * 去掉 `@版本` 后缀,得到裸包名(`@scope/name@1.2.3` → `@scope/name`)。
282
+ *
283
+ * 用它去 profile 清单/安装目录里查东西 —— 清单的键是裸包名,
284
+ * 带着 `@latest` 去查会永远查不到。
285
+ */
286
+ export function stripVersion(target) {
287
+ const value = String(target || "");
288
+ const matched = /^(.*?)@[^@/]+$/.exec(value);
289
+ return matched ? matched[1] : value;
290
+ }
291
+
292
+ /**
293
+ * 把安装任务复位成「已结束」—— **不依赖 close 事件**的兜底解锁。
294
+ *
295
+ * 🔴 2026-10-14 事故(用户实测,代价=整个插件面板再也装不了东西):
296
+ * 超时分支只把 error 置成 "timeout" 并 kill 掉**直系**子进程,而真正的安装是
297
+ * **孙进程**(宿主 → dsh CLI → pnpm):SIGKILL 打不到孙进程,它继续跑;孙进程继承了
298
+ * 管道,于是直系子进程的 close 永远不触发 —— 而 active 的唯一复位点就在 close 里。
299
+ * 结果是 active 永久为 true,之后每一次安装都被守卫拦成 409;现场实测卡死 36 分钟,
300
+ * 界面只显示「安装失败:an install is already running」,用户没有任何自救手段。
301
+ *
302
+ * 所以这里做三件事:①无条件解锁;②把仍在跑的进程组再杀一次(best effort);
303
+ * ③**补读一次磁盘**——超时时真实安装很可能已经成功(本轮事故正是 4.4.2 → 4.4.3
304
+ * 已落盘却报失败),把事实交给界面,别让"超时"被读成"什么都没发生"。
305
+ *
306
+ * @param reason 记进 error 的兜底原因(仅在 error 为空时使用)
307
+ * @param seq 调用方认定的任务序号;与当前序号不符则**不动手**(老计时器迟到)
308
+ *
309
+ * 导出是给 test-local.mjs 用的(同 desktopShellCli / errorLineFrom 的先例):
310
+ * "迟到计时器必须无害"这条只能从外部验。
311
+ */
312
+ export function forceUnlock(reason, seq) {
313
+ if (seq !== undefined && seq !== installSeq) return false;
314
+ if (!installJob.active) return false;
315
+ installJob.active = false;
316
+ installJob.finishedAt = Date.now();
317
+ installJob.stage = "failed";
318
+ if (!installJob.error) installJob.error = reason || "unlocked";
319
+ killInstallTree();
320
+ if (installJob.pkg) {
321
+ const after = installedVersionOf(installJob.pkg);
322
+ if (after !== null && after !== installJob.before) {
323
+ installJob.after = after;
324
+ installJob.outcome = "changed";
325
+ installJob.changed = true;
326
+ /* 版本真变了 ⇒ 更新检查与"已安装"标注的缓存都得作废,否则界面刷新后
327
+ 还显示旧版本号,用户会判定"升级没成功"。 */
328
+ updatesCache = { at: 0, value: null };
329
+ installedCache = { at: 0, value: {} };
330
+ }
331
+ }
332
+ return true;
333
+ }
334
+
335
+ /** 按**进程组**杀掉当前安装(detached 让子进程自成一组,杀组才不会漏掉孙进程)。 */
336
+ function killInstallTree() {
337
+ const child = installChild;
338
+ installChild = null;
339
+ if (!child || !child.pid) return;
340
+ try {
341
+ process.kill(-child.pid, "SIGKILL");
342
+ return;
343
+ } catch (error) {
344
+ /* 进程组不可用(Windows / 已经退出)→ 退回只杀直系子进程 */
345
+ }
346
+ try {
347
+ child.kill("SIGKILL");
348
+ } catch (error) {
349
+ /* already gone */
350
+ }
351
+ }
352
+
353
+ function startInstall(target, verb) {
156
354
  const invocation = dshInvocation();
157
355
  if (invocation === null) {
158
356
  installJob.active = false;
@@ -160,6 +358,10 @@ function startInstall(target) {
160
358
  installJob.error = "cannot locate the dsh entry point (process.argv[1])";
161
359
  return;
162
360
  }
361
+ /* verb:add(安装/升级)或 remove(卸载)。同一条 spawn/轮询/脱敏通道,
362
+ 所以三态结论(changed/same/none)对两者都成立:
363
+ remove 时 changed = 卸掉了 / same = 还在(没卸成)/ none = 本来就没装。 */
364
+ installJob.verb = verb === "remove" ? "remove" : "add";
163
365
  installJob.active = true;
164
366
  installJob.stage = "running";
165
367
  installJob.target = target;
@@ -168,13 +370,31 @@ function startInstall(target) {
168
370
  installJob.code = null;
169
371
  installJob.output = [];
170
372
  installJob.error = null;
373
+ /* 兼容性闸门是**预期结果**而非意外故障,单独占一个字段,供界面给可操作的说明 */
374
+ installJob.why = null;
375
+ installJob.reject = null;
376
+ /* 装之前的版本号:装完由 host **亲自读磁盘**比对。
377
+ 实测(2026-10-12)dsh 的 `plugin add` 对已安装的包会**静默空转** ——
378
+ 退出码 0、pnpm.log 0 字节、版本纹丝不动。若只看退出码,界面会谎报"已安装"。 */
379
+ installJob.pkg = stripVersion(target);
380
+ installJob.before = installedVersionOf(installJob.pkg);
381
+ installJob.after = null;
382
+ installJob.changed = null;
383
+ installJob.outcome = null;
171
384
 
172
385
  const binDir = path.dirname(process.execPath);
173
- const child = spawn(invocation.file, [...invocation.args, "plugin", "--profile", PROFILE, "add", target], {
386
+ /* 本任务的序号:所有**延迟**收尾(超时宽限、exit 兜底)都要拿它比对,
387
+ 否则迟到的老计时器会把之后那个健康的任务解锁掉。 */
388
+ const seq = ++installSeq;
389
+ const child = spawn(invocation.file, [...invocation.args, "plugin", "--profile", PROFILE, installJob.verb, target], {
174
390
  cwd: invocation.cwd,
175
391
  env: sanitizedEnv(binDir),
176
392
  stdio: ["ignore", "pipe", "pipe"],
393
+ /* detached ⇒ 子进程自成进程组,超时可以按 -pid 杀掉**整棵树**。
394
+ 不这么做的话孙进程(真正干活的 pnpm)活下来,close 就永远不来。 */
395
+ detached: true,
177
396
  });
397
+ installChild = child;
178
398
 
179
399
  const push = (chunk) => {
180
400
  const text = String(chunk);
@@ -186,28 +406,124 @@ function startInstall(target) {
186
406
 
187
407
  const timer = setTimeout(() => {
188
408
  installJob.error = "timeout";
189
- try { child.kill("SIGKILL"); } catch (error) { /* already gone */ }
409
+ /* 按进程组杀整棵树 —— 只杀直系子进程会把真正干活的 pnpm 孙进程留下
410
+ (2026-10-14 实测它又活了 36 分钟,并把宿主永久卡进 409)。 */
411
+ killInstallTree();
412
+ /* 但 kill 不保证 close 一定来(孙进程握着管道 / 直系子进程已被换掉)⇒ 到点强制解锁。
413
+ 这一层是**必须**的:close 是 active 的唯一复位点,它缺席就等于宿主死锁。 */
414
+ setTimeout(() => {
415
+ if (forceUnlock("timeout", seq)) {
416
+ console.warn(`[dpharness] install of ${target} timed out and did not settle — unlocked`);
417
+ }
418
+ }, INSTALL_SETTLE_MS);
190
419
  }, INSTALL_TIMEOUT_MS);
191
420
 
192
421
  child.on("error", (error) => {
193
422
  clearTimeout(timer);
423
+ if (seq !== installSeq) return;
194
424
  installJob.active = false;
195
425
  installJob.stage = "failed";
196
426
  installJob.error = String((error && error.message) || error);
197
427
  installJob.finishedAt = Date.now();
428
+ installChild = null;
429
+ });
430
+ /**
431
+ * exit 兜底:进程退了、但 stdio 还被孙进程攥着 ⇒ close 可能永远不来。
432
+ * 等一个宽限期,让 close 有机会做完整收尾(读磁盘核对三态);它没来就自己解锁。
433
+ */
434
+ child.on("exit", () => {
435
+ setTimeout(() => {
436
+ if (forceUnlock("exit-without-close", seq)) {
437
+ console.warn(`[dpharness] install of ${target} exited without closing its pipes — unlocked`);
438
+ }
439
+ }, INSTALL_SETTLE_MS);
198
440
  });
199
441
  child.on("close", (code) => {
200
442
  clearTimeout(timer);
443
+ if (seq !== installSeq) return;
444
+ installChild = null;
201
445
  installJob.active = false;
202
446
  installJob.code = code;
203
447
  installJob.finishedAt = Date.now();
204
448
  installJob.stage = code === 0 ? "done" : "failed";
205
- if (code !== 0 && installJob.error === null) installJob.error = errorLine();
449
+ if (code === 0) {
450
+ /* 装完**读磁盘**核对:退出码 0 不等于装上了(dsh 对已安装的包会静默空转)。
451
+ ⚠️ 必须三态 —— 别把"本来就是这个版本"说成"什么都没装"(2026-10-12 用户被这句误导:
452
+ 他在目录卡片上点「安装」装一个早就装好的插件,界面报"什么都没装",他读成安装失败):
453
+ changed 装上了 / 升级了 → 需要重启
454
+ same **本来就是目标版本** → 这是成功,不是失败
455
+ none 装前装后都查不到 → 那才是真的什么都没发生 */
456
+ installJob.after = installedVersionOf(installJob.pkg);
457
+ installJob.outcome = installJob.before === null && installJob.after === null
458
+ ? "none"
459
+ : (installJob.before === installJob.after ? "same" : "changed");
460
+ installJob.changed = installJob.outcome === "changed";
461
+ /* 装成了就把更新检查的缓存作废:否则界面刷新后拿到的还是装之前那份清单,
462
+ "升完还显示可升级" —— 用户只会判定"升级没成功"(2026-10-12 实测撞到)。 */
463
+ updatesCache = { at: 0, value: null };
464
+ /* 已装版本变了,目录卡片上的「已安装」标注也要跟着刷新 */
465
+ installedCache = { at: 0, value: {} };
466
+ }
467
+ if (code !== 0 && installJob.error === null) {
468
+ const blocked = incompatibleFrom(installJob.output.join(""));
469
+ if (blocked) {
470
+ installJob.why = "incompatible";
471
+ installJob.reject = blocked;
472
+ /* 给一个结构化、可检索的兜底描述;界面会按 why 翻成人话,不依赖这句 */
473
+ installJob.error = `dsh rejected ${blocked.spec} (incompatible with dsh ${blocked.dsh})`;
474
+ } else {
475
+ /* 供应链策略拒绝也单独成类(同 incompatible 的做法):它是**预期结果**,
476
+ 界面要给出条目、剩余等待时间与通路,而不是一句英文错误码。 */
477
+ const aged = releaseAgeFrom(installJob.output.join(""));
478
+ if (aged) {
479
+ installJob.why = "release-age";
480
+ installJob.reject = aged;
481
+ installJob.error = `pnpm supply-chain policy rejected ${aged.count} lockfile entries (minimumReleaseAge)`;
482
+ } else {
483
+ installJob.error = errorLine();
484
+ }
485
+ }
486
+ }
206
487
  });
207
488
  }
208
489
 
490
+ /**
491
+ * 展示前的统一脱敏。
492
+ *
493
+ * 为什么必须在**服务端**做(2026-09-30 用户提出,且这次是我先踩了):
494
+ * pnpm 输出的尾部会原样出现在面板卡片上(安装失败时用于定位),而 `.npmrc` 里的
495
+ * registry token 一旦落到卡片上就会被截图、被日志外带、被会话记录保存 ——
496
+ * **换 token 也挡不住,因为展示路径还在**。所以堵点是"展示"而不是"凭据"。
497
+ *
498
+ * pnpm 多数情况会自己打成 `Bearer npm_[hidden]`(实测 11.7.0),但那不是契约;
499
+ * 这里按最坏情况兜底:只要形如凭据就替换成 `***`。
500
+ *
501
+ * ⚠️ 调用顺序固定为「先截断、后脱敏」—— 反过来的话,截断会把 token 切成半截,
502
+ * 半截 token 照样是泄露,而且再也匹配不上任何模式。
503
+ */
504
+ const SECRET_PATTERNS = [
505
+ /* 第三方已自带的部分脱敏(pnpm 实测就是 `Bearer npm_[hidden]`,2026-09-30)。
506
+ 内容虽然隐藏了,但"日志里会出现 token"这件事本身就该消失——统一压成 ***,
507
+ 信息量不减:`Bearer ***` 仍然告诉读者这次请求带了凭据。 */
508
+ [/\bnpm_\[[^\]]*\]/g, "***"],
509
+ /* .npmrc 常见写法://registry.npmjs.org/:_authToken=xxx、_auth、_password */
510
+ [/((?:_authToken|_auth|_password|password|token)\s*[=:]\s*)\S+/gi, "$1***"],
511
+ /* Authorization 头:Authorization: Bearer xxx / Basic xxx */
512
+ [/(authorization\s*[=:]\s*)(?:bearer|basic|token)\s+\S+/gi, "$1***"],
513
+ /* 无字段名的裸方案前缀:Bearer npm_xxx(pnpm 的错误提示就是这个形状) */
514
+ [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{12,}/gi, "$1 ***"],
515
+ /* npm 的 token 形状本身 */
516
+ [/npm_[A-Za-z0-9]{16,}/g, "npm_***"],
517
+ ];
518
+
519
+ export function redactSecrets(text) {
520
+ let out = String(text == null ? "" : text);
521
+ for (const [pattern, replacement] of SECRET_PATTERNS) out = out.replace(pattern, replacement);
522
+ return out;
523
+ }
524
+
209
525
  function tail() {
210
- return installJob.output.join("").trim().slice(-600);
526
+ return redactSecrets(installJob.output.join("").trim().slice(-600));
211
527
  }
212
528
 
213
529
  /**
@@ -219,7 +535,78 @@ function tail() {
219
535
  * a distinctive pnpm error code first, generic wording only as a fallback.
220
536
  */
221
537
  function errorLine() {
222
- return errorLineFrom(installJob.output.join(""));
538
+ /* 与 tail() 同一口径:这一行同样会展示在卡片上,必须脱敏后再出 */
539
+ return redactSecrets(errorLineFrom(installJob.output.join("")));
540
+ }
541
+
542
+ /**
543
+ * dsh **自带的兼容性闸门**拒绝安装时的专用识别。
544
+ *
545
+ * 实测(2026-10-12,桌面版 dsh 0.2.0-rc.2):`dsh plugin add <pkg>@latest` 会拿目标版本的
546
+ * peerDependencies 跟本机 dsh 比对,不匹配就**硬拒绝**,输出形如:
547
+ * dsh: installation rejected: Plugin dsh-restart@0.1.2 is incompatible with dsh 0.2.0-rc.2:
548
+ * peerDependencies {…}. Running it may cause crashes or data loss. …
549
+ * dsh: nothing was installed.
550
+ *
551
+ * ⚠️ 这段文本里**没有** ERR_ / error / failed 任何一个关键词,所以通用的 errorLineFrom()
552
+ * 抓不到它,界面只剩一句 "dsh: nothing was installed." —— 用户根本看不出为什么"升级不了"
553
+ * (本次实际踩到)。这里把它识别成一个**闭集原因**(incompatible)并带上两端版本,
554
+ * 交给界面翻成人话:该说的说清(拒绝原因 + 放行通道),且**不代用户放行**。
555
+ */
556
+ export function incompatibleFrom(text) {
557
+ const matched = /installation rejected:\s*Plugin\s+(\S+?)\s+is incompatible with dsh\s+([^\s:]+)/i.exec(String(text || ""));
558
+ if (!matched) return null;
559
+ const spec = matched[1];
560
+ const at = spec.lastIndexOf("@");
561
+ return {
562
+ /* name@version 拆开:scoped 包(@scope/name@1.2.3)取最后一个 @ 才是版本分隔符 */
563
+ name: at > 0 ? spec.slice(0, at) : spec,
564
+ version: at > 0 ? spec.slice(at + 1) : "",
565
+ spec,
566
+ dsh: matched[2],
567
+ };
568
+ }
569
+
570
+ /**
571
+ * pnpm **供应链策略**拒绝时的专用识别(pnpm 11 内置 `minimumReleaseAge`,2026-10-14 实测)。
572
+ *
573
+ * 原文形状:
574
+ * [ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] 3 lockfile entries failed verification:
575
+ * dsh-connect-workbuddy@4.4.5 was published at 2026-10-13T20:06:51.203Z, within the minimumReleaseAge cutoff (…)
576
+ *
577
+ * 为什么必须单独识别:它**不是"安装出错"**,而是**策略性拒绝** —— 用户能做的只有「等它满 24 小时」
578
+ * 或「改本机 profile 的豁免名单」,界面得说清"哪几条、大概还要等多久、去哪儿加豁免"。
579
+ * 通用的 errorLineFrom() 只会给出头部那一行 `[ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] 3 lockfile …`,
580
+ * 用户既看不出这是什么、也不知道下一步做什么(2026-10-14 用户实际撞到,卡片上只有这行原文)。
581
+ *
582
+ * ⚠️ 附带一条实测出来、值得写进界面提示的坑:`minimumReleaseAgeExclude` 是**同一包名只认第一条匹配**
583
+ * (pnpm 源码 evaluateVersionPolicy 命中 name 就 return)⇒ 同一个包写成多条 `name@v1`/`name@v2`
584
+ * 时**只有第一条生效**,必须写成同一条规则 `name@v1 || v2`,或用通配符。
585
+ */
586
+ export function releaseAgeFrom(text) {
587
+ const source = String(text || "");
588
+ if (!source.includes("MINIMUM_RELEASE_AGE_VIOLATION")) return null;
589
+ const entries = [];
590
+ let cutoff = null;
591
+ for (const line of source.split(/\r?\n/)) {
592
+ const matched = /(\S+) was published at ([\dT:.Z+-]+), within the minimumReleaseAge cutoff \(([\dT:.Z+-]+)\)/.exec(line);
593
+ if (matched === null) continue;
594
+ const at = matched[1].lastIndexOf("@");
595
+ entries.push({
596
+ /* scoped 包(@scope/name@1.2.3)取最后一个 @ 才是版本分隔符 */
597
+ name: at > 0 ? matched[1].slice(0, at) : matched[1],
598
+ version: at > 0 ? matched[1].slice(at + 1) : "",
599
+ publishedAt: matched[2],
600
+ });
601
+ if (cutoff === null) cutoff = matched[3];
602
+ }
603
+ const counted = /(\d+) lockfile entr(?:y|ies) failed verification/.exec(source);
604
+ return {
605
+ /* 头部条数可能大于可见条数(pnpm 超过上限会省略 "…and N more"),两个都留着 */
606
+ count: counted ? Number(counted[1]) : entries.length,
607
+ cutoff,
608
+ entries,
609
+ };
223
610
  }
224
611
 
225
612
  /** Same extraction, exposed for tests (input is the raw captured output). */
@@ -242,10 +629,18 @@ function jobView() {
242
629
  return {
243
630
  active: installJob.active,
244
631
  stage: installJob.stage,
632
+ verb: installJob.verb,
245
633
  target: installJob.target,
246
634
  seconds: installJob.active ? Math.round((Date.now() - installJob.startedAt) / 1000) : 0,
247
635
  code: installJob.code,
248
636
  error: installJob.error,
637
+ why: installJob.why,
638
+ reject: installJob.reject,
639
+ pkg: installJob.pkg,
640
+ before: installJob.before,
641
+ after: installJob.after,
642
+ outcome: installJob.outcome,
643
+ changed: installJob.changed,
249
644
  tail: installJob.output.length > 0 ? tail() : "",
250
645
  };
251
646
  }
@@ -292,6 +687,8 @@ export function pkgState(pkg, manifest = profileManifest()) {
292
687
  const cache = new Map();
293
688
  /** /api/best 单键缓存(榜单每月只重算一次,5 分钟缓存足够) */
294
689
  let bestCache = { at: 0, value: null };
690
+ /** /api/sets 单键缓存(套装同样每月才同步一次,缓存策略与 /best 一致) */
691
+ let setsCache = { at: 0, value: null };
295
692
  let eventWindow = { startedAt: 0, count: 0 };
296
693
 
297
694
  /**
@@ -448,8 +845,12 @@ function slim(item) {
448
845
  src: pkgName ? "npm" : "repo",
449
846
  /** 站点是否验证通过(pass);未验证/警告都按保守处理 */
450
847
  verified,
451
- // `--profile web` 是 dsh CLI 必需参数;target 已是同口径的结果
452
- cmd: target ? `dsh plugin --profile web add ${target}` : null,
848
+ /* ⚠️ 这里必须用**本机真实 profile**,不能抄站点详情页的 `--profile web`(2026-10-12 修正)。
849
+ 原先照抄站点口径是想"两个出口给同一句话",但对 desktop profile 的用户来说,
850
+ 复制出来的命令会装进 **web** profile —— 桌面上永远看不到那个插件,
851
+ 用户只会得出"安装不成功"(实测用户就是这么撞上的)。
852
+ 站点无法知道你本机用的是哪个 profile,所以这一处**必须分歧**:命令是给人当场执行的。 */
853
+ cmd: target ? `dsh plugin --profile ${PROFILE} add ${target}` : null,
453
854
  };
454
855
  }
455
856
 
@@ -483,7 +884,7 @@ async function fetchCatalog(params) {
483
884
  const now = Date.now();
484
885
  const hit = cache.get(key);
485
886
  if (hit && now - hit.at < CACHE_TTL_MS) {
486
- return { count: hit.value.count, plugins: hit.value.plugins, cached: true, fetchedAt: hit.at };
887
+ return { count: hit.value.count, total: hit.value.total, plugins: hit.value.plugins, cached: true, fetchedAt: hit.at };
487
888
  }
488
889
 
489
890
  const controller = new AbortController();
@@ -500,7 +901,13 @@ async function fetchCatalog(params) {
500
901
  if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
501
902
  const body = await response.json();
502
903
  const list = Array.isArray(body && body.plugins) ? body.plugins : [];
503
- const value = { count: list.length, plugins: list.map(slim) };
904
+ /* 上游同时给两个数:count = 本次返回条数,total = 该筛选下的真实命中总数。
905
+ ⚠️ 以前只取 list.length 当结果数,于是「共 N 条结果」里的 N 永远等于 take
906
+ (默认 30)—— 搜索前后这个数字完全不变,用户据此判定「搜索不生效」
907
+ (2026-09-30 实测:搜「统计」真实命中 106 条,面板写死「共 30 条结果」)。
908
+ total 缺失时退回 list.length,保证老上游下文案仍有意义。 */
909
+ const total = Number.isFinite(body && body.total) ? body.total : list.length;
910
+ const value = { count: list.length, total, plugins: list.map(slim) };
504
911
  cache.set(key, { at: Date.now(), value });
505
912
  return { ...value, cached: false, fetchedAt: Date.now() };
506
913
  } finally {
@@ -559,6 +966,89 @@ async function fetchBest() {
559
966
  }
560
967
  }
561
968
 
969
+ /**
970
+ * 「组合方案套装」(站点 /api/sets 的同源数据,2026-10-13 新增)。
971
+ *
972
+ * 与 /best 的分工:best 是同类**横向**最优(按小类导购);sets 是跨插件**纵向**
973
+ * 组合(一整套协作方案 + 安装顺序 + 冲突提示)。两者都回答"该装哪个",但粒度不同 ——
974
+ * 用户说"我要做 OCR"时,套装才是答案。
975
+ *
976
+ * ⚠️ 命令一律**由本机拼装**,不抄站点给的字符串:
977
+ * · 站点侧的命令常量 profile 是 `web`,而本机可能是 desktop(抄了就是错命令,
978
+ * 桌面用户装进 web profile 后永远看不到 —— 2026-10-12 已实测踩过);
979
+ * · 站点条目自带 `pluginTier`(core|related)与 `installCheck`,`slim` 已有同一套
980
+ * target 口径(pass 用包名,否则 owner/repo)+ 本机 profile 注入;
981
+ * · `related`(MCP / Koishi / 通用客户端等无 npm 归属可核验的生态)走 git clone ——
982
+ * 与站点 lib/installCmd.ts 的 resolveSetItemCommand 同为一条规则。
983
+ * 批量命令 = 逐条命令按安装顺序换行拼接(与站点 buildSetInstallBlock 同语义)。
984
+ *
985
+ * ⚠️ 套装条目的 `tier`(套装内必要性 required|enhance|optional)与插件的 `tier`
986
+ * (生态分层 core|related)**同名不同义**,传输时后者已由站点改名为 `pluginTier`。
987
+ */
988
+ async function fetchSets() {
989
+ const now = Date.now();
990
+ if (setsCache.value && now - setsCache.at < CACHE_TTL_MS) {
991
+ return { ...setsCache.value, cached: true, fetchedAt: setsCache.at };
992
+ }
993
+ const controller = new AbortController();
994
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
995
+ try {
996
+ const response = await fetch(SETS_UPSTREAM, {
997
+ headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
998
+ signal: controller.signal,
999
+ });
1000
+ if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
1001
+ const body = await response.json();
1002
+ const installed = installedMap();
1003
+ const sets = (Array.isArray(body && body.sets) ? body.sets : []).map((set) => {
1004
+ const items = (Array.isArray(set.items) ? set.items : []).map((raw) => {
1005
+ /* tier 覆盖成**插件的**生态分层再交给 slim —— 否则 slim 会把套装必要性
1006
+ (required/enhance/optional)当生态分层读,"related → git clone" 永远不成立。 */
1007
+ const shaped = slim(Object.assign({}, raw, { tier: raw.pluginTier, category: null }));
1008
+ if (shaped.tier === "related" && shaped.fullName) {
1009
+ shaped.cmd = `git clone https://github.com/${shaped.fullName}.git`;
1010
+ shaped.src = "repo";
1011
+ }
1012
+ return Object.assign(shaped, {
1013
+ /* 套装内必要性(与 slim 的 tier 不是一回事,单列一个字段避免混用) */
1014
+ need: raw.tier || "enhance",
1015
+ /* 槽位职责:这个"位置"是干什么的(滚动槽位每月可能换人,所以不写插件名) */
1016
+ slotRole: raw.slotRole || null,
1017
+ installed: installedOf(shaped, installed),
1018
+ });
1019
+ });
1020
+ return {
1021
+ slug: set.slug || null,
1022
+ name: set.name || null,
1023
+ summary: set.summary || "",
1024
+ audience: set.audience || null,
1025
+ sceneLabel: set.sceneLabel || null,
1026
+ itemCount: items.length,
1027
+ risk: set.risk || null,
1028
+ syncedMonth: set.syncedMonth || null,
1029
+ syncedSlots: typeof set.syncedSlots === "number" ? set.syncedSlots : null,
1030
+ syncedReplaced: typeof set.syncedReplaced === "number" ? set.syncedReplaced : null,
1031
+ conflictNote: set.conflictNote || null,
1032
+ steps: set.steps || null,
1033
+ exampleParams: set.exampleParams || null,
1034
+ effectNote: set.effectNote || null,
1035
+ url: set.url ? `${SITE}${set.url}` : null,
1036
+ /* 批量安装命令:逐条命令按顺序换行拼接(顺序即安装顺序) */
1037
+ installBlock: items.map((item) => item.cmd).filter(Boolean).join("\n"),
1038
+ items,
1039
+ };
1040
+ }).filter((set) => set.itemCount > 0);
1041
+ const value = {
1042
+ total: sets.length,
1043
+ sets,
1044
+ };
1045
+ setsCache = { at: Date.now(), value };
1046
+ return { ...value, cached: false, fetchedAt: Date.now() };
1047
+ } finally {
1048
+ clearTimeout(timer);
1049
+ }
1050
+ }
1051
+
562
1052
  function withinEventBudget() {
563
1053
  const now = Date.now(); if (now - eventWindow.startedAt > EVENT_WINDOW_MS) {
564
1054
  eventWindow = { startedAt: now, count: 0 };
@@ -610,8 +1100,10 @@ function buildTrackPayload(input) {
610
1100
  // 旧版 open 事件用的字段名是 `scope`,保留兼容,避免同一含义两个键。
611
1101
  const via = detail.via || detail.scope;
612
1102
  if (via) parts.push("via=" + clean(via, 12));
613
- // `why` 是**闭集枚举**(market_http / busy / timeout / cli_exit …),
1103
+ // `why` 是**闭集枚举**(http_405 / network / busy / timeout / cli_exit …),
614
1104
  // 不是错误原文:原文可能含本地路径与包名,既超长又不可聚合。
1105
+ // 2026-09-30 起 HTTP 失败细化为 `http_<status>`(原 market_http 已被取代)——
1106
+ // 只有区分 405(路由缺席)/403(被拦)/5xx(上游故障)才能定位市场通道的问题。
615
1107
  if (detail.why) parts.push("why=" + clean(detail.why, 24));
616
1108
  // 布尔量只在**明确知道**时才写入(调用方不传即省略)。
617
1109
  // 省略 = 未知,与 `=0`(明确为否)必须在数据层可区分 —— 否则「查不到」
@@ -636,6 +1128,460 @@ function registerRoute(ctx, pathname, handler) {
636
1128
  );
637
1129
  }
638
1130
 
1131
+ /* --------------------------------------------------------------- 更新日志 */
1132
+ /** /api/dpharness/changelog 的结果缓存(日志正文与版本号都不是秒级变化的数据)。 */
1133
+ let changelogCache = null;
1134
+
1135
+ /**
1136
+ * 任一个包在 npm 上的最新版(走 npmmirror)。本插件自身与「已装插件」的检查共用它。
1137
+ *
1138
+ * 查不到就返回 null —— **既不编造版本号,也不把「查不到」当成「已是最新」**:
1139
+ * 这两件事在界面上是两句不同的话,混为一谈会让离线用户以为自己已经最新而错过升级。
1140
+ * (同类三态问题本插件已踩过一次:postinstall 的 restarted 绝不用 false 兜底。)
1141
+ */
1142
+ async function fetchNpmVersion(pkg) {
1143
+ const controller = new AbortController();
1144
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1145
+ try {
1146
+ const response = await fetch(npmLatestUrl(pkg), {
1147
+ headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
1148
+ signal: controller.signal,
1149
+ });
1150
+ if (!response.ok) throw new Error(`npm HTTP ${response.status}`);
1151
+ const body = await response.json();
1152
+ const version = body && typeof body.version === "string" ? body.version.trim() : "";
1153
+ return /^\d+\.\d+\.\d+/.test(version) ? version : null;
1154
+ } catch (error) {
1155
+ return null;
1156
+ } finally {
1157
+ clearTimeout(timer);
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * GitHub Releases(可选增强)。
1163
+ *
1164
+ * 仓库没发过 Release 时 GitHub 返回 `[]`(实测 2026-10-12 就是这种状态),
1165
+ * 网络/代理失败返回 null —— 两者都不该让「更新日志」整体不可用,故一律降级到内置底稿。
1166
+ */
1167
+ async function fetchReleases() {
1168
+ const controller = new AbortController();
1169
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1170
+ try {
1171
+ const response = await fetch(RELEASES_URL, {
1172
+ headers: { accept: "application/vnd.github+json", "user-agent": `dsh-dpharness/${VERSION}` },
1173
+ signal: controller.signal,
1174
+ });
1175
+ if (!response.ok) throw new Error(`github HTTP ${response.status}`);
1176
+ const body = await response.json();
1177
+ return Array.isArray(body) ? body : [];
1178
+ } catch (error) {
1179
+ return null;
1180
+ } finally {
1181
+ clearTimeout(timer);
1182
+ }
1183
+ }
1184
+
1185
+ /* --------------------------------------------- 已装插件的更新检查(v0.5.0) */
1186
+ /** 逐包出站请求的并发上限。全串行会拖到十几秒,全并发容易触发镜像限流。 */
1187
+ const UPDATE_CONCURRENCY = 6;
1188
+ /** 结果缓存。比目录的 5 分钟更长:这一段是 N 个出站请求,不该被反复触发。 */
1189
+ const UPDATE_TTL_MS = 10 * 60 * 1000;
1190
+ /** 「检查更新」按钮连点时的最小间隔:缓存可以绕过,但镜像不能被连点打爆。 */
1191
+ const UPDATE_MIN_FORCE_MS = 30 * 1000;
1192
+ let updatesCache = { at: 0, value: null };
1193
+
1194
+ /** profile 目录。与 profileManifest() 同源,避免两处各拼一次路径。 */
1195
+ function profileDir() {
1196
+ return path.join(os.homedir(), ".dsh", "profiles", PROFILE);
1197
+ }
1198
+
1199
+ /**
1200
+ * profile 里声明过的依赖清单(即「用户装了什么」)。
1201
+ *
1202
+ * 纯函数 + 入参可注入,便于单测;`bundled` 与 pkgState() 同口径
1203
+ * —— bundles 是更强的信号:包躺在 node_modules 里也可能根本没被加载。
1204
+ */
1205
+ export function pluginCandidates(manifest) {
1206
+ if (manifest === null || typeof manifest !== "object") return [];
1207
+ const deps = manifest.dependencies && typeof manifest.dependencies === "object" ? manifest.dependencies : null;
1208
+ if (deps === null) return [];
1209
+ const profile = manifest.dsh && manifest.dsh.profile ? manifest.dsh.profile : null;
1210
+ const bundles = profile && Array.isArray(profile.bundles) ? profile.bundles : [];
1211
+ /* spec 一并带出来:它决定"这个包能不能靠 plugin add 升级"(见 classifySpec) */
1212
+ return Object.keys(deps).sort().map((name) => ({
1213
+ name,
1214
+ bundled: bundles.includes(name),
1215
+ spec: typeof deps[name] === "string" ? deps[name] : "",
1216
+ }));
1217
+ }
1218
+
1219
+ /**
1220
+ * 依赖 spec 的形态 —— 它决定"还能不能升级",这是实测撞出来的三类:
1221
+ *
1222
+ * local : `link:…` / `file:…` —— **本地开发链接**,指向本机源码目录。
1223
+ * "升级"它等于去装 npm 上的版本,既会被 dsh 的兼容性闸门拒,
1224
+ * **语义上也是错的**(用户自己正在开发这个包)。实测本机 desktop profile
1225
+ * 20 个依赖里有 11 个是这种,其中就包括本插件自己。
1226
+ * pinned : `0.5.27` 这种**精确锁定**。`plugin add` 不会把它挪走(实测版本号纹丝不动)。
1227
+ * range : `^0.8.5` 这类允许浮动的范围。
1228
+ *
1229
+ * 判定只看清单里写的形态,不猜语义 —— 猜错会误伤(比如把范围包当成锁定包)。
1230
+ */
1231
+ export function classifySpec(spec) {
1232
+ const value = String(spec || "");
1233
+ if (value.startsWith("link:") || value.startsWith("file:")) return "local";
1234
+ if (/^\d/.test(value)) return "pinned";
1235
+ return "range";
1236
+ }
1237
+
1238
+ /**
1239
+ * 读一个已装包在 profile 里的实际版本,并判断它是不是 dsh 插件。
1240
+ *
1241
+ * 判据按**插件契约**判,不按包名猜(`dsh-` 前缀不是契约,第三方包名五花八门):
1242
+ * · package.json 里声明了 dsh 字段(dsh.bundle / dsh.client),或
1243
+ * · 依赖里出现 @deepseek-ai/dsh —— 与站点 lib/detect.ts 的分层判据同源。
1244
+ * 读不到返回 null(未知),调用方必须把它和「不是插件」分开处理。
1245
+ */
1246
+ export function readInstalled(name, dir = profileDir()) {
1247
+ try {
1248
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, "node_modules", name, "package.json"), "utf8"));
1249
+ const deps = manifest.dependencies && typeof manifest.dependencies === "object" ? manifest.dependencies : {};
1250
+ const peers = manifest.peerDependencies && typeof manifest.peerDependencies === "object" ? manifest.peerDependencies : {};
1251
+ return {
1252
+ version: typeof manifest.version === "string" ? manifest.version : null,
1253
+ plugin: Boolean(manifest.dsh && typeof manifest.dsh === "object")
1254
+ || Object.prototype.hasOwnProperty.call(deps, "@deepseek-ai/dsh")
1255
+ || Object.prototype.hasOwnProperty.call(peers, "@deepseek-ai/dsh"),
1256
+ /* 原文描述。中文名/说明都没有时,界面拿它兜底并明确标注「未汉化」——不假装有中文。 */
1257
+ desc: typeof manifest.description === "string" ? manifest.description.trim().slice(0, 200) : "",
1258
+ };
1259
+ } catch (error) {
1260
+ return null;
1261
+ }
1262
+ }
1263
+
1264
+ /* -------------------------------------- 已装插件的「这是谁」(v0.5.0) */
1265
+ /**
1266
+ * 只显示 npm 包名(dsh-context / billion-context),用户认不出这是哪个插件 ——
1267
+ * 「更新」页面的价值就塌了一半(它要回答的是"我装的哪些该升级",前提是认得出是谁)。
1268
+ *
1269
+ * 两个来源**互补且都不完整**(2026-10-12 实测本机 desktop profile 的 20 个依赖):
1270
+ * · 本机 `<pkg>/locale/zh.json` 的 meta.title:15/20 —— 离线、零请求,
1271
+ * 而且是**包自己声明**的,最贴近"这是谁";
1272
+ * · 站点目录(`take=500`,而目录共 17304 条):9/20 —— 但补上了本机完全没有的那 5 个。
1273
+ * 并集 20/20。单用任何一个都会让一部分插件只剩裸包名 —— 那就等于没说。
1274
+ */
1275
+ const IDENTITY_TTL_MS = 30 * 60 * 1000;
1276
+ let identityCache = { at: 0, value: new Map() };
1277
+
1278
+ /**
1279
+ * 读包自己声明的中文元数据(离线)。读不到返回 null —— **不猜、不翻译、不编造**。
1280
+ *
1281
+ * 顺带清掉 meta.title 里常见的那截包名:社区惯例写成
1282
+ * 「模型优惠时钟 (dsh-client-ui-model-clock)」,而包名在界面上另有位置,
1283
+ * 重复一次只会让行更挤。只在括号里含 ASCII 字母时才当它是包名(「插件(官方)」不该被砍)。
1284
+ */
1285
+ export function localIdentity(name, dir = profileDir()) {
1286
+ const base = path.join(dir, "node_modules", name, "locale");
1287
+ for (const file of ["zh.json", "zh-CN.json"]) {
1288
+ try {
1289
+ const meta = JSON.parse(fs.readFileSync(path.join(base, file), "utf8")).meta || {};
1290
+ const title = typeof meta.title === "string" ? meta.title.trim() : "";
1291
+ if (!/[\u4e00-\u9fff]/.test(title)) continue;
1292
+ const cleaned = title.replace(/\s*[((][^))]*[A-Za-z@][^))]*[))]\s*$/, "").trim() || title;
1293
+ return { nameZh: cleaned.slice(0, 40), note: pickZh(meta.description, 80) || "" };
1294
+ } catch (error) {
1295
+ /* 没有这个文件、或不是 JSON —— 继续试下一个候选文件名 */
1296
+ }
1297
+ }
1298
+ return null;
1299
+ }
1300
+
1301
+ /** 站点目录里 pkgName → { nameZh, note } 的映射(一次 take=500,缓存)。 */
1302
+ async function fetchCatalogIdentity() {
1303
+ const now = Date.now();
1304
+ if (now - identityCache.at < IDENTITY_TTL_MS) return identityCache.value;
1305
+ const controller = new AbortController();
1306
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1307
+ try {
1308
+ const response = await fetch(`${UPSTREAM}?take=500`, {
1309
+ headers: { accept: "application/json", "user-agent": `dsh-dpharness/${VERSION}` },
1310
+ signal: controller.signal,
1311
+ });
1312
+ if (!response.ok) throw new Error(`upstream HTTP ${response.status}`);
1313
+ const body = await response.json();
1314
+ const map = new Map();
1315
+ (Array.isArray(body && body.plugins) ? body.plugins : []).forEach((item) => {
1316
+ const pkg = item && item.installCheck && item.installCheck.pkgName;
1317
+ if (!pkg) return;
1318
+ const nameZh = typeof item.nameZh === "string" && /[\u4e00-\u9fff]/.test(item.nameZh) ? item.nameZh.trim().slice(0, 40) : "";
1319
+ const note = pickZh(item.tagline, 80) || pickZh(item.descriptionZh, 80) || "";
1320
+ if (nameZh || note) map.set(pkg, { nameZh, note });
1321
+ });
1322
+ identityCache = { at: now, value: map };
1323
+ return map;
1324
+ } catch (error) {
1325
+ /* 站点不可达就只靠本机 locale —— 降级,不影响更新检查本身 */
1326
+ return new Map();
1327
+ } finally {
1328
+ clearTimeout(timer);
1329
+ }
1330
+ }
1331
+
1332
+ /** 安装目录里的版本号;查不到返回 null(未知,不等于"没装")。 */
1333
+ function installedVersionOf(pkg) {
1334
+ const info = readInstalled(pkg);
1335
+ return info ? info.version : null;
1336
+ }
1337
+
1338
+ /** 一个目录条目对应的已装版本(先按 npm 包名查,退回 owner/repo),查不到就 null。 */
1339
+ function installedOf(item, map) {
1340
+ if (!item || !map) return null;
1341
+ return map[item.pkg || ""] || map[item.fullName || ""] || null;
1342
+ }
1343
+
1344
+ /**
1345
+ * profile 里"已装了哪些、装的什么版本"(键为包名)。
1346
+ *
1347
+ * 用途:目录卡片上把「安装」标成「已安装 vX」—— 实测有用户对着一个早就装好的插件
1348
+ * 反复点「安装」,然后判定"安装不成功"(他无从知道那东西其实已经在跑了)。
1349
+ * 30 秒缓存:搜索是边打字边发的,不该每次都读几十个 package.json。
1350
+ */
1351
+ let installedCache = { at: 0, value: {} };
1352
+ function installedMap() {
1353
+ const now = Date.now();
1354
+ if (now - installedCache.at < 30 * 1000) return installedCache.value;
1355
+ const dir = profileDir();
1356
+ const map = {};
1357
+ pluginCandidates(profileManifest()).forEach((row) => {
1358
+ const info = readInstalled(row.name, dir);
1359
+ if (info && info.version) map[row.name] = info.version;
1360
+ });
1361
+ installedCache = { at: now, value: map };
1362
+ return map;
1363
+ }
1364
+
1365
+ /** 带并发上限的 map:保住顺序,也别把镜像打爆。 */
1366
+ async function mapLimit(items, limit, worker) {
1367
+ const results = new Array(items.length);
1368
+ let cursor = 0;
1369
+ const runners = [];
1370
+ for (let index = 0; index < Math.min(limit, items.length); index += 1) {
1371
+ runners.push((async () => {
1372
+ while (cursor < items.length) {
1373
+ /* 取号与自增都是**同步**完成的(在 await 之前),所以两个 runner 不会拿到同一个下标 */
1374
+ const current = cursor;
1375
+ cursor += 1;
1376
+ results[current] = await worker(items[current], current);
1377
+ }
1378
+ })());
1379
+ }
1380
+ await Promise.all(runners);
1381
+ return results;
1382
+ }
1383
+
1384
+ /** 排序权重:可升级的最前,其次未知,最后已最新 —— 让「该做什么」排在最上面。 */
1385
+ function rankUpdate(entry) {
1386
+ if (entry.outdated === true) return 0;
1387
+ if (entry.outdated === null) return 1;
1388
+ return 2;
1389
+ }
1390
+
1391
+ /** 按「可升级 → 未知 → 已最新,再按包名」排序(就地排序,返回同一个数组便于断言)。 */
1392
+ export function sortUpdates(entries) {
1393
+ return (Array.isArray(entries) ? entries : []).slice().sort((a, b) => (rankUpdate(a) - rankUpdate(b)) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1394
+ }
1395
+
1396
+ /**
1397
+ * 组装一次完整的更新检查结果:本插件自身 + 已装插件。
1398
+ *
1399
+ * 本插件**从已装列表里摘出来单独给**(self)—— 它同时出现在 profile 的 dependencies 里,
1400
+ * 两处都列会让人以为有两个不同的东西要升级。
1401
+ */
1402
+ /** pluginManager 的已知拒绝原因(界面据此出中文;不在表里的原样展示)。 */
1403
+ const TOGGLE_FAILURE_CODES = ["unknown-plugin", "management-required", "unaddressable", "incompatible-version"];
1404
+
1405
+ /** 使用频次引擎失败时不产出结论(三态),绝不让「没测到」冒充「没在用」。 */
1406
+ function safeUsageReport() {
1407
+ try {
1408
+ return getUsageReport();
1409
+ } catch {
1410
+ return null;
1411
+ }
1412
+ }
1413
+
1414
+ /**
1415
+ * 启用状态(三态):从运行时 `pluginManager` 服务读取。
1416
+ * 服务不存在(或读取失败)→ null,全部按「未知」处理,不猜。
1417
+ */
1418
+ async function enabledMapOf(ctx) {
1419
+ try {
1420
+ const manager = ctx && typeof ctx.get === "function" ? ctx.get("pluginManager") : undefined;
1421
+ if (!manager || typeof manager.listPlugins !== "function") return null;
1422
+ const rows = await manager.listPlugins();
1423
+ const map = new Map();
1424
+ for (const row of Array.isArray(rows) ? rows : []) {
1425
+ if (row && typeof row.moduleName === "string") map.set(row.moduleName, row.enabled !== false);
1426
+ }
1427
+ return map;
1428
+ } catch {
1429
+ return null;
1430
+ }
1431
+ }
1432
+
1433
+ /** 安装/最近变化时间(粗略):node_modules/<pkg> 的 mtime。link: 包指向源码目录,不适用,给 null。 */
1434
+ function installedAtOf(name, dir, kind) {
1435
+ if (kind === "local") return null;
1436
+ try {
1437
+ return fs.statSync(path.join(dir, "node_modules", name)).mtimeMs || null;
1438
+ } catch {
1439
+ return null;
1440
+ }
1441
+ }
1442
+
1443
+ /** 单个包的使用记录;引擎不可用给 null,无归属工具的包给 { measurable:false }。 */
1444
+ function usageFor(usageReport, pkg) {
1445
+ if (!usageReport) return null;
1446
+ const found = usageReport.plugins && usageReport.plugins[pkg];
1447
+ if (found) return found;
1448
+ return { measurable: false, calls: 0, sessions: 0, lastUsedMs: null, tools: [] };
1449
+ }
1450
+
1451
+ async function buildUpdates(ctx) {
1452
+ const dir = profileDir();
1453
+ const candidates = pluginCandidates(profileManifest());
1454
+ const usageReport = safeUsageReport();
1455
+ const enabledByPkg = await enabledMapOf(ctx);
1456
+ const installed = await mapLimit(candidates, UPDATE_CONCURRENCY, (candidate) => readInstalled(candidate.name, dir));
1457
+ const rows = candidates.map((candidate, index) => ({ ...candidate, info: installed[index], kind: classifySpec(candidate.spec) }));
1458
+ /* 本地链接的包**不参与更新检查**:它们的"版本"来自本机源码,跟 npm 上的最新版没有关系。
1459
+ 实测本机 desktop profile 的 20 个依赖里有 11 个是这种(含本插件自己)——
1460
+ 把它们当"可升级"列出来,只会让用户点一次、失败一次(而且方向本来就是错的)。 */
1461
+ const locals = rows.filter((row) => row.kind === "local").map((row) => {
1462
+ const usageRow = usageFor(usageReport, row.name);
1463
+ const enabled = enabledByPkg ? (enabledByPkg.has(row.name) ? enabledByPkg.get(row.name) : null) : null;
1464
+ return {
1465
+ name: row.name,
1466
+ spec: row.spec,
1467
+ enabled,
1468
+ installedAtMs: installedAtOf(row.name, dir, row.kind),
1469
+ usage: usageRow,
1470
+ tier: classifyUsage(enabled, usageRow),
1471
+ };
1472
+ });
1473
+ const plugins = rows.filter((row) => row.kind !== "local" && row.info && row.info.plugin && row.name !== PKG_NAME);
1474
+ const versions = await mapLimit(plugins, UPDATE_CONCURRENCY, (row) => fetchNpmVersion(row.name));
1475
+
1476
+ /* 「这是谁」:先读本机 locale(离线、零请求),缺口再用站点目录补一次 —— 并集才完整 */
1477
+ const identity = new Map();
1478
+ plugins.forEach((row) => {
1479
+ const found = localIdentity(row.name, dir);
1480
+ if (found) identity.set(row.name, found);
1481
+ });
1482
+ if (plugins.some((row) => {
1483
+ const found = identity.get(row.name);
1484
+ return !found || !found.nameZh || !found.note;
1485
+ })) {
1486
+ const site = await fetchCatalogIdentity();
1487
+ plugins.forEach((row) => {
1488
+ const extra = site.get(row.name);
1489
+ if (!extra) return;
1490
+ const found = identity.get(row.name) || { nameZh: "", note: "" };
1491
+ identity.set(row.name, { nameZh: found.nameZh || extra.nameZh, note: found.note || extra.note });
1492
+ });
1493
+ }
1494
+
1495
+ let selfIdentity = localIdentity(PKG_NAME, dir);
1496
+ if (!selfIdentity || !selfIdentity.nameZh || !selfIdentity.note) {
1497
+ const extra = (await fetchCatalogIdentity()).get(PKG_NAME);
1498
+ if (extra) {
1499
+ selfIdentity = {
1500
+ nameZh: (selfIdentity && selfIdentity.nameZh) || extra.nameZh,
1501
+ note: (selfIdentity && selfIdentity.note) || extra.note,
1502
+ };
1503
+ }
1504
+ }
1505
+ if (!selfIdentity) selfIdentity = { nameZh: "", note: "" };
1506
+
1507
+ const selfLatest = await fetchNpmVersion(PKG_NAME);
1508
+ const entries = sortUpdates(plugins.map((row, index) => {
1509
+ const current = row.info.version;
1510
+ const latest = versions[index];
1511
+ const found = identity.get(row.name) || { nameZh: "", note: "" };
1512
+ const usageRow = usageFor(usageReport, row.name);
1513
+ const enabled = enabledByPkg ? (enabledByPkg.has(row.name) ? enabledByPkg.get(row.name) : null) : null;
1514
+ return {
1515
+ name: row.name,
1516
+ /* 中文名可能为空 —— 界面回落显示包名,并明确标注「未汉化」,绝不假装有中文 */
1517
+ nameZh: found.nameZh,
1518
+ /* 说明:优先包自己/站点的中文,其次本机 package.json 的原文(英文,界面会标未汉化) */
1519
+ note: found.note || row.info.desc,
1520
+ bundled: row.bundled,
1521
+ /* 清单里的 spec 与它的形态(range / pinned)。界面据此说明"为什么升不动"。 */
1522
+ spec: row.spec,
1523
+ kind: row.kind,
1524
+ current,
1525
+ latest,
1526
+ /* 使用频次与保留价值(本机计算、零上传;详见 lib/usage.js 的口径说明) */
1527
+ enabled,
1528
+ installedAtMs: installedAtOf(row.name, dir, row.kind),
1529
+ usage: usageRow,
1530
+ /* 等级:core/common/occasional/silent/disabled/unmeasurable/unknown —— 客户端直接消费 */
1531
+ tier: classifyUsage(enabled, usageRow),
1532
+ /* 三态:任一端拿不到就不下结论(null),绝不用 false 兜底 */
1533
+ outdated: latest && current ? compareVersions(current, latest) < 0 : null,
1534
+ /* ⚠️ 用**具体版本号**(dsh-context@0.69.1),不要 `@latest`。
1535
+ 实测(2026-10-12,桌面版 dsh 0.2.0-rc.2):
1536
+ dsh plugin --profile desktop add dsh-context@latest → 静默空转(pnpm.log 0 字节、版本不动)
1537
+ dsh plugin --profile desktop add dsh-context@0.69.1 → 成功(Done in 1.7s)
1538
+ 既然更新检查已经知道目标版本,就没有理由再走那条空转的路。 */
1539
+ upgrade: latest
1540
+ ? `dsh plugin --profile ${PROFILE} add ${row.name}@${latest}`
1541
+ : `dsh plugin --profile ${PROFILE} add ${row.name}@latest`,
1542
+ };
1543
+ }));
1544
+
1545
+ return {
1546
+ ok: true,
1547
+ rev: SHAPE_REV,
1548
+ profile: PROFILE,
1549
+ fetchedAt: Date.now(),
1550
+ self: {
1551
+ name: PKG_NAME,
1552
+ nameZh: selfIdentity.nameZh,
1553
+ note: selfIdentity.note,
1554
+ current: VERSION,
1555
+ latest: selfLatest,
1556
+ outdated: selfLatest ? compareVersions(VERSION, selfLatest) < 0 : null,
1557
+ /* 同已装插件:走具体版本号,`@latest` 在 dsh 这条路上是空转的(见 buildUpdates 的注释) */
1558
+ upgrade: selfLatest
1559
+ ? `dsh plugin --profile ${PROFILE} add ${PKG_NAME}@${selfLatest}`
1560
+ : `dsh plugin --profile ${PROFILE} add ${PKG_NAME}@latest`,
1561
+ },
1562
+ plugins: entries,
1563
+ /* 使用频次统计口径(本机计算,零上传)。null = 引擎不可用,客户端按「无法度量」展示 */
1564
+ usageMeta: usageReport
1565
+ ? {
1566
+ windowDays: usageReport.windowDays,
1567
+ generatedAtMs: usageReport.generatedAtMs,
1568
+ cacheAgeMs: usageReport.cacheAgeMs,
1569
+ scanned: usageReport.scanned,
1570
+ }
1571
+ : null,
1572
+ /* 本地链接的包(link:/file:)单列:它们不参与更新检查,但用户需要知道"它们为什么不在列表里" */
1573
+ locals: locals,
1574
+ counts: {
1575
+ installed: candidates.length,
1576
+ skipped: candidates.length - plugins.length,
1577
+ local: locals.length,
1578
+ checked: entries.length,
1579
+ outdated: entries.filter((entry) => entry.outdated === true).length,
1580
+ unknown: entries.filter((entry) => entry.outdated === null).length,
1581
+ },
1582
+ };
1583
+ }
1584
+
639
1585
  export function apply(ctx) {
640
1586
  // 「分类精选」:站点 /best 专区的同源数据(月度策展,每小类 2~3 个)
641
1587
  registerRoute(ctx, "/api/dpharness/best", async (req, res) => {
@@ -653,7 +1599,34 @@ export function apply(ctx) {
653
1599
  fetchedAt: new Date(result.fetchedAt).toISOString(),
654
1600
  month: result.month,
655
1601
  total: result.total,
656
- categories: result.categories,
1602
+ /* 同搜索:给榜单条目也标上「已安装 vX」(那几张卡片同样有「安装」按钮) */
1603
+ categories: (Array.isArray(result.categories) ? result.categories : []).map((cat) => Object.assign({}, cat, {
1604
+ subs: (Array.isArray(cat.subs) ? cat.subs : []).map((sub) => Object.assign({}, sub, {
1605
+ items: (Array.isArray(sub.items) ? sub.items : []).map((item) => Object.assign({}, item, { installed: installedOf(item, installedMap()) })),
1606
+ })),
1607
+ })),
1608
+ });
1609
+ } catch (error) {
1610
+ sendJson(res, 502, { ok: false, error: String((error && error.message) || error) });
1611
+ }
1612
+ });
1613
+
1614
+ // 「组合方案套装」:站点 /sets 专区的同源数据(跨插件纵向组合,见 fetchSets 注释)
1615
+ registerRoute(ctx, "/api/dpharness/sets", async (req, res) => {
1616
+ if (req.method !== "GET") {
1617
+ res.writeHead(405, { allow: "GET" });
1618
+ res.end();
1619
+ return;
1620
+ }
1621
+ try {
1622
+ const result = await fetchSets();
1623
+ sendJson(res, 200, {
1624
+ ok: true,
1625
+ source: `${SITE}/sets`,
1626
+ cached: result.cached,
1627
+ fetchedAt: new Date(result.fetchedAt).toISOString(),
1628
+ total: result.total,
1629
+ sets: result.sets,
657
1630
  });
658
1631
  } catch (error) {
659
1632
  sendJson(res, 502, { ok: false, error: String((error && error.message) || error) });
@@ -676,7 +1649,9 @@ export function apply(ctx) {
676
1649
  fetchedAt: new Date(result.fetchedAt).toISOString(),
677
1650
  query: Object.fromEntries(params),
678
1651
  count: result.count,
679
- plugins: result.plugins,
1652
+ total: result.total,
1653
+ /* 「已装了哪些」**不进缓存**:装完要立刻在卡片上看到「已安装 vX」 */
1654
+ plugins: result.plugins.map((item) => Object.assign({}, item, { installed: installedOf(item, installedMap()) })),
680
1655
  });
681
1656
  } catch (error) {
682
1657
  const message = error && error.name === "AbortError" ? "upstream timeout" : String((error && error.message) || error);
@@ -751,8 +1726,26 @@ export function apply(ctx) {
751
1726
  return;
752
1727
  }
753
1728
  if (installJob.active) {
754
- sendJson(res, 409, { ok: false, error: "an install is already running", job: jobView() });
755
- return;
1729
+ const elapsed = Date.now() - installJob.startedAt;
1730
+ if (elapsed > INSTALL_TIMEOUT_MS + INSTALL_SETTLE_MS) {
1731
+ /* 早已越过「超时 + 宽限」却还标着 active ⇒ 只可能是收尾路径没跑到
1732
+ (宿主从旧版本热更新上来、计时器所在进程被挂起…)。这时**自愈**比让用户去
1733
+ 重启 dsh 合理:现场实测(2026-10-14)用户因此彻底装不了任何插件,
1734
+ 而界面上只有一句英文报错、没有任何自救入口。 */
1735
+ console.warn(`[dpharness] install job stuck for ${Math.round(elapsed / 1000)}s — self-healing`);
1736
+ forceUnlock("stale", installSeq);
1737
+ } else {
1738
+ sendJson(res, 409, {
1739
+ ok: false,
1740
+ /* 保留原文:它同时是**兼容旧客户端的兜底文案**,按 why 翻的界面读 why 就好 */
1741
+ error: "an install is already running",
1742
+ /* why 是闭集枚举:界面据此出中文,别把英文原文直接摊给用户 */
1743
+ why: "busy",
1744
+ seconds: Math.round(elapsed / 1000),
1745
+ job: jobView(),
1746
+ });
1747
+ return;
1748
+ }
756
1749
  }
757
1750
  let input;
758
1751
  try {
@@ -766,8 +1759,89 @@ export function apply(ctx) {
766
1759
  sendJson(res, 400, { ok: false, error: "unsafe plugin target rejected" });
767
1760
  return;
768
1761
  }
769
- startInstall(target);
770
- sendJson(res, 202, { ok: true, target, profile: PROFILE, job: jobView() });
1762
+ /* verb 是**闭集**:只认 add / remove,别的一律按 add 走(不接受任何未枚举的动作) */
1763
+ const verb = input && input.verb === "remove" ? "remove" : "add";
1764
+ startInstall(target, verb);
1765
+ sendJson(res, 202, { ok: true, target, verb, profile: PROFILE, job: jobView() });
1766
+ });
1767
+
1768
+ /**
1769
+ * 启用/禁用(「禁用观察」通道)。
1770
+ *
1771
+ * 走运行时 `pluginManager.setPluginEnabled(entryId, enabled)`——它把改动写进 profile 的
1772
+ * patch 并即时应用(`reload`),比"卸载"温和得多:可随时恢复、不改依赖清单。
1773
+ * 与卸载一样要求两步确认在**客户端**做(这里只承接已确认的调用)。
1774
+ *
1775
+ * 三态纪律:
1776
+ * · 宿主没有该服务(旧内核)→ 501 `unsupported`(明说"不支持",不冒充失败);
1777
+ * · 同名多入口 / 无 entryId / 只读行 → 409 带 code,界面据此出中文;
1778
+ * · 改完**复读真值**——`setPluginEnabled` 可能被更高优先级的层覆盖(overridden),
1779
+ * 响应里的 `enabled` 永远是"实际状态"而不是"请求状态"。
1780
+ */
1781
+ registerRoute(ctx, "/api/dpharness/toggle", async (req, res) => {
1782
+ if (req.method !== "POST") {
1783
+ res.writeHead(405, { allow: "POST" });
1784
+ res.end();
1785
+ return;
1786
+ }
1787
+ let input;
1788
+ try {
1789
+ input = JSON.parse((await readBody(req, 2048)) || "{}");
1790
+ } catch (error) {
1791
+ sendJson(res, 400, { ok: false, error: String((error && error.message) || error) });
1792
+ return;
1793
+ }
1794
+ const name = typeof (input && input.name) === "string" ? input.name.trim().slice(0, 214) : "";
1795
+ const want = input && input.enabled === true;
1796
+ if (!name) {
1797
+ sendJson(res, 400, { ok: false, error: "missing plugin name", code: "missing-name" });
1798
+ return;
1799
+ }
1800
+ /* 禁自己等于把管理界面一起关掉:明确拒绝(卸载通道也有同样的保护) */
1801
+ if (name === PKG_NAME) {
1802
+ sendJson(res, 400, { ok: false, error: "refusing to toggle dsh-dpharness itself", code: "self" });
1803
+ return;
1804
+ }
1805
+ const manager = ctx && typeof ctx.get === "function" ? ctx.get("pluginManager") : undefined;
1806
+ if (!manager || typeof manager.listPlugins !== "function" || typeof manager.setPluginEnabled !== "function") {
1807
+ sendJson(res, 501, { ok: false, error: "toggle is not supported by this host", code: "unsupported" });
1808
+ return;
1809
+ }
1810
+ try {
1811
+ const rows = await manager.listPlugins();
1812
+ const matches = (Array.isArray(rows) ? rows : []).filter((row) => row && row.moduleName === name);
1813
+ if (matches.length === 0) {
1814
+ sendJson(res, 404, { ok: false, error: "plugin entry not found", code: "not-found" });
1815
+ return;
1816
+ }
1817
+ if (matches.length > 1) {
1818
+ sendJson(res, 409, { ok: false, error: "multiple entries share this name", code: "ambiguous" });
1819
+ return;
1820
+ }
1821
+ const row = matches[0];
1822
+ if (typeof row.entryId !== "string" || !row.entryId) {
1823
+ sendJson(res, 409, { ok: false, error: "entry cannot be addressed", code: "unaddressable" });
1824
+ return;
1825
+ }
1826
+ if (row.enabled === want) {
1827
+ sendJson(res, 200, { ok: true, name, enabled: want, changed: false });
1828
+ return;
1829
+ }
1830
+ await manager.setPluginEnabled(row.entryId, want);
1831
+ const after = (await manager.listPlugins()).find((item) => item && item.entryId === row.entryId);
1832
+ const actual = after ? after.enabled !== false : null;
1833
+ sendJson(res, 200, {
1834
+ ok: true,
1835
+ name,
1836
+ enabled: actual,
1837
+ changed: actual === want,
1838
+ ...(actual === want ? {} : { overridden: true }),
1839
+ });
1840
+ } catch (error) {
1841
+ const raw = String((error && error.message) || error);
1842
+ const code = (error && typeof error.code === "string" && error.code) || (TOGGLE_FAILURE_CODES.includes(raw) ? raw : undefined);
1843
+ sendJson(res, 409, { ok: false, error: raw, ...(code ? { code } : {}) });
1844
+ }
771
1845
  });
772
1846
 
773
1847
  /**
@@ -806,6 +1880,87 @@ export function apply(ctx) {
806
1880
  });
807
1881
  });
808
1882
 
1883
+ /**
1884
+ * 更新日志(只读)。
1885
+ *
1886
+ * 三个字段的语义必须分开、**不能互相兜底**:
1887
+ * current = 本进程加载的插件版本(来自代码常量,唯一可信来源)
1888
+ * latest = npm 最新版;null = 没查到(≠ 已是最新)
1889
+ * outdated = true / false / null(null = 无从判断,例:离线)
1890
+ * 同一条响应里给出 upgrade 命令,并用**本机真实 profile** 拼 —— 用户不用猜 profile 名
1891
+ * (桌面版是 desktop 而不是 web,这个坑 2026-09-30 已经踩过一次)。
1892
+ *
1893
+ * 日志正文来自内置底稿(lib/changelog.js);仓库发过 Release 之后,
1894
+ * releases 会按版本号覆盖/补齐底稿(mergeChangelog 的规则写在那里)。
1895
+ */
1896
+ registerRoute(ctx, "/api/dpharness/changelog", async (req, res) => {
1897
+ if (req.method !== "GET") {
1898
+ res.writeHead(405, { allow: "GET" });
1899
+ res.end();
1900
+ return;
1901
+ }
1902
+ const now = Date.now();
1903
+ if (changelogCache && now - changelogCache.at < CACHE_TTL_MS) {
1904
+ sendJson(res, 200, { ...changelogCache.value, cached: true });
1905
+ return;
1906
+ }
1907
+ // 两个外部查询互不依赖:并发发出去,任一失败都不影响另一个
1908
+ const [releases, latest] = await Promise.all([fetchReleases(), fetchNpmVersion(PKG_NAME)]);
1909
+ const value = {
1910
+ ok: true,
1911
+ rev: SHAPE_REV,
1912
+ current: VERSION,
1913
+ latest,
1914
+ outdated: latest ? compareVersions(VERSION, latest) < 0 : null,
1915
+ repo: REPO,
1916
+ source: releases && releases.length > 0 ? "builtin+github" : "builtin",
1917
+ upgrade: `dsh plugin --profile ${PROFILE} add dsh-dpharness@latest`,
1918
+ entries: mergeChangelog(CHANGELOG, releases),
1919
+ cached: false,
1920
+ fetchedAt: now,
1921
+ };
1922
+ changelogCache = { at: now, value };
1923
+ sendJson(res, 200, value);
1924
+ });
1925
+
1926
+ /**
1927
+ * 插件更新检查(只读)。
1928
+ *
1929
+ * 两件事一起回答(2026-10-12 的需求「新增检查插件更新入口,更新红点提醒能力」):
1930
+ * 1. 本插件自己有没有新版本(self);
1931
+ * 2. 用户**已安装的 dsh 插件**里,哪些有更新的版本(plugins)。
1932
+ *
1933
+ * 数据来源与代价必须写清楚:
1934
+ * · 「装了哪些」= profile 的 dependencies,本机磁盘读取,零网络;
1935
+ * · 「最新版」= 逐包问 npmmirror(本机实测 23 个依赖),故并发上限 6、整体缓存 10 分钟;
1936
+ * · 站点 /api/plugins **不提供版本字段**,所以没法拿目录当版本源 —— 只能逐包问 registry。
1937
+ * `?refresh=1` 可绕过缓存(「检查更新」按钮),但 30 秒内只放行一次,避免连点把镜像打爆。
1938
+ *
1939
+ * 三态纪律同 changelog:outdated 为 true / false / null(null = 任一端拿不到,不下结论)。
1940
+ */
1941
+ registerRoute(ctx, "/api/dpharness/updates", async (req, res) => {
1942
+ if (req.method !== "GET") {
1943
+ res.writeHead(405, { allow: "GET" });
1944
+ res.end();
1945
+ return;
1946
+ }
1947
+ const now = Date.now();
1948
+ const fresh = now - updatesCache.at < UPDATE_TTL_MS;
1949
+ const force = readParams(req).get("refresh") === "1";
1950
+ if (updatesCache.value && fresh && !(force && now - updatesCache.at >= UPDATE_MIN_FORCE_MS)) {
1951
+ sendJson(res, 200, { ...updatesCache.value, cached: true });
1952
+ return;
1953
+ }
1954
+ try {
1955
+ const value = await buildUpdates(ctx);
1956
+ updatesCache = { at: Date.now(), value };
1957
+ sendJson(res, 200, { ...value, cached: false });
1958
+ } catch (error) {
1959
+ /* 失败必须显式报错,不能悄悄回一份空清单 —— 空清单会被界面读成「全都已是最新」 */
1960
+ sendJson(res, 500, { ok: false, error: String((error && error.message) || error) });
1961
+ }
1962
+ });
1963
+
809
1964
  registerRoute(ctx, "/api/dpharness/meta", (req, res) => {
810
1965
  if (req.method !== "GET") {
811
1966
  res.writeHead(405, { allow: "GET" });
@@ -824,9 +1979,13 @@ export function apply(ctx) {
824
1979
  routes: [
825
1980
  "/api/dpharness/search",
826
1981
  "/api/dpharness/best",
1982
+ "/api/dpharness/sets",
827
1983
  "/api/dpharness/event",
828
1984
  "/api/dpharness/install",
829
1985
  "/api/dpharness/postinstall",
1986
+ "/api/dpharness/toggle",
1987
+ "/api/dpharness/changelog",
1988
+ "/api/dpharness/updates",
830
1989
  "/api/dpharness/meta",
831
1990
  ],
832
1991
  events: Array.from(EVENT_ALLOWLIST),