dsh-concierge 0.0.0-stage → 0.20.4

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/index.js ADDED
@@ -0,0 +1,2700 @@
1
+ /**
2
+ * dsh-concierge — Host half.
3
+ *
4
+ * Serves a small same-origin JSON API used by the settings page:
5
+ * GET /dsh-concierge/status[?refresh=1] app + plugin update status
6
+ * POST /dsh-concierge/update { name } -> plugin update
7
+ *
8
+ * Sources:
9
+ * - app: resources/app-update.yml + the generic feed it names
10
+ * - plugins: pluginManager.listBundles() / listVersions()
11
+ * - market: pluginMarket configured indexes (entry lookup per plugin)
12
+ * - git: GitHub releases (or tags) for git-installed bundles
13
+ *
14
+ * Updates go through pluginManager.updateBundle(), so pnpm, rollback on
15
+ * failure and restart reporting stay owned by the plugin manager.
16
+ */
17
+ import { spawn } from 'node:child_process'
18
+ import { createReadStream, existsSync } from 'node:fs'
19
+ import { mkdir, readFile, rm, stat as statOf, writeFile } from 'node:fs/promises'
20
+ import { homedir } from 'node:os'
21
+ import path from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ export const inject = ['webServer']
25
+
26
+ const ROUTE = '/dsh-concierge'
27
+ const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
28
+ const CACHE_TTL_MS = 5 * 60 * 1000
29
+ const FETCH_TIMEOUT_MS = 12_000
30
+ const CONCURRENCY = 32
31
+ const REGISTRY_TIMEOUT_MS = 12_000
32
+ const MIRROR_BASE = 'https://registry.npmmirror.com'
33
+ const GITHUB_API = 'https://api.github.com'
34
+ const GITHUB_RELEASES = 'https://github.com/deepseek-ai/deepseek-harness/releases'
35
+ // Names whose last update asked for a restart; checked once on the next Host start.
36
+ const PENDING_FILE = path.join(homedir(), '.dsh', 'update-center', 'pending.json')
37
+
38
+ // Safe-mode helpers: when a broken third-party bundle keeps the app from
39
+ // starting, nothing inside the app can fix it, so the plugin writes a pair of
40
+ // double-click scripts that disable third-party bundles before launch.
41
+ const SAFE_DIR = path.join(homedir(), '.dsh', 'update-center')
42
+ const SETTINGS_FILE = path.join(SAFE_DIR, 'settings.json')
43
+
44
+ // A GitHub token raises the anonymous 60 requests/hour to 5,000. It can come
45
+ // from the environment or from the settings file the page writes.
46
+ let storedToken = null
47
+ // Whether safe-launch.cmd should fall back to safe mode when the app crashes.
48
+ let safeModeAuto = true
49
+
50
+ async function readSettings() {
51
+ try {
52
+ const text = await readFile(SETTINGS_FILE, 'utf8')
53
+ const parsed = JSON.parse(text)
54
+ if (parsed && typeof parsed.githubToken === 'string') storedToken = parsed.githubToken
55
+ if (parsed && typeof parsed.safeModeAuto === 'boolean') safeModeAuto = parsed.safeModeAuto
56
+ } catch {
57
+ /* no settings yet */
58
+ }
59
+ }
60
+
61
+ async function writeSettings() {
62
+ try {
63
+ await mkdir(SAFE_DIR, { recursive: true })
64
+ await writeFile(
65
+ SETTINGS_FILE,
66
+ JSON.stringify({ githubToken: storedToken || '', safeModeAuto }, null, 2),
67
+ 'utf8',
68
+ )
69
+ } catch {
70
+ /* best effort */
71
+ }
72
+ }
73
+
74
+ function maskToken(token) {
75
+ if (!token) return null
76
+ if (token.length <= 8) return '****'
77
+ // Keep the recognizable prefix so the page can say which kind of token it is.
78
+ const prefix = /^(github_pat_|ghp_|gho_|ghu_|ghs_|ghr_)/.exec(token)
79
+ if (prefix) return `${prefix[1]}…${token.slice(-4)}`
80
+ return `${token.slice(0, 4)}…${token.slice(-4)}`
81
+ }
82
+
83
+ const SAFE_MODE_PS1 = String.raw`param([switch]$Silent)
84
+ $ErrorActionPreference = 'Stop'
85
+ $profileDir = Join-Path $env:USERPROFILE '.dsh\profiles\desktop'
86
+ $exe = Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'
87
+ $pkg = Join-Path $profileDir 'package.json'
88
+ $patch = Join-Path $profileDir 'cordis.patch.yml'
89
+ $backupDir = Join-Path $env:USERPROFILE '.dsh\update-center\safe-backup'
90
+
91
+ $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
92
+ if ($running) {
93
+ Write-Host '应用正在运行,请先完全退出 DeepSeek Harness,再运行本脚本。' -ForegroundColor Yellow
94
+ if (-not $Silent) { Read-Host '按回车退出' }
95
+ exit 1
96
+ }
97
+
98
+ New-Item -ItemType Directory -Force -Path $backupDir | Out-Null
99
+ Copy-Item $pkg (Join-Path $backupDir 'package.json') -Force
100
+ if (Test-Path $patch) { Copy-Item $patch (Join-Path $backupDir 'cordis.patch.yml') -Force }
101
+
102
+ $json = Get-Content $pkg -Raw -Encoding UTF8 | ConvertFrom-Json
103
+ $json.dsh.profile.bundles = @($json.dsh.profile.bundles | Where-Object { $_ -like '@deepseek-ai/*' })
104
+ $json | ConvertTo-Json -Depth 100 | Set-Content $pkg -Encoding UTF8
105
+
106
+ Write-Host '已进入安全模式:只加载官方插件,第三方插件已临时停用。' -ForegroundColor Green
107
+ Write-Host '恢复:双击 restore-mode.cmd'
108
+ Start-Process -FilePath $exe
109
+ if (-not $Silent) { Read-Host '按回车关闭窗口' }
110
+ `
111
+
112
+ const RESTORE_PS1 = String.raw`param([switch]$Silent)
113
+ $ErrorActionPreference = 'Stop'
114
+ $profileDir = Join-Path $env:USERPROFILE '.dsh\profiles\desktop'
115
+ $exe = Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'
116
+ $backupDir = Join-Path $env:USERPROFILE '.dsh\update-center\safe-backup'
117
+
118
+ $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
119
+ if ($running) {
120
+ Write-Host '应用正在运行,请先完全退出 DeepSeek Harness,再运行本脚本。' -ForegroundColor Yellow
121
+ if (-not $Silent) { Read-Host '按回车退出' }
122
+ exit 1
123
+ }
124
+
125
+ if (-not (Test-Path (Join-Path $backupDir 'package.json'))) {
126
+ Write-Host '没有找到安全模式备份,无法恢复。' -ForegroundColor Yellow
127
+ if (-not $Silent) { Read-Host '按回车退出' }
128
+ exit 1
129
+ }
130
+
131
+ Copy-Item (Join-Path $backupDir 'package.json') (Join-Path $profileDir 'package.json') -Force
132
+ if (Test-Path (Join-Path $backupDir 'cordis.patch.yml')) {
133
+ Copy-Item (Join-Path $backupDir 'cordis.patch.yml') (Join-Path $profileDir 'cordis.patch.yml') -Force
134
+ }
135
+
136
+ Write-Host '已恢复原来的插件配置。' -ForegroundColor Green
137
+ # 手动恢复后清零自动恢复的计数,避免下次启动又触发一次。
138
+ @{ cleanStarts = 0; restoreAttempts = 0 } | ConvertTo-Json | Set-Content -Path (Join-Path $env:USERPROFILE '.dsh\update-center\safe-state.json') -Encoding UTF8
139
+ Start-Process -FilePath $exe
140
+ if (-not $Silent) { Read-Host '按回车关闭窗口' }
141
+ `
142
+
143
+ const SAFE_LAUNCH_PS1 = String.raw`param([switch]$Silent)
144
+ $ErrorActionPreference = 'Stop'
145
+ $exe = Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'
146
+ $profileDir = Join-Path $env:USERPROFILE '.dsh\profiles\desktop'
147
+ $pkg = Join-Path $profileDir 'package.json'
148
+ $patch = Join-Path $profileDir 'cordis.patch.yml'
149
+ $backupDir = Join-Path $env:USERPROFILE '.dsh\update-center\safe-backup'
150
+
151
+ $stateFile = Join-Path $env:USERPROFILE '.dsh\update-center\safe-state.json'
152
+ $logFile = Join-Path $env:USERPROFILE '.dsh\update-center\safe-launch.log'
153
+
154
+ function Note($m) { "$([DateTime]::Now.ToString('o')) $m" | Out-File -FilePath $logFile -Encoding utf8 -Append }
155
+ function ReadState {
156
+ if (-not (Test-Path $stateFile)) { return @{ cleanStarts = 0; restoreAttempts = 0 } }
157
+ try {
158
+ $s = Get-Content $stateFile -Raw -Encoding UTF8 | ConvertFrom-Json
159
+ return @{ cleanStarts = [int]$s.cleanStarts; restoreAttempts = [int]$s.restoreAttempts }
160
+ } catch { return @{ cleanStarts = 0; restoreAttempts = 0 } }
161
+ }
162
+ function WriteState($clean, $attempts) {
163
+ @{ cleanStarts = $clean; restoreAttempts = $attempts } | ConvertTo-Json | Set-Content -Path $stateFile -Encoding UTF8
164
+ }
165
+
166
+ $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
167
+ if ($running) { Write-Host '应用已经在运行。' -ForegroundColor Yellow; if (-not $Silent) { Read-Host '按回车退出' }; exit 0 }
168
+
169
+ $state = ReadState
170
+ Start-Process -FilePath $exe
171
+ Write-Host '正在启动,观察 30 秒看是否崩溃...'
172
+ Note 'started, watching'
173
+ Start-Sleep -Seconds 30
174
+ $alive = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
175
+ if ($alive) {
176
+ $clean = $state.cleanStarts + 1
177
+ WriteState $clean $state.restoreAttempts
178
+ Note "clean start #$clean"
179
+ Write-Host '启动正常。' -ForegroundColor Green
180
+ # 连续两次正常启动 + 有备份 = 应用已经好了:自动把原插件配置放回去并重启一次。
181
+ # 恢复后如果又崩,下次启动会重新落回安全模式;连续两次恢复失败就不再自动尝试。
182
+ if ($clean -ge 2 -and $state.restoreAttempts -lt 2 -and (Test-Path (Join-Path $backupDir 'package.json'))) {
183
+ Write-Host '连续两次启动正常,自动恢复原插件配置并重启...' -ForegroundColor Cyan
184
+ Note 'auto restore'
185
+ Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
186
+ Start-Sleep -Seconds 3
187
+ Copy-Item (Join-Path $backupDir 'package.json') $pkg -Force
188
+ if (Test-Path (Join-Path $backupDir 'cordis.patch.yml')) { Copy-Item (Join-Path $backupDir 'cordis.patch.yml') $patch -Force }
189
+ WriteState 0 ($state.restoreAttempts + 1)
190
+ Start-Process -FilePath $exe
191
+ Note 'restored and restarted'
192
+ }
193
+ if (-not $Silent) { Read-Host '按回车关闭窗口' }
194
+ exit 0
195
+ }
196
+
197
+ Write-Host '检测到启动失败,自动进入安全模式...' -ForegroundColor Yellow
198
+ Note 'start failed, entering safe mode'
199
+ Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
200
+ Start-Sleep -Seconds 2
201
+
202
+ New-Item -ItemType Directory -Force -Path $backupDir | Out-Null
203
+ Copy-Item $pkg (Join-Path $backupDir 'package.json') -Force
204
+ if (Test-Path $patch) { Copy-Item $patch (Join-Path $backupDir 'cordis.patch.yml') -Force }
205
+
206
+ $json = Get-Content $pkg -Raw -Encoding UTF8 | ConvertFrom-Json
207
+ $json.dsh.profile.bundles = @($json.dsh.profile.bundles | Where-Object { $_ -like '@deepseek-ai/*' })
208
+ $json | ConvertTo-Json -Depth 100 | Set-Content $pkg -Encoding UTF8
209
+ WriteState 0 $state.restoreAttempts
210
+
211
+ Start-Process -FilePath $exe
212
+ Write-Host '已用安全模式重启(只加载官方插件)。连续两次正常启动后会自动恢复;也可以双击 restore-mode.cmd 立即恢复。' -ForegroundColor Green
213
+ if (-not $Silent) { Read-Host '按回车关闭窗口' }
214
+ `
215
+
216
+ const PLAIN_LAUNCH_PS1 = String.raw`param([switch]$Silent)
217
+ $ErrorActionPreference = 'Stop'
218
+ $exe = Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'
219
+
220
+ $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
221
+ if ($running) { Write-Host '应用已经在运行。' -ForegroundColor Yellow; if (-not $Silent) { Read-Host '按回车退出' }; exit 0 }
222
+
223
+ Start-Process -FilePath $exe
224
+ Write-Host '已启动(自动安全模式已关闭)。' -ForegroundColor Green
225
+ `
226
+
227
+ // Hand off to the .vbs and exit: the console window closes immediately and the
228
+ // app is started from a hidden host, so its stdout never attaches to a console.
229
+ const CMD_WRAPPER = (script) => `@echo off\r\nwscript.exe "%~dp0${String(script).replace(/\.ps1$/, '')}.vbs"\r\nexit /b 0\r\n`
230
+
231
+ // Silent twin of the .cmd wrappers: window style 0 hides the console entirely.
232
+ const VBS_WRAPPER = (script) => `Set shell = CreateObject("WScript.Shell")\r\nSet fso = CreateObject("Scripting.FileSystemObject")\r\ndir = fso.GetParentFolderName(WScript.ScriptFullName)\r\nshell.Run "powershell -NoProfile -ExecutionPolicy Bypass -File """ & dir & "\\${script}"" -Silent", 0, False\r\n`
233
+
234
+ async function writeSafeModeScripts() {
235
+ try {
236
+ await mkdir(SAFE_DIR, { recursive: true })
237
+ // A BOM keeps Windows PowerShell 5.1 from reading the Chinese text as ANSI.
238
+ const bom = '\uFEFF'
239
+ await writeFile(path.join(SAFE_DIR, 'safe-mode.ps1'), bom + SAFE_MODE_PS1, 'utf8')
240
+ await writeFile(path.join(SAFE_DIR, 'restore-mode.ps1'), bom + RESTORE_PS1, 'utf8')
241
+ await writeFile(path.join(SAFE_DIR, 'safe-mode.cmd'), CMD_WRAPPER('safe-mode.ps1'), 'utf8')
242
+ await writeFile(path.join(SAFE_DIR, 'restore-mode.cmd'), CMD_WRAPPER('restore-mode.ps1'), 'utf8')
243
+ // The switch decides whether safe-launch.cmd watches for a crash and falls
244
+ // back to safe mode, or just starts the app.
245
+ const launchScript = safeModeAuto ? SAFE_LAUNCH_PS1 : PLAIN_LAUNCH_PS1
246
+ await writeFile(path.join(SAFE_DIR, 'safe-launch.ps1'), bom + launchScript, 'utf8')
247
+ await writeFile(path.join(SAFE_DIR, 'safe-launch.cmd'), CMD_WRAPPER('safe-launch.ps1'), 'utf8')
248
+ // Silent variants for people who do not want a console window at all.
249
+ await writeFile(path.join(SAFE_DIR, 'safe-launch.vbs'), VBS_WRAPPER('safe-launch.ps1'), 'utf8')
250
+ await writeFile(path.join(SAFE_DIR, 'safe-mode.vbs'), VBS_WRAPPER('safe-mode.ps1'), 'utf8')
251
+ await writeFile(path.join(SAFE_DIR, 'restore-mode.vbs'), VBS_WRAPPER('restore-mode.ps1'), 'utf8')
252
+ } catch {
253
+ /* best effort */
254
+ }
255
+ }
256
+
257
+ export function apply(ctx) {
258
+ const state = {
259
+ cache: null,
260
+ inflight: null,
261
+ targets: new Map(),
262
+ // One in-flight update per package, so a second request cannot race the first.
263
+ updating: new Set(),
264
+ autoEnabled: true,
265
+ autoBusy: false,
266
+ lastAuto: null,
267
+ autoTimer: null,
268
+ }
269
+
270
+ // 自动更新的开关存在磁盘上:以前它只是页面里的一个 localStorage 标志,
271
+ // 宿主完全不知道——所以「自动更新」必须等你打开更新页才发生。
272
+ const autoFile = path.join(homedir(), '.dsh', 'update-center', 'auto.json')
273
+ const readAuto = async () => {
274
+ try {
275
+ const parsed = JSON.parse(await readFile(autoFile, 'utf8'))
276
+ state.autoEnabled = !parsed || parsed.enabled !== false
277
+ } catch {
278
+ state.autoEnabled = true
279
+ }
280
+ return state.autoEnabled
281
+ }
282
+ const writeAuto = async (enabled) => {
283
+ state.autoEnabled = Boolean(enabled)
284
+ try {
285
+ await mkdir(path.dirname(autoFile), { recursive: true })
286
+ await writeFile(autoFile, JSON.stringify({ enabled: state.autoEnabled }), 'utf8')
287
+ } catch {
288
+ /* 写不进去就只留在内存里,不因此禁用功能 */
289
+ }
290
+ return state.autoEnabled
291
+ }
292
+ void readAuto()
293
+
294
+ // 宿主侧定时检查:不依赖任何页面开着。启动 90 秒后先跑一次(避开启动高峰),
295
+ // 之后每 30 分钟一次。
296
+ const autoTick = async () => {
297
+ if (!state.autoEnabled || state.autoBusy) return
298
+ state.autoBusy = true
299
+ try {
300
+ const data = await getStatus(ctx, state, true)
301
+ const rows = (data.plugins || []).filter((row) => row.updateAvailable)
302
+ if (!rows.length) return
303
+ const results = []
304
+ for (const row of rows) {
305
+ const result = await runUpdate(ctx, state, row.name)
306
+ results.push({
307
+ name: row.name,
308
+ ok: Boolean(result && result.ok),
309
+ error: result && result.error ? String(result.error) : null,
310
+ })
311
+ }
312
+ state.lastAuto = { at: Date.now(), results }
313
+ } catch {
314
+ /* 下一轮再试 */
315
+ } finally {
316
+ state.autoBusy = false
317
+ }
318
+ }
319
+ ctx.effect(() => {
320
+ const first = setTimeout(autoTick, 90 * 1000)
321
+ const loop = setInterval(autoTick, 30 * 60 * 1000)
322
+ state.autoTimer = loop
323
+ return () => {
324
+ clearTimeout(first)
325
+ clearInterval(loop)
326
+ state.autoTimer = null
327
+ }
328
+ }, 'dsh-concierge: auto update loop')
329
+
330
+ ctx.effect(
331
+ () => ctx.webServer.register({
332
+ kind: 'exact',
333
+ path: `${ROUTE}/auto`,
334
+ handler: withGuard(ctx, async (request, response) => {
335
+ if (request.method === 'GET') {
336
+ return sendNodeJson(response, { ok: true, enabled: state.autoEnabled, lastAuto: state.lastAuto }, 200)
337
+ }
338
+ try {
339
+ const body = await readNodeJson(request)
340
+ const enabled = await writeAuto(!body || body.enabled !== false)
341
+ return sendNodeJson(response, { ok: true, enabled }, 200)
342
+ } catch (error) {
343
+ return sendNodeJson(response, { ok: false, error: messageOf(error) }, 400)
344
+ }
345
+ }),
346
+ }),
347
+ 'dsh-concierge: auto update route',
348
+ )
349
+
350
+ ctx.effect(
351
+ () => ctx.webServer.register({
352
+ kind: 'prefix',
353
+ path: ROUTE,
354
+ resource: (request, peer) => handle(ctx, state, request, peer),
355
+ }),
356
+ 'dsh-concierge: read route',
357
+ )
358
+
359
+ // Resource routes answer GET/HEAD only, so the mutations have their own routes.
360
+ ctx.effect(
361
+ () => ctx.webServer.register({
362
+ kind: 'exact',
363
+ path: `${ROUTE}/update`,
364
+ handler: withGuard(ctx, (request, response) => handleUpdate(ctx, state, request, response)),
365
+ }),
366
+ 'dsh-concierge: update route',
367
+ )
368
+
369
+ ctx.effect(
370
+ () => ctx.webServer.register({
371
+ kind: 'exact',
372
+ path: `${ROUTE}/install`,
373
+ handler: withGuard(ctx, (request, response) => handleInstall(ctx, state, request, response)),
374
+ }),
375
+ 'dsh-concierge: install route',
376
+ )
377
+
378
+ ctx.effect(
379
+ () => ctx.webServer.register({
380
+ kind: 'exact',
381
+ path: `${ROUTE}/restart`,
382
+ handler: withGuard(ctx, (request, response) => handleRestart(ctx, request, response)),
383
+ }),
384
+ 'dsh-concierge: restart route',
385
+ )
386
+
387
+ ctx.effect(
388
+ () => ctx.webServer.register({
389
+ kind: 'exact',
390
+ path: `${ROUTE}/toggle`,
391
+ handler: withGuard(ctx, (request, response) => handleToggle(ctx, request, response)),
392
+ }),
393
+ 'dsh-concierge: toggle route',
394
+ )
395
+
396
+ ctx.effect(
397
+ () => ctx.webServer.register({
398
+ kind: 'exact',
399
+ path: `${ROUTE}/open`,
400
+ handler: withGuard(ctx, (request, response) => handleOpen(ctx, request, response)),
401
+ }),
402
+ 'dsh-concierge: open route',
403
+ )
404
+
405
+ ctx.effect(
406
+ () => ctx.webServer.register({
407
+ kind: 'exact',
408
+ path: `${ROUTE}/install-git`,
409
+ handler: withGuard(ctx, (request, response) => handleInstallGit(ctx, state, request, response)),
410
+ }),
411
+ 'dsh-concierge: install git route',
412
+ )
413
+
414
+ ctx.effect(
415
+ () => ctx.webServer.register({
416
+ kind: 'exact',
417
+ path: `${ROUTE}/sources`,
418
+ handler: withGuard(ctx, (request, response) => handleSources(state, request, response)),
419
+ }),
420
+ 'dsh-concierge: sources route',
421
+ )
422
+
423
+ ctx.effect(
424
+ () => ctx.webServer.register({
425
+ kind: 'exact',
426
+ path: `${ROUTE}/guide`,
427
+ handler: withGuard(ctx, (request, response) => handleGuide(request, response)),
428
+ }),
429
+ 'dsh-concierge: guide route',
430
+ )
431
+
432
+ ctx.effect(
433
+ () => ctx.webServer.register({
434
+ kind: 'exact',
435
+ path: `${ROUTE}/uninstall`,
436
+ handler: withGuard(ctx, (request, response) => handleUninstall(ctx, state, request, response)),
437
+ }),
438
+ 'dsh-concierge: uninstall route',
439
+ )
440
+
441
+ ctx.effect(
442
+ () => ctx.webServer.register({
443
+ kind: 'exact',
444
+ path: `${ROUTE}/install-npm`,
445
+ handler: withGuard(ctx, (request, response) => handleInstallNpm(ctx, state, request, response)),
446
+ }),
447
+ 'dsh-concierge: install npm route',
448
+ )
449
+
450
+ ctx.effect(
451
+ () => ctx.webServer.register({
452
+ kind: 'exact',
453
+ path: `${ROUTE}/settings`,
454
+ handler: withGuard(ctx, (request, response) => handleSettings(request, response)),
455
+ }),
456
+ 'dsh-concierge: settings route',
457
+ )
458
+
459
+ ctx.effect(
460
+ () => ctx.webServer.register({
461
+ kind: 'exact',
462
+ path: `${ROUTE}/about`,
463
+ handler: withGuard(ctx, (request, response) => handleAbout(request, response)),
464
+ }),
465
+ 'dsh-concierge: about route',
466
+ )
467
+
468
+ // 自定义背景:页面是 dsh-app:// 文档,读不了本地 file://,所以由宿主把选中的
469
+ // 图片/视频流出来。只放行图片和视频扩展名。
470
+ ctx.effect(
471
+ () => ctx.webServer.register({
472
+ kind: 'exact',
473
+ path: `${ROUTE}/wallpaper`,
474
+ handler: withGuard(ctx, (request, response) => handleWallpaper(request, response)),
475
+ }),
476
+ 'dsh-concierge: wallpaper route',
477
+ )
478
+
479
+ ctx.effect(
480
+ () => ctx.webServer.register({
481
+ kind: 'exact',
482
+ path: `${ROUTE}/startup-boost`,
483
+ handler: withGuard(ctx, (request, response) => handleStartupBoost(request, response)),
484
+ }),
485
+ 'dsh-concierge: startup boost route',
486
+ )
487
+
488
+ ctx.effect(
489
+ () => ctx.webServer.register({
490
+ kind: 'exact',
491
+ path: `${ROUTE}/window-corners`,
492
+ handler: withGuard(ctx, (request, response) => handleWindowCorners(request, response)),
493
+ }),
494
+ 'dsh-concierge: window corners route',
495
+ )
496
+
497
+ ctx.effect(
498
+ () => ctx.webServer.register({
499
+ kind: 'exact',
500
+ path: `${ROUTE}/perf-report`,
501
+ handler: withGuard(ctx, (request, response) => handlePerfReport(request, response)),
502
+ }),
503
+ 'dsh-concierge: perf report route',
504
+ )
505
+
506
+ // A plugin updated into a broken state should not keep breaking every start.
507
+ ctx.effect(() => {
508
+ const timer = setTimeout(() => {
509
+ void runStartupCheck(ctx)
510
+ }, 2500)
511
+ return () => clearTimeout(timer)
512
+ }, 'dsh-concierge: startup self-check')
513
+
514
+ // Keep the double-click recovery scripts on disk so they are there even when
515
+ // the app cannot start any more.
516
+ ctx.effect(() => {
517
+ void writeSafeModeScripts()
518
+ void readSettings()
519
+ void repairOwnLink()
520
+ return () => {}
521
+ }, 'dsh-concierge: safe-mode scripts')
522
+ }
523
+
524
+ async function handleRestart(ctx, request, response) {
525
+ if (request.method !== 'POST') {
526
+ response.statusCode = 405
527
+ response.setHeader('allow', 'POST')
528
+ response.end()
529
+ return
530
+ }
531
+ try {
532
+ const result = await requestAppRestart(ctx)
533
+ sendNodeJson(response, result, result.ok ? 202 : 400)
534
+ } catch (error) {
535
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
536
+ }
537
+ }
538
+
539
+ async function handleToggle(ctx, request, response) {
540
+ if (request.method !== 'POST') {
541
+ response.statusCode = 405
542
+ response.setHeader('allow', 'POST')
543
+ response.end()
544
+ return
545
+ }
546
+ try {
547
+ const body = await readNodeJson(request)
548
+ const result = await togglePlugin(ctx, body)
549
+ sendNodeJson(response, result, result.ok ? 200 : 400)
550
+ } catch (error) {
551
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
552
+ }
553
+ }
554
+
555
+ async function togglePlugin(ctx, body) {
556
+ const name = body && typeof body.name === 'string' ? body.name : ''
557
+ const enabled = Boolean(body && body.enabled)
558
+ if (!name) return { ok: false, error: '缺少插件名' }
559
+ const pm = ctx.get('pluginManager')
560
+ if (!pm || typeof pm.setPluginEnabled !== 'function') return { ok: false, error: 'pluginManager 不支持启停' }
561
+
562
+ let entryId = null
563
+ try {
564
+ const plugins = await pm.listPlugins()
565
+ const row = plugins.find((item) => item && (item.moduleName === name || item.packageName === name))
566
+ entryId = row && row.entryId ? row.entryId : null
567
+ } catch {
568
+ entryId = null
569
+ }
570
+ if (!entryId) {
571
+ try {
572
+ const bundles = await pm.listBundles()
573
+ const bundle = bundles.find((item) => item && item.name === name)
574
+ entryId = bundle && bundle.entryId ? bundle.entryId : null
575
+ } catch {
576
+ entryId = null
577
+ }
578
+ }
579
+ if (!entryId) return { ok: false, error: `找不到 ${name} 的入口` }
580
+
581
+ try {
582
+ const result = await pm.setPluginEnabled(entryId, enabled)
583
+ return { ok: true, enabled, result }
584
+ } catch (error) {
585
+ return { ok: false, error: messageOf(error) }
586
+ }
587
+ }
588
+
589
+ function normalizeGitSpec(input) {
590
+ const text = String(input || '').trim()
591
+ if (!text) return null
592
+ if (/^github:/i.test(text)) return text
593
+ const match = /^https?:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i.exec(text)
594
+ if (match) return `github:${match[1]}/${match[2]}`
595
+ if (/^git\+/.test(text) || /^ssh:\/\//.test(text) || /^https?:\/\/[^/]+\/.+\.git/i.test(text)) return text
596
+ return null
597
+ }
598
+
599
+ // GitHub repositories the user watches: checked for new releases even when the
600
+ // plugin is not installed, and installed on demand from the row.
601
+ const SOURCES_FILE = path.join(homedir(), '.dsh', 'update-center', 'github-sources.json')
602
+
603
+ async function readSources() {
604
+ try {
605
+ const text = await readFile(SOURCES_FILE, 'utf8')
606
+ const parsed = JSON.parse(text)
607
+ if (Array.isArray(parsed)) return parsed.filter((item) => typeof item === 'string')
608
+ } catch {
609
+ /* none yet */
610
+ }
611
+ return []
612
+ }
613
+
614
+ async function writeSources(list) {
615
+ try {
616
+ await mkdir(path.dirname(SOURCES_FILE), { recursive: true })
617
+ await writeFile(SOURCES_FILE, JSON.stringify(list, null, 2), 'utf8')
618
+ } catch {
619
+ /* best effort */
620
+ }
621
+ }
622
+
623
+ function normalizeSourceRepo(input) {
624
+ const text = String(input || '').trim()
625
+ if (!text) return null
626
+ const shorthand = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/.exec(text)
627
+ if (shorthand) return `${shorthand[1]}/${shorthand[2]}`
628
+ const url = /^https?:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(text)
629
+ if (url) return `${url[1]}/${url[2]}`
630
+ const bare = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(text)
631
+ if (bare) return `${bare[1]}/${bare[2]}`
632
+ return null
633
+ }
634
+
635
+ async function handleSettings(request, response) {
636
+ try {
637
+ if (request.method === 'GET') {
638
+ const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null
639
+ sendNodeJson(response, {
640
+ ok: true,
641
+ hasToken: Boolean(env || storedToken),
642
+ fromEnv: Boolean(env),
643
+ masked: maskToken(env || storedToken),
644
+ safeModeAuto,
645
+ }, 200)
646
+ return
647
+ }
648
+ if (request.method !== 'POST') {
649
+ response.statusCode = 405
650
+ response.setHeader('allow', 'GET, POST')
651
+ response.end()
652
+ return
653
+ }
654
+ const body = await readNodeJson(request)
655
+ if (typeof body.githubToken === 'string') {
656
+ const token = body.githubToken.trim()
657
+ storedToken = token || null
658
+ }
659
+ const autoChanged = typeof body.safeModeAuto === 'boolean' && body.safeModeAuto !== safeModeAuto
660
+ if (typeof body.safeModeAuto === 'boolean') safeModeAuto = body.safeModeAuto
661
+ await writeSettings()
662
+ if (autoChanged) await writeSafeModeScripts()
663
+ const env = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null
664
+ sendNodeJson(response, {
665
+ ok: true,
666
+ hasToken: Boolean(storedToken || env),
667
+ fromEnv: Boolean(env),
668
+ masked: maskToken(env || storedToken),
669
+ safeModeAuto,
670
+ }, 200)
671
+ } catch (error) {
672
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
673
+ }
674
+ }
675
+
676
+ // Startup boost: the Host cannot touch Defender itself (that needs elevation),
677
+ // so it writes a small script and asks Windows to run it elevated. The script
678
+ // reports back through a JSON file the page polls.
679
+ const STARTUP_BOOST_FILE = path.join(SAFE_DIR, 'startup-boost.json')
680
+ const STARTUP_BOOST_SCRIPT = path.join(SAFE_DIR, 'startup-boost.ps1')
681
+ const STARTUP_BOOST_LAUNCHER = path.join(SAFE_DIR, 'startup-boost-launch.ps1')
682
+
683
+ function startupBoostPaths() {
684
+ return [
685
+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'DeepSeek Harness'),
686
+ path.join(homedir(), '.dsh'),
687
+ path.dirname(PLUGIN_DIR),
688
+ ].filter(Boolean)
689
+ }
690
+
691
+ function buildStartupBoostScript(enabled) {
692
+ const quoted = startupBoostPaths()
693
+ .map((item) => `'${String(item).replace(/'/g, "''")}'`)
694
+ .join(', ')
695
+ const action = enabled
696
+ ? 'Add-MpPreference -ExclusionPath $p -ErrorAction Stop'
697
+ : 'Remove-MpPreference -ExclusionPath $p -ErrorAction Stop'
698
+ return `$ErrorActionPreference = 'Stop'
699
+ $paths = @(${quoted})
700
+ $result = [ordered]@{
701
+ ok = $true
702
+ enabled = ${enabled ? '$true' : '$false'}
703
+ at = (Get-Date).ToString('o')
704
+ paths = @()
705
+ errors = @()
706
+ }
707
+ foreach ($p in $paths) {
708
+ if (-not (Test-Path $p)) { $result.errors += "missing: $p"; continue }
709
+ try {
710
+ ${action}
711
+ $result.paths += $p
712
+ } catch {
713
+ $result.ok = $false
714
+ $result.errors += $_.Exception.Message
715
+ }
716
+ }
717
+ $json = $result | ConvertTo-Json -Depth 4
718
+ [System.IO.File]::WriteAllText('${STARTUP_BOOST_FILE.replace(/'/g, "''")}', $json, (New-Object System.Text.UTF8Encoding($false)))
719
+ `
720
+ }
721
+
722
+ async function readStartupBoost() {
723
+ try {
724
+ // PowerShell's Set-Content -Encoding UTF8 writes a BOM; JSON.parse chokes on it.
725
+ const text = (await readFile(STARTUP_BOOST_FILE, 'utf8')).replace(/^\uFEFF/, '')
726
+ const parsed = JSON.parse(text)
727
+ return parsed && typeof parsed === 'object' ? parsed : null
728
+ } catch {
729
+ return null
730
+ }
731
+ }
732
+
733
+ async function handleStartupBoost(request, response) {
734
+ try {
735
+ if (request.method === 'GET') {
736
+ sendNodeJson(response, { ok: true, state: await readStartupBoost() }, 200)
737
+ return
738
+ }
739
+ if (request.method !== 'POST') {
740
+ response.statusCode = 405
741
+ response.setHeader('allow', 'GET, POST')
742
+ response.end()
743
+ return
744
+ }
745
+ const body = await readNodeJson(request)
746
+ const enabled = body.enabled === true
747
+ await mkdir(SAFE_DIR, { recursive: true })
748
+ await writeFile(STARTUP_BOOST_SCRIPT, `\uFEFF${buildStartupBoostScript(enabled)}`, 'utf8')
749
+ // Elevation lives in its own .ps1: passing the whole Start-Process call as
750
+ // a -Command string got mangled by Node's Windows argument quoting.
751
+ await writeFile(
752
+ STARTUP_BOOST_LAUNCHER,
753
+ `\uFEFF$ErrorActionPreference = 'Stop'\r\nStart-Process powershell -Verb RunAs -WindowStyle Hidden -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-File','${STARTUP_BOOST_SCRIPT.replace(/'/g, "''")}')\r\n`,
754
+ 'utf8',
755
+ )
756
+ // detached: true puts the child in a new process group and the elevation
757
+ // prompt then never shows; a plain spawn lets Windows raise UAC normally.
758
+ const child = spawn('powershell.exe', [
759
+ '-NoProfile',
760
+ '-ExecutionPolicy',
761
+ 'Bypass',
762
+ '-File',
763
+ STARTUP_BOOST_LAUNCHER,
764
+ ], { stdio: 'ignore', windowsHide: true })
765
+ child.on('error', () => {})
766
+ child.unref()
767
+ sendNodeJson(response, { ok: true, launched: true }, 200)
768
+ } catch (error) {
769
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
770
+ }
771
+ }
772
+
773
+ // 窗口外框圆角:BrowserWindow 的构造参数(roundedCorners)插件改不了,但 DWM 的
774
+ // 圆角偏好可以在运行时改。DWMWA_WINDOW_CORNER_PREFERENCE = 33,
775
+ // DWMWCP_DONOTROUND = 1,DWMWCP_ROUND = 2。和 dsh-win11-material 的做法一致:
776
+ // 插件跑在 Host 进程里,能调 Win32/DWM,只是动不了窗口构造参数。
777
+ //
778
+ // DWMWA_BORDER_COLOR = 34:Windows 11 会给窗口画一圈 1px 边框。开了「无边框窗口」
779
+ // 之后这圈边框和内容的边会并排成两条线,把它设成 DWMWA_COLOR_NONE(0xFFFFFFFE)
780
+ // 就没有外框了。关掉时设回 DWMWA_COLOR_DEFAULT(0xFFFFFFFF)。
781
+ //
782
+ // 找窗口不用 MainWindowHandle:启动早期它可能是 0,而且 DevTools 也算主窗口。
783
+ // 这里枚举该进程的所有可见顶层窗口,取面积最大的那个(DevTools 和对话框都小得多),
784
+ // 这个做法抄自 dsh-transparent,它踩过「标题为空时匹配不到」的坑。
785
+ //
786
+ // watch:应用在启动收尾时还会 show / setBounds / 改状态,Electron 每次都会重写窗口
787
+ // 样式,把这里设的 DWM 属性冲掉。所以第一次应用之后盯一段时间,每 1.5 秒重设一次。
788
+ const WINDOW_CORNER_SCRIPT = (square, borderless, watch) => [
789
+ "$ErrorActionPreference = 'Stop'",
790
+ 'Add-Type -TypeDefinition @"',
791
+ 'using System;',
792
+ 'using System.Runtime.InteropServices;',
793
+ 'public class DshDwmWindow {',
794
+ ' public delegate bool EnumProc(IntPtr h, IntPtr l);',
795
+ ' public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }',
796
+ ' [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);',
797
+ ' [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);',
798
+ ' [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);',
799
+ ' [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);',
800
+ ' [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size);',
801
+ '}',
802
+ '"@',
803
+ "$procs = @(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue)",
804
+ "if ($procs.Count -eq 0) { Write-Output 'no-window'; exit 0 }",
805
+ '$global:pids = @($procs | ForEach-Object { $_.Id })',
806
+ '$global:found = [IntPtr]::Zero',
807
+ '$global:best = 0',
808
+ '$cb = [DshDwmWindow+EnumProc]{',
809
+ ' param($h, $l)',
810
+ ' if (-not [DshDwmWindow]::IsWindowVisible($h)) { return $true }',
811
+ ' $p = 0',
812
+ ' [void][DshDwmWindow]::GetWindowThreadProcessId($h, [ref]$p)',
813
+ ' if ($global:pids -notcontains $p) { return $true }',
814
+ ' $r = New-Object DshDwmWindow+RECT',
815
+ ' if (-not [DshDwmWindow]::GetWindowRect($h, [ref]$r)) { return $true }',
816
+ ' $ww = $r.Right - $r.Left',
817
+ ' $hh = $r.Bottom - $r.Top',
818
+ ' if ($ww -lt 700 -or $hh -lt 500) { return $true }',
819
+ ' $area = $ww * $hh',
820
+ ' if ($area -gt $global:best) { $global:best = $area; $global:found = $h }',
821
+ ' return $true',
822
+ '}',
823
+ '[void][DshDwmWindow]::EnumWindows($cb, [IntPtr]::Zero)',
824
+ '$w = $global:found',
825
+ "if ($w -eq [IntPtr]::Zero) { Write-Output 'no-window'; exit 0 }",
826
+ `$corner = ${square ? 1 : 2}`,
827
+ // 0xFFFFFFFE / 0xFFFFFFFF 超过 int 上限,用负的等价值(unchecked (int))。
828
+ `$border = ${borderless ? -2 : -1}`,
829
+ 'function Apply-DshDwm {',
830
+ ' $v = $corner',
831
+ ' $hr1 = [DshDwmWindow]::DwmSetWindowAttribute($w, 33, [ref]$v, 4)',
832
+ ' $b = $border',
833
+ ' $hr2 = [DshDwmWindow]::DwmSetWindowAttribute($w, 34, [ref]$b, 4)',
834
+ " Write-Output ('hr=' + $hr1 + ' border=' + $hr2)",
835
+ '}',
836
+ 'Apply-DshDwm',
837
+ `$watch = ${watch}`,
838
+ 'if ($watch -gt 0) {',
839
+ ' $end = (Get-Date).AddSeconds($watch)',
840
+ ' while ((Get-Date) -lt $end) {',
841
+ ' Start-Sleep -Milliseconds 1500',
842
+ ' $v = $corner',
843
+ ' [void][DshDwmWindow]::DwmSetWindowAttribute($w, 33, [ref]$v, 4)',
844
+ ' $b = $border',
845
+ ' [void][DshDwmWindow]::DwmSetWindowAttribute($w, 34, [ref]$b, 4)',
846
+ ' }',
847
+ '}',
848
+ ].join('\n')
849
+
850
+ function runPowerShellCommand(script, timeoutMs = 8000) {
851
+ return new Promise((resolve) => {
852
+ let child
853
+ try {
854
+ child = spawn('powershell.exe', [
855
+ '-NoProfile',
856
+ '-NonInteractive',
857
+ '-WindowStyle',
858
+ 'Hidden',
859
+ '-Command',
860
+ script,
861
+ ], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
862
+ } catch (error) {
863
+ resolve({ ok: false, error: messageOf(error) })
864
+ return
865
+ }
866
+ let out = ''
867
+ let err = ''
868
+ const timer = setTimeout(() => {
869
+ try {
870
+ child.kill()
871
+ } catch {
872
+ /* already gone */
873
+ }
874
+ resolve({ ok: false, error: 'timeout' })
875
+ }, timeoutMs)
876
+ child.stdout.on('data', (chunk) => { out += chunk })
877
+ child.stderr.on('data', (chunk) => { err += chunk })
878
+ child.on('error', (error) => {
879
+ clearTimeout(timer)
880
+ resolve({ ok: false, error: messageOf(error) })
881
+ })
882
+ child.on('close', (code) => {
883
+ clearTimeout(timer)
884
+ resolve({
885
+ ok: code === 0 && out.includes('hr=0'),
886
+ output: out.trim(),
887
+ error: code === 0 ? undefined : (err.trim() || `exit ${code}`),
888
+ })
889
+ })
890
+ })
891
+ }
892
+
893
+ async function handleWindowCorners(request, response) {
894
+ if (request.method !== 'POST') {
895
+ response.statusCode = 405
896
+ response.setHeader('allow', 'POST')
897
+ response.end()
898
+ return
899
+ }
900
+ try {
901
+ const body = await readNodeJson(request)
902
+ const square = body && body.square === true
903
+ const borderless = body && body.borderless === true
904
+ // 盯多久(秒)。只让第一次调用带这个值:之后每次改设置再起一个 15 秒的
905
+ // PowerShell 进程没有意义,还会叠起来。
906
+ const rawWatch = body && Number(body.watch)
907
+ const watch = Number.isFinite(rawWatch) ? Math.max(0, Math.min(30, Math.round(rawWatch))) : 0
908
+ const result = await runPowerShellCommand(
909
+ WINDOW_CORNER_SCRIPT(square, borderless, watch),
910
+ (watch + 8) * 1000,
911
+ )
912
+ sendNodeJson(response, {
913
+ ok: result.ok,
914
+ square,
915
+ borderless,
916
+ watch,
917
+ output: result.output || '',
918
+ error: result.error || '',
919
+ }, result.ok ? 200 : 500)
920
+ } catch (error) {
921
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
922
+ }
923
+ }
924
+
925
+ // 诊断落盘:客户端把「流式开始/结束」前后的长帧和 fps 样本发上来,写成一个 JSON,
926
+ // 方便事后判断掉帧是模糊挂回去的那次重绘,还是应用自己在收尾。
927
+ const PERF_REPORT_FILE = path.join(homedir(), '.dsh', 'update-center', 'perf-report.json')
928
+
929
+ async function handlePerfReport(request, response) {
930
+ if (request.method !== 'POST') {
931
+ response.statusCode = 405
932
+ response.setHeader('allow', 'POST')
933
+ response.end()
934
+ return
935
+ }
936
+ try {
937
+ const body = await readNodeJson(request)
938
+ await mkdir(path.dirname(PERF_REPORT_FILE), { recursive: true })
939
+ const report = { receivedAt: new Date().toISOString(), ...body }
940
+ await writeFile(PERF_REPORT_FILE, JSON.stringify(report, null, 2), 'utf8')
941
+ sendNodeJson(response, { ok: true, file: PERF_REPORT_FILE }, 200)
942
+ } catch (error) {
943
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
944
+ }
945
+ }
946
+
947
+ // pnpm occasionally rewrites this plugin's link spec with mojibake (the path
948
+ // becomes E:/????/...). The junction keeps working until the next install
949
+ // rebuilds it from the broken spec, so repair the spec while we are running.
950
+ async function repairOwnLink() {
951
+ try {
952
+ const pkgFile = path.join(homedir(), '.dsh', 'profiles', 'desktop', 'package.json')
953
+ const pkg = JSON.parse(await readFile(pkgFile, 'utf8'))
954
+ const spec = pkg && pkg.dependencies ? pkg.dependencies['dsh-concierge'] : null
955
+ if (typeof spec !== 'string' || !spec.startsWith('link:')) return
956
+ if (existsSync(spec.slice(5))) return
957
+ pkg.dependencies['dsh-concierge'] = `link:${PLUGIN_DIR.replace(/\\/g, '/')}`
958
+ await writeFile(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8')
959
+ } catch {
960
+ /* best effort */
961
+ }
962
+ }
963
+
964
+ // The About page shows the plugin's own package.json and CHANGELOG.md, so the
965
+ // version and the notes live in exactly one place on disk.
966
+ async function readChangelog() {
967
+ try {
968
+ const text = await readFile(path.join(PLUGIN_DIR, 'CHANGELOG.md'), 'utf8')
969
+ const entries = []
970
+ let current = null
971
+ let section = null
972
+ for (const line of text.split(/\r?\n/)) {
973
+ // 「## [0.2.8] - 2026-11-22」「## [0.2.6 – 0.2.7] - …」「## [Unreleased]」
974
+ const heading = /^##\s+(.+?)\s*$/.exec(line)
975
+ if (heading) {
976
+ const title = heading[1].trim()
977
+ const m = /^\[?([^\]]+?)\]?(?:\s+-\s+(.+))?$/.exec(title)
978
+ const version = m ? m[1].trim() : title
979
+ const date = m && m[2] ? m[2].trim() : ''
980
+ current = { version, date, sections: [] }
981
+ entries.push(current)
982
+ section = null
983
+ continue
984
+ }
985
+ // 「### Added」这类分组
986
+ const sub = /^###\s+(.+?)\s*$/.exec(line)
987
+ if (sub && current) {
988
+ section = { title: sub[1].trim(), items: [] }
989
+ current.sections.push(section)
990
+ continue
991
+ }
992
+ // 「> 一句头条」
993
+ const quote = /^>\s*(.+?)\s*$/.exec(line)
994
+ if (quote && current) {
995
+ if (!current.headline) current.headline = quote[1].trim()
996
+ continue
997
+ }
998
+ const item = /^[-*]\s+(.+?)\s*$/.exec(line)
999
+ if (item && current) {
1000
+ if (!section) {
1001
+ section = { title: '', items: [] }
1002
+ current.sections.push(section)
1003
+ }
1004
+ section.items.push(item[1].trim())
1005
+ }
1006
+ }
1007
+ return entries
1008
+ } catch {
1009
+ return []
1010
+ }
1011
+ }
1012
+
1013
+ async function handleAbout(request, response) {
1014
+ if (request.method !== 'GET') {
1015
+ response.statusCode = 405
1016
+ response.setHeader('allow', 'GET')
1017
+ response.end()
1018
+ return
1019
+ }
1020
+ try {
1021
+ let pkg = {}
1022
+ try {
1023
+ pkg = JSON.parse(await readFile(path.join(PLUGIN_DIR, 'package.json'), 'utf8'))
1024
+ } catch {
1025
+ pkg = {}
1026
+ }
1027
+ const repository = pkg.repository && typeof pkg.repository === 'object'
1028
+ ? pkg.repository.url
1029
+ : pkg.repository
1030
+ sendNodeJson(response, {
1031
+ ok: true,
1032
+ name: pkg.name || 'dsh-concierge',
1033
+ version: pkg.version || '0.0.0',
1034
+ description: pkg.description || '',
1035
+ license: pkg.license || '',
1036
+ repository: repository || '',
1037
+ changelog: await readChangelog(),
1038
+ }, 200)
1039
+ } catch (error) {
1040
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1041
+ }
1042
+ }
1043
+
1044
+ function normalizeNpmSpec(input) {
1045
+ const text = String(input || '').trim()
1046
+ if (!text) return null
1047
+ const match = /^(@[A-Za-z0-9_.-]+\/)?[A-Za-z0-9_.-]+(?:@[A-Za-z0-9_.^~<>=|*xX-]+)?$/.exec(text)
1048
+ return match ? text : null
1049
+ }
1050
+
1051
+ async function handleInstallNpm(ctx, state, request, response) {
1052
+ if (request.method !== 'POST') {
1053
+ response.statusCode = 405
1054
+ response.setHeader('allow', 'POST')
1055
+ response.end()
1056
+ return
1057
+ }
1058
+ try {
1059
+ const body = await readNodeJson(request)
1060
+ const spec = normalizeNpmSpec(body && body.spec)
1061
+ if (!spec) {
1062
+ sendNodeJson(response, { ok: false, error: '不是可识别的包名' }, 400)
1063
+ return
1064
+ }
1065
+ const pm = ctx.get('pluginManager')
1066
+ if (!pm || typeof pm.installBundle !== 'function') {
1067
+ sendNodeJson(response, { ok: false, error: 'pluginManager 服务不可用' }, 400)
1068
+ return
1069
+ }
1070
+ // pnpm 的 minimumReleaseAge(fresh-release hold)会拒绝刚发布的版本,然后
1071
+ // 静默装一个旧版——表现就是「装上了但版本不对」。先把最新版号钉死再装。
1072
+ const { name: pkgName, version: pkgVersion } = splitNpmSpec(spec)
1073
+ let target = spec
1074
+ if (pkgName && !pkgVersion) {
1075
+ const latest = await mirrorLatest(pkgName).catch(() => null)
1076
+ if (latest) target = `${pkgName}@${latest}`
1077
+ }
1078
+ const result = await pm.installBundle(target, {})
1079
+ state.cache = null
1080
+ const application = result && result.application
1081
+ const failed = application === 'failed' || application === 'cancelled'
1082
+ let error
1083
+ if (failed && result && result.error) {
1084
+ const raw = result.error.diagnostic || result.error.code || '安装失败'
1085
+ error = /approve-builds|build scripts/i.test(String(raw))
1086
+ ? '这个插件需要执行构建脚本,pnpm 默认拦截。到插件市场点「允许构建脚本并重试」,或在终端跑 pnpm approve-builds 后重试。'
1087
+ : raw
1088
+ }
1089
+ sendNodeJson(response, { ok: !failed, spec: target, error, result }, 200)
1090
+ } catch (error) {
1091
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1092
+ }
1093
+ }
1094
+
1095
+ const WALLPAPER_TYPES = {
1096
+ '.jpg': 'image/jpeg',
1097
+ '.jpeg': 'image/jpeg',
1098
+ '.png': 'image/png',
1099
+ '.webp': 'image/webp',
1100
+ '.avif': 'image/avif',
1101
+ '.gif': 'image/gif',
1102
+ '.mp4': 'video/mp4',
1103
+ '.webm': 'video/webm',
1104
+ '.mov': 'video/quicktime',
1105
+ }
1106
+
1107
+ async function handleWallpaper(request, response) {
1108
+ try {
1109
+ const url = new URL(request.url || '/', 'http://localhost')
1110
+ const raw = url.searchParams.get('path') || ''
1111
+ if (!raw) {
1112
+ response.statusCode = 400
1113
+ response.end('missing path')
1114
+ return
1115
+ }
1116
+ const absolute = path.resolve(raw)
1117
+ const type = WALLPAPER_TYPES[path.extname(absolute).toLowerCase()]
1118
+ if (!type) {
1119
+ response.statusCode = 415
1120
+ response.end('unsupported type')
1121
+ return
1122
+ }
1123
+ const info = await statOf(absolute).catch(() => null)
1124
+ if (!info || !info.isFile()) {
1125
+ response.statusCode = 404
1126
+ response.end('not found')
1127
+ return
1128
+ }
1129
+ response.setHeader('content-type', type)
1130
+ response.setHeader('content-length', String(info.size))
1131
+ response.setHeader('cache-control', 'no-cache')
1132
+ const stream = createReadStream(absolute)
1133
+ stream.on('error', () => {
1134
+ try {
1135
+ response.destroy()
1136
+ } catch {
1137
+ /* already gone */
1138
+ }
1139
+ })
1140
+ stream.pipe(response)
1141
+ } catch (error) {
1142
+ response.statusCode = 500
1143
+ response.end(messageOf(error))
1144
+ }
1145
+ }
1146
+
1147
+ async function handleUninstall(ctx, state, request, response) {
1148
+ if (request.method !== 'POST') {
1149
+ response.statusCode = 405
1150
+ response.setHeader('allow', 'POST')
1151
+ response.end()
1152
+ return
1153
+ }
1154
+ try {
1155
+ const body = await readNodeJson(request)
1156
+ const name = body && typeof body.name === 'string' ? body.name : ''
1157
+ if (!name) {
1158
+ sendNodeJson(response, { ok: false, error: '缺少插件名' }, 400)
1159
+ return
1160
+ }
1161
+ const pm = ctx.get('pluginManager')
1162
+ if (!pm || typeof pm.removeBundle !== 'function') {
1163
+ sendNodeJson(response, { ok: false, error: 'pluginManager 服务不可用' }, 400)
1164
+ return
1165
+ }
1166
+ const result = await pm.removeBundle(name)
1167
+ state.cache = null
1168
+ const application = result && result.application
1169
+ const failed = application === 'failed' || application === 'cancelled'
1170
+ const error = failed && result && result.error
1171
+ ? (result.error.diagnostic || result.error.code || '卸载失败')
1172
+ : undefined
1173
+ sendNodeJson(response, { ok: !failed, error, result }, 200)
1174
+ } catch (error) {
1175
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1176
+ }
1177
+ }
1178
+
1179
+ async function handleGuide(request, response) {
1180
+ if (request.method !== 'GET') {
1181
+ response.statusCode = 405
1182
+ response.setHeader('allow', 'GET')
1183
+ response.end()
1184
+ return
1185
+ }
1186
+ try {
1187
+ const url = new URL(request.url, 'http://localhost')
1188
+ const repo = normalizeSourceRepo(url.searchParams.get('repo') || '')
1189
+ if (!repo) {
1190
+ sendNodeJson(response, { ok: false, error: '缺少仓库' }, 400)
1191
+ return
1192
+ }
1193
+ const guide = await fetchGuide(repo)
1194
+ sendNodeJson(response, guide, guide.ok ? 200 : 400)
1195
+ } catch (error) {
1196
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1197
+ }
1198
+ }
1199
+
1200
+ async function handleSources(state, request, response) {
1201
+ if (request.method !== 'POST') {
1202
+ response.statusCode = 405
1203
+ response.setHeader('allow', 'POST')
1204
+ response.end()
1205
+ return
1206
+ }
1207
+ try {
1208
+ const body = await readNodeJson(request)
1209
+ const action = body && body.action === 'remove' ? 'remove' : 'add'
1210
+ const repo = normalizeSourceRepo(body && body.url)
1211
+ if (!repo) {
1212
+ sendNodeJson(response, { ok: false, error: '不是可识别的 GitHub 地址' }, 400)
1213
+ return
1214
+ }
1215
+ let list = await readSources()
1216
+ if (action === 'add') {
1217
+ if (!list.includes(repo)) list.push(repo)
1218
+ } else {
1219
+ list = list.filter((item) => item !== repo)
1220
+ }
1221
+ await writeSources(list)
1222
+ state.cache = null
1223
+ sendNodeJson(response, { ok: true, sources: list }, 200)
1224
+ } catch (error) {
1225
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1226
+ }
1227
+ }
1228
+
1229
+ async function repoPackageName(repo) {
1230
+ try {
1231
+ const response = await fetchWithTimeout(
1232
+ `https://raw.githubusercontent.com/${repo}/HEAD/package.json`,
1233
+ { headers: { 'user-agent': 'dsh-concierge' } },
1234
+ 8000,
1235
+ )
1236
+ if (!response.ok) return null
1237
+ const pkg = await response.json().catch(() => null)
1238
+ return pkg && typeof pkg.name === 'string' ? pkg.name : null
1239
+ } catch {
1240
+ return null
1241
+ }
1242
+ }
1243
+
1244
+ async function checkSources(bundles) {
1245
+ const list = await readSources()
1246
+ if (list.length === 0) return []
1247
+ const rows = await mapLimit(list, 6, async (repo) => {
1248
+ const row = {
1249
+ repo,
1250
+ url: `https://github.com/${repo}`,
1251
+ installed: false,
1252
+ installedVersion: null,
1253
+ latest: null,
1254
+ releaseUrl: null,
1255
+ updateAvailable: false,
1256
+ error: null,
1257
+ }
1258
+ // The same plugin can be installed from a tarball or a local path, so match
1259
+ // by the repository's package name as well as by its install source.
1260
+ const packageName = await repoPackageName(repo)
1261
+ row.packageName = packageName
1262
+ let installed = bundles.find((bundle) => {
1263
+ if (!bundle) return false
1264
+ const source = String(bundle.source || (bundle.installTarget && bundle.installTarget.spec) || '')
1265
+ return source.includes(repo)
1266
+ })
1267
+ if (!installed && packageName) {
1268
+ installed = bundles.find((bundle) => bundle && bundle.name === packageName)
1269
+ }
1270
+ if (installed) {
1271
+ row.installed = true
1272
+ row.installedVersion = installed.version || null
1273
+ row.installedName = installed.name || null
1274
+ }
1275
+ try {
1276
+ const latest = await githubLatest(repo)
1277
+ if (latest) {
1278
+ row.latest = latest.version
1279
+ row.releaseUrl = latest.url
1280
+ row.updateAvailable = Boolean(
1281
+ row.installed && row.installedVersion && compareVersions(latest.version, row.installedVersion) > 0,
1282
+ )
1283
+ }
1284
+ } catch (error) {
1285
+ const message = messageOf(error)
1286
+ row.error = /HTTP 40[13]|rate limit/i.test(message) ? 'GitHub 速率限制' : message
1287
+ }
1288
+ return row
1289
+ })
1290
+ rows.sort((a, b) => a.repo.localeCompare(b.repo))
1291
+ return rows
1292
+ }
1293
+
1294
+ // Multi-step plugins (memory starters and the like) document their install in
1295
+ // the repository README; pull the quick-start steps out so the panel can walk
1296
+ // the user through them after the bundle itself is installed.
1297
+ function extractSteps(markdown) {
1298
+ const lines = String(markdown || '').split(/\r?\n/)
1299
+ const steps = []
1300
+ let inSection = false
1301
+ let inFence = false
1302
+ for (const line of lines) {
1303
+ if (/^\s*```/.test(line)) {
1304
+ inFence = !inFence
1305
+ continue
1306
+ }
1307
+ const heading = /^#{1,4}\s+(.*)$/.exec(line)
1308
+ if (heading && !inFence) {
1309
+ const title = heading[1].trim()
1310
+ if (!inSection && /(快速开始|安装|使用|getting started|install|setup|quick start)/i.test(title)) {
1311
+ inSection = true
1312
+ continue
1313
+ }
1314
+ if (inSection && steps.length >= 2) break
1315
+ continue
1316
+ }
1317
+ if (!inSection || inFence) continue
1318
+ const item = /^\s*(?:\d+[.)]|[-*])\s+(.+)$/.exec(line)
1319
+ if (item) {
1320
+ const text = item[1].replace(/`/g, '').replace(/\*\*/g, '').trim()
1321
+ if (text.length > 1 && text.length < 300) steps.push(text)
1322
+ }
1323
+ if (steps.length >= 10) break
1324
+ }
1325
+ return steps
1326
+ }
1327
+
1328
+ async function fetchGuide(repo) {
1329
+ const response = await fetchWithTimeout(
1330
+ `${GITHUB_API}/repos/${repo}/readme`,
1331
+ { headers: { ...githubHeaders(), accept: 'application/vnd.github.raw' } },
1332
+ 10000,
1333
+ )
1334
+ if (!response.ok) return { ok: false, error: `HTTP ${response.status}` }
1335
+ const text = await response.text()
1336
+ return {
1337
+ ok: true,
1338
+ repo,
1339
+ url: `https://github.com/${repo}`,
1340
+ steps: extractSteps(text),
1341
+ }
1342
+ }
1343
+
1344
+ async function resolveGitHead(repo) {
1345
+ try {
1346
+ const response = await fetchWithTimeout(`${GITHUB_API}/repos/${repo}/commits/HEAD`, { headers: githubHeaders() }, 8000)
1347
+ if (!response.ok) return null
1348
+ const commit = await response.json().catch(() => null)
1349
+ return commit && typeof commit.sha === 'string' ? commit.sha : null
1350
+ } catch {
1351
+ return null
1352
+ }
1353
+ }
1354
+
1355
+ async function handleInstallGit(ctx, state, request, response) {
1356
+ if (request.method !== 'POST') {
1357
+ response.statusCode = 405
1358
+ response.setHeader('allow', 'POST')
1359
+ response.end()
1360
+ return
1361
+ }
1362
+ try {
1363
+ const body = await readNodeJson(request)
1364
+ let spec = normalizeGitSpec(body && body.url)
1365
+ if (!spec) {
1366
+ sendNodeJson(response, { ok: false, error: '不是可识别的 Git 地址' }, 400)
1367
+ return
1368
+ }
1369
+ // Pin the install to a full commit: only a pinned Git spec is updatable
1370
+ // (and rollback-able) through the plugin manager afterwards.
1371
+ const shorthand = /^github:([^#]+)$/.exec(spec)
1372
+ if (shorthand) {
1373
+ const sha = await resolveGitHead(shorthand[1])
1374
+ if (sha) spec = `github:${shorthand[1]}#${sha}`
1375
+ }
1376
+ const pm = ctx.get('pluginManager')
1377
+ if (!pm || typeof pm.installBundle !== 'function') {
1378
+ sendNodeJson(response, { ok: false, error: 'pluginManager 服务不可用' }, 400)
1379
+ return
1380
+ }
1381
+ const result = await pm.installBundle(spec, {})
1382
+ state.cache = null
1383
+ const application = result && result.application
1384
+ const failed = application === 'failed' || application === 'cancelled'
1385
+ let error
1386
+ if (failed && result && result.error) {
1387
+ const raw = result.error.diagnostic || result.error.code || '安装失败'
1388
+ error = /approve-builds|build scripts/i.test(String(raw))
1389
+ ? '这个插件需要执行构建脚本,pnpm 默认拦截。到插件市场点「允许构建脚本并重试」,或在终端跑 pnpm approve-builds 后重试。'
1390
+ : raw
1391
+ }
1392
+ sendNodeJson(response, { ok: !failed, spec, error, result }, 200)
1393
+ } catch (error) {
1394
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1395
+ }
1396
+ }
1397
+
1398
+ async function handleOpen(ctx, request, response) {
1399
+ if (request.method !== 'POST') {
1400
+ response.statusCode = 405
1401
+ response.setHeader('allow', 'POST')
1402
+ response.end()
1403
+ return
1404
+ }
1405
+ try {
1406
+ const body = await readNodeJson(request)
1407
+ const target = body && body.target === 'config' ? 'config' : body && body.target === 'safe' ? 'safe' : 'plugins'
1408
+ const dir = profileDir()
1409
+ const openPath = target === 'safe'
1410
+ ? SAFE_DIR
1411
+ : existsSync(target === 'config' ? path.join(dir, 'cordis.patch.yml') : path.join(dir, 'node_modules'))
1412
+ ? (target === 'config' ? path.join(dir, 'cordis.patch.yml') : path.join(dir, 'node_modules'))
1413
+ : dir
1414
+ const result = openInExplorer(openPath)
1415
+ sendNodeJson(response, result, result.ok ? 200 : 400)
1416
+ } catch (error) {
1417
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1418
+ }
1419
+ }
1420
+
1421
+ function profileDir() {
1422
+ const profile = process.env.DSH_PROFILE || 'desktop'
1423
+ return path.join(homedir(), '.dsh', 'profiles', profile)
1424
+ }
1425
+
1426
+ function openInExplorer(target) {
1427
+ if (process.platform !== 'win32') return { ok: false, error: '仅支持 Windows' }
1428
+ try {
1429
+ const child = spawn('explorer.exe', [target], { detached: true, stdio: 'ignore', windowsHide: true })
1430
+ child.on('error', () => {})
1431
+ child.unref()
1432
+ return { ok: true, path: target }
1433
+ } catch (error) {
1434
+ return { ok: false, error: messageOf(error) }
1435
+ }
1436
+ }
1437
+
1438
+ async function readPending() {
1439
+ try {
1440
+ const text = await readFile(PENDING_FILE, 'utf8')
1441
+ const parsed = JSON.parse(text)
1442
+ if (Array.isArray(parsed.disabled)) return parsed.disabled
1443
+ } catch {
1444
+ /* no pending record */
1445
+ }
1446
+ return []
1447
+ }
1448
+
1449
+ /**
1450
+ * Relaunch the desktop app without dsh-desktop-restart: a PowerShell helper is
1451
+ * created through WMI, so it lives outside this process tree (and its job
1452
+ * object), then kills the Electron main process and starts the executable.
1453
+ */
1454
+ async function requestAppRestart(ctx) {
1455
+ if (process.platform !== 'win32') return { ok: false, error: '仅支持 Windows' }
1456
+ const exe = process.execPath
1457
+ if (!exe || !existsSync(exe)) return { ok: false, error: '找不到应用可执行文件' }
1458
+ const parent = process.ppid
1459
+ if (!parent) return { ok: false, error: '找不到宿主进程' }
1460
+
1461
+ const dir = path.join(homedir(), '.dsh', 'update-center')
1462
+ await mkdir(dir, { recursive: true })
1463
+ const log = path.join(dir, 'restart.log')
1464
+ const script = path.join(dir, 'restart.ps1')
1465
+ const quote = (value) => String(value).replace(/'/g, "''")
1466
+ const lines = [
1467
+ "$ErrorActionPreference = 'SilentlyContinue'",
1468
+ `$exe = '${quote(exe)}'`,
1469
+ `$parent = ${parent}`,
1470
+ `$log = '${quote(log)}'`,
1471
+ 'function Note($m) { "$([DateTime]::Now.ToString(\'o\')) $m" | Out-File -FilePath $log -Encoding utf8 -Append }',
1472
+ "Note 'helper start'",
1473
+ 'Start-Sleep -Seconds 2',
1474
+ 'Stop-Process -Id $parent -Force',
1475
+ "Note 'killed parent'",
1476
+ // Starting while an old instance still holds the single-instance lock makes
1477
+ // the new one quit silently, which is what leaves a window without the
1478
+ // composer. Wait for every instance to be gone first.
1479
+ 'for ($i = 0; $i -lt 40; $i++) {',
1480
+ " if (-not (Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue)) { break }",
1481
+ ' Start-Sleep -Milliseconds 500',
1482
+ '}',
1483
+ "Note 'all instances gone'",
1484
+ 'Start-Sleep -Seconds 1',
1485
+ 'for ($i = 0; $i -lt 3; $i++) {',
1486
+ ' Start-Process -FilePath $exe',
1487
+ ' Note "launched $i"',
1488
+ ' Start-Sleep -Seconds 10',
1489
+ ' $p = Get-Process | Where-Object { $_.Path -eq $exe }',
1490
+ ' if ($p) { Note "back"; break }',
1491
+ '}',
1492
+ ]
1493
+ await writeFile(script, lines.join('\n'), 'utf8')
1494
+ // A console program created through WMI still flashes a console window before
1495
+ // -WindowStyle Hidden takes effect. wscript.exe is a GUI process, so starting
1496
+ // it produces no console at all, and it then runs PowerShell with style 0.
1497
+ const helperVbs = path.join(dir, 'restart-helper.vbs')
1498
+ await writeFile(
1499
+ helperVbs,
1500
+ `Set shell = CreateObject("WScript.Shell")\r\nshell.Run "powershell -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File ""${quote(script)}""", 0, False\r\n`,
1501
+ 'utf8',
1502
+ )
1503
+ const commandLine = `wscript.exe "${helperVbs}"`
1504
+ const wmi = `Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='${quote(commandLine)}'}`
1505
+ const helper = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', wmi], {
1506
+ stdio: 'ignore',
1507
+ windowsHide: true,
1508
+ })
1509
+ helper.on('error', () => {})
1510
+ return { ok: true, restarting: true, logPath: log }
1511
+ }
1512
+
1513
+ async function recordPending(name) {
1514
+ try {
1515
+ await mkdir(path.dirname(PENDING_FILE), { recursive: true })
1516
+ let names = []
1517
+ try {
1518
+ const previous = JSON.parse(await readFile(PENDING_FILE, 'utf8'))
1519
+ if (Array.isArray(previous.names)) names = previous.names
1520
+ } catch {
1521
+ names = []
1522
+ }
1523
+ if (!names.includes(name)) names.push(name)
1524
+ await writeFile(PENDING_FILE, JSON.stringify({ names, at: Date.now() }), 'utf8')
1525
+ } catch {
1526
+ /* the self-check is best effort */
1527
+ }
1528
+ }
1529
+
1530
+ async function runStartupCheck(ctx) {
1531
+ try {
1532
+ if (!existsSync(PENDING_FILE)) return
1533
+ const pending = JSON.parse(await readFile(PENDING_FILE, 'utf8'))
1534
+ const names = Array.isArray(pending.names) ? pending.names : []
1535
+ if (names.length === 0) {
1536
+ await rm(PENDING_FILE, { force: true })
1537
+ return
1538
+ }
1539
+ const pm = ctx.get('pluginManager')
1540
+ if (!pm || typeof pm.listPlugins !== 'function') return
1541
+ const plugins = await pm.listPlugins()
1542
+ const failed = plugins.filter((row) => row && row.fiberPhase === 'failed' && names.includes(row.moduleName))
1543
+ const disabled = []
1544
+ for (const row of failed) {
1545
+ try {
1546
+ await pm.setPluginEnabled(row.entryId, false)
1547
+ disabled.push(row.moduleName)
1548
+ } catch {
1549
+ /* leave it; the next start reports the same failure */
1550
+ }
1551
+ }
1552
+ await writeFile(PENDING_FILE, JSON.stringify({ checkedAt: Date.now(), disabled }), 'utf8')
1553
+ } catch {
1554
+ /* the self-check is best effort */
1555
+ }
1556
+ }
1557
+
1558
+ async function handleInstall(ctx, state, request, response) {
1559
+ if (request.method !== 'POST') {
1560
+ response.statusCode = 405
1561
+ response.setHeader('allow', 'POST')
1562
+ response.end()
1563
+ return
1564
+ }
1565
+ try {
1566
+ const body = await readNodeJson(request)
1567
+ const result = await installVersion(ctx, state, body)
1568
+ sendNodeJson(response, result, result.ok ? 200 : 400)
1569
+ } catch (error) {
1570
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1571
+ }
1572
+ }
1573
+
1574
+ async function listVersions(ctx, state, name) {
1575
+ if (!name) return { ok: false, error: '缺少插件名' }
1576
+ const pm = ctx.get('pluginManager')
1577
+ if (!pm) return { ok: false, error: 'pluginManager 服务不可用' }
1578
+
1579
+ let current = null
1580
+ let kind = null
1581
+ let source = null
1582
+ try {
1583
+ const bundles = await pm.listBundles()
1584
+ const bundle = bundles.find((item) => item && item.name === name)
1585
+ current = bundle ? bundle.version : null
1586
+ kind = bundle ? bundle.update || null : null
1587
+ source = bundle ? (bundle.source || (bundle.installTarget && bundle.installTarget.spec) || null) : null
1588
+ } catch {
1589
+ /* keep nulls */
1590
+ }
1591
+ if (kind === 'git') {
1592
+ return listGitVersions(name, current, source)
1593
+ }
1594
+ if (kind && kind !== 'registry') {
1595
+ return { ok: false, error: '本地安装的插件没有可回退的版本' }
1596
+ }
1597
+
1598
+ // The manager only lists versions newer than the installed one, so read the
1599
+ // full published list from the mirror's abbreviated packument instead.
1600
+ try {
1601
+ const path = String(name).replace('/', '%2F')
1602
+ const response = await fetchWithTimeout(
1603
+ `${MIRROR_BASE}/${path}`,
1604
+ { headers: { accept: 'application/vnd.npm.install-v1+json' } },
1605
+ 8000,
1606
+ )
1607
+ if (response.ok) {
1608
+ const body = await response.json().catch(() => null)
1609
+ const published = body && body.versions && typeof body.versions === 'object' ? Object.keys(body.versions) : []
1610
+ if (published.length > 0) {
1611
+ const sorted = published.sort((a, b) => compareVersions(b, a))
1612
+ return {
1613
+ ok: true,
1614
+ current,
1615
+ versions: sorted.slice(0, 100).map((version) => ({
1616
+ version,
1617
+ incompatible: false,
1618
+ deprecated: body.versions[version] && body.versions[version].deprecated
1619
+ ? String(body.versions[version].deprecated)
1620
+ : null,
1621
+ })),
1622
+ }
1623
+ }
1624
+ }
1625
+ } catch {
1626
+ /* fall through to the manager */
1627
+ }
1628
+
1629
+ if (typeof pm.listVersions === 'function') {
1630
+ const list = await withTimeout(pm.listVersions(name), REGISTRY_TIMEOUT_MS, '版本检查超时')
1631
+ if (list.status === 'listed' && Array.isArray(list.versions)) {
1632
+ return {
1633
+ ok: true,
1634
+ current,
1635
+ versions: list.versions.slice(0, 100).map((item) => ({
1636
+ version: item.version,
1637
+ incompatible: Boolean(item.incompatible),
1638
+ deprecated: item.deprecated || null,
1639
+ })),
1640
+ }
1641
+ }
1642
+ }
1643
+ return { ok: false, error: '无法读取版本列表' }
1644
+ }
1645
+
1646
+ async function listGitVersions(name, current, source) {
1647
+ const repo = parseGitHubRepo(source)
1648
+ if (!repo) return { ok: false, error: '无法从安装源识别 GitHub 仓库' }
1649
+ const response = await fetchWithTimeout(`${GITHUB_API}/repos/${repo}/tags?per_page=100`, { headers: githubHeaders() })
1650
+ if (!response.ok) return { ok: false, error: `GitHub tags: HTTP ${response.status}` }
1651
+ const tags = await response.json()
1652
+ const versions = []
1653
+ for (const tag of Array.isArray(tags) ? tags : []) {
1654
+ const tagName = tag && typeof tag.name === 'string' ? tag.name : null
1655
+ if (!tagName) continue
1656
+ const version = tagToVersion(tagName)
1657
+ if (!version) continue
1658
+ versions.push({
1659
+ version,
1660
+ ref: `git+https://github.com/${repo}.git#${tagName}`,
1661
+ tag: tagName,
1662
+ incompatible: false,
1663
+ deprecated: null,
1664
+ })
1665
+ }
1666
+ versions.sort((a, b) => compareVersions(b.version, a.version))
1667
+ return { ok: true, current, kind: 'git', repo, versions: versions.slice(0, 100) }
1668
+ }
1669
+
1670
+ async function installVersion(ctx, state, body) {
1671
+ const name = body && typeof body.name === 'string' ? body.name : ''
1672
+ const version = body && typeof body.version === 'string' ? body.version : ''
1673
+ if (!name || !version) return { ok: false, error: '缺少插件名或版本' }
1674
+ if (state.updating.has(name)) return { ok: false, error: `${name} 正在更新,请稍候` }
1675
+ const pm = ctx.get('pluginManager')
1676
+ if (!pm) return { ok: false, error: 'pluginManager 服务不可用' }
1677
+
1678
+ let bundle = null
1679
+ try {
1680
+ const bundles = await pm.listBundles()
1681
+ bundle = bundles.find((item) => item && item.name === name) || null
1682
+ } catch {
1683
+ bundle = null
1684
+ }
1685
+ if (!bundle) return { ok: false, error: `未安装 ${name}` }
1686
+ if (bundle.version === version) return { ok: false, error: '已经是这个版本' }
1687
+ if (bundle.update === 'git') return installGitVersion(ctx, state, bundle, version, body)
1688
+ if (bundle.update !== 'registry') return { ok: false, error: '本地安装的插件没有可回退的版本' }
1689
+
1690
+ const previous = bundle.version
1691
+ state.updating.add(name)
1692
+ try {
1693
+ // updateBundle refuses anything but a newer version, so a rollback removes the
1694
+ // copy and installs the requested version, restoring the previous one on failure.
1695
+ const removed = await pm.removeBundle(name)
1696
+ if (removed && (removed.application === 'failed' || removed.application === 'cancelled')) {
1697
+ state.cache = null
1698
+ const reason = removed.error && removed.error.diagnostic ? removed.error.diagnostic : '移除失败'
1699
+ return { ok: false, error: reason }
1700
+ }
1701
+ try {
1702
+ const result = await pm.installBundle(`${name}@${version}`, {
1703
+ saveExact: true,
1704
+ expected: { name, version },
1705
+ })
1706
+ state.cache = null
1707
+ const application = result && result.application
1708
+ return { ok: application !== 'failed' && application !== 'cancelled', result }
1709
+ } catch (error) {
1710
+ try {
1711
+ await pm.installBundle(`${name}@${previous}`, {
1712
+ saveExact: true,
1713
+ expected: { name, version: previous },
1714
+ })
1715
+ } catch {
1716
+ /* restore failed; report the original error */
1717
+ }
1718
+ state.cache = null
1719
+ return { ok: false, error: messageOf(error) }
1720
+ }
1721
+ } finally {
1722
+ state.updating.delete(name)
1723
+ }
1724
+ }
1725
+
1726
+ async function installGitVersion(ctx, state, bundle, version, body) {
1727
+ const name = bundle.name
1728
+ const spec = body && typeof body.spec === 'string' ? body.spec : ''
1729
+ if (!spec) return { ok: false, error: '缺少 Git 安装地址' }
1730
+ if (state.updating.has(name)) return { ok: false, error: `${name} 正在更新,请稍候` }
1731
+ const pm = ctx.get('pluginManager')
1732
+ if (!pm) return { ok: false, error: 'pluginManager 服务不可用' }
1733
+
1734
+ const previous = bundle.version
1735
+ const previousSpec = bundle.source || (bundle.installTarget && bundle.installTarget.spec) || null
1736
+ state.updating.add(name)
1737
+ try {
1738
+ const removed = await pm.removeBundle(name)
1739
+ if (removed && (removed.application === 'failed' || removed.application === 'cancelled')) {
1740
+ state.cache = null
1741
+ return { ok: false, error: '移除失败' }
1742
+ }
1743
+ try {
1744
+ const result = await pm.installBundle(spec, { expected: { name, version } })
1745
+ state.cache = null
1746
+ const application = result && result.application
1747
+ return { ok: application !== 'failed' && application !== 'cancelled', result }
1748
+ } catch (error) {
1749
+ if (previousSpec) {
1750
+ try {
1751
+ await pm.installBundle(previousSpec, { expected: { name, version: previous } })
1752
+ } catch {
1753
+ /* restore failed; report the original error */
1754
+ }
1755
+ }
1756
+ state.cache = null
1757
+ return { ok: false, error: messageOf(error) }
1758
+ }
1759
+ } finally {
1760
+ state.updating.delete(name)
1761
+ }
1762
+ }
1763
+
1764
+ async function handleUpdate(ctx, state, request, response) {
1765
+ if (request.method !== 'POST') {
1766
+ response.statusCode = 405
1767
+ response.setHeader('allow', 'POST')
1768
+ response.end()
1769
+ return
1770
+ }
1771
+ try {
1772
+ const body = await readNodeJson(request)
1773
+ const result = await updateOne(ctx, state, body)
1774
+ sendNodeJson(response, result, result.ok ? 200 : 400)
1775
+ } catch (error) {
1776
+ sendNodeJson(response, { ok: false, error: messageOf(error) }, 500)
1777
+ }
1778
+ }
1779
+
1780
+ function readNodeJson(request) {
1781
+ return new Promise((resolve, reject) => {
1782
+ const chunks = []
1783
+ let size = 0
1784
+ request.on('data', (chunk) => {
1785
+ size += chunk.length
1786
+ if (size > 1_000_000) {
1787
+ request.destroy()
1788
+ reject(new Error('request body too large'))
1789
+ return
1790
+ }
1791
+ chunks.push(chunk)
1792
+ })
1793
+ request.on('end', () => {
1794
+ try {
1795
+ resolve(chunks.length > 0 ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {})
1796
+ } catch {
1797
+ resolve({})
1798
+ }
1799
+ })
1800
+ request.on('error', reject)
1801
+ })
1802
+ }
1803
+
1804
+ function sendNodeJson(response, value, status) {
1805
+ const body = JSON.stringify(value)
1806
+ response.statusCode = status
1807
+ response.setHeader('content-type', 'application/json; charset=utf-8')
1808
+ response.setHeader('cache-control', 'no-store')
1809
+ response.end(body)
1810
+ }
1811
+
1812
+ // 这些路由挂在 DSH 自己的 web 服务器上(`responder.handler(req, res)` 只传两个
1813
+ // 参数,拿不到 resource 路由那种 peer/principal),所以浏览器里任何一个页面都能
1814
+ // 往 127.0.0.1:<端口>/dsh-concierge/* 发请求。应用自己的 IPC 通道校验了
1815
+ // dsh-app://app/ 来源,这一层没有,于是补一个调用方校验:
1816
+ // - 同源(Origin 的 host 与请求的 Host 一致,浏览器里直接打开 DSH 网页就是这种)
1817
+ // - 应用内页面(dsh-app://app)
1818
+ // - 没有 Origin 的请求(同源 GET、curl、插件自己的 fetch)
1819
+ // 跨站请求一律 403。`sec-fetch-site: cross-site` 是浏览器自己标的,先看它。
1820
+ function callerAllowed(request) {
1821
+ const headers = request && request.headers ? request.headers : {}
1822
+ if (String(headers['sec-fetch-site'] || '') === 'cross-site') return false
1823
+ const origin = headers.origin
1824
+ if (!origin || origin === 'null') return true
1825
+ if (origin.startsWith('dsh-app://')) return true
1826
+ try {
1827
+ return new URL(origin).host === String(headers.host || '')
1828
+ } catch {
1829
+ return false
1830
+ }
1831
+ }
1832
+
1833
+ // DSH 自己的访问检查:Connection 的 Host/Origin 校验 + 浏览器凭据(登录后种下的
1834
+ // cookie)。插件的路由不经过 /api 那条链,所以要显式调一次;没有 connection 服务
1835
+ // 的宿主(比如极简 profile)直接跳过,不让插件因此不可用。
1836
+ function connectionRejection(ctx, request) {
1837
+ try {
1838
+ const connection = ctx && typeof ctx.get === 'function' ? ctx.get('connection') : null
1839
+ if (!connection || typeof connection.requestRejection !== 'function') return undefined
1840
+ return connection.requestRejection({ headers: (request && request.headers) || {} })
1841
+ } catch {
1842
+ return undefined
1843
+ }
1844
+ }
1845
+
1846
+ function withGuard(ctx, handler) {
1847
+ return (request, response) => {
1848
+ const rejected = connectionRejection(ctx, request)
1849
+ if (rejected) {
1850
+ sendNodeJson(response, { ok: false, error: 'unauthorized' }, rejected)
1851
+ return undefined
1852
+ }
1853
+ if (!callerAllowed(request)) {
1854
+ sendNodeJson(response, { ok: false, error: 'forbidden' }, 403)
1855
+ return undefined
1856
+ }
1857
+ return handler(request, response)
1858
+ }
1859
+ }
1860
+
1861
+ async function handle(ctx, state, request, peer) {
1862
+ try {
1863
+ const rejected = connectionRejection(ctx, request)
1864
+ if (rejected) {
1865
+ return json({ ok: false, error: 'unauthorized' }, rejected)
1866
+ }
1867
+ if (peer && peer.principal && peer.principal.kind !== 'owner') {
1868
+ return json({ ok: false, error: 'forbidden' }, 403)
1869
+ }
1870
+ const url = new URL(request.url)
1871
+ const rest = normalizeRest(url.pathname)
1872
+
1873
+ if (request.method === 'GET' && (rest === '/' || rest === '/health')) {
1874
+ return json({ ok: true, plugin: 'dsh-concierge' })
1875
+ }
1876
+ if (request.method === 'GET' && rest === '/status') {
1877
+ const refresh = url.searchParams.get('refresh') === '1'
1878
+ const data = await getStatus(ctx, state, refresh)
1879
+ return json(data)
1880
+ }
1881
+ if (request.method === 'GET' && rest === '/versions') {
1882
+ const result = await listVersions(ctx, state, url.searchParams.get('name') || '')
1883
+ return json(result, result.ok ? 200 : 400)
1884
+ }
1885
+ return json({ ok: false, error: 'not-found' }, 404)
1886
+ } catch (error) {
1887
+ return json({ ok: false, error: messageOf(error) }, 500)
1888
+ }
1889
+ }
1890
+
1891
+ function normalizeRest(pathname) {
1892
+ let rest = pathname.startsWith(ROUTE) ? pathname.slice(ROUTE.length) : pathname
1893
+ if (!rest.startsWith('/')) rest = `/${rest}`
1894
+ rest = rest.replace(/\/+$/, '')
1895
+ return rest || '/'
1896
+ }
1897
+
1898
+ function json(value, status = 200) {
1899
+ return new Response(JSON.stringify(value), {
1900
+ status,
1901
+ headers: {
1902
+ 'content-type': 'application/json; charset=utf-8',
1903
+ 'cache-control': 'no-store',
1904
+ },
1905
+ })
1906
+ }
1907
+
1908
+ async function getStatus(ctx, state, refresh) {
1909
+ const now = Date.now()
1910
+ if (!refresh && state.cache && now - state.cache.at < CACHE_TTL_MS) {
1911
+ return state.cache.data
1912
+ }
1913
+ if (state.inflight) return state.inflight
1914
+ const run = scan(ctx, state)
1915
+ .then((data) => {
1916
+ state.cache = { at: Date.now(), data }
1917
+ return data
1918
+ })
1919
+ .finally(() => {
1920
+ state.inflight = null
1921
+ })
1922
+ state.inflight = run
1923
+ return run
1924
+ }
1925
+
1926
+ async function scan(ctx, state) {
1927
+ const pm = ctx.get('pluginManager')
1928
+
1929
+ let bundles = []
1930
+ let bundleError = null
1931
+ if (pm) {
1932
+ try {
1933
+ bundles = await pm.listBundles()
1934
+ } catch (error) {
1935
+ bundleError = messageOf(error)
1936
+ }
1937
+ } else {
1938
+ bundleError = 'pluginManager service is unavailable'
1939
+ }
1940
+
1941
+ // The app feed and the plugin lookups do not depend on each other.
1942
+ const [plugins, app, sources] = await Promise.all([
1943
+ checkPlugins(pm, bundles).then((rows) => {
1944
+ if (bundleError) {
1945
+ for (const row of rows) row.error = row.error || bundleError
1946
+ }
1947
+ return rows
1948
+ }),
1949
+ checkApp(),
1950
+ checkSources(bundles).catch(() => []),
1951
+ ])
1952
+
1953
+ state.targets = new Map()
1954
+ for (const row of plugins) {
1955
+ if (row.target) state.targets.set(row.name, row.target)
1956
+ }
1957
+
1958
+ const updatable = plugins.filter((row) => row.updateAvailable).length
1959
+ const pending = await readPending()
1960
+ return {
1961
+ checkedAt: Date.now(),
1962
+ app,
1963
+ plugins,
1964
+ sources,
1965
+ pending: { disabled: pending },
1966
+ auto: state.autoEnabled,
1967
+ lastAuto: state.lastAuto,
1968
+ summary: {
1969
+ total: plugins.length,
1970
+ updatable,
1971
+ appUpdate: Boolean(app.updateAvailable),
1972
+ },
1973
+ }
1974
+ }
1975
+
1976
+ /* ------------------------------------------------------------------ app -- */
1977
+
1978
+ async function checkApp() {
1979
+ const app = {
1980
+ mode: 'web',
1981
+ name: 'DeepSeek Harness',
1982
+ current: null,
1983
+ latest: null,
1984
+ channel: null,
1985
+ feedUrl: null,
1986
+ downloadUrl: null,
1987
+ githubUrl: GITHUB_RELEASES,
1988
+ updateAvailable: false,
1989
+ error: null,
1990
+ }
1991
+
1992
+ const resources = findResourcesDir()
1993
+ if (!resources) {
1994
+ app.error = '未找到桌面版安装目录,跳过应用本体检查'
1995
+ return app
1996
+ }
1997
+ app.mode = 'desktop'
1998
+
1999
+ const pkg = await readJsonFile(path.join(resources, 'app.asar', 'package.json'))
2000
+ if (pkg) {
2001
+ if (typeof pkg.name === 'string' && pkg.name) app.packageName = pkg.name
2002
+ if (typeof pkg.version === 'string' && pkg.version) app.current = pkg.version
2003
+ const origin = pkg.dshMandatoryUpdatePolicy && pkg.dshMandatoryUpdatePolicy.origin
2004
+ if (typeof origin === 'string' && origin) app.downloadUrl = origin
2005
+ }
2006
+
2007
+ const config = await readTextFile(path.join(resources, 'app-update.yml'))
2008
+ if (!config) {
2009
+ app.error = '未找到 app-update.yml'
2010
+ return app
2011
+ }
2012
+ const parsed = parseSimpleYaml(config)
2013
+ const base = parsed.url
2014
+ app.channel = parsed.channel || 'latest'
2015
+ const feed = feedUrl(base, app.channel)
2016
+ app.feedUrl = feed
2017
+ if (!feed) {
2018
+ app.error = 'app-update.yml 缺少可用的更新源地址'
2019
+ return app
2020
+ }
2021
+
2022
+ try {
2023
+ const response = await fetchWithTimeout(feed, {
2024
+ headers: { 'cache-control': 'no-cache' },
2025
+ })
2026
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
2027
+ const text = await response.text()
2028
+ const feedData = parseSimpleYaml(text)
2029
+ app.latest = typeof feedData.version === 'string' ? feedData.version : null
2030
+ app.updateAvailable = Boolean(
2031
+ app.current && app.latest && compareVersions(app.latest, app.current) > 0,
2032
+ )
2033
+ if (!app.latest) app.error = '更新源没有给出 version'
2034
+ } catch (error) {
2035
+ app.error = `读取更新源失败:${messageOf(error)}`
2036
+ }
2037
+ return app
2038
+ }
2039
+
2040
+ function findResourcesDir() {
2041
+ const candidates = []
2042
+ if (process.resourcesPath) candidates.push(process.resourcesPath)
2043
+ const exe = process.env.DSH_NODE_EXECUTABLE || process.execPath
2044
+ if (exe) {
2045
+ const dir = path.dirname(exe)
2046
+ candidates.push(path.join(dir, 'resources'))
2047
+ candidates.push(path.join(dir, '..', 'Resources'))
2048
+ }
2049
+ for (const candidate of candidates) {
2050
+ try {
2051
+ if (candidate && existsSync(candidate)) return candidate
2052
+ } catch {
2053
+ /* keep looking */
2054
+ }
2055
+ }
2056
+ return null
2057
+ }
2058
+
2059
+ function feedUrl(base, channel) {
2060
+ if (!base) return null
2061
+ const name = process.platform === 'darwin'
2062
+ ? `${channel}-mac`
2063
+ : process.platform === 'linux'
2064
+ ? `${channel}-linux`
2065
+ : channel
2066
+ try {
2067
+ return new URL(`${name}.yml`, base.endsWith('/') ? base : `${base}/`).href
2068
+ } catch {
2069
+ return null
2070
+ }
2071
+ }
2072
+
2073
+ /* -------------------------------------------------------------- plugins -- */
2074
+
2075
+ async function checkPlugins(pm, bundles) {
2076
+ const installed = bundles.filter((bundle) => (
2077
+ bundle
2078
+ && bundle.availability === 'profile'
2079
+ && bundle.installed === true
2080
+ && typeof bundle.version === 'string'
2081
+ && bundle.version
2082
+ && bundle.official !== true
2083
+ ))
2084
+
2085
+ const rows = await mapLimit(installed, CONCURRENCY, async (bundle) => {
2086
+ const row = {
2087
+ name: bundle.name,
2088
+ title: bundle.meta && bundle.meta.title ? bundle.meta.title : bundle.name,
2089
+ version: bundle.version,
2090
+ latest: null,
2091
+ kind: bundle.update || 'local',
2092
+ source: bundle.source || (bundle.installTarget && bundle.installTarget.spec) || null,
2093
+ repo: null,
2094
+ enabled: bundle.enabled !== false,
2095
+ updateAvailable: false,
2096
+ releaseUrl: null,
2097
+ homepage: bundle.meta && typeof bundle.meta.homepage === 'string' ? bundle.meta.homepage : null,
2098
+ changelog: null,
2099
+ error: null,
2100
+ notes: [],
2101
+ target: null,
2102
+ }
2103
+
2104
+ try {
2105
+ // A GitHub spec without a pinned commit is classified as "local" by the
2106
+ // manager, but it is still a Git install: check its releases like one.
2107
+ const looksGit = bundle.update === 'git'
2108
+ || /^github:/.test(String(row.source || ''))
2109
+ || /github\.com[:/]/.test(String(row.source || ''))
2110
+ if (bundle.update === 'registry') {
2111
+ await checkRegistry(pm, bundle, row)
2112
+ } else if (looksGit) {
2113
+ row.kind = 'git'
2114
+ await checkGitHub(bundle, row)
2115
+ } else {
2116
+ await checkLocal(bundle, row)
2117
+ }
2118
+ } catch (error) {
2119
+ row.error = messageOf(error)
2120
+ }
2121
+ return row
2122
+ })
2123
+
2124
+ rows.sort((a, b) => {
2125
+ if (a.updateAvailable !== b.updateAvailable) return a.updateAvailable ? -1 : 1
2126
+ return a.name.localeCompare(b.name)
2127
+ })
2128
+ return rows
2129
+ }
2130
+
2131
+ async function checkRegistry(pm, bundle, row) {
2132
+ if (!pm || typeof pm.listVersions !== 'function') {
2133
+ row.error = 'pluginManager.listVersions 不可用'
2134
+ return
2135
+ }
2136
+
2137
+ // Fast path: if the mirror's dist-tag is not newer than what is installed, there is
2138
+ // nothing to resolve, so the slow packument lookup can be skipped entirely.
2139
+ const mirror = await mirrorLatest(bundle.name).catch(() => null)
2140
+ if (mirror && compareVersions(mirror, bundle.version) <= 0) {
2141
+ row.latest = mirror
2142
+ return
2143
+ }
2144
+
2145
+ const list = await withTimeout(pm.listVersions(bundle.name), REGISTRY_TIMEOUT_MS, '版本检查超时')
2146
+ if (list.status === 'listed' && Array.isArray(list.versions) && list.versions.length > 0) {
2147
+ const compatible = list.versions.filter((item) => !item.incompatible)
2148
+ const newest = compatible[0] || list.versions[0]
2149
+ row.latest = newest.version
2150
+ row.updateAvailable = compareVersions(newest.version, bundle.version) > 0
2151
+ if (newest.incompatible) row.notes.push('新版本与当前 DSH 版本不兼容')
2152
+ if (newest.deprecated) row.notes.push(`新版本已标记废弃:${newest.deprecated}`)
2153
+ if (row.updateAvailable) row.target = { version: newest.version }
2154
+ return
2155
+ }
2156
+ if (list.status === 'refused') {
2157
+ row.error = list.reason || list.problem || '无法读取版本列表'
2158
+ }
2159
+ }
2160
+
2161
+ // Local installs (link / file) have no registry and no release feed, so compare
2162
+ // the source directory itself: its package.json version, and for a Git checkout
2163
+ // the last commit seen by this plugin.
2164
+ const LOCAL_STATE_FILE = path.join(homedir(), '.dsh', 'update-center', 'local-state.json')
2165
+
2166
+ function sourceToDir(source) {
2167
+ const text = String(source || '').trim()
2168
+ let rest = null
2169
+ if (text.startsWith('link:')) rest = text.slice(5)
2170
+ else if (text.startsWith('file:')) rest = text.slice(5)
2171
+ else if (path.isAbsolute(text)) rest = text
2172
+ if (!rest) return null
2173
+ rest = rest.split('#')[0].split('?')[0]
2174
+ return path.isAbsolute(rest) ? rest : null
2175
+ }
2176
+
2177
+ async function readLocalState() {
2178
+ try {
2179
+ const text = await readFile(LOCAL_STATE_FILE, 'utf8')
2180
+ const parsed = JSON.parse(text)
2181
+ return parsed && typeof parsed === 'object' ? parsed : {}
2182
+ } catch {
2183
+ return {}
2184
+ }
2185
+ }
2186
+
2187
+ async function writeLocalState(name, commit) {
2188
+ try {
2189
+ await mkdir(path.dirname(LOCAL_STATE_FILE), { recursive: true })
2190
+ const state = await readLocalState()
2191
+ state[name] = commit
2192
+ await writeFile(LOCAL_STATE_FILE, JSON.stringify(state, null, 2), 'utf8')
2193
+ } catch {
2194
+ /* best effort */
2195
+ }
2196
+ }
2197
+
2198
+ function tgzVersion(file) {
2199
+ return new Promise((resolve) => {
2200
+ try {
2201
+ const child = spawn('tar', ['-xOf', file, 'package/package.json'], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
2202
+ let out = ''
2203
+ child.stdout.on('data', (chunk) => {
2204
+ out += chunk.toString('utf8')
2205
+ })
2206
+ child.on('error', () => resolve(null))
2207
+ child.on('close', (code) => {
2208
+ if (code !== 0 || !out) {
2209
+ resolve(null)
2210
+ return
2211
+ }
2212
+ try {
2213
+ const pkg = JSON.parse(out)
2214
+ resolve(pkg && typeof pkg.version === 'string' ? pkg.version : null)
2215
+ } catch {
2216
+ resolve(null)
2217
+ }
2218
+ })
2219
+ } catch {
2220
+ resolve(null)
2221
+ }
2222
+ })
2223
+ }
2224
+
2225
+ function gitOutput(dir, args) {
2226
+ return new Promise((resolve) => {
2227
+ try {
2228
+ const child = spawn('git', ['-C', dir, ...args], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
2229
+ let out = ''
2230
+ child.stdout.on('data', (chunk) => {
2231
+ out += chunk.toString('utf8')
2232
+ })
2233
+ child.on('error', () => resolve(null))
2234
+ child.on('close', (code) => resolve(code === 0 ? out.trim() : null))
2235
+ } catch {
2236
+ resolve(null)
2237
+ }
2238
+ })
2239
+ }
2240
+
2241
+ async function checkLocal(bundle, row) {
2242
+ const dir = sourceToDir(row.source)
2243
+ if (!dir) {
2244
+ row.notes.push('本地安装,源路径不可识别')
2245
+ return
2246
+ }
2247
+ if (!existsSync(dir)) {
2248
+ row.notes.push('源路径不存在')
2249
+ return
2250
+ }
2251
+ let isDir = false
2252
+ try {
2253
+ const stat = await statOf(dir)
2254
+ isDir = Boolean(stat && stat.isDirectory())
2255
+ } catch {
2256
+ isDir = false
2257
+ }
2258
+ if (!isDir) {
2259
+ // Tarball install: read its package.json when tar can, and remember the
2260
+ // file's size+mtime so a replaced tarball still shows up as an update.
2261
+ const sourceVersion = await tgzVersion(dir)
2262
+ if (sourceVersion && bundle.version && compareVersions(sourceVersion, bundle.version) > 0) {
2263
+ row.latest = sourceVersion
2264
+ row.updateAvailable = true
2265
+ row.target = { spec: row.source, version: sourceVersion }
2266
+ row.notes.push('源压缩包版本更新')
2267
+ return
2268
+ }
2269
+ let fingerprint = null
2270
+ try {
2271
+ const stat = await statOf(dir)
2272
+ fingerprint = `${stat.size}:${Math.round(stat.mtimeMs)}`
2273
+ } catch {
2274
+ fingerprint = null
2275
+ }
2276
+ if (!fingerprint) {
2277
+ row.notes.push('压缩包安装,无法读取源文件')
2278
+ return
2279
+ }
2280
+ const state = await readLocalState()
2281
+ const key = `${bundle.name}:file`
2282
+ const seen = state[key]
2283
+ if (!seen) {
2284
+ await writeLocalState(key, fingerprint)
2285
+ row.notes.push('压缩包安装,已记录源文件')
2286
+ } else if (seen !== fingerprint) {
2287
+ row.updateAvailable = true
2288
+ row.latest = sourceVersion || bundle.version
2289
+ row.target = { spec: row.source, version: sourceVersion || bundle.version }
2290
+ row.notes.push('源压缩包已更新')
2291
+ } else {
2292
+ row.notes.push('压缩包安装,源文件没有变化')
2293
+ }
2294
+ return
2295
+ }
2296
+
2297
+ const pkg = await readJsonFile(path.join(dir, 'package.json'))
2298
+ const sourceVersion = pkg && typeof pkg.version === 'string' ? pkg.version : null
2299
+ const isLink = String(row.source || '').startsWith('link:')
2300
+
2301
+ if (sourceVersion && bundle.version && compareVersions(sourceVersion, bundle.version) > 0) {
2302
+ row.latest = sourceVersion
2303
+ row.updateAvailable = true
2304
+ row.target = { spec: row.source, version: sourceVersion }
2305
+ row.notes.push('源目录版本更新')
2306
+ return
2307
+ }
2308
+
2309
+ if (existsSync(path.join(dir, '.git'))) {
2310
+ const head = await gitOutput(dir, ['rev-parse', 'HEAD'])
2311
+ if (head) {
2312
+ row.localCommit = head
2313
+ const state = await readLocalState()
2314
+ const seen = state[bundle.name]
2315
+ if (!seen) {
2316
+ await writeLocalState(bundle.name, head)
2317
+ row.notes.push('本地 Git 安装,已记录当前提交')
2318
+ } else if (seen !== head && !isLink) {
2319
+ row.updateAvailable = true
2320
+ row.latest = sourceVersion || bundle.version
2321
+ row.target = { spec: row.source, version: sourceVersion || bundle.version }
2322
+ row.notes.push('源仓库有新提交')
2323
+ } else if (seen !== head && isLink) {
2324
+ await writeLocalState(bundle.name, head)
2325
+ row.notes.push('本地 Git 安装(link),代码实时生效')
2326
+ } else {
2327
+ row.notes.push('本地 Git 安装,源没有变化')
2328
+ }
2329
+ return
2330
+ }
2331
+ }
2332
+ row.notes.push(isLink ? '本地 link 安装,代码实时生效' : '本地安装,源版本一致')
2333
+ }
2334
+
2335
+ async function checkGitHub(bundle, row) {
2336
+ const source = bundle.source || (bundle.installTarget && bundle.installTarget.spec) || ''
2337
+ const repo = parseGitHubRepo(source)
2338
+ if (!repo) {
2339
+ row.notes.push('无法从安装源识别 GitHub 仓库')
2340
+ return
2341
+ }
2342
+ row.repo = repo
2343
+ let latest = null
2344
+ try {
2345
+ latest = await githubLatest(repo)
2346
+ } catch (error) {
2347
+ const message = messageOf(error)
2348
+ if (/HTTP 40[13]|rate limit/i.test(message)) {
2349
+ row.error = 'GitHub 速率限制,配置 GITHUB_TOKEN 可提高上限'
2350
+ return
2351
+ }
2352
+ throw error
2353
+ }
2354
+ if (!latest) {
2355
+ row.notes.push('GitHub 上没有可用的发布版本')
2356
+ return
2357
+ }
2358
+ row.latest = latest.version
2359
+ row.releaseUrl = latest.url
2360
+ row.changelog = latest.body ? String(latest.body).slice(0, 1200) : null
2361
+ row.updateAvailable = compareVersions(latest.version, bundle.version) > 0
2362
+ if (row.updateAvailable) {
2363
+ // The spec must pin a commit of the installed copy's repository directory,
2364
+ // so keep the form the plugin was installed with (github: vs git+https).
2365
+ const githubShorthand = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/.exec(String(source || ''))
2366
+ row.target = {
2367
+ version: latest.version,
2368
+ spec: githubShorthand
2369
+ ? `github:${githubShorthand[1]}/${githubShorthand[2]}#${latest.sha}`
2370
+ : `git+https://github.com/${repo}.git#${latest.sha}`,
2371
+ }
2372
+ }
2373
+ }
2374
+
2375
+ function parseGitHubRepo(source) {
2376
+ const text = String(source || '')
2377
+ let match = /github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/.exec(text)
2378
+ if (match) return `${match[1]}/${match[2]}`
2379
+ match = /github\.com[:/]([^/\s]+)\/([^/\s#?]+)/.exec(text)
2380
+ if (match) return `${match[1]}/${match[2].replace(/\.git$/, '')}`
2381
+ return null
2382
+ }
2383
+
2384
+ async function githubLatest(repo) {
2385
+ const headers = githubHeaders()
2386
+ let tag = null
2387
+ let url = null
2388
+ let body = null
2389
+
2390
+ let response = await fetchWithTimeout(`${GITHUB_API}/repos/${repo}/releases/latest`, { headers })
2391
+ if (response.status === 404) {
2392
+ response = await fetchWithTimeout(`${GITHUB_API}/repos/${repo}/tags?per_page=20`, { headers })
2393
+ if (!response.ok) throw new Error(`GitHub tags: HTTP ${response.status}`)
2394
+ const tags = await response.json()
2395
+ const best = pickBestTag(Array.isArray(tags) ? tags : [])
2396
+ if (!best) return null
2397
+ tag = best
2398
+ } else if (response.ok) {
2399
+ const release = await response.json()
2400
+ if (!release || release.draft || !release.tag_name) return null
2401
+ tag = release.tag_name
2402
+ url = typeof release.html_url === 'string' ? release.html_url : null
2403
+ body = typeof release.body === 'string' ? release.body : null
2404
+ } else {
2405
+ throw new Error(`GitHub releases: HTTP ${response.status}`)
2406
+ }
2407
+
2408
+ const version = tagToVersion(tag)
2409
+ if (!version) return null
2410
+
2411
+ const commitResponse = await fetchWithTimeout(
2412
+ `${GITHUB_API}/repos/${repo}/commits/${encodeURIComponent(tag)}`,
2413
+ { headers },
2414
+ )
2415
+ if (!commitResponse.ok) throw new Error(`GitHub commit: HTTP ${commitResponse.status}`)
2416
+ const commit = await commitResponse.json()
2417
+ const sha = commit && typeof commit.sha === 'string' ? commit.sha : null
2418
+ if (!sha) return null
2419
+
2420
+ return {
2421
+ version,
2422
+ tag,
2423
+ sha,
2424
+ url: url || `https://github.com/${repo}/releases/tag/${encodeURIComponent(tag)}`,
2425
+ body,
2426
+ }
2427
+ }
2428
+
2429
+ function pickBestTag(tags) {
2430
+ let best = null
2431
+ for (const tag of tags) {
2432
+ const name = tag && typeof tag.name === 'string' ? tag.name : null
2433
+ if (!name) continue
2434
+ const version = tagToVersion(name)
2435
+ if (!version) continue
2436
+ if (!best || compareVersions(version, best.version) > 0) best = { name, version }
2437
+ }
2438
+ return best ? best.name : null
2439
+ }
2440
+
2441
+ function tagToVersion(tag) {
2442
+ const text = String(tag || '').trim().replace(/^v/i, '')
2443
+ return parseVersion(text) ? text : null
2444
+ }
2445
+
2446
+ function githubHeaders() {
2447
+ const headers = {
2448
+ accept: 'application/vnd.github+json',
2449
+ 'user-agent': 'dsh-concierge',
2450
+ 'x-github-api-version': '2022-11-28',
2451
+ }
2452
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || storedToken || ''
2453
+ if (token) headers.authorization = `Bearer ${token}`
2454
+ return headers
2455
+ }
2456
+
2457
+ /* --------------------------------------------------------------- update -- */
2458
+
2459
+ async function updateOne(ctx, state, body) {
2460
+ const name = body && typeof body.name === 'string' ? body.name : ''
2461
+ if (!name) return { ok: false, error: '缺少插件名' }
2462
+ if (state.updating.has(name)) {
2463
+ return { ok: false, error: `${name} 正在更新,请稍候` }
2464
+ }
2465
+ state.updating.add(name)
2466
+ try {
2467
+ return await runUpdate(ctx, state, name)
2468
+ } finally {
2469
+ state.updating.delete(name)
2470
+ }
2471
+ }
2472
+
2473
+ async function runUpdate(ctx, state, name) {
2474
+ const pm = ctx.get('pluginManager')
2475
+ if (!pm) return { ok: false, error: 'pluginManager 服务不可用' }
2476
+
2477
+ let target = state.targets.get(name)
2478
+ if (!target) {
2479
+ await getStatus(ctx, state, true)
2480
+ target = state.targets.get(name)
2481
+ }
2482
+ if (!target) return { ok: false, error: `${name} 没有可用的更新` }
2483
+
2484
+ const bundles = await pm.listBundles()
2485
+ const bundle = bundles.find((item) => item && item.name === name)
2486
+ if (!bundle) return { ok: false, error: `未安装 ${name}` }
2487
+
2488
+ try {
2489
+ let result
2490
+ if (bundle.update === 'registry') {
2491
+ result = await pm.updateBundle(name, target.version)
2492
+ } else if (bundle.update === 'git' && target.spec) {
2493
+ try {
2494
+ result = await pm.updateBundle(name, target.version, { spec: target.spec })
2495
+ } catch (error) {
2496
+ // A Git install may refuse a foreign spec form; reinstall from the pinned spec.
2497
+ const fallback = await reinstallFromSpec(ctx, state, bundle, target.spec, target.version)
2498
+ if (fallback.ok) return fallback
2499
+ throw error
2500
+ }
2501
+ } else if (!bundle.update && target.spec) {
2502
+ return reinstallFromSpec(ctx, state, bundle, target.spec, target.version)
2503
+ } else {
2504
+ return { ok: false, error: '该插件不是可更新的安装类型' }
2505
+ }
2506
+ state.cache = null
2507
+ const application = result && result.result ? result.result.application : undefined
2508
+ if (application === 'restart-required') await recordPending(name)
2509
+ return {
2510
+ ok: application !== 'failed' && application !== 'cancelled',
2511
+ result,
2512
+ }
2513
+ } catch (error) {
2514
+ state.cache = null
2515
+ return { ok: false, error: messageOf(error) }
2516
+ }
2517
+ }
2518
+
2519
+ async function reinstallFromSpec(ctx, state, bundle, spec, version) {
2520
+ const pm = ctx.get('pluginManager')
2521
+ if (!pm) return { ok: false, error: 'pluginManager 服务不可用' }
2522
+ try {
2523
+ const removed = await pm.removeBundle(bundle.name)
2524
+ if (removed && (removed.application === 'failed' || removed.application === 'cancelled')) {
2525
+ state.cache = null
2526
+ return { ok: false, error: '移除失败' }
2527
+ }
2528
+ try {
2529
+ const result = await pm.installBundle(spec, { expected: { name: bundle.name, version } })
2530
+ state.cache = null
2531
+ const application = result && result.application
2532
+ return { ok: application !== 'failed' && application !== 'cancelled', result }
2533
+ } catch (error) {
2534
+ // Put the previous copy back so a failed reinstall never leaves a hole.
2535
+ const previousSpec = bundle.source || (bundle.installTarget && bundle.installTarget.spec) || null
2536
+ if (previousSpec) {
2537
+ try {
2538
+ await pm.installBundle(previousSpec, { expected: { name: bundle.name, version: bundle.version } })
2539
+ } catch {
2540
+ /* restore failed; report the original error */
2541
+ }
2542
+ }
2543
+ state.cache = null
2544
+ return { ok: false, error: messageOf(error) }
2545
+ }
2546
+ } catch (error) {
2547
+ state.cache = null
2548
+ return { ok: false, error: messageOf(error) }
2549
+ }
2550
+ }
2551
+
2552
+ /* -------------------------------------------------------------- helpers -- */
2553
+
2554
+ function withTimeout(promise, ms, message) {
2555
+ return new Promise((resolve, reject) => {
2556
+ const timer = setTimeout(() => reject(new Error(message || 'timeout')), ms)
2557
+ promise.then(
2558
+ (value) => {
2559
+ clearTimeout(timer)
2560
+ resolve(value)
2561
+ },
2562
+ (error) => {
2563
+ clearTimeout(timer)
2564
+ reject(error)
2565
+ },
2566
+ )
2567
+ })
2568
+ }
2569
+
2570
+ async function mapLimit(items, limit, worker) {
2571
+ const results = new Array(items.length)
2572
+ let cursor = 0
2573
+ const size = Math.max(1, Math.min(limit, items.length))
2574
+ const runners = Array.from({ length: size }, async () => {
2575
+ while (true) {
2576
+ const index = cursor
2577
+ cursor += 1
2578
+ if (index >= items.length) return
2579
+ results[index] = await worker(items[index], index)
2580
+ }
2581
+ })
2582
+ await Promise.all(runners)
2583
+ return results
2584
+ }
2585
+
2586
+ function parseSimpleYaml(text) {
2587
+ const out = {}
2588
+ for (const line of String(text || '').split(/\r?\n/)) {
2589
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
2590
+ if (!match) continue
2591
+ let value = match[2].trim()
2592
+ if (!value) continue
2593
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
2594
+ value = value.slice(1, -1)
2595
+ }
2596
+ out[match[1]] = value
2597
+ }
2598
+ return out
2599
+ }
2600
+
2601
+ async function readTextFile(file) {
2602
+ try {
2603
+ return await readFile(file, 'utf8')
2604
+ } catch {
2605
+ return null
2606
+ }
2607
+ }
2608
+
2609
+ async function readJsonFile(file) {
2610
+ const text = await readTextFile(file)
2611
+ if (!text) return null
2612
+ try {
2613
+ return JSON.parse(text)
2614
+ } catch {
2615
+ return null
2616
+ }
2617
+ }
2618
+
2619
+ function fetchWithTimeout(url, init = {}, timeoutMs = FETCH_TIMEOUT_MS) {
2620
+ const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
2621
+ ? AbortSignal.timeout(timeoutMs)
2622
+ : undefined
2623
+ return fetch(url, { ...init, signal, redirect: 'follow' })
2624
+ }
2625
+
2626
+ // A dist-tag request is a few hundred bytes; the npm packument is ~150 KB and takes
2627
+ // seconds. The mirror answers in tens of milliseconds from mainland networks.
2628
+ async function mirrorLatest(name) {
2629
+ const path = String(name || '').replace('/', '%2F')
2630
+ const response = await fetchWithTimeout(`${MIRROR_BASE}/${path}/latest`, { headers: { accept: 'application/json' } }, 6000)
2631
+ if (!response.ok) return null
2632
+ const body = await response.json().catch(() => null)
2633
+ return body && typeof body.version === 'string' ? body.version : null
2634
+ }
2635
+
2636
+ // "@scope/name@1.2.3" / "name@1.2.3" / "name" → { name, version }
2637
+ function splitNpmSpec(spec) {
2638
+ const value = String(spec || '').trim()
2639
+ if (!value) return { name: '', version: '' }
2640
+ if (value.startsWith('@')) {
2641
+ const slash = value.indexOf('/')
2642
+ if (slash < 0) return { name: value, version: '' }
2643
+ const rest = value.slice(slash + 1)
2644
+ const at = rest.indexOf('@')
2645
+ return at < 0
2646
+ ? { name: value, version: '' }
2647
+ : { name: value.slice(0, slash + 1 + at), version: rest.slice(at + 1) }
2648
+ }
2649
+ const at = value.indexOf('@')
2650
+ return at < 0 ? { name: value, version: '' } : { name: value.slice(0, at), version: value.slice(at + 1) }
2651
+ }
2652
+
2653
+ function messageOf(error) {
2654
+ if (!error) return '未知错误'
2655
+ if (typeof error === 'string') return error
2656
+ if (error.name === 'TimeoutError' || error.name === 'AbortError') return '请求超时'
2657
+ return error.message ? String(error.message) : String(error)
2658
+ }
2659
+
2660
+ function parseVersion(value) {
2661
+ const match = /^\s*v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(String(value || ''))
2662
+ if (!match) return null
2663
+ return {
2664
+ major: Number(match[1]),
2665
+ minor: Number(match[2]),
2666
+ patch: Number(match[3]),
2667
+ pre: match[4] ? match[4].split('.') : [],
2668
+ }
2669
+ }
2670
+
2671
+ function compareVersions(left, right) {
2672
+ const a = parseVersion(left)
2673
+ const b = parseVersion(right)
2674
+ if (!a || !b) return String(left).localeCompare(String(right))
2675
+ for (const key of ['major', 'minor', 'patch']) {
2676
+ if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1
2677
+ }
2678
+ if (a.pre.length === 0 && b.pre.length === 0) return 0
2679
+ if (a.pre.length === 0) return 1
2680
+ if (b.pre.length === 0) return -1
2681
+ const length = Math.max(a.pre.length, b.pre.length)
2682
+ for (let i = 0; i < length; i += 1) {
2683
+ const x = a.pre[i]
2684
+ const y = b.pre[i]
2685
+ if (x === undefined) return -1
2686
+ if (y === undefined) return 1
2687
+ const xNumeric = /^\d+$/.test(x)
2688
+ const yNumeric = /^\d+$/.test(y)
2689
+ if (xNumeric && yNumeric) {
2690
+ if (Number(x) !== Number(y)) return Number(x) < Number(y) ? -1 : 1
2691
+ } else if (xNumeric) {
2692
+ return -1
2693
+ } else if (yNumeric) {
2694
+ return 1
2695
+ } else if (x !== y) {
2696
+ return x < y ? -1 : 1
2697
+ }
2698
+ }
2699
+ return 0
2700
+ }