dsh-plugin 1.1.1 → 1.2.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 (113) hide show
  1. package/README.en.md +5 -5
  2. package/README.md +5 -5
  3. package/client/client.js +4772 -1659
  4. package/client/client.js.map +1 -1
  5. package/lib/http/routes.js +451 -28
  6. package/lib/index.js +5 -1
  7. package/lib/services/{install-types.js → install/install-types.js} +8 -2
  8. package/lib/services/install/install.js +4 -0
  9. package/lib/services/install/npm-check.js +55 -0
  10. package/lib/services/{npm-resolve.js → install/npm-resolve.js} +11 -5
  11. package/lib/services/{preflight.js → install/preflight.js} +23 -7
  12. package/lib/services/{task-queue.js → install/task-queue.js} +166 -71
  13. package/lib/services/loader.js +60 -1
  14. package/lib/services/log.js +138 -0
  15. package/lib/services/probe.js +157 -0
  16. package/lib/services/{installed-versions.js → profile/installed-versions.js} +5 -1
  17. package/lib/services/{pending-restart.js → profile/pending-restart.js} +1 -1
  18. package/lib/services/{profile.js → profile/profile.js} +59 -4
  19. package/lib/services/{progress.js → profile/progress.js} +4 -0
  20. package/lib/services/settings.js +60 -0
  21. package/lib/types/http/routes.d.ts +1 -1
  22. package/lib/types/index.d.ts +5 -1
  23. package/lib/types/services/{install-types.d.ts → install/install-types.d.ts} +13 -4
  24. package/lib/types/services/{install.d.ts → install/install.d.ts} +9 -5
  25. package/lib/types/services/install/npm-check.d.ts +12 -0
  26. package/lib/types/services/{npm-resolve.d.ts → install/npm-resolve.d.ts} +2 -1
  27. package/lib/types/services/{task-queue.d.ts → install/task-queue.d.ts} +5 -1
  28. package/lib/types/services/loader.d.ts +14 -4
  29. package/lib/types/services/log.d.ts +49 -0
  30. package/lib/types/services/probe.d.ts +30 -0
  31. package/lib/types/services/{pending-restart.d.ts → profile/pending-restart.d.ts} +9 -3
  32. package/lib/types/services/{profile.d.ts → profile/profile.d.ts} +6 -2
  33. package/lib/types/services/{progress.d.ts → profile/progress.d.ts} +4 -0
  34. package/lib/types/services/settings.d.ts +24 -0
  35. package/package.json +1 -1
  36. package/src/client/components/PluginHubSection.tsx +346 -121
  37. package/src/client/components/{CatalogList.tsx → catalog/CatalogList.tsx} +15 -7
  38. package/src/client/components/{PluginCard.tsx → catalog/PluginCard.tsx} +10 -5
  39. package/src/client/components/layout/CatalogControls.tsx +80 -0
  40. package/src/client/components/{CatalogHeader.tsx → layout/CatalogHeader.tsx} +8 -4
  41. package/src/client/components/{CategoryTabs.tsx → layout/CategoryTabs.tsx} +7 -3
  42. package/src/client/components/layout/SectionTabs.tsx +60 -0
  43. package/src/client/components/{AboutModal.tsx → modals/AboutModal.tsx} +11 -7
  44. package/src/client/components/{HubUpdateModal.tsx → modals/HubUpdateModal.tsx} +9 -5
  45. package/src/client/components/modals/InstalledDetailModal.tsx +193 -0
  46. package/src/client/components/modals/LogsModal.tsx +301 -0
  47. package/src/client/components/modals/LogsPathModal.tsx +161 -0
  48. package/src/client/components/{NotificationsModal.tsx → modals/NotificationsModal.tsx} +51 -20
  49. package/src/client/components/{ProgressView.tsx → modals/ProgressView.tsx} +6 -2
  50. package/src/client/components/{modals.tsx → modals/modals.tsx} +121 -40
  51. package/src/client/components/{Dropdown.tsx → ui/Dropdown.tsx} +18 -6
  52. package/src/client/components/ui/Toggle.tsx +28 -0
  53. package/src/client/components/ui/icons.tsx +343 -0
  54. package/src/client/components/views/CustomInstallView.tsx +250 -0
  55. package/src/client/components/views/DiagnosticsView.tsx +172 -0
  56. package/src/client/components/views/InstalledView.tsx +328 -0
  57. package/src/client/components/views/LogsView.tsx +150 -0
  58. package/src/client/components/views/MarketView.tsx +66 -0
  59. package/src/client/components/views/SettingsView.tsx +273 -0
  60. package/src/client/data/catalog.ts +38 -0
  61. package/src/client/data/host.ts +107 -0
  62. package/src/client/data/hub.ts +41 -0
  63. package/src/client/hooks/useCatalog.ts +77 -117
  64. package/src/client/hooks/useIncrementalList.ts +46 -0
  65. package/src/client/hooks/useLanguage.ts +40 -0
  66. package/src/client/hooks/useSettings.ts +90 -0
  67. package/src/client/hooks/useTaskQueue.ts +168 -47
  68. package/src/client/index.tsx +4 -0
  69. package/src/client/locales.ts +365 -39
  70. package/src/client/logic/constants.ts +87 -0
  71. package/src/client/{lib → logic}/failures.ts +99 -74
  72. package/src/client/{lib → logic}/format.ts +4 -0
  73. package/src/client/logic/install-command.ts +56 -0
  74. package/src/client/logic/installed.ts +207 -0
  75. package/src/client/logic/normalize.ts +52 -0
  76. package/src/client/{lib → logic}/renderMarkdown.ts +4 -0
  77. package/src/client/logic/urls.ts +125 -0
  78. package/src/client/styles/CustomInstallView.module.css +191 -0
  79. package/src/client/styles/DiagnosticsView.module.css +231 -0
  80. package/src/client/styles/Dropdown.module.css +46 -41
  81. package/src/client/styles/Header.module.css +105 -133
  82. package/src/client/styles/InstalledView.module.css +447 -0
  83. package/src/client/styles/List.module.css +11 -1
  84. package/src/client/styles/LogsView.module.css +503 -0
  85. package/src/client/styles/Modal.module.css +357 -71
  86. package/src/client/styles/SectionTabs.module.css +142 -0
  87. package/src/client/styles/SettingsView.module.css +232 -0
  88. package/src/client/styles/Toggle.module.css +60 -0
  89. package/src/client/styles/tokens.module.css +6 -1
  90. package/src/client/types.ts +28 -4
  91. package/src/server/http/routes.ts +426 -28
  92. package/src/server/index.ts +5 -1
  93. package/src/server/services/{install-types.ts → install/install-types.ts} +13 -5
  94. package/src/server/services/{install.ts → install/install.ts} +9 -5
  95. package/src/server/services/install/npm-check.ts +53 -0
  96. package/src/server/services/{npm-resolve.ts → install/npm-resolve.ts} +11 -5
  97. package/src/server/services/{preflight.ts → install/preflight.ts} +24 -7
  98. package/src/server/services/{task-queue.ts → install/task-queue.ts} +168 -68
  99. package/src/server/services/loader.ts +59 -1
  100. package/src/server/services/log.ts +167 -0
  101. package/src/server/services/probe.ts +157 -0
  102. package/src/server/services/{installed-versions.ts → profile/installed-versions.ts} +5 -1
  103. package/src/server/services/{pending-restart.ts → profile/pending-restart.ts} +9 -3
  104. package/src/server/services/{profile.ts → profile/profile.ts} +58 -4
  105. package/src/server/services/{progress.ts → profile/progress.ts} +4 -0
  106. package/src/server/services/settings.ts +79 -0
  107. package/lib/services/install.js +0 -4
  108. package/src/client/components/CatalogControls.tsx +0 -104
  109. package/src/client/components/icons.tsx +0 -125
  110. package/src/client/lib/catalog.ts +0 -272
  111. package/src/client/lib/env.ts +0 -16
  112. /package/lib/types/services/{preflight.d.ts → install/preflight.d.ts} +0 -0
  113. /package/lib/types/services/{installed-versions.d.ts → profile/installed-versions.d.ts} +0 -0
