dsh-coexist-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,918 @@
1
+ import fs from 'node:fs'
2
+ import fsp from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { execFile } from 'node:child_process'
5
+ import { promisify } from 'node:util'
6
+ import { createBackup } from './backup.js'
7
+ import { resolveHome, resolveProfile, profilePackageJson, profilePatch } from './paths.js'
8
+ import { satisfies } from './semver.js'
9
+ import { dumpConfig } from './dumpconfig.js'
10
+ import { desktopDir, restoreDesktop } from './desktop.js'
11
+
12
+ const execFileAsync = promisify(execFile)
13
+ const CLI_PACKAGE = 'dsh-coexist-cli'
14
+
15
+ const KNOWN_APP_DIRS = [
16
+ path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'DSH NEXT', 'DSH NEXT.exe'),
17
+ '/Applications/DSH NEXT.app/Contents/MacOS/DSH NEXT',
18
+ '/opt/DSH NEXT/dsh-next',
19
+ ]
20
+
21
+ const ASAR_DSH_PACKAGE = '/node_modules/@deepseek-ai/dsh/package.json'
22
+
23
+ function readJsonSync(file) {
24
+ try {
25
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
26
+ } catch {
27
+ return null
28
+ }
29
+ }
30
+
31
+ async function writeJson(file, value) {
32
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`
33
+ await fsp.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
34
+ try {
35
+ await fsp.rename(tmp, file)
36
+ } catch (err) {
37
+ if (err.code === 'EEXIST' || err.code === 'EPERM') {
38
+ await fsp.rm(file, { force: true })
39
+ await fsp.rename(tmp, file)
40
+ return
41
+ }
42
+ await fsp.rm(tmp, { force: true })
43
+ throw err
44
+ }
45
+ }
46
+
47
+ async function pathExists(file) {
48
+ try {
49
+ await fsp.access(file)
50
+ return true
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+
56
+ function findAsarEntry(node, prefix, wanted) {
57
+ for (const [name, child] of Object.entries(node?.files ?? {})) {
58
+ const current = `${prefix}/${name}`
59
+ if (current === wanted) return child
60
+ if (child?.files) {
61
+ const hit = findAsarEntry(child, current, wanted)
62
+ if (hit) return hit
63
+ }
64
+ }
65
+ return null
66
+ }
67
+
68
+ /** 只读取 asar 头和一个条目,避免把 200MB 的 app.asar 整个载入内存。 */
69
+ export function readAsarEntry(asarFile, entryPath) {
70
+ let fd
71
+ try {
72
+ fd = fs.openSync(asarFile, 'r')
73
+ const head = Buffer.alloc(16)
74
+ fs.readSync(fd, head, 0, 16, 0)
75
+ const headerSize = head.readUInt32LE(12)
76
+ const contentBase = 8 + head.readUInt32LE(4)
77
+ const headerBuf = Buffer.alloc(headerSize)
78
+ fs.readSync(fd, headerBuf, 0, headerSize, 16)
79
+ const header = JSON.parse(headerBuf.toString('utf8'))
80
+
81
+ const candidates = entryPath.startsWith('/') ? [entryPath] : [entryPath, `/${entryPath}`]
82
+ let entry = null
83
+ for (const candidate of candidates) {
84
+ entry = findAsarEntry(header, '', candidate)
85
+ if (entry) break
86
+ }
87
+ if (!entry || typeof entry.size !== 'number') return null
88
+
89
+ const buf = Buffer.alloc(entry.size)
90
+ fs.readSync(fd, buf, 0, entry.size, contentBase + Number(entry.offset ?? 0))
91
+ return buf
92
+ } catch {
93
+ return null
94
+ } finally {
95
+ if (fd !== undefined) {
96
+ try {
97
+ fs.closeSync(fd)
98
+ } catch {
99
+ // ignore
100
+ }
101
+ }
102
+ }
103
+ }
104
+
105
+ export function readAsarJson(asarFile, entryPath) {
106
+ const buf = readAsarEntry(asarFile, entryPath)
107
+ if (!buf) return null
108
+ try {
109
+ return JSON.parse(buf.toString('utf8'))
110
+ } catch {
111
+ return null
112
+ }
113
+ }
114
+
115
+ /** 定位桌面版 app.asar;找不到返回 null,由版本检测继续尝试其他来源。 */
116
+ export function findDesktopAsar(explicitApp) {
117
+ const candidates = [explicitApp, process.env.DSH_DESKTOP_APP, ...KNOWN_APP_DIRS].filter(Boolean)
118
+ for (const candidate of candidates) {
119
+ const resolved = path.resolve(candidate)
120
+ const dir = resolved.endsWith('.exe') || resolved.endsWith('dsh-next')
121
+ ? path.dirname(resolved)
122
+ : resolved
123
+ for (const asar of [
124
+ path.join(dir, 'resources', 'app.asar'),
125
+ path.join(dir, 'Contents', 'Resources', 'app.asar'),
126
+ path.join(dir, 'app.asar'),
127
+ ]) {
128
+ if (fs.existsSync(asar)) return { appExe: resolved, asar }
129
+ }
130
+ }
131
+ return null
132
+ }
133
+
134
+ function findPackageUpwards(startDir, name) {
135
+ let dir = startDir
136
+ for (let depth = 0; depth < 8; depth += 1) {
137
+ const manifest = readJsonSync(path.join(dir, 'node_modules', name, 'package.json'))
138
+ if (manifest) return manifest
139
+ const parent = path.dirname(dir)
140
+ if (parent === dir) break
141
+ dir = parent
142
+ }
143
+ return null
144
+ }
145
+
146
+ function readHostPackageVersion(name, host, profileDir) {
147
+ const readAsar = () => {
148
+ if (!host.asar) return null
149
+ return readAsarJson(host.asar, `/node_modules/${name}/package.json`)
150
+ }
151
+ const readProfile = () => findPackageUpwards(profileDir, name)
152
+
153
+ const fromProfile = host.source !== 'desktop'
154
+ const first = fromProfile ? readProfile() : readAsar()
155
+ if (first?.version) return first.version
156
+ const second = fromProfile ? readAsar() : readProfile()
157
+ return second?.version ?? null
158
+ }
159
+
160
+ function detectCliVersion() {
161
+ const entry = process.argv[1]
162
+ if (!entry) return null
163
+ let dir = path.dirname(entry)
164
+ for (let depth = 0; depth < 6; depth += 1) {
165
+ const manifest = readJsonSync(path.join(dir, 'package.json'))
166
+ if (manifest?.name === '@deepseek-ai/dsh' && manifest.version) return manifest.version
167
+ const parent = path.dirname(dir)
168
+ if (parent === dir) break
169
+ dir = parent
170
+ }
171
+ return null
172
+ }
173
+
174
+ /**
175
+ * 识别宿主 DSH 版本。优先级:显式参数/环境变量 > 正在运行的 dsh CLI > profile 所在依赖树 > 桌面 asar。
176
+ */
177
+ export function detectDshVersion(options = {}) {
178
+ const explicit = options.dshVersion ?? process.env.DSH_VERSION
179
+ if (explicit) {
180
+ // 显式版本覆盖只替换版本号,仍保留桌面 appExe/asar,供内置 pnpm 使用。
181
+ const desktop = findDesktopAsar(options.app)
182
+ return {
183
+ version: explicit,
184
+ source: 'env',
185
+ asar: desktop?.asar ?? null,
186
+ appExe: desktop?.appExe ?? null,
187
+ }
188
+ }
189
+
190
+ const cliVersion = detectCliVersion()
191
+ if (cliVersion) return { version: cliVersion, source: 'cli' }
192
+
193
+ const home = resolveHome(options.home)
194
+ const profile = resolveProfile(home, options.profile ?? defaultProfile(home))
195
+ const desktop = findDesktopAsar(options.app)
196
+
197
+ const local = findPackageUpwards(profile.dir, '@deepseek-ai/dsh')
198
+ if (local?.version) {
199
+ return { version: local.version, source: 'profile', asar: desktop?.asar ?? null, appExe: desktop?.appExe ?? null }
200
+ }
201
+
202
+ if (desktop) {
203
+ const manifest = readAsarJson(desktop.asar, ASAR_DSH_PACKAGE)
204
+ if (manifest?.version) {
205
+ return { version: manifest.version, source: 'desktop', asar: desktop.asar, appExe: desktop.appExe }
206
+ }
207
+ }
208
+
209
+ return { version: null, source: null, asar: desktop?.asar ?? null, appExe: desktop?.appExe ?? null }
210
+ }
211
+
212
+ /** 桌面用户默认就是 desktop;没有该 profile 时退回 web。 */
213
+ export function defaultProfile(home) {
214
+ return fs.existsSync(path.join(home, 'profiles', 'desktop')) ? 'desktop' : 'web'
215
+ }
216
+
217
+ export function readInstalledManifest(profileDir, name) {
218
+ return readJsonSync(path.join(profileDir, 'node_modules', name, 'package.json'))
219
+ }
220
+
221
+ function hostPackagesFor(manifest, host, profileDir) {
222
+ const names = new Set(['@deepseek-ai/dsh'])
223
+ for (const name of Object.keys(manifest?.peerDependencies ?? {})) names.add(name)
224
+ const versions = {}
225
+ for (const name of names) {
226
+ versions[name] =
227
+ name === '@deepseek-ai/dsh'
228
+ ? host.version
229
+ : readHostPackageVersion(name, host, profileDir)
230
+ }
231
+ return versions
232
+ }
233
+
234
+ /**
235
+ * 判断一个插件能否在宿主版本上运行。
236
+ * engines.dsh 与 peerDependencies 都参与;读不到宿主版本时记为 unknown,不误报为不兼容。
237
+ */
238
+ export function evaluateCompatibility(manifest, host, profileDir) {
239
+ const checks = []
240
+ const range = manifest?.engines?.dsh
241
+ if (range) {
242
+ const ok = host.version ? satisfies(host.version, range) : null
243
+ checks.push({
244
+ kind: 'engine',
245
+ name: 'dsh',
246
+ range,
247
+ actual: host.version,
248
+ ok,
249
+ required: host.version ? null : 'unknown host version',
250
+ })
251
+ }
252
+
253
+ const hostVersions = hostPackagesFor(manifest, host, profileDir)
254
+ for (const [name, peerRange] of Object.entries(manifest?.peerDependencies ?? {})) {
255
+ const actual = hostVersions[name] ?? null
256
+ const optional = manifest?.peerDependenciesMeta?.[name]?.optional === true
257
+ const ok = actual ? satisfies(actual, peerRange) : null
258
+ checks.push({
259
+ kind: 'peer',
260
+ name,
261
+ range: peerRange,
262
+ actual,
263
+ ok,
264
+ optional,
265
+ required: actual ? null : 'package not found in host',
266
+ })
267
+ }
268
+
269
+ const blocked = checks.filter((check) => check.ok === false)
270
+ return {
271
+ status: blocked.length > 0 ? 'blocked' : checks.some((c) => c.ok === null) ? 'unknown' : 'ok',
272
+ checks,
273
+ }
274
+ }
275
+
276
+ function parseViewJson(text) {
277
+ try {
278
+ return JSON.parse(text)
279
+ } catch {
280
+ return null
281
+ }
282
+ }
283
+
284
+ async function inspectRemote(spec, runCommand) {
285
+ const runner = runCommand ?? defaultRunCommand
286
+ const attempt = findNpmCli()
287
+ ? { file: process.execPath, args: [findNpmCli(), 'view', spec, '--json'] }
288
+ : {
289
+ file: process.platform === 'win32' ? 'npm.cmd' : 'npm',
290
+ args: ['view', spec, '--json'],
291
+ }
292
+ try {
293
+ const { stdout } = await runner(attempt.file, attempt.args, { timeout: 60_000 })
294
+ const data = parseViewJson(stdout)
295
+ if (!data) return null
296
+ const entry = Array.isArray(data) ? data[data.length - 1] : data
297
+ if (!entry?.name) return null
298
+ return {
299
+ name: entry.name,
300
+ version: entry.version ?? null,
301
+ manifest: {
302
+ name: entry.name,
303
+ version: entry.version,
304
+ engines: entry.engines,
305
+ peerDependencies: entry.peerDependencies,
306
+ peerDependenciesMeta: entry.peerDependenciesMeta,
307
+ dsh: entry.dsh,
308
+ },
309
+ source: 'npm',
310
+ }
311
+ } catch {
312
+ return null
313
+ }
314
+ }
315
+
316
+ async function inspectPlugin(options) {
317
+ const profileDir = options.profileDir
318
+ const spec = options.spec
319
+ const abs = path.resolve(spec)
320
+ if (fs.existsSync(path.join(abs, 'package.json'))) {
321
+ const manifest = readJsonSync(path.join(abs, 'package.json'))
322
+ return { name: manifest.name, version: manifest.version, manifest, source: 'path', dir: abs }
323
+ }
324
+
325
+ const installed = readInstalledManifest(profileDir, spec)
326
+ if (installed) {
327
+ return { name: installed.name, version: installed.version, manifest: installed, source: 'profile' }
328
+ }
329
+
330
+ const remote = await inspectRemote(spec, options.runCommand)
331
+ if (remote) return remote
332
+
333
+ throw new Error(`Cannot resolve plugin: ${spec}`)
334
+ }
335
+
336
+ function resolveBundledPnpm(appExe) {
337
+ if (!appExe) return null
338
+ const base = path.join(path.dirname(appExe), 'resources', 'runtime')
339
+ for (const platform of ['x64', 'arm64']) {
340
+ const root = path.join(base, platform, 'primary-runtime', 'dependencies')
341
+ const node = path.join(root, 'node', 'bin', 'node.exe')
342
+ const pnpm = path.join(root, 'pnpm', 'bin', 'pnpm.cjs')
343
+ if (process.platform !== 'win32') continue
344
+ if (fs.existsSync(node) && fs.existsSync(pnpm)) return { name: 'pnpm', file: node, prefix: [pnpm] }
345
+ }
346
+ return null
347
+ }
348
+
349
+ async function defaultRunCommand(file, args, options = {}) {
350
+ // Windows 上 node 不会直接 spawn .cmd/.bat(EINVAL),必须交给 shell。
351
+ const needsShell = process.platform === 'win32' && /\.(cmd|bat)$/i.test(file)
352
+ return execFileAsync(file, args, {
353
+ cwd: options.cwd,
354
+ timeout: options.timeout ?? 120_000,
355
+ windowsHide: true,
356
+ shell: needsShell,
357
+ maxBuffer: 8 * 1024 * 1024,
358
+ env: { ...process.env, ...(options.env ?? {}) },
359
+ })
360
+ }
361
+
362
+ async function tryRun(runner, attempts, cwd) {
363
+ const errors = []
364
+ for (const attempt of attempts) {
365
+ try {
366
+ const output = await runner(attempt.file, [...(attempt.prefix ?? []), ...attempt.args], {
367
+ cwd,
368
+ timeout: 180_000,
369
+ })
370
+ return { ok: true, pm: attempt.name, output }
371
+ } catch (err) {
372
+ errors.push(`${attempt.name}: ${err.stderr?.trim() || err.message}`)
373
+ }
374
+ }
375
+ return { ok: false, errors }
376
+ }
377
+
378
+ function findNpmCli() {
379
+ const candidates = [
380
+ path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'),
381
+ path.join(process.env.APPDATA ?? '', 'npm', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
382
+ path.join(process.env.ProgramFiles ?? '', 'nodejs', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
383
+ ]
384
+ for (const candidate of candidates) {
385
+ if (candidate && fs.existsSync(candidate)) return candidate
386
+ }
387
+ return null
388
+ }
389
+
390
+ function npmAttempt(args) {
391
+ const cli = findNpmCli()
392
+ if (cli) return { name: 'npm', file: process.execPath, prefix: [cli], args }
393
+ return {
394
+ name: 'npm',
395
+ file: process.platform === 'win32' ? 'npm.cmd' : 'npm',
396
+ args,
397
+ }
398
+ }
399
+
400
+ function managerAttempts(spec, appExe, action) {
401
+ const attempts = []
402
+ const bundled = resolveBundledPnpm(appExe)
403
+ if (bundled) {
404
+ attempts.push({
405
+ name: 'pnpm(bundled)',
406
+ file: bundled.file,
407
+ prefix: bundled.prefix,
408
+ args: [action, spec, '--config.strictDepBuilds=false'],
409
+ })
410
+ }
411
+ if (action === 'add') {
412
+ attempts.push(npmAttempt(['install', spec, '--save-exact', '--no-audit', '--no-fund']))
413
+ } else {
414
+ attempts.push(npmAttempt(['uninstall', spec, '--no-audit', '--no-fund']))
415
+ }
416
+ return attempts
417
+ }
418
+
419
+ async function copyDir(source, dest) {
420
+ await fsp.rm(dest, { recursive: true, force: true })
421
+ await fsp.mkdir(dest, { recursive: true })
422
+ for (const entry of await fsp.readdir(source, { withFileTypes: true })) {
423
+ if (entry.name === 'node_modules' || entry.name === '.tmp' || entry.name === 'test') continue
424
+ const from = path.join(source, entry.name)
425
+ const to = path.join(dest, entry.name)
426
+ if (entry.isDirectory()) await copyDir(from, to)
427
+ else if (entry.isSymbolicLink()) {
428
+ await fsp.symlink(await fsp.readlink(from), to).catch(() => {})
429
+ } else await fsp.copyFile(from, to)
430
+ }
431
+ }
432
+
433
+ /** 记录 node_modules 顶层包名(含 scope),用来发现包管理器偷偷 prune 掉的包。 */
434
+ export function snapshotNodeModules(profileDir) {
435
+ const root = path.join(profileDir, 'node_modules')
436
+ const names = new Set()
437
+ if (!fs.existsSync(root)) return names
438
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
439
+ if (!entry.isDirectory()) continue
440
+ if (entry.name === '.ignored' || entry.name === '.pnpm' || entry.name === '.bin') continue
441
+ if (entry.name.startsWith('@')) {
442
+ const scope = path.join(root, entry.name)
443
+ for (const child of fs.readdirSync(scope, { withFileTypes: true })) {
444
+ if (child.isDirectory()) names.add(`${entry.name}/${child.name}`)
445
+ }
446
+ } else {
447
+ names.add(entry.name)
448
+ }
449
+ }
450
+ return names
451
+ }
452
+
453
+ function findIgnoredCopy(profileDir, name) {
454
+ const ignoredRoot = path.join(profileDir, 'node_modules', '.ignored')
455
+ const exact = path.join(ignoredRoot, name)
456
+ if (fs.existsSync(exact)) return exact
457
+ for (let index = 1; index <= 20; index += 1) {
458
+ const candidate = path.join(ignoredRoot, `${name}_${index}`)
459
+ if (fs.existsSync(candidate)) return candidate
460
+ }
461
+ return null
462
+ }
463
+
464
+ /**
465
+ * pnpm/npm 会把不在依赖树里的包(包括手工安装的共存插件和 peer)移到 .ignored。
466
+ * 安装/卸载后把这类包放回去,避免"装一个插件把另一个插件弄没"。
467
+ */
468
+ export async function restorePrunedPackages(profileDir, before) {
469
+ const restored = []
470
+ for (const name of before) {
471
+ const target = path.join(profileDir, 'node_modules', name)
472
+ if (fs.existsSync(target)) continue
473
+ const source = findIgnoredCopy(profileDir, name)
474
+ if (!source) continue
475
+ await fsp.mkdir(path.dirname(target), { recursive: true })
476
+ await fsp.cp(source, target, { recursive: true, force: true })
477
+ restored.push(name)
478
+ }
479
+ return restored
480
+ }
481
+
482
+ /**
483
+ * 本地开发/自安装:把仓库里的 CLI 作为 file: 依赖一起放进 profile,
484
+ * 这样插件安装后 UI 不依赖 PATH 上的 dsh-coexist。
485
+ * 从 npm 安装时不需要这一步(依赖会按版本解析)。
486
+ */
487
+ async function stageLocalCli(profileDir, pluginDir) {
488
+ const candidates = [
489
+ path.join(pluginDir, 'node_modules', CLI_PACKAGE),
490
+ path.resolve(pluginDir, '..', 'cli'),
491
+ ]
492
+ const source = candidates.find((dir) => readJsonSync(path.join(dir, 'package.json'))?.name === CLI_PACKAGE)
493
+ if (!source) return null
494
+
495
+ const staged = path.join(profileDir, '.dsh-coexist', 'plugins', CLI_PACKAGE)
496
+ await copyDir(source, staged)
497
+ return {
498
+ dir: staged,
499
+ // 相对于插件包目录:staged 插件与 CLI 是兄弟目录;node_modules 回退时同理。
500
+ rel: `file:../${CLI_PACKAGE}`,
501
+ }
502
+ }
503
+
504
+ async function rewriteDependency(file, name, value) {
505
+ const manifest = readJsonSync(file)
506
+ if (!manifest) return
507
+ manifest.dependencies ??= {}
508
+ manifest.dependencies[name] = value
509
+ await writeJson(file, manifest)
510
+ }
511
+
512
+ /**
513
+ * 共存插件本身也要被依赖树记录,否则下一次任何安装都会把它 prune 掉。
514
+ * 已存在于 node_modules 时,复制到 profile 内部并写成 file: 依赖。
515
+ */
516
+ async function trackCoexistPlugin(profileDir, manifest) {
517
+ const name = 'dsh-coexist-plugin'
518
+ if (!manifest?.dsh?.profile?.bundles?.includes(name)) return null
519
+ if (manifest.dependencies?.[name]) return null
520
+ const current = path.join(profileDir, 'node_modules', name)
521
+ if (!fs.existsSync(path.join(current, 'package.json'))) return null
522
+
523
+ const staged = path.join(profileDir, '.dsh-coexist', 'plugins', name)
524
+ await copyDir(current, staged)
525
+ const cli = await stageLocalCli(profileDir, current)
526
+ if (cli) await rewriteDependency(path.join(staged, 'package.json'), CLI_PACKAGE, cli.rel)
527
+ manifest.dependencies ??= {}
528
+ manifest.dependencies[name] = `file:.dsh-coexist/plugins/${name}`
529
+ return name
530
+ }
531
+
532
+ function ensureBundle(manifest, name) {
533
+ manifest.dsh ??= {}
534
+ manifest.dsh.profile ??= {}
535
+ const bundles = Array.isArray(manifest.dsh.profile.bundles) ? manifest.dsh.profile.bundles : []
536
+ if (!bundles.includes(name)) bundles.push(name)
537
+ manifest.dsh.profile.bundles = bundles
538
+ return bundles.includes(name)
539
+ }
540
+
541
+ async function restoreBackupFiles(backup) {
542
+ const restored = []
543
+ for (const item of backup?.manifest?.files ?? []) {
544
+ const source = path.join(backup.dir, item.rel)
545
+ if (!(await pathExists(source))) continue
546
+ await fsp.mkdir(path.dirname(item.file), { recursive: true })
547
+ await fsp.copyFile(source, item.file)
548
+ restored.push(item.file)
549
+ }
550
+ return restored
551
+ }
552
+
553
+ async function removeIfEmpty(dir) {
554
+ try {
555
+ const entries = await fsp.readdir(dir)
556
+ if (entries.length === 0) await fsp.rmdir(dir)
557
+ } catch {
558
+ // 目录不存在或非空都无需处理。
559
+ }
560
+ }
561
+
562
+ /**
563
+ * 卸载后的磁盘清理:
564
+ * - 本地安装会复制到 `.dsh-coexist/plugins/<name>`,卸载时一起删掉;
565
+ * - 卸载共存插件本身时,再删掉随插件分发的 CLI 和旧版快捷方式启动器;
566
+ * - `purge` 时连同 `~/.dsh/coexist`(备份、报告、配置)一起删除。
567
+ */
568
+ async function cleanupInstallArtifacts(profileDir, name, home, options = {}) {
569
+ const cleaned = []
570
+ const stagedRoot = path.join(profileDir, '.dsh-coexist', 'plugins')
571
+
572
+ const remove = async (target) => {
573
+ if (!(await pathExists(target))) return
574
+ await fsp.rm(target, { recursive: true, force: true })
575
+ cleaned.push(target)
576
+ }
577
+
578
+ await remove(path.join(stagedRoot, name))
579
+
580
+ if (name === 'dsh-coexist-plugin') {
581
+ await remove(path.join(stagedRoot, CLI_PACKAGE))
582
+ const legacy = desktopDir(home)
583
+ if (await pathExists(legacy)) {
584
+ try {
585
+ await restoreDesktop({ home })
586
+ await remove(legacy)
587
+ } catch {
588
+ // 快捷方式恢复失败时不阻断卸载,残留目录由用户手动清理。
589
+ }
590
+ }
591
+ }
592
+
593
+ await removeIfEmpty(stagedRoot)
594
+ await removeIfEmpty(path.join(profileDir, '.dsh-coexist'))
595
+
596
+ if (options.purge) {
597
+ await remove(path.join(home, 'coexist'))
598
+ }
599
+
600
+ return cleaned
601
+ }
602
+
603
+ function verifyPluginDir(profileDir, name) {
604
+ const dir = path.join(profileDir, 'node_modules', name)
605
+ const manifest = readJsonSync(path.join(dir, 'package.json'))
606
+ if (!manifest) return { ok: false, error: `package not found after install: ${dir}` }
607
+ if (manifest.main && !fs.existsSync(path.resolve(dir, manifest.main))) {
608
+ return { ok: false, error: `entry not found: ${manifest.main}` }
609
+ }
610
+ const patch = manifest.dsh?.bundle?.patch
611
+ if (patch && !fs.existsSync(path.resolve(dir, patch))) {
612
+ return { ok: false, error: `bundle patch not found: ${patch}` }
613
+ }
614
+ return { ok: true, dir, manifest, warnings: [] }
615
+ }
616
+
617
+ /**
618
+ * 安装一个插件:版本识别 → 兼容检查 → 备份 → 安装 → 写入 bundles → 校验。
619
+ * 任何一步失败都会恢复 package.json / lockfile,并返回 rolledBack。
620
+ */
621
+ export async function installPlugin(options = {}) {
622
+ const home = resolveHome(options.home)
623
+ const profileName = options.profile ?? defaultProfile(home)
624
+ const profile = resolveProfile(home, profileName)
625
+ const pkgFile = profilePackageJson(profile.dir)
626
+
627
+ if (!fs.existsSync(pkgFile)) {
628
+ throw new Error(`Profile not found: ${profile.dir}`)
629
+ }
630
+
631
+ const host = detectDshVersion({ ...options, home, profile: profileName })
632
+ if (!host.version) {
633
+ throw new Error('Cannot detect the DSH version. Pass --dsh-version <version> or --app <path-to-DSH>.')
634
+ }
635
+
636
+ const inspected = await inspectPlugin({
637
+ profileDir: profile.dir,
638
+ spec: options.spec,
639
+ runCommand: options.runCommand,
640
+ })
641
+ const compatibility = evaluateCompatibility(inspected.manifest, host, profile.dir)
642
+
643
+ const result = {
644
+ ok: false,
645
+ dryRun: options.dryRun === true,
646
+ profile: profileName,
647
+ profileDir: profile.dir,
648
+ host,
649
+ plugin: { name: inspected.name, version: inspected.version },
650
+ compatibility,
651
+ backup: null,
652
+ installed: false,
653
+ bundles: [],
654
+ warnings: [],
655
+ }
656
+
657
+ if (result.dryRun) return result
658
+ if (compatibility.status === 'blocked' && !options.force) {
659
+ result.error = 'Plugin is not compatible with this DSH version. Re-run with --force to install anyway.'
660
+ return result
661
+ }
662
+ if (compatibility.status === 'blocked') {
663
+ result.warnings.push('installed despite compatibility failure (--force)')
664
+ }
665
+
666
+ const beforeManifest = readJsonSync(pkgFile)
667
+ const hadPackage = Boolean(
668
+ readJsonSync(path.join(profile.dir, 'node_modules', inspected.name, 'package.json')),
669
+ )
670
+ const backup = await createBackup(home, [
671
+ pkgFile,
672
+ profilePatch(profile.dir),
673
+ path.join(profile.dir, 'pnpm-lock.yaml'),
674
+ path.join(profile.dir, 'package-lock.json'),
675
+ ])
676
+ result.backup = backup.dir
677
+
678
+ const trackedCoexist = await trackCoexistPlugin(profile.dir, beforeManifest)
679
+ if (trackedCoexist) await writeJson(pkgFile, beforeManifest)
680
+ const snapshot = snapshotNodeModules(profile.dir)
681
+
682
+ try {
683
+ const local = inspected.source === 'path'
684
+ let spec = options.spec
685
+ let localSpec = null
686
+ if (local) {
687
+ const staged = path.join(profile.dir, '.dsh-coexist', 'plugins', inspected.name)
688
+ await copyDir(inspected.dir, staged)
689
+ if (inspected.name === 'dsh-coexist-plugin') {
690
+ const cli = await stageLocalCli(profile.dir, inspected.dir)
691
+ if (cli) await rewriteDependency(path.join(staged, 'package.json'), CLI_PACKAGE, cli.rel)
692
+ }
693
+ localSpec = `file:${path.relative(profile.dir, staged).split(path.sep).join('/')}`
694
+ spec = localSpec
695
+ }
696
+
697
+ const runner = options.runCommand ?? defaultRunCommand
698
+ const ran = await tryRun(runner, managerAttempts(spec, host.appExe, 'add'), profile.dir)
699
+
700
+ if (!ran.ok) {
701
+ const present = verifyPluginDir(profile.dir, inspected.name)
702
+ if (present.ok) {
703
+ // pnpm 11 在忽略 build scripts 时会以非 0 退出,但依赖已经装好。
704
+ result.packageManager = ran.pm ?? 'package-manager (non-zero exit)'
705
+ result.warnings.push(
706
+ `package manager exited non-zero but the package is installed: ${ran.errors.join(' | ')}`,
707
+ )
708
+ } else if (!local) {
709
+ throw new Error(`Package manager failed: ${ran.errors.join(' | ')}`)
710
+ } else {
711
+ // 本地插件没有依赖:包管理器不可用时直接复制进 node_modules。
712
+ await copyDir(inspected.dir, path.join(profile.dir, 'node_modules', inspected.name))
713
+ if (inspected.name === 'dsh-coexist-plugin') {
714
+ const cli = await stageLocalCli(profile.dir, inspected.dir)
715
+ if (cli) {
716
+ await copyDir(cli.dir, path.join(profile.dir, 'node_modules', CLI_PACKAGE))
717
+ await rewriteDependency(
718
+ path.join(profile.dir, 'node_modules', inspected.name, 'package.json'),
719
+ CLI_PACKAGE,
720
+ cli.rel,
721
+ )
722
+ }
723
+ }
724
+ if (ran.errors.length > 0) {
725
+ result.warnings.push(`package manager unavailable, used local copy: ${ran.errors.join(' | ')}`)
726
+ }
727
+ }
728
+ } else {
729
+ result.packageManager = ran.pm
730
+ }
731
+
732
+ const restoredPackages = await restorePrunedPackages(profile.dir, snapshot)
733
+ if (restoredPackages.length > 0) {
734
+ result.restoredPackages = restoredPackages
735
+ result.warnings.push(
736
+ `restored packages pruned by the package manager: ${restoredPackages.join(', ')}`,
737
+ )
738
+ }
739
+
740
+ const manifest = readJsonSync(pkgFile)
741
+ if (!manifest) throw new Error(`Broken profile package.json: ${pkgFile}`)
742
+ manifest.dependencies ??= {}
743
+ if (!manifest.dependencies[inspected.name]) {
744
+ manifest.dependencies[inspected.name] = localSpec ?? inspected.version ?? 'latest'
745
+ }
746
+ ensureBundle(manifest, inspected.name)
747
+ await writeJson(pkgFile, manifest)
748
+
749
+ const verified = verifyPluginDir(profile.dir, inspected.name)
750
+ if (!verified.ok) throw new Error(verified.error)
751
+ result.warnings.push(...verified.warnings)
752
+
753
+ if (options.dumpConfig !== false) {
754
+ const dump = await dumpConfig({ home, profile: profileName, dshBin: options.dshBin })
755
+ if (dump.ok) {
756
+ result.dumpConfig = { ok: true, bytes: dump.stdout?.length ?? 0 }
757
+ } else if (/not found|ENOENT/i.test(dump.error ?? '')) {
758
+ result.dumpConfig = { ok: false, skipped: true, error: dump.error }
759
+ } else {
760
+ result.dumpConfig = { ok: false, error: dump.error }
761
+ result.warnings.push(`dump-config check failed: ${dump.error}`)
762
+ }
763
+ }
764
+
765
+ result.installed = true
766
+ result.ok = true
767
+ result.depAdded = !beforeManifest?.dependencies?.[inspected.name]
768
+ result.bundles = manifest.dsh.profile.bundles
769
+ return result
770
+ } catch (err) {
771
+ const restored = await restoreBackupFiles(backup)
772
+ const restoredPackages = await restorePrunedPackages(profile.dir, snapshot)
773
+ if (restoredPackages.length > 0) result.restoredPackages = restoredPackages
774
+ if (!hadPackage) {
775
+ await fsp
776
+ .rm(path.join(profile.dir, 'node_modules', inspected.name), { recursive: true, force: true })
777
+ .catch(() => {})
778
+ }
779
+ result.error = err.message
780
+ result.rolledBack = true
781
+ result.restored = restored
782
+ return result
783
+ }
784
+ }
785
+
786
+ /** 卸载插件:备份 → 从 bundles/dependencies 移除 → 尽力删除包目录。 */
787
+ export async function uninstallPlugin(options = {}) {
788
+ const home = resolveHome(options.home)
789
+ const profileName = options.profile ?? defaultProfile(home)
790
+ const profile = resolveProfile(home, profileName)
791
+ const pkgFile = profilePackageJson(profile.dir)
792
+ const manifest = readJsonSync(pkgFile)
793
+ if (!manifest) throw new Error(`Profile not found: ${profile.dir}`)
794
+
795
+ const name = options.spec
796
+ const backup = await createBackup(home, [
797
+ pkgFile,
798
+ profilePatch(profile.dir),
799
+ path.join(profile.dir, 'pnpm-lock.yaml'),
800
+ path.join(profile.dir, 'package-lock.json'),
801
+ ])
802
+ const result = { ok: true, profile: profileName, plugin: name, backup: backup.dir, removed: [] }
803
+ const snapshot = snapshotNodeModules(profile.dir)
804
+
805
+ const bundles = manifest.dsh?.profile?.bundles
806
+ if (Array.isArray(bundles)) {
807
+ manifest.dsh.profile.bundles = bundles.filter((item) => item !== name)
808
+ if (manifest.dsh.profile.bundles.length !== bundles.length) result.removed.push('bundles')
809
+ }
810
+ if (manifest.dependencies?.[name]) {
811
+ delete manifest.dependencies[name]
812
+ result.removed.push('dependencies')
813
+ }
814
+ await writeJson(pkgFile, manifest)
815
+
816
+ const runner = options.runCommand ?? defaultRunCommand
817
+ const attempts = managerAttempts(name, null, 'remove')
818
+ const ran = await tryRun(runner, attempts, profile.dir)
819
+ await fsp
820
+ .rm(path.join(profile.dir, 'node_modules', name), { recursive: true, force: true })
821
+ .catch(() => {})
822
+ const restoredPackages = await restorePrunedPackages(
823
+ profile.dir,
824
+ [...snapshot].filter((item) => item !== name),
825
+ )
826
+ if (restoredPackages.length > 0) {
827
+ result.restoredPackages = restoredPackages
828
+ result.warnings ??= []
829
+ result.warnings.push(
830
+ `restored packages pruned by the package manager: ${restoredPackages.join(', ')}`,
831
+ )
832
+ }
833
+ result.packageManager = ran.ok ? ran.pm : null
834
+ if (!ran.ok) {
835
+ result.warnings ??= []
836
+ result.warnings.push('package manager unavailable; removed the package directory only')
837
+ }
838
+ result.cleaned = await cleanupInstallArtifacts(profile.dir, name, home, options)
839
+ result.purged = options.purge === true
840
+ return result
841
+ }
842
+
843
+ /**
844
+ * rollback 恢复 package.json/lockfile 后,node_modules 里被 prune 的依赖需要重装。
845
+ * 只做 best-effort:包管理器不可用时返回错误,不阻断 rollback。
846
+ */
847
+ export async function reinstallDependencies(options = {}) {
848
+ const home = resolveHome(options.home)
849
+ const profileName = options.profile ?? defaultProfile(home)
850
+ const profile = resolveProfile(home, profileName)
851
+ const host = detectDshVersion({ ...options, home, profile: profileName })
852
+ const runner = options.runCommand ?? defaultRunCommand
853
+
854
+ const attempts = []
855
+ const bundled = resolveBundledPnpm(host.appExe)
856
+ if (bundled) {
857
+ attempts.push({
858
+ name: 'pnpm(bundled)',
859
+ file: bundled.file,
860
+ prefix: bundled.prefix,
861
+ args: ['install', '--config.strictDepBuilds=false'],
862
+ })
863
+ }
864
+ attempts.push(npmAttempt(['install', '--no-audit', '--no-fund']))
865
+
866
+ const ran = await tryRun(runner, attempts, profile.dir)
867
+ return {
868
+ ok: ran.ok,
869
+ profile: profileName,
870
+ profileDir: profile.dir,
871
+ packageManager: ran.ok ? ran.pm : null,
872
+ errors: ran.ok ? [] : ran.errors,
873
+ }
874
+ }
875
+
876
+ /**
877
+ * 版本兼容矩阵:宿主版本 + 每个已安装/已启用插件的引擎与 peer 检查结果。
878
+ * N 个插件共用同一套规则,不假设只有两个。
879
+ */
880
+ export async function buildMatrix(options = {}) {
881
+ const home = resolveHome(options.home)
882
+ const profileName = options.profile ?? defaultProfile(home)
883
+ const profile = resolveProfile(home, profileName)
884
+ const manifest = readJsonSync(profilePackageJson(profile.dir))
885
+ if (!manifest) throw new Error(`Profile not found: ${profile.dir}`)
886
+
887
+ const host = detectDshVersion({ ...options, home, profile: profileName })
888
+ const names = new Set([
889
+ ...(manifest.dsh?.profile?.bundles ?? []),
890
+ ...Object.keys(manifest.dependencies ?? {}),
891
+ ])
892
+
893
+ const rows = []
894
+ for (const name of [...names].sort()) {
895
+ const installed = readInstalledManifest(profile.dir, name)
896
+ if (!installed) {
897
+ const hostVersion = name.startsWith('@deepseek-ai/')
898
+ ? readHostPackageVersion(name, host, profile.dir)
899
+ : null
900
+ if (hostVersion) {
901
+ rows.push({ name, installed: true, version: hostVersion, status: 'host', checks: [] })
902
+ } else {
903
+ rows.push({ name, installed: false, status: 'missing', checks: [] })
904
+ }
905
+ continue
906
+ }
907
+ const compatibility = evaluateCompatibility(installed, host, profile.dir)
908
+ rows.push({
909
+ name,
910
+ installed: true,
911
+ version: installed.version,
912
+ status: compatibility.status,
913
+ checks: compatibility.checks,
914
+ })
915
+ }
916
+
917
+ return { profile: profileName, profileDir: profile.dir, host, rows }
918
+ }