@@ -0,0 +1,55 @@
1
+ /**
2
+ * DSH-Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
6
+ * 本机 npm 环境检测:判断一次安装失败是否源于「本机 npm 版本过低」。
7
+ *
8
+ * 背景:pnpm 在 git 源插件的 prepare 阶段会调 npm 装依赖,npm arborist 在解 peer 依赖时
9
+ * 有已知内部崩溃 —— `Cannot read properties of null (reading 'edgesOut')`(build-ideal-tree.js
10
+ * 的 #loadPeerSet),官方标记 Cannot Reproduce(npm/cli#8261、#9787),npm 11.6.0 起不再复现。
11
+ * 该报错会被 pnpm 包进 ERR_PNPM_PREPARE_PACKAGE 输出,若按插件打包问题引导提 Issue 就误导了用户。
12
+ *
13
+ * 这里的 `npmTooLowMarker` 是纯函数(输出文本 + 环境 → 标记行或 null),不触碰任务/队列,
14
+ * 由调用方(task-queue.ts)负责把标记追加到任务输出;spawn 读 npm 版本是唯一副作用,独立可测。
15
+ */
16
+ import { spawnSync } from 'node:child_process';
17
+ /** npm arborist 内部崩溃特征:`Cannot read properties of null (reading 'edgesOut')`。 */
18
+ export const NPM_CRASH_EDGES_OUT_RE = /Cannot read properties of null \(reading 'edgesOut'\)|edgesOut/i;
19
+ /** 该缺陷在 npm 11.6.0 起不再复现;低于此版本遇到 edgesOut 崩溃即判「本机 npm 版本过低」。 */
20
+ export const NPM_MIN_VERSION = [11, 6, 0];
21
+ /** 读本机 npm 版本(major.minor.patch);npm 不在 PATH 或执行失败/超时时返回 null(不妄下结论)。 */
22
+ export function npmVersionOf(env) {
23
+ try {
24
+ const res = spawnSync('npm', ['-v'], { env, encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'pipe'] });
25
+ if (res.error !== undefined || res.status !== 0)
26
+ return null;
27
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(res.stdout ?? '');
28
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ function belowMin(v) {
35
+ for (let i = 0; i < NPM_MIN_VERSION.length; i++) {
36
+ if (v[i] < NPM_MIN_VERSION[i])
37
+ return true;
38
+ if (v[i] > NPM_MIN_VERSION[i])
39
+ return false;
40
+ }
41
+ return false;
42
+ }
43
+ /**
44
+ * 安装失败输出含 npm arborist edgesOut 崩溃特征,且本机 npm 版本低于阈值时,返回
45
+ * `[npm-too-low] npm@X.Y.Z …` 标记行;否则返回 null。前端据此展示「本机 npm 版本过低」
46
+ * 的准确原因,避免该报错被误判成插件打包/分发问题。
47
+ */
48
+ export function npmTooLowMarker(output, env) {
49
+ if (!NPM_CRASH_EDGES_OUT_RE.test(output))
50
+ return null;
51
+ const v = npmVersionOf(env);
52
+ if (v === null || !belowMin(v))
53
+ return null;
54
+ return `[npm-too-low] npm@${v.join('.')} — npm arborist crashed while resolving peer deps ('edgesOut'); local npm is below ${NPM_MIN_VERSION.join('.')}; upgrade npm (npm install -g npm@latest) and retry`;
55
+ }
@@ -1,10 +1,14 @@
1
1
  /**
2
+ * DSH-Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
2
6
  * npm 包反查:git 分发不完整(缺构建产物/子模块)导致安装失败时,用 npm
3
7
  * registry 的搜索接口按 repository 地址反查该仓库对应的官方 npm 包。
4
8
  *
5
9
  * 这是通用机制,不针对任何具体插件:只要作者发布了 repository 指向该
6
10
  * GitHub 仓库的 npm 包(scope 名与 GitHub 用户名是否一致无所谓),就能命中,
7
- * 从而把「git 直装必败」的插件切换到 npm 通道安装。命中结果带内存缓存,
11
+ * 从而把 git 分发不完整的插件切换到 npm 通道安装。命中结果带内存缓存,
8
12
  * 避免同一会话内重复查询 registry。
9
13
  */
10
14
  import { get } from 'node:https';
@@ -16,21 +20,23 @@ const REQUEST_TIMEOUT_MS = 8000;
16
20
  * 反查 repo(`owner/repo`)对应的官方 npm 包名;未命中、网络异常或超时返回 null。
17
21
  * 返回 null 不代表仓库一定没有 npm 包,只代表本次未能确认 —— 调用方应保留
18
22
  * 原有错误路径,反查只是额外的一次尝试。
23
+ * @param registry - npm 镜像源地址(空串 = 官方 https://registry.npmjs.org)
19
24
  */
20
- export function resolveNpmPackage(repo) {
25
+ export function resolveNpmPackage(repo, registry = '') {
21
26
  const key = repo.toLowerCase();
22
27
  if (cache.has(key))
23
28
  return Promise.resolve(cache.get(key) ?? null);
24
- const name = searchRepo(repo);
29
+ const name = searchRepo(repo, registry);
25
30
  name.then((found) => cache.set(key, found)).catch(() => cache.set(key, null));
26
31
  return name;
27
32
  }
28
33
  /** 用 npm search 接口按 repository 地址反查,并做铁证校验(包元数据必须指向该仓库)。 */
29
- function searchRepo(repo) {
34
+ function searchRepo(repo, registry) {
30
35
  const [owner, name] = repo.split('/');
31
36
  if (owner === undefined || name === undefined || name === '')
32
37
  return Promise.resolve(null);
33
- const url = `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(`repository:${owner}/${name}`)}&size=10`;
38
+ const base = registry === '' ? 'https://registry.npmjs.org' : registry.replace(/\/+$/, '');
39
+ const url = `${base}/-/v1/search?text=${encodeURIComponent(`repository:${owner}/${name}`)}&size=10`;
34
40
  return new Promise((resolve) => {
35
41
  const req = get(url, { timeout: REQUEST_TIMEOUT_MS }, (res) => {
36
42
  if (res.statusCode !== 200) {
@@ -1,5 +1,9 @@
1
1
  /**
2
- * 安装前预检:对 `github:` 源的插件,检查其分发(codeload tarball)里是否
2
+ * DSH-Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
6
+ * 安装前预检:对 GitHub 源的插件,检查其分发(codeload tarball)里是否
3
7
  * 真的包含 package.json 声明的入口文件(main / exports["."].default)。
4
8
  * git 分发常不提交构建产物(lib/ 等),这类残缺包装完会让宿主重启加载插件树时
5
9
  * ERR_MODULE_NOT_FOUND 直接崩溃 —— 预检在动手安装前就把它们拦下,避免白装一次。
@@ -13,15 +17,22 @@ import { tmpdir } from 'node:os';
13
17
  import { join } from 'node:path';
14
18
  import { pipeline } from 'node:stream/promises';
15
19
  import { promisify } from 'node:util';
20
+ import { githubRepoOf } from '../profile/profile.js';
16
21
  const execFileAsync = promisify(execFile);
22
+ /** 单次网络操作超时(ms):git ls-remote / codeload 下载。网络不可达时不能无限挂起,
23
+ * 否则 `/install` 请求永远不返回、任务不入队、前端进度卡 0%。超时后放行(交给装后校验)。 */
24
+ const PREFLIGHT_TIMEOUT_MS = 15_000;
17
25
  export async function preflightTarget(target) {
18
- const m = /^github:([^/]+)\/([^/]+)$/.exec(target);
19
- if (m === null)
26
+ const source = githubRepoOf(target);
27
+ if (source === null)
20
28
  return { ok: true, missing: null };
21
- const [, owner, repo] = m;
29
+ const [owner, repo] = source.split('/');
22
30
  let commit = '';
23
31
  try {
24
- const { stdout } = await execFileAsync('git', ['ls-remote', `https://github.com/${owner}/${repo}.git`, 'HEAD']);
32
+ const { stdout } = await execFileAsync('git', ['ls-remote', `https://github.com/${owner}/${repo}.git`, 'HEAD'], {
33
+ timeout: PREFLIGHT_TIMEOUT_MS,
34
+ maxBuffer: 1024 * 1024,
35
+ });
25
36
  commit = stdout.split(/\s+/)[0] ?? '';
26
37
  }
27
38
  catch {
@@ -55,13 +66,15 @@ export async function preflightTarget(target) {
55
66
  }
56
67
  function download(url, dest) {
57
68
  return new Promise((resolve, reject) => {
58
- get(url, (res) => {
69
+ const req = get(url, { timeout: PREFLIGHT_TIMEOUT_MS }, (res) => {
59
70
  if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 303) {
60
71
  res.resume();
61
72
  if (res.headers.location) {
62
73
  void download(res.headers.location, dest).then(resolve, reject);
63
74
  return;
64
75
  }
76
+ reject(new Error('download failed: redirect without location'));
77
+ return;
65
78
  }
66
79
  if (res.statusCode !== 200) {
67
80
  res.resume();
@@ -69,7 +82,10 @@ function download(url, dest) {
69
82
  return;
70
83
  }
71
84
  void pipeline(res, createWriteStream(dest)).then(resolve, reject);
72
- }).on('error', reject);
85
+ });
86
+ // 网络不可达时 connect/响应可能无限挂起:超时销毁,避免预检卡死(放行交给装后校验)
87
+ req.on('timeout', () => req.destroy(new Error(`download timeout after ${PREFLIGHT_TIMEOUT_MS}ms`)));
88
+ req.on('error', reject);
73
89
  });
74
90
  }
75
91
  /** 从 tarball 提取并解析一个 JSON 文件;文件不存在或解析失败返回 null。 */
@@ -1,4 +1,8 @@
1
1
  /**
2
+ * DSH-Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
2
6
  * 后台安装/卸载任务队列:内存任务注册表 + FIFO 串行 worker + 子进程生命周期管理。
3
7
  * 每个任务一次 `dsh plugin --profile <profile> <action> <target>` 子进程,
4
8
  * 输出流式收集到任务上;卸载成功时尝试从运行中 loader 即时停用(见 loader.ts)。
@@ -7,10 +11,12 @@ import { spawn } from 'node:child_process';
7
11
  import { readFileSync, statSync } from 'node:fs';
8
12
  import { dirname, join, resolve } from 'node:path';
9
13
  import { CAPTURE_LIMIT_BYTES, MAX_TASKS, MAX_TASK_LINES } from './install-types.js';
10
- import { cleanLine, estimateProgress } from './progress.js';
11
- import { removeLoadedEntry } from './loader.js';
12
- import { addPendingRestart, clearPendingRestart } from './pending-restart.js';
13
- import { addAllowBuildsKey, parseAllowBuildsKey, profileDirectory } from './profile.js';
14
+ import { npmTooLowMarker } from './npm-check.js';
15
+ import { cleanLine, estimateProgress } from '../profile/progress.js';
16
+ import { removeLoadedEntry } from '../loader.js';
17
+ import { addPendingRestart, clearPendingRestart } from '../profile/pending-restart.js';
18
+ import { addAllowBuildsKey, githubRepoOf, parseAllowBuildsKey, profileDirectory } from '../profile/profile.js';
19
+ import { appendLog } from '../log.js';
14
20
  /** In-memory task registry, keyed by task id. */
15
21
  const tasks = new Map();
16
22
  let nextTaskId = 1;
@@ -142,7 +148,7 @@ function stopChild(child) {
142
148
  * Progress is visible through `getTask(id)` / `activeTask()` until done.
143
149
  */
144
150
  export function startPluginMutation(options) {
145
- const task = { id: nextTaskId, target: options.target, displayTarget: options.displayTarget, action: options.action, status: 'pending', timedOut: false, exitCode: null, progress: 0, lines: [], attempts: options.attempts ?? [], needsRestart: false };
151
+ const task = { id: nextTaskId, target: options.target, displayTarget: options.displayTarget, globalNpm: options.globalNpm, action: options.action, status: 'pending', timedOut: false, exitCode: null, progress: 0, lines: [], attempts: options.attempts ?? [], needsRestart: false };
146
152
  nextTaskId = nextTaskId >= Number.MAX_SAFE_INTEGER ? 1 : nextTaskId + 1;
147
153
  tasks.set(task.id, task);
148
154
  if (tasks.size > MAX_TASKS) {
@@ -155,6 +161,15 @@ export function startPluginMutation(options) {
155
161
  });
156
162
  }
157
163
  queue.push({ task, options: { ...options } });
164
+ // 系统日志:记录任务入队(安装/卸载开始)
165
+ const category = options.action === 'add' ? 'install' : 'uninstall';
166
+ appendLog(options.profile, {
167
+ at: Date.now(),
168
+ level: 'info',
169
+ category,
170
+ event: `${category}.start`,
171
+ message: `${options.action === 'add' ? '开始安装' : '开始卸载'} ${options.displayTarget ?? options.target}`,
172
+ });
158
173
  pumpQueue();
159
174
  return task;
160
175
  }
@@ -169,6 +184,36 @@ function pumpQueue() {
169
184
  task.status = 'running';
170
185
  void runPluginMutation({ ...options, task }).finally(() => {
171
186
  runningChildren.delete(task.id);
187
+ // 系统日志:任务终态(成功/失败/取消),按动作归类安装/卸载日志
188
+ const show = task.displayTarget ?? task.target;
189
+ const category = task.action === 'add' ? 'install' : 'uninstall';
190
+ if (task.status === 'done') {
191
+ appendLog(options.profile, {
192
+ at: Date.now(),
193
+ level: 'success',
194
+ category,
195
+ event: `${category}.done`,
196
+ message: `${task.action === 'add' ? '安装成功' : '卸载成功'} ${show}${task.needsRestart ? '(待重启生效)' : ''}`,
197
+ });
198
+ }
199
+ else if (task.status === 'failed') {
200
+ appendLog(options.profile, {
201
+ at: Date.now(),
202
+ level: 'error',
203
+ category,
204
+ event: `${category}.fail`,
205
+ message: `${task.action === 'add' ? '安装失败' : '卸载失败'} ${show}`,
206
+ });
207
+ }
208
+ else if (task.status === 'cancelled') {
209
+ appendLog(options.profile, {
210
+ at: Date.now(),
211
+ level: 'warn',
212
+ category,
213
+ event: 'task.cancel',
214
+ message: `已取消 ${show}`,
215
+ });
216
+ }
172
217
  // 已终态的任务移出队列:既防 queue 数组无限增长(内存泄漏),也让下一轮 pump 干净
173
218
  const idx = queue.findIndex((it) => it.task === task);
174
219
  if (idx >= 0)
@@ -182,23 +227,34 @@ function pumpQueue() {
182
227
  * Never rejects; failures surface through the result / task state.
183
228
  */
184
229
  function spawnMutation(options) {
185
- const { action, profile, target, timeoutMs = 5 * 60 * 1000, env, task, displayTarget, uninstallLoader } = options;
186
- const invocation = cliInvocation();
187
- const args = [...invocation.prefixArgs, 'plugin', '--profile', profile, action, target];
188
- // 记录实际执行的命令(npm 通道显示包名,git 通道显示 github: 源):失败提 Issue 时
189
- // 「已尝试的安装方式」如实展示完整命令链,作者一眼看清我们跑过什么
190
- const executed = `dsh plugin --profile ${profile} ${action} ${target}`;
230
+ const { action, profile, target, timeoutMs = 5 * 60 * 1000, env, task, displayTarget, uninstallLoader, globalNpm } = options;
231
+ // 全局 npm 安装:直接 spawn 本机 npm(`npm install -g <pkgs>`),不是 dsh plugin 命令
232
+ const isGlobalNpm = (globalNpm ?? []).length > 0;
233
+ const invocation = isGlobalNpm
234
+ ? { file: 'npm', prefixArgs: [], cwd: process.cwd(), useShell: process.platform === 'win32' }
235
+ : cliInvocation();
236
+ const args = isGlobalNpm
237
+ ? ['install', '-g', ...(globalNpm ?? [])]
238
+ : [...invocation.prefixArgs, 'plugin', '--profile', profile, action, target];
239
+ // 记录实际执行的命令(npm 通道显示包名,git 通道显示 HTTPS 源),
240
+ // 失败提 Issue 时作为「已尝试的安装方式」随附
241
+ const executed = isGlobalNpm
242
+ ? `npm install -g ${(globalNpm ?? []).join(' ')}`
243
+ : `dsh plugin --profile ${profile} ${action} ${target}`;
191
244
  if (task && !task.attempts.includes(executed)) {
192
245
  task.attempts.push(executed);
193
246
  }
194
- return new Promise((resolvePromise) => {
247
+ // 单次 spawn 并捕获结果:流式输出打日志 + 超时/取消兜底,close 后 resolve。
248
+ // 不做任何终态后处理(exitCode/status/needsRestart 由下方统一收尾),
249
+ // 这样全局 npm 首次失败后可以干净地换参数重试一次。
250
+ const spawnOnce = (attemptArgs) => new Promise((resolveOnce) => {
195
251
  let stdout = '';
196
252
  let stderr = '';
197
253
  let timedOut = false;
198
254
  let settled = false;
199
255
  let child;
200
256
  try {
201
- child = spawn(invocation.file, args, {
257
+ child = spawn(invocation.file, attemptArgs, {
202
258
  cwd: invocation.cwd,
203
259
  env,
204
260
  shell: invocation.useShell,
@@ -214,7 +270,7 @@ function spawnMutation(options) {
214
270
  task.exitCode = null;
215
271
  pushLine(task, `[error] ${error instanceof Error ? error.message : String(error)}`);
216
272
  }
217
- resolvePromise({
273
+ resolveOnce({
218
274
  exitCode: null,
219
275
  timedOut: false,
220
276
  error: error instanceof Error ? error.message : String(error),
@@ -230,9 +286,8 @@ function spawnMutation(options) {
230
286
  let progressTimer;
231
287
  let exitWatch;
232
288
  let forceSettle;
233
- // 唯一收尾入口:close / error / 兜底超时 三者只放行一次,
234
- // 保证 runPluginMutation 必然 resolve、队列 worker 必然继续推进
235
- const settle = (result) => {
289
+ // 唯一收尾入口:close / error / 兜底超时 三者只放行一次,确保任务持续推进
290
+ const settleOnce = (result) => {
236
291
  if (settled)
237
292
  return;
238
293
  settled = true;
@@ -246,7 +301,7 @@ function spawnMutation(options) {
246
301
  clearTimeout(forceSettle);
247
302
  if (task)
248
303
  runningChildren.delete(task.id);
249
- resolvePromise(result);
304
+ resolveOnce(result);
250
305
  };
251
306
  timer = setTimeout(() => {
252
307
  timedOut = true;
@@ -264,7 +319,7 @@ function spawnMutation(options) {
264
319
  else
265
320
  stderr = (stderr + text).slice(-CAPTURE_LIMIT_BYTES);
266
321
  if (task) {
267
- // 原生透传 pnpm 输出:stdout/stderr 原样入日志,不做格式化,保证报错信息完整可见
322
+ // 原生透传 pnpm/npm 输出:stdout/stderr 原样入日志,不做格式化,保证报错信息完整可见
268
323
  for (const line of text.split(/\r?\n|\r/)) {
269
324
  if (line.trim() !== '')
270
325
  pushLine(task, line.trimEnd());
@@ -275,9 +330,8 @@ function spawnMutation(options) {
275
330
  child.stderr?.on('data', (chunk) => collect('stderr', chunk));
276
331
  child.once('exit', () => {
277
332
  // dsh 内部会 fork pnpm:pnpm 退出后仍攥着 stdout/stderr 管道时,
278
- // close 事件永不到来(历史队列卡死根因——取消路径曾因此卡死,用整组 SIGKILL 解决;
279
- // 自然失败路径没有兜底)。exit 后给 close 一段宽限,未按时触发则整组清理强制结束,
280
- // 保证任务必然进入终态、后续排队任务自动启动。
333
+ // close 事件不会到来。exit 后给 close 一段宽限,未按时触发则整组清理强制结束,
334
+ // 确保任务进入终态、后续排队任务自动启动。
281
335
  exitWatch = setTimeout(() => {
282
336
  if (settled)
283
337
  return;
@@ -294,7 +348,7 @@ function spawnMutation(options) {
294
348
  task.timedOut = true;
295
349
  pushLine(task, '[timed out]');
296
350
  }
297
- settle({ exitCode: null, timedOut: true, error: 'child failed to close', stdout, stderr });
351
+ settleOnce({ exitCode: null, timedOut: true, error: 'child failed to close', stdout, stderr });
298
352
  }, 5_000);
299
353
  }, 3_000);
300
354
  });
@@ -304,46 +358,66 @@ function spawnMutation(options) {
304
358
  task.exitCode = null;
305
359
  pushLine(task, `[error] ${error.message}`);
306
360
  }
307
- settle({ exitCode: null, timedOut: false, error: error.message, stdout, stderr });
361
+ settleOnce({ exitCode: null, timedOut: false, error: error.message, stdout, stderr });
308
362
  });
309
- child.once('close', async (code) => {
310
- try {
311
- if (task) {
312
- task.exitCode = code;
313
- task.timedOut = timedOut;
314
- if (task.status !== 'cancelled') {
315
- task.status = timedOut || code !== 0 ? 'failed' : 'done';
316
- if (task.status === 'done') {
317
- task.progress = 100;
318
- if (action === 'remove' && uninstallLoader) {
319
- // 卸载成功 → 主动从运行中 loader 停用该包条目;
320
- // 仅当宿主从未加载过它(磁盘已干净)才判「无需重启」;
321
- // 只要曾在 loader 中存活(停用过 live entry)就仍要求重启——
322
- // 带 UI 的插件(侧边栏面板等宿主启动时渲染的槽位)disable 后不会
323
- // 主动消失,重启才能立即摘除面板
324
- const removed = await removeLoadedEntry(uninstallLoader, target);
325
- task.needsRestart = !removed;
326
- if (removed)
327
- clearPendingRestart(displayTarget ?? target);
328
- else
329
- addPendingRestart(displayTarget ?? target, 'uninstall');
330
- }
331
- else {
332
- // 安装成功(或卸载但无 loader 引用)→ 登记待重启:
333
- // 插件要宿主重启才会挂载/卸载干净,重启前一直提醒;展示目标用 displayTarget(owner/repo)
334
- task.needsRestart = true;
335
- addPendingRestart(displayTarget ?? target, action === 'add' ? 'install' : 'uninstall');
336
- }
337
- }
338
- pushLine(task, timedOut ? '[timed out]' : `[exit ${code ?? '?'}]`);
363
+ child.once('close', (code) => {
364
+ settleOnce({ exitCode: code, timedOut, error: null, stdout, stderr });
365
+ });
366
+ });
367
+ return (async () => {
368
+ let result = await spawnOnce(args);
369
+ // npm 11 的 arborist peer-set bug(`Cannot read properties of null (reading 'children')`,npm/cli#9911):
370
+ // 某些包的 peerDependencies 用「双段 prerelease 范围」(如 dsh-tui@0.9.0 的 `^0.1.0-rc.6 || ^0.1.1-rc.1`,
371
+ // 26 个必需 peer 全是这种形状)会让 `npm install -g` 在解析阶段直接崩溃 —— 退出码 1、什么都没装,
372
+ // 与是不是从我们界面发起无关(终端里同样复现)。首次失败后自动带 `--legacy-peer-deps` 重试一次:
373
+ // 跳过 peer 自动解析即可绕过该 bug(peer 通常由同装的 @deepseek-ai/dsh 依赖树天然提供)。
374
+ // 二次尝试仍失败则保留其错误信息,不掩盖真正的原因。
375
+ if (isGlobalNpm && result.exitCode !== 0 && !result.timedOut && task?.status !== 'cancelled') {
376
+ const retryArgs = ['install', '-g', '--legacy-peer-deps', ...(globalNpm ?? [])];
377
+ const retryExecuted = `npm install -g --legacy-peer-deps ${(globalNpm ?? []).join(' ')}`;
378
+ if (task && !task.attempts.includes(retryExecuted))
379
+ task.attempts.push(retryExecuted);
380
+ if (task)
381
+ pushLine(task, '[npm] peer-set resolution crashed npm (known npm bug) — retrying with --legacy-peer-deps');
382
+ result = await spawnOnce(retryArgs);
383
+ }
384
+ // 统一终态后处理:exitCode/status/needsRestart 以最后一次尝试为准
385
+ if (task) {
386
+ task.exitCode = result.exitCode;
387
+ task.timedOut = result.timedOut;
388
+ if (task.status !== 'cancelled') {
389
+ task.status = result.timedOut || result.exitCode !== 0 ? 'failed' : 'done';
390
+ if (task.status === 'done') {
391
+ task.progress = 100;
392
+ if (isGlobalNpm) {
393
+ // 全局 npm 安装:装的是本机 CLI 工具(如 dsh-tui),不进任何 profile,无需宿主重启
394
+ task.needsRestart = false;
395
+ }
396
+ else if (action === 'remove' && uninstallLoader) {
397
+ // 卸载成功 → 主动从运行中 loader 停用该包条目;
398
+ // 仅当宿主从未加载过它(磁盘已干净)才判「无需重启」;
399
+ // 只要曾在 loader 中存活(停用过 live entry)就仍要求重启——
400
+ // 带 UI 的插件(侧边栏面板等宿主启动时渲染的槽位)disable 后不会
401
+ // 主动消失,重启才能立即摘除面板
402
+ const removed = await removeLoadedEntry(uninstallLoader, target);
403
+ task.needsRestart = !removed;
404
+ if (removed)
405
+ clearPendingRestart(displayTarget ?? target);
406
+ else
407
+ addPendingRestart(displayTarget ?? target, 'uninstall');
408
+ }
409
+ else {
410
+ // 安装成功(或卸载但无 loader 引用)→ 登记待重启:
411
+ // 插件要宿主重启才会挂载/卸载干净,重启前一直提醒;展示目标用 displayTarget(owner/repo)
412
+ task.needsRestart = true;
413
+ addPendingRestart(displayTarget ?? target, action === 'add' ? 'install' : 'uninstall');
339
414
  }
340
415
  }
416
+ pushLine(task, result.timedOut ? '[timed out]' : `[exit ${result.exitCode ?? '?'}]`);
341
417
  }
342
- finally {
343
- settle({ exitCode: code, timedOut, error: null, stdout, stderr });
344
- }
345
- });
346
- });
418
+ }
419
+ return result;
420
+ })();
347
421
  }
348
422
  /**
349
423
  * 安装后校验已装包的入口文件(package.json 的 main / exports["."].default)是否真实存在。
@@ -360,8 +434,11 @@ export function verifyInstalledEntry(profile, target) {
360
434
  return { name: null, missing: null };
361
435
  }
362
436
  const deps = (profilePkg?.dependencies ?? {});
363
- // target 自身是依赖名(npm 包),或通过 github: specifier 反查依赖名
364
- const name = deps[target] !== undefined ? target : Object.keys(deps).find((k) => deps[k] === target);
437
+ // target 自身是依赖名(npm 包),或通过 Git specifier 反查依赖名
438
+ const targetRepo = githubRepoOf(target)?.toLowerCase();
439
+ const name = targetRepo !== undefined
440
+ ? Object.keys(deps).find((k) => githubRepoOf(deps[k])?.toLowerCase() === targetRepo)
441
+ : deps[target] !== undefined ? target : Object.keys(deps).find((k) => deps[k] === target);
365
442
  if (!name)
366
443
  return { name: null, missing: null };
367
444
  const pkgDir = join(profileDirectory(profile), 'node_modules', name);
@@ -395,6 +472,19 @@ function ignoredBuildKeys(output) {
395
472
  .map((s) => s.trim())
396
473
  .filter((s) => s !== '');
397
474
  }
475
+ /** npm arborist edgesOut 崩溃 + 本机 npm 版本过低 → 把 [npm-too-low] 标记追加到任务输出,
476
+ * 前端据此展示「本机 npm 版本过低」的准确原因 —— 避免该报错被外层 ERR_PNPM_PREPARE_PACKAGE
477
+ * 误判成插件打包/分发问题、误导用户提 Issue。检测逻辑在独立的 npm-check.ts(本机 npm 环境职责)。 */
478
+ function annotateNpmTooLow(result, options) {
479
+ if (options.action !== 'add' || result.exitCode === 0 || result.timedOut)
480
+ return result;
481
+ const line = npmTooLowMarker(`${result.stderr}\n${result.stdout}`, options.env);
482
+ if (line === null)
483
+ return result;
484
+ if (options.task && options.task.status !== 'cancelled')
485
+ pushLine(options.task, line);
486
+ return { ...result, stderr: `${result.stderr}\n${line}`, error: result.error ? `${result.error}\n${line}` : line };
487
+ }
398
488
  /**
399
489
  * Run a plugin mutation with one recovery path: when `add` fails because
400
490
  * pnpm's allowBuilds gate blocks a build script — either the git-hosted
@@ -405,8 +495,10 @@ function ignoredBuildKeys(output) {
405
495
  * Other failures fall through to the single-spawn result.
406
496
  */
407
497
  export async function runPluginMutation(options) {
408
- const result = await spawnMutation(options);
409
- if (options.action === 'add' && result.exitCode !== 0 && !result.timedOut) {
498
+ let result = await spawnMutation(options);
499
+ // allowBuilds 放行 / 装后入口校验都是 profile 专属(pnpm 装进 profile 的场景);
500
+ // 全局 npm 安装直接走 npm,无 pnpm allowBuilds 拦截、也不进 profile,跳过这两类恢复
501
+ if (options.action === 'add' && result.exitCode !== 0 && !result.timedOut && (options.globalNpm ?? []).length === 0) {
410
502
  const output = `${result.stderr}\n${result.stdout}`;
411
503
  // git 源:pnpm 打印的 key@url 提示
412
504
  if (output.includes('ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED')) {
@@ -420,15 +512,16 @@ export async function runPluginMutation(options) {
420
512
  pushLine(options.task, `[allow build] ${key}`);
421
513
  }
422
514
  addAllowBuildsKey(options.profile, key);
423
- return spawnMutation(options);
515
+ result = await spawnMutation(options);
424
516
  }
425
517
  }
426
518
  // 依赖原生模块/构建脚本被 pnpm v11 拦截(ERR_PNPM_IGNORED_BUILDS):git 与 npm 源都会出现。
427
519
  // allowBuilds 的 key 是输出里列出的 name@version(如 node-pty@1.1.0),逐个放行后重试一次;
428
520
  // 输出解析不到时回退用目标名(插件自身构建脚本被拦的 npm 场景)。
429
- if (output.includes('ERR_PNPM_IGNORED_BUILDS')) {
430
- const keys = ignoredBuildKeys(output);
431
- if (keys.length === 0 && !options.target.startsWith('github:'))
521
+ // 用重试后的最终结果判断:git 源放行 prepare 后可能又在依赖层撞上原生构建拦截。
522
+ if (result.exitCode !== 0 && !result.timedOut && `${result.stderr}\n${result.stdout}`.includes('ERR_PNPM_IGNORED_BUILDS')) {
523
+ const keys = ignoredBuildKeys(`${result.stderr}\n${result.stdout}`);
524
+ if (keys.length === 0 && githubRepoOf(options.target) === null)
432
525
  keys.push(options.target);
433
526
  if (keys.length > 0) {
434
527
  if (options.task) {
@@ -438,13 +531,14 @@ export async function runPluginMutation(options) {
438
531
  }
439
532
  for (const key of keys)
440
533
  addAllowBuildsKey(options.profile, key);
441
- return spawnMutation(options);
534
+ result = await spawnMutation(options);
442
535
  }
443
536
  }
444
537
  }
445
538
  // pnpm 安装本身成功,但目标包入口文件缺失(git 分发缺构建产物)→ 判为失败:
446
- // 撤销刚登记的待重启,避免用户重启时宿主加载残缺包直接崩溃
447
- if (options.action === 'add' && result.exitCode === 0 && !result.timedOut) {
539
+ // 撤销刚登记的待重启,避免用户重启时宿主加载残缺包直接崩溃。
540
+ // 全局 npm 安装不进 profile(profile deps 里没有这些包),跳过入口校验
541
+ if (options.action === 'add' && result.exitCode === 0 && !result.timedOut && (options.globalNpm ?? []).length === 0) {
448
542
  const verified = verifyInstalledEntry(options.profile, options.target);
449
543
  if (verified.name !== null && verified.missing !== null) {
450
544
  clearPendingRestart(options.displayTarget ?? options.target);
@@ -458,5 +552,6 @@ export async function runPluginMutation(options) {
458
552
  return { exitCode: 1, timedOut: false, error: `entry file missing: ${verified.missing}`, stdout: result.stdout, stderr: `${result.stderr}\n${detail}` };
459
553
  }
460
554
  }
461
- return result;
555
+ // npm arborist edgesOut 崩溃 + 本机 npm 版本过低 → 追加 [npm-too-low] 标记,前端据此给准确原因
556
+ return annotateNpmTooLow(result, options);
462
557
  }
@@ -1,7 +1,14 @@
1
1
  /**
2
+ * DSH-Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
2
6
  * 运行中 loader 的读取与停用:卸载成功后对匹配条目做 live-disable,
3
7
  * 使卸载立即生效(刷新页面不再加载已卸载的 client bundle,也无需重启)。
4
8
  */
9
+ import { readFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { profileDirectory } from './profile/profile.js';
5
12
  /** 运行中 loader 的全部条目(id + options.name),诊断用。 */
6
13
  export function dumpLoaderEntries(loader) {
7
14
  if (!loader)
@@ -12,6 +19,20 @@ export function dumpLoaderEntries(loader) {
12
19
  }
13
20
  return entries;
14
21
  }
22
+ /**
23
+ * 判断某 npm 包名是否已加载进运行中 loader(宽匹配:条目名存在别名变体)。
24
+ * 官方 `ctx.loader.entries()` 遍历整棵树(reference.md §1.3),条目名 == 插件作者声明的名字。
25
+ * 安装完成但未重启时条目不在 loader → 返回 false,UI 据此标「待重启/未加载」。
26
+ */
27
+ export function isEntryLoaded(loader, name) {
28
+ if (!loader)
29
+ return false;
30
+ for (const entry of Array.from(loader.entries())) {
31
+ if (nameMatches(entry.options?.name, name))
32
+ return true;
33
+ }
34
+ return false;
35
+ }
15
36
  /**
16
37
  * 卸载目标(npm 包名,如 `@scope/widget`)与 loader 条目名的匹配。
17
38
  * loader 条目名由插件作者/工具写入,形式不可控,常见变体:
@@ -19,7 +40,8 @@ export function dumpLoaderEntries(loader) {
19
40
  * - 去 `@` 前缀:`scope/widget`
20
41
  * - 去 scope 的短名:`widget`
21
42
  * - scope 分隔符变 `-`:`scope-widget`
22
- * 因此归一化后比较全串与短名两个维度。profile 内包名唯一,宽松匹配不会误伤其它包。
43
+ * - 包内模块路径:`widget/extensions/dsh/index.js`(bundle patch 的 name 常写成模块路径)
44
+ * 因此归一化后比较全串、短名、路径前缀三个维度。profile 内包名唯一,宽松匹配不会误伤其它包。
23
45
  */
24
46
  function nameMatches(entryName, target) {
25
47
  if (!entryName)
@@ -41,6 +63,13 @@ function nameMatches(entryName, target) {
41
63
  // 目标短名 `widget` 是它的尾段)——用「条目名以短名结尾」收口,避免误伤。
42
64
  if (tShort.length >= 2 && e.endsWith(`-${tShort}`))
43
65
  return true;
66
+ // 4) 条目名是目标包内的模块路径(`aegis/extensions/dsh/index.js` 属于包 `aegis`,
67
+ // `@scope/pkg/dist/x.js` 属于 `@scope/pkg`):归一化会吞掉路径分隔符,
68
+ // 必须在归一化前用原始形态做「target/」前缀判断(大小写不敏感)。
69
+ const rawE = entryName.trim().toLowerCase();
70
+ const rawT = target.trim().toLowerCase();
71
+ if (rawE === rawT || rawE.startsWith(`${rawT}/`))
72
+ return true;
44
73
  return false;
45
74
  }
46
75
  /**
@@ -103,3 +132,33 @@ export async function removeLoadedEntry(loader, name) {
103
132
  console.log(`[hub-uninstall] disable ${name} -> ${result ? 'ok/clean' : 'timed out or failed'}`);
104
133
  return result;
105
134
  }
135
+ /**
136
+ * 判断某已安装包是否是真正的 dsh 插件(宿主会加载 / 值得提示「待重启」):
137
+ * 1) 包名已写进 profile 的 `dsh.profile.bundles`(宿主启动时按清单加载);
138
+ * 2) 或包内 package.json 声明了 dsh 配置(`dsh.bundle` / `dsh.profile` 等)或 dsh 相关 keywords。
139
+ * 两者都满足不了(如 GitHub 官方示例仓库 octocat/Hello-World)说明它不是 dsh 插件,
140
+ * 装上也不会被宿主加载——UI 据此不再提示「待重启」,避免误导用户反复重启一个不会生效的东西。
141
+ */
142
+ export function isDshPlugin(profile, name) {
143
+ // 1) profile 级 bundles 清单:包名在清单里 → 宿主启动会加载它
144
+ try {
145
+ const profilePkg = JSON.parse(readFileSync(join(profileDirectory(profile), 'package.json'), 'utf8'));
146
+ if (Array.isArray(profilePkg.dsh?.profile?.bundles)) {
147
+ if (profilePkg.dsh.profile.bundles.includes(name))
148
+ return true;
149
+ }
150
+ }
151
+ catch { /* profile 读取失败按无 bundles 处理 */ }
152
+ // 2) 包内声明:dsh 字段(bundle patch / profile 配置)或 dsh 关键字
153
+ try {
154
+ const pkg = JSON.parse(readFileSync(join(profileDirectory(profile), 'node_modules', name, 'package.json'), 'utf8'));
155
+ if (pkg.dsh)
156
+ return true;
157
+ if (Array.isArray(pkg.keywords)) {
158
+ if (pkg.keywords.some((k) => typeof k === 'string' && /^(?:dsh|dsh-plugin)$/i.test(k)))
159
+ return true;
160
+ }
161
+ }
162
+ catch { /* 包缺失 / 无 package.json → 不是 dsh 插件 */ }
163
+ return false;
164
+ }