@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1784 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +71 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1548 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1494 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +739 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +409 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/task-board.mjs +57 -0
  210. package/teams.mjs +58 -0
@@ -0,0 +1,777 @@
1
+ /* Profile-scoped plugin management. No shell input, dependencies or client-selected paths. */
2
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, readdirSync, copyFileSync, cpSync, unlinkSync, realpathSync, openSync, closeSync } from 'node:fs'
3
+ import { dirname, basename, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { createHash } from 'node:crypto'
6
+ import { spawn, execFile } from 'node:child_process'
7
+ import { prepareReleasePlan, profileRevision, backupTransaction, writeWorkspace, mergeReleaseRules, releasePolicy, verifyInstalled, treeDigest, restoreTransaction, canonicalPath, replaceFile } from './plugin-transaction.mjs'
8
+ import { createMarketAdapter, createReadmeReader } from './market.mjs'
9
+
10
+ const REGISTRY = 'https://registry.npmjs.org'
11
+ const SELF = fileURLToPath(import.meta.url)
12
+ const packagePattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?![\s\S])/
13
+ const versionPattern = /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?(?![\s\S])/
14
+ const idPattern = /^[a-zA-Z0-9-]{16,80}(?![\s\S])/
15
+ const read = path => JSON.parse(readFileSync(path, 'utf8'))
16
+ function atomic(path, value) {
17
+ const tmp = path + '.' + process.pid + '.tmp'
18
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
19
+ replaceFile(tmp, path)
20
+ }
21
+ const fail = (message, status = 400) => Object.assign(new Error(message), { status })
22
+ const protectedPackage = name => name === '@hyprnos/dsh-remote-plugin' || name.startsWith('@deepseek-ai/')
23
+ const revision = path => createHash('sha256').update(readFileSync(path)).digest('hex')
24
+ const registryDependency = value => typeof value === 'string' && !/[:/\\]/.test(value) && !value.startsWith('.')
25
+ function newerVersion(next, previous) {
26
+ const parse = value => /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\w-]+(?:\.[\w-]+)*))?(?:\+[\w.-]+)?$/.exec(value || '')
27
+ const a = parse(next), b = parse(previous)
28
+ if (!a || !b || [a, b].some(parts => parts[4]?.split('.').some(v => /^0\d+$/.test(v)))) return false
29
+ const numeric = (x, y) => x.length !== y.length ? Math.sign(x.length - y.length) : x === y ? 0 : x < y ? -1 : 1
30
+ for (let i = 1; i <= 3; i++) { const order = numeric(a[i], b[i]); if (order) return order > 0 }
31
+ if (!a[4] || !b[4]) return !a[4] && !!b[4]
32
+ const x = a[4].split('.'), y = b[4].split('.')
33
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
34
+ if (x[i] === y[i]) continue
35
+ if (x[i] === undefined || y[i] === undefined) return y[i] === undefined
36
+ const nx = /^\d+$/.test(x[i]), ny = /^\d+$/.test(y[i])
37
+ return (nx && ny ? numeric(x[i], y[i]) : nx !== ny ? nx ? -1 : 1 : x[i] < y[i] ? -1 : 1) > 0
38
+ }
39
+ return false
40
+ }
41
+ function batchTargets(body, state) {
42
+ if (body.name !== 'all-plugins' || !Array.isArray(body.targets) || !body.targets.length || body.targets.length > 100) throw fail('无效的批量更新列表')
43
+ const names = new Set()
44
+ const targets = body.targets.map(target => {
45
+ if (!target || !packagePattern.test(target.name || '') || !versionPattern.test(target.version || '') || names.has(target.name)) throw fail('无效或重复的批量更新目标')
46
+ names.add(target.name)
47
+ const item = state.items.find(item => item.name === target.name)
48
+ if (!item || !(item.managed && item.bundle || item.selfUpdate) || !registryDependency(item.requested)) throw fail('批量更新只接受当前 profile 的 registry 插件:' + target.name, 409)
49
+ if (!newerVersion(target.version, item.version)) throw fail('批量更新不能重装、降级或替换未知版本:' + target.name, 409)
50
+ return { name: target.name, version: target.version, fromVersion: item.version, enabled: item.enabled }
51
+ })
52
+ return targets.sort((a, b) => (a.name === '@hyprnos/dsh-remote-plugin') - (b.name === '@hyprnos/dsh-remote-plugin') || a.name.localeCompare(b.name))
53
+ }
54
+ const targetIdentity = targets => JSON.stringify((Array.isArray(targets) ? targets : []).map(target => ({ name: target?.name, version: target?.version })).sort((a, b) => String(a.name).localeCompare(String(b.name))))
55
+ function adapterInterfaces(ctx) {
56
+ // Shape checks only: never query balances, read content or activate sessions.
57
+ const result = {}
58
+ for (const [id, name, method] of [['cost', 'costMeter', 'getState'], ['tasks', 'taskBoard', 'snapshot']]) {
59
+ try { const service = ctx.get?.(name); result[id] = { supported: service ? typeof service[method] === 'function' : null } }
60
+ catch { result[id] = { supported: null } }
61
+ }
62
+ return result
63
+ }
64
+ // A detached worker can replace/delete its ledger between two manager reads.
65
+ // Windows sharing violations are uncertain ownership, never proof of death.
66
+ function ownershipText(path) {
67
+ try { return readFileSync(path, 'utf8') } catch (error) {
68
+ if (error.code === 'ENOENT') return null
69
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) return undefined
70
+ throw error
71
+ }
72
+ }
73
+ const ownershipPending = '任务锁正在更新或暂时无法读取,已保留锁;请稍后刷新。'
74
+
75
+ let windowsProbe
76
+ function windowsProcessIds() {
77
+ // Windows can return EPERM for an exited PID. Enumerate OS processes instead;
78
+ // failure or malformed output must never be interpreted as an empty list.
79
+ if (!windowsProbe) windowsProbe = new Promise((resolveIds, reject) => {
80
+ execFile(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
81
+ ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; ConvertTo-Json -Compress -InputObject @(Get-Process -ErrorAction Stop | Select-Object -ExpandProperty Id)'],
82
+ { windowsHide: true, timeout: 5000, maxBuffer: 1024 * 1024 }, (error, stdout) => {
83
+ if (error) return reject(error)
84
+ try {
85
+ const ids = JSON.parse(stdout.replace(/^\uFEFF/, ''))
86
+ if (!Array.isArray(ids) || !ids.length || !ids.every(Number.isInteger)) throw new Error('Invalid process list')
87
+ resolveIds(new Set(ids))
88
+ } catch (error) { reject(error) }
89
+ })
90
+ }).finally(() => { windowsProbe = null })
91
+ return windowsProbe
92
+ }
93
+
94
+ export async function probeProcesses(pids, runtime = process, enumerate = windowsProcessIds) {
95
+ const states = new Map(), uncertain = []
96
+ for (const pid of new Set(pids.filter(pid => Number.isInteger(pid) && pid > 0))) {
97
+ try { runtime.kill(pid, 0); states.set(pid, 'alive') }
98
+ catch (error) {
99
+ states.set(pid, error.code === 'ESRCH' ? 'dead' : 'unknown')
100
+ if (error.code === 'EPERM' && runtime.platform === 'win32') uncertain.push(pid)
101
+ }
102
+ }
103
+ if (uncertain.length) {
104
+ try {
105
+ const ids = await enumerate()
106
+ for (const pid of uncertain) states.set(pid, ids.has(pid) ? 'alive' : 'dead')
107
+ } catch { /* Keep unknown on timeout, denied access or unavailable OS query. */ }
108
+ }
109
+ return states
110
+ }
111
+
112
+ // Never clear a live worker or its package-manager child. PID reuse fails closed.
113
+ async function recoverDeadLock(storage, probe = probeProcesses) {
114
+ const path = join(storage, 'lock.json')
115
+ const original = ownershipText(path)
116
+ if (original === null) return
117
+ if (original === undefined) return ownershipPending
118
+ const owner = JSON.parse(original)
119
+ if (!idPattern.test(owner.id || '')) throw fail('插件任务锁损坏,请在主机检查', 409)
120
+ const launchPath = join(storage, 'launch-' + owner.id + '.json')
121
+ const launchRecord = ownershipText(launchPath)
122
+ if (launchRecord === undefined) return ownershipPending
123
+ const workerPid = owner.workerPid || (launchRecord ? JSON.parse(launchRecord).pid : null)
124
+ const pids = workerPid ? [workerPid, owner.cliPid] : [owner.launcherPid, owner.cliPid]
125
+ if (pids.some(pid => pid != null && (!Number.isSafeInteger(pid) || pid <= 0))) return '任务锁进程信息损坏,已保留锁;请在主机检查。'
126
+ const states = await probe(pids)
127
+ const currentOwner = ownershipText(path), currentLaunch = ownershipText(launchPath)
128
+ if (currentOwner === undefined || currentLaunch === undefined) return ownershipPending
129
+ if (currentOwner !== original || currentLaunch !== launchRecord) return
130
+ if ([...states.values()].some(state => state !== 'dead')) {
131
+ return [...states.values()].includes('unknown')
132
+ ? '无法确认任务进程是否已退出,已保留锁;请在主机检查进程权限与操作记录。'
133
+ : '主机任务进程仍在运行,其他修改暂不可用;可展开操作记录查看日志。'
134
+ }
135
+ if (!workerPid && (!owner.launcherPid || !Number.isFinite(owner.createdAt) || Date.now() - owner.createdAt < 30000)) return
136
+ const jobPath = join(storage, 'job-' + owner.id + '.json')
137
+ if (existsSync(jobPath)) {
138
+ const job = read(jobPath)
139
+ if (['queued', 'running'].includes(job.phase)) {
140
+ job.phase = 'interrupted'; job.endedAt = Date.now(); job.restartRequired = true
141
+ job.message = '任务进程已退出,已解除锁定。文件可能已改变,请核对插件状态;未执行自动回滚。'
142
+ if (job.transactionStarted && existsSync(join(storage, 'backup-' + owner.id, 'transaction.json'))) {
143
+ try { job.recoveryState = { revision: profileRevision(dirname(storage)), installed: treeDigest(join(dirname(storage), 'node_modules')) } }
144
+ catch { /* Incomplete evidence requires host recovery, never a blind restore. */ }
145
+ }
146
+ atomic(jobPath, job)
147
+ }
148
+ }
149
+ // All reads/writes here are synchronous; recheck ownership before unlinking.
150
+ if (ownershipText(path) === original) {
151
+ copyFileSync(path, join(storage, 'recovered-lock-' + owner.id + '.json'))
152
+ unlinkSync(path)
153
+ }
154
+ }
155
+
156
+ async function profileLock(dir, probe = probeProcesses) {
157
+ const path = join(dir, 'package.json.lock')
158
+ if (!existsSync(path)) return null
159
+ const raw = readFileSync(path, 'utf8'), text = raw.trim()
160
+ const pid = /^\d+$/.test(text) ? Number(text) : null
161
+ if (!Number.isSafeInteger(pid) || pid <= 0) return { path, raw, state: 'unknown', message: 'DSH 配置锁格式无法识别,请在主机检查 package.json.lock。' }
162
+ const state = (await probe([pid])).get(pid) || 'unknown'
163
+ if (!existsSync(path)) return null
164
+ if (readFileSync(path, 'utf8') !== raw) return { state: 'unknown', message: 'DSH 配置锁已变化,请刷新后重试。' }
165
+ return { path, raw, pid, state, message: state === 'dead'
166
+ ? '检测到已退出进程遗留的 DSH 配置锁;下一次操作会备份并回收。'
167
+ : state === 'alive' ? 'DSH 配置被进程 ' + pid + ' 占用,请等待主机操作结束后重试。'
168
+ : '无法确认 DSH 配置锁进程 ' + pid + ' 是否已退出,请在主机检查;锁已保留。' }
169
+ }
170
+
171
+ export function detectProfile(ctx, cli = process.argv[1], runtime = process) {
172
+ try {
173
+ const dir = realpathSync(fileURLToPath(ctx.root?.baseUrl || ctx.baseUrl))
174
+ const manifest = read(join(dir, 'package.json'))
175
+ if (basename(dirname(dir)) !== 'profiles' || !Array.isArray(manifest.dsh?.profile?.bundles)) return null
176
+ const name = basename(dir)
177
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*(?![\s\S])/.test(name)) return null
178
+ const base = { dir, name, home: dirname(dirname(dir)), cli: null }
179
+ // Desktop reserves this profile for its installation-owned carrier CLI.
180
+ // Bind to the host that booted this root, never a global CLI or PATH entry.
181
+ if (name === 'desktop') {
182
+ try {
183
+ const entry = realpathSync(cli), hostRoot = dirname(dirname(entry))
184
+ const host = read(join(hostRoot, 'package.json'))
185
+ const runtimeDir = realpathSync(resolve(hostRoot, '../../..'))
186
+ const bundled = read(join(runtimeDir, 'package.json'))
187
+ const carrier = join(hostRoot, 'lib', 'cli.js')
188
+ if (runtime.versions?.electron && host.name === '@deepseek-ai/dsh-desktop-host'
189
+ && entry === realpathSync(join(hostRoot, 'lib', 'index.js'))
190
+ && bundled.name === '@deepseek-ai/dsh-desktop-runtime' && bundled.version === host.version
191
+ && runtimeDir === realpathSync(runtime.argv[2]) && dir === realpathSync(runtime.argv[3])
192
+ && existsSync(carrier)) return { ...base, cli: carrier, cliMode: 'desktop' }
193
+ } catch {}
194
+ return base
195
+ }
196
+ let root
197
+ try { root = dirname(realpathSync(cli)) } catch { return base }
198
+ let found = null
199
+ for (let i = 0; i < 5; i++, root = dirname(root)) {
200
+ try { if (read(join(root, 'package.json')).name === '@deepseek-ai/dsh') { found = join(root, 'lib', 'bin.js'); break } } catch {}
201
+ }
202
+ return { ...base, cli: found && existsSync(found) ? found : null }
203
+ } catch { return null }
204
+ }
205
+
206
+ async function registryJson(path, signal = AbortSignal.timeout(20000)) {
207
+ const response = await fetch(REGISTRY + path, { signal, redirect: 'error' })
208
+ if (!response.ok) { await response.body?.cancel(); throw fail('npm registry ' + path + ': HTTP ' + response.status, 502) }
209
+ let raw = '', bytes = 0
210
+ const decoder = new TextDecoder()
211
+ for await (const chunk of response.body) {
212
+ bytes += chunk.length
213
+ if (bytes > 8 * 1024 * 1024) throw fail('Registry response too large: ' + path + ' (' + bytes + ' bytes; limit ' + 8 * 1024 * 1024 + ')', 502)
214
+ raw += decoder.decode(chunk, { stream: true })
215
+ }
216
+ raw += decoder.decode()
217
+ return JSON.parse(raw)
218
+ }
219
+
220
+ export async function pluginDetails(name, version = 'latest') {
221
+ if (!packagePattern.test(name) || !(version === 'latest' || versionPattern.test(version))) throw fail('Invalid package or version')
222
+ const data = await registryJson('/' + encodeURIComponent(name) + '/' + encodeURIComponent(version))
223
+ if (data.name !== name || !versionPattern.test(data.version)) throw fail('Invalid registry metadata', 502)
224
+ return {
225
+ name, version: data.version, description: String(data.description || ''),
226
+ bundle: typeof data.dsh?.bundle?.patch === 'string',
227
+ license: typeof data.license === 'string' ? data.license : '',
228
+ homepage: typeof data.homepage === 'string' ? data.homepage : '',
229
+ engines: data.engines || {}, peers: data.peerDependencies || {},
230
+ protected: protectedPackage(name), source: REGISTRY,
231
+ }
232
+ }
233
+
234
+ const publicationCache = new Map()
235
+ // Validate full package JSON without accumulating all-version manifests. Only
236
+ // requested string/string-map fields are retained; unrelated content is skipped.
237
+ function registryProjection(fields) {
238
+ const stack = [], result = Object.create(null)
239
+ let root = false, done = false, token = '', mode = '', escaped = false, unicode = 0, capture = false, retained = 0
240
+ let prefixLimit = Infinity, decodedChars = 0, truncatedString = false
241
+ const invalid = () => { throw fail('Invalid npm publication metadata', 502) }
242
+ const wanted = frame => frame.keep || stack.length === 1 && Object.hasOwn(fields, frame.key)
243
+ function accept(kind, value) {
244
+ const frame = stack.at(-1)
245
+ if (kind === '}' || kind === ']') {
246
+ if (!frame || frame.kind !== (kind === '}' ? '{' : '[') || !['first', 'end'].includes(frame.state)) invalid()
247
+ stack.pop(); if (!stack.length) done = true
248
+ return
249
+ }
250
+ if (kind === ':') { if (frame?.state !== 'colon') invalid(); frame.state = 'value'; return }
251
+ if (kind === ',') { if (frame?.state !== 'end') invalid(); frame.state = frame.kind === '{' ? 'key' : 'value'; return }
252
+ if (frame?.kind === '{' && ['first', 'key'].includes(frame.state)) {
253
+ if (kind !== 'string') invalid()
254
+ frame.key = value; frame.state = 'colon'; return
255
+ }
256
+ if (frame && !(frame.state === 'value' || frame.kind === '[' && frame.state === 'first')) invalid()
257
+ if (!frame && (root || kind !== '{')) invalid()
258
+ const keep = frame ? wanted(frame) : false
259
+ if (keep && (stack.length === 1 && fields[frame.key] === 'map' ? kind !== '{' : kind !== 'string')) invalid()
260
+ const container = kind === '{' || kind === '['
261
+ const next = container ? kind === '{' ? Object.create(null) : [] : value
262
+ if (!frame) root = true
263
+ else {
264
+ if (keep) {
265
+ const target = stack.length === 1 ? result : frame.value
266
+ if (frame.kind === '[') target.push(next)
267
+ else { if (Object.hasOwn(target, frame.key)) invalid(); target[frame.key] = next }
268
+ }
269
+ frame.state = 'end'
270
+ }
271
+ if (container) {
272
+ if (stack.length >= 64) invalid()
273
+ stack.push({ kind, state: 'first', keep, value: next, key: '' })
274
+ }
275
+ }
276
+ function append(char) {
277
+ if (capture) {
278
+ if (++retained > 1024 * 1024) throw fail('npm publication fields exceed 1048576 characters', 502)
279
+ token += char
280
+ }
281
+ }
282
+ function stringUnit() {
283
+ // Stop at a complete decoded UTF-16 unit, never in a JSON escape. Keep one
284
+ // extra character so the existing README adapter reports truncation.
285
+ if (capture && ++decodedChars >= prefixLimit) { capture = false; truncatedString = true }
286
+ }
287
+ function push(raw) {
288
+ for (let i = 0; i < raw.length; i++) {
289
+ const char = raw[i]
290
+ if (mode === 'string') {
291
+ append(char)
292
+ if (unicode) { if (!/[a-fA-F0-9]/.test(char)) invalid(); unicode--; if (!unicode) stringUnit(); continue }
293
+ if (escaped) { if (char === 'u') unicode = 4; else if (!'"\\/bfnrt'.includes(char)) invalid(); escaped = false; if (char !== 'u') stringUnit(); continue }
294
+ if (char === '\\') { escaped = true; continue }
295
+ if (char === '"') { accept('string', capture ? JSON.parse(token) : truncatedString ? JSON.parse(token + '"') : undefined); mode = ''; token = ''; continue }
296
+ if (char.charCodeAt(0) < 32) invalid()
297
+ stringUnit()
298
+ continue
299
+ }
300
+ if (mode === 'scalar') {
301
+ if (!/[\s,}\]]/.test(char)) { if (token.length >= 128) invalid(); token += char; continue }
302
+ if (!/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/.test(token)) invalid()
303
+ accept('scalar', JSON.parse(token)); mode = ''; token = ''; i--; continue
304
+ }
305
+ if (/^[ \r\n\t]$/.test(char)) continue
306
+ if (done) invalid()
307
+ if ('{}[]:,'.includes(char)) { accept(char); continue }
308
+ if (char === '"') {
309
+ const frame = stack.at(-1)
310
+ capture = !!frame && (frame.kind === '{' && ['first', 'key'].includes(frame.state) ? frame.keep || stack.length === 1 : wanted(frame))
311
+ prefixLimit = stack.length === 1 && frame?.state === 'value' && frame.key === 'readme' ? 100001 : Infinity
312
+ decodedChars = 0; truncatedString = false
313
+ token = ''; mode = 'string'; append(char); continue
314
+ }
315
+ if (!/[tfn\d-]/.test(char)) invalid()
316
+ token = char; mode = 'scalar'
317
+ }
318
+ }
319
+ return { push, finish() { if (!done || mode || stack.length) invalid(); return result } }
320
+ }
321
+ async function registryMetadata(name, signal, fields) {
322
+ if (!packagePattern.test(name)) throw fail('Invalid package')
323
+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000)
324
+ let data, bytes = 0
325
+ try {
326
+ const response = await fetch(REGISTRY + '/' + encodeURIComponent(name), { signal: requestSignal, redirect: 'error', headers: { accept: 'application/json' } })
327
+ if (!response.ok) { await response.body?.cancel(); throw fail('HTTP ' + response.status, 502) }
328
+ const projection = registryProjection(fields), decoder = new TextDecoder('utf-8', { fatal: true })
329
+ for await (const chunk of response.body) {
330
+ bytes += chunk.length
331
+ if (bytes > 64 * 1024 * 1024) throw fail('Registry response too large (' + bytes + ' bytes; limit 67108864)', 502)
332
+ projection.push(decoder.decode(chunk, { stream: true }))
333
+ }
334
+ projection.push(decoder.decode()); data = projection.finish()
335
+ if (data.name !== name) throw fail('Invalid npm package identity', 502)
336
+ } catch (error) {
337
+ const reason = requestSignal.aborted ? 'npm 元数据读取超时或已取消' : error.status ? error.message : 'Registry response failed or invalid'
338
+ throw fail('npm ' + name + ': ' + reason + ' (received ' + bytes + ' bytes)', 502)
339
+ }
340
+ return data
341
+ }
342
+ // install-v1 metadata omits `time`; keep full-format publication evidence.
343
+ export async function publicationTimes(name, signal, versions = []) {
344
+ if (!packagePattern.test(name)) throw fail('Invalid package')
345
+ const cached = publicationCache.get(name)
346
+ if (cached?.until > Date.now() && versions.every(version => Object.hasOwn(cached.value, version))) return cached.value
347
+ const data = await registryMetadata(name, signal, { name: 'string', time: 'map' })
348
+ if (!data.time) throw fail('npm ' + name + ': npm 未提供可核验的发布时间', 502)
349
+ publicationCache.set(name, { value: data.time, until: Date.now() + 5 * 60000 })
350
+ if (publicationCache.size > 1500) publicationCache.delete(publicationCache.keys().next().value)
351
+ return data.time
352
+ }
353
+ async function readmeRegistryJson(path, signal) {
354
+ const name = decodeURIComponent(path.slice(1))
355
+ return registryMetadata(name, signal, { name: 'string', readme: 'string', 'dist-tags': 'map' })
356
+ }
357
+
358
+ export function createPluginCenter(ctx, options = {}) {
359
+ const market = createMarketAdapter(ctx), readme = createReadmeReader(options.registryJson || readmeRegistryJson)
360
+ const profile = options.profile === undefined ? detectProfile(ctx) : options.profile
361
+ const details = options.details || pluginDetails
362
+ const probe = options.probeProcesses || probeProcesses
363
+ const launch = options.launch || (args => {
364
+ const desktop = profile?.cliMode === 'desktop'
365
+ // A self-update can replace this module's package directory. Run a private
366
+ // snapshot from the profile ledger, with an explicit stable working dir.
367
+ const workerFile = join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.mjs')
368
+ const transactionName = 'transaction-' + args[2] + '.mjs'
369
+ const marketName = 'market-' + args[2] + '.mjs'
370
+ writeFileSync(join(profile.dir, '.remote-plugin-center', transactionName), readFileSync(new URL('./plugin-transaction.mjs', import.meta.url)), { flag: 'wx', mode: 0o600 })
371
+ writeFileSync(join(profile.dir, '.remote-plugin-center', marketName), readFileSync(new URL('./market.mjs', import.meta.url)), { flag: 'wx', mode: 0o600 })
372
+ writeFileSync(workerFile, readFileSync(SELF, 'utf8').replace("'./plugin-transaction.mjs'", JSON.stringify('./' + transactionName)).replace("'./market.mjs'", JSON.stringify('./' + marketName)), { flag: 'wx', mode: 0o600 })
373
+ const errorLog = openSync(join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.log'), 'a', 0o600)
374
+ let child
375
+ try {
376
+ // 这里是短命的插件事务 worker:只在插件安装/更新期间存在,不构成对 DSH 安装目录的
377
+ // 长期占用,因此继续使用 process.execPath(桌面版会显式加 ELECTRON_RUN_AS_NODE)。
378
+ // 若将来出现同类 Windows 文件锁(占用 DSH 安装目录导致更新失败),再统一到
379
+ // packages/plugin/index.mjs 的 resolveGatewayRuntime()。
380
+ child = spawn(process.execPath, [...(desktop ? ['--expose-internals'] : []), workerFile, '--worker', ...args], {
381
+ cwd: profile.dir, detached: true, windowsHide: true, stdio: ['ignore', 'ignore', errorLog],
382
+ env: { ...process.env, ...(desktop ? { ELECTRON_RUN_AS_NODE: '1' } : {}) },
383
+ })
384
+ } finally { closeSync(errorLog) }
385
+ return new Promise((resolveLaunch, reject) => {
386
+ child.once('error', reject)
387
+ child.once('spawn', () => { child.unref(); resolveLaunch(child.pid) })
388
+ })
389
+ })
390
+ const manifestPath = profile && join(profile.dir, 'package.json')
391
+ const initialRevision = profile && revision(manifestPath)
392
+ const storage = profile && join(profile.dir, '.remote-plugin-center')
393
+ let submitting = false
394
+ async function preflight(body) {
395
+ if (!profile?.cli) throw fail('当前环境只读', 409)
396
+ if (!body || !['install', 'update', 'remove', 'update-all'].includes(body.action) || !packagePattern.test(body.name || '') || (!['remove', 'update-all'].includes(body.action) && !versionPattern.test(body.version || ''))) throw fail('Invalid operation')
397
+ if (protectedPackage(body.name) && !(body.action === 'update' && body.name === '@hyprnos/dsh-remote-plugin')) throw fail('核心插件请通过主机维护流程管理', 409)
398
+ if (body.revision !== revision(manifestPath)) throw fail('插件列表已变化,请刷新', 409)
399
+ const state = await inventory()
400
+ if (state.busy || state.profileLock && state.profileLock.state !== 'dead') throw fail('已有插件任务或配置锁,请等待后重试', 409)
401
+ if (body.action === 'update-all') {
402
+ body = { ...body, targets: batchTargets(body, state) }
403
+ for (let i = 0; i < body.targets.length; i += 6) await Promise.all(body.targets.slice(i, i + 6).map(async target => {
404
+ if (!(await details(target.name, target.version)).bundle) throw fail('该版本未声明 DSH bundle:' + target.name)
405
+ }))
406
+ }
407
+ const plan = await prepareReleasePlan(profile.dir, body, options.publicationTimes || publicationTimes)
408
+ const key = createHash('sha256').update(JSON.stringify(plan) + Math.random()).digest('hex')
409
+ mkdirSync(storage, { recursive: true, mode: 0o700 })
410
+ atomic(join(storage, 'preflight-' + key + '.json'), plan)
411
+ // Never return configuration text, tokens or registry credentials to the UI.
412
+ const { workspace, ...review } = plan
413
+ return { ok: true, plan: { ...review, key } }
414
+ }
415
+ async function inventory() {
416
+ const busyReason = storage ? await recoverDeadLock(storage, probe) : ''
417
+ let runtime = [], runtimeAvailable = false
418
+ const loader = ctx.get?.('loader') || ctx.loader
419
+ if (loader?.entries) {
420
+ runtime = [...loader.entries()].filter(entry => !entry.options.group).map(entry => ({
421
+ id: entry.id, name: entry.options.name, enabled: !entry.disabled,
422
+ phase: ['pending', 'loading', 'active', 'failed', 'disposed', 'unloading'][entry.fiber?.state] || 'inactive',
423
+ }))
424
+ runtimeAvailable = true
425
+ }
426
+ if (!profile) return { ok: true, writable: false, reason: '无法确认当前 DSH profile;仅显示运行状态。', runtime, runtimeAvailable, items: [], operations: [] }
427
+ const manifest = read(manifestPath)
428
+ const bundles = manifest.dsh.profile.bundles
429
+ const names = [...new Set([...bundles, ...Object.keys(manifest.dependencies || {})])]
430
+ const items = names.map(name => {
431
+ let pkg = null
432
+ if (packagePattern.test(name)) {
433
+ try { pkg = read(join(profile.dir, 'node_modules', ...name.split('/'), 'package.json')) } catch {}
434
+ }
435
+ const displayName = typeof pkg?.displayName === 'string' ? pkg.displayName : typeof pkg?.dsh?.displayName === 'string' ? pkg.dsh.displayName : name
436
+ return { name, displayName, version: pkg?.version || '', requested: manifest.dependencies?.[name] || '',
437
+ enabled: bundles.includes(name), bundle: !!pkg?.dsh?.bundle?.patch || bundles.includes(name),
438
+ managed: !!manifest.dependencies?.[name] && !protectedPackage(name),
439
+ selfUpdate: name === '@hyprnos/dsh-remote-plugin' && !!profile.cli,
440
+ description: pkg?.description || '', runtime: runtime.filter(entry => entry.name === name) }
441
+ })
442
+ let operations = []
443
+ if (existsSync(storage)) operations = readdirSync(storage).filter(name => /^job-[a-zA-Z0-9-]+\.json$/.test(name)).map(name => {
444
+ try { return read(join(storage, name)) } catch { return null }
445
+ }).filter(Boolean).sort((a, b) => b.startedAt - a.startedAt).slice(0, 20).map(publicJob)
446
+ const lockPath = join(storage, 'lock.json')
447
+ const ownerText = ownershipText(lockPath)
448
+ const owner = ownerText === null ? null : ownerText === undefined ? {} : JSON.parse(ownerText)
449
+ const legacyLock = owner && idPattern.test(owner.id || '') && !owner.launcherPid && !owner.workerPid && !owner.cliPid && !existsSync(join(storage, 'launch-' + owner.id + '.json'))
450
+ return { ok: true, profile: profile.name, revision: revision(manifestPath), writable: !!profile.cli, adaptations: adapterInterfaces(ctx),
451
+ reason: profile.cli ? '' : profile.name === 'desktop'
452
+ ? '未能验证当前桌面安装的插件管理入口;仅显示状态,请检查 DSH Desktop 版本与安装完整性。'
453
+ : '当前启动方式没有可验证的 DSH CLI,管理操作不可用。',
454
+ pendingRestart: revision(manifestPath) !== initialRevision || operations.some(job => job.phase === 'interrupted' && job.restartRequired),
455
+ busy: submitting || !!owner, busyReason: owner ? busyReason || '主机任务正在启动;可查看操作记录。' : '',
456
+ profileLock: await profileLock(profile.dir, probe).then(lock => lock && ({ state: lock.state, message: lock.message })),
457
+ recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
458
+ capabilities: { preflight: true, restore: true, updateAll: true }, items, runtime, runtimeAvailable, operations }
459
+ }
460
+ function recoverLegacy(body) {
461
+ if (!profile?.cli || submitting) throw fail('当前不能恢复任务', 409)
462
+ const lockPath = join(storage, 'lock.json')
463
+ if (!existsSync(lockPath)) throw fail('任务锁已变化,请刷新', 409)
464
+ const owner = read(lockPath)
465
+ if (!idPattern.test(body.id || '') || body.id !== owner.id || owner.launcherPid || owner.workerPid || owner.cliPid || existsSync(join(storage, 'launch-' + owner.id + '.json'))) throw fail('仅支持人工恢复无进程信息的旧任务锁', 409)
466
+ if (revision(manifestPath) !== body.revision) throw fail('插件列表已变化,请刷新', 409)
467
+ if (body.confirmNoRunningProcess !== true) throw fail('请先在主机确认插件安装进程已退出', 409)
468
+ const jobPath = join(storage, 'job-' + owner.id + '.json')
469
+ if (existsSync(jobPath)) {
470
+ const job = read(jobPath)
471
+ if (['queued', 'running'].includes(job.phase)) {
472
+ job.phase = 'interrupted'; job.endedAt = Date.now(); job.restartRequired = true
473
+ job.message = '用户核对进程后解除了旧任务锁;保留现有文件和备份,未执行自动回滚。'
474
+ atomic(jobPath, job)
475
+ }
476
+ }
477
+ renameSync(lockPath, join(storage, 'recovered-lock-' + owner.id + '.json'))
478
+ return { ok: true }
479
+ }
480
+ async function submit(body) {
481
+ if (!profile?.cli) throw fail('Current DSH profile is read-only', 409)
482
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('Invalid operation')
483
+ const { id, action, name, version } = body
484
+ if (!idPattern.test(id || '') || !packagePattern.test(name || '') || !['install', 'update', 'update-all', 'remove', 'enable', 'disable', 'restore'].includes(action)) throw fail('Invalid operation')
485
+ const selfUpdate = name === '@hyprnos/dsh-remote-plugin' && action === 'update'
486
+ if (protectedPackage(name) && !selfUpdate && action !== 'restore') throw fail('核心插件与 Remote 的卸载、启停请通过主机维护流程管理', 409)
487
+ if (selfUpdate && body.confirmSelfUpdate !== true) throw fail('请确认 Remote 本体更新及重启后生效', 409)
488
+ mkdirSync(storage, { recursive: true, mode: 0o700 })
489
+ await recoverDeadLock(storage, probe)
490
+ const jobPath = join(storage, 'job-' + id + '.json')
491
+ if (existsSync(jobPath)) {
492
+ const previous = read(jobPath)
493
+ if (previous.action !== action || previous.name !== name || previous.version !== (version || '') || (previous.restoreFrom || '') !== (body.restoreFrom || '') || (previous.planKey || '') !== (body.preflightKey || '') || action === 'update-all' && targetIdentity(previous.targets) !== targetIdentity(body.targets)) throw fail('Operation id already used', 409)
494
+ return publicJob(previous)
495
+ }
496
+ if (submitting) throw fail('另一个插件操作正在准备中', 409)
497
+ submitting = true
498
+ try {
499
+ if (revision(manifestPath) !== body.revision) throw fail('插件列表已变化,请刷新后重试', 409)
500
+ const manifest = read(manifestPath)
501
+ const installed = Object.hasOwn(manifest.dependencies || {}, name)
502
+ if (!['restore', 'update-all'].includes(action) && (action === 'install' && installed || action !== 'install' && !installed)) throw fail('安装状态已变化,请刷新', 409)
503
+ let plan = null, restoreFrom = null
504
+ if (body.preflightKey) {
505
+ if (!/^[a-f0-9]{64}$/.test(body.preflightKey)) throw fail('无效的预检凭据')
506
+ const preflightPath = join(storage, 'preflight-' + body.preflightKey + '.json')
507
+ if (!existsSync(preflightPath)) throw fail('预检凭据已失效,请重新预检', 409)
508
+ plan = read(preflightPath)
509
+ if (plan.action !== action || plan.name !== name || plan.version !== (version || '') || plan.expiresAt < Date.now() || plan.revision !== profileRevision(profile.dir)) throw fail('预检已过期或配置已变化,请重新预检', 409)
510
+ if ((plan.blockers.length || plan.ruleChanges.length) && body.confirmReleasePolicy !== true) throw fail('请明确批准预检中列出的精确版本豁免及重复规则合并', 409)
511
+ }
512
+ if (action === 'update-all') {
513
+ if (!plan || targetIdentity(plan.targets) !== targetIdentity(body.targets)) throw fail('批量更新必须使用已确认的完整预检列表', 409)
514
+ batchTargets(body, await inventory())
515
+ if (plan.targets.some(target => target.name === '@hyprnos/dsh-remote-plugin') && body.confirmSelfUpdate !== true) throw fail('请确认批量更新包含 Remote 本体', 409)
516
+ }
517
+ if (action === 'restore') {
518
+ if (!idPattern.test(body.restoreFrom || '') || body.confirmRestore !== true) throw fail('请确认恢复失败前的插件和配置', 409)
519
+ const source = read(join(storage, 'job-' + body.restoreFrom + '.json'))
520
+ if (source.name !== name || !['failed', 'interrupted'].includes(source.phase) || !source.recoveryState || source.restoredBy) throw fail('该任务没有可安全恢复的备份', 409)
521
+ if (source.recoveryState.revision !== profileRevision(profile.dir)) throw fail('失败后配置已改变,请在主机核对', 409)
522
+ restoreFrom = body.restoreFrom
523
+ }
524
+ if (['install', 'update'].includes(action)) {
525
+ if (!versionPattern.test(version || '')) throw fail('需要明确的版本号')
526
+ const metadata = await details(name, version)
527
+ if (!metadata.bundle) throw fail('该版本未声明 DSH bundle,不能作为插件安装')
528
+ }
529
+ if (['enable', 'disable'].includes(action)) {
530
+ const pkg = read(join(profile.dir, 'node_modules', ...name.split('/'), 'package.json'))
531
+ if (!pkg.dsh?.bundle?.patch) throw fail('该依赖不是 DSH bundle')
532
+ }
533
+ if (revision(manifestPath) !== body.revision) throw fail('插件配置已变化,请刷新', 409)
534
+ const lock = join(storage, 'lock.json')
535
+ try { writeFileSync(lock, JSON.stringify({ id, launcherPid: process.pid, createdAt: Date.now() }), { flag: 'wx', mode: 0o600 }) }
536
+ catch (error) { if (error.code === 'EEXIST') throw fail('已有插件任务运行中;请查看操作记录', 409); throw error }
537
+ const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', stage: 'queued', startedAt: Date.now(), updatedAt: Date.now(), log: '', restartRequired: false,
538
+ ...(action === 'update-all' ? { targets: plan.targets.map(target => ({ ...target, phase: 'queued' })) } : {}),
539
+ ...(plan ? { plan, planKey: body.preflightKey } : {}), ...(restoreFrom ? { restoreFrom } : {}) }
540
+ try {
541
+ atomic(jobPath, job)
542
+ const pid = await launch([profile.dir, profile.cli, id, profile.cliMode || 'node'])
543
+ // Separate ledger: the launcher must never overwrite a worker's CLI PID.
544
+ if (Number.isInteger(pid) && pid > 0) atomic(join(storage, 'launch-' + id + '.json'), { pid })
545
+ } catch (error) {
546
+ job.phase = 'failed'; job.message = '无法启动插件任务'; job.endedAt = Date.now()
547
+ atomic(jobPath, job); unlinkSync(lock); throw error
548
+ }
549
+ return publicJob(job)
550
+ } finally { submitting = false }
551
+ }
552
+ async function handle(method, sub, body = {}, query = new URLSearchParams()) {
553
+ if (method === 'GET' && sub === '/state') return inventory()
554
+ if (method === 'GET' && sub === '/details') return { ok: true, item: await details(query.get('name') || '', query.get('version') || 'latest') }
555
+ if (method === 'GET' && sub === '/readme') return readme(query.get('name') || '', query.get('version') || '')
556
+ if (method === 'GET' && sub === '/market/indexes') return market.indexes()
557
+ if (method === 'GET' && sub === '/market') {
558
+ const q = String(query.get('q') || '').trim()
559
+ const sort = query.get('sort') || (q ? 'relevance' : 'index')
560
+ if (!['index', 'relevance', 'published'].includes(sort)) return { ok: false, code: 'invalid-query' }
561
+ return market.search(query.get('index') || '', { text: q, offset: Number(query.get('offset') || 0), limit: 20,
562
+ sort: sort === 'published' ? { kind: sort, direction: 'desc' } : { kind: sort },
563
+ ...(query.get('category') ? { category: query.get('category') } : {}),
564
+ ...(query.has('fetchedAt') ? { fetchedAt: Number(query.get('fetchedAt')) } : {}),
565
+ ...(query.get('refresh') === '1' ? { refresh: true } : {}) })
566
+ }
567
+ if (method === 'POST' && sub === '/operations') {
568
+ if (['install', 'update', 'update-all', 'remove'].includes(body.action) && !body.preflightKey) throw fail('请先预检并确认更新计划;旧版客户端需升级 Remote 页面', 409)
569
+ return { ok: true, operation: await submit(body) }
570
+ }
571
+ if (method === 'POST' && sub === '/preflight') return preflight(body)
572
+ if (method === 'POST' && sub === '/recover') return recoverLegacy(body)
573
+ throw fail('Unknown plugin endpoint', 404)
574
+ }
575
+ return { handle, inventory, submit, preflight }
576
+ }
577
+
578
+ function publicJob(job) {
579
+ const { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired } = job
580
+ return { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired,
581
+ ...(job.targets ? { targets: job.targets.map(({ name, version, fromVersion, phase, message }) => ({ name, version, fromVersion, phase, message })) } : {}),
582
+ canRestore: !!job.recoveryState && !job.restoredBy && ['failed', 'interrupted'].includes(phase), restoredBy: job.restoredBy || '' }
583
+ }
584
+
585
+ // pnpm refuses packages younger than `minimumReleaseAge` and verifies the whole
586
+ // lockfile up front, so one immature entry fails every install — including a
587
+ // rollback to an older version. Same-name rules in `minimumReleaseAgeExclude`
588
+ // are matched first-match-wins, so the entry pnpm appends on each install can be
589
+ // silently dead. Neither fact is visible in the raw pnpm output.
590
+ const immaturePublished = /^\s*((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)@([^\s@]+)\s+was published at\s/
591
+ export function immatureReleaseNotice(log) {
592
+ if (typeof log !== 'string' || !/MINIMUM_RELEASE_AGE_VIOLATION/.test(log)) return null
593
+ const entries = []
594
+ for (const line of log.split('\n')) {
595
+ const match = immaturePublished.exec(line)
596
+ if (match && !entries.some(entry => entry.name === match[1] && entry.version === match[2])) entries.push({ name: match[1], version: match[2] })
597
+ }
598
+ const shown = entries.slice(0, 5).map(entry => entry.name + '@' + entry.version).join('、') + (entries.length > 5 ? ' 等 ' + entries.length + ' 条' : '')
599
+ return (entries.length === 0
600
+ ? 'pnpm 的供应链策略拒绝了当前 pnpm-lock.yaml:其中至少一条记录发布不满 minimumReleaseAge,但日志没有列出具体条目。'
601
+ : 'pnpm 的供应链策略拦住了 ' + shown + '(发布不满 minimumReleaseAge)。')
602
+ + '请在主机核对 profile 的 pnpm-workspace.yaml:同一个包名只会生效第一条 minimumReleaseAgeExclude 规则,第二条起被静默忽略,而 pnpm 每次成功安装都会自动追加一条,所以后追加的豁免可能等于不存在;'
603
+ + '并且校验覆盖整份 lockfile,只要有一条不合格,安装和降级回滚会一起失败。请返回插件详情重新预检,核对后批准列出的精确版本;同名包的精确版本豁免会合并成一条(`- 包名@版本 || 版本`)。'
604
+ + '也可等待日志中被拦包的最小发布年龄窗口结束后再重试。报错包可能不是本次更新目标,失败也不表示已安装目标版本;配置备份保存在当前 profile 的 .remote-plugin-center/backup-任务ID 目录。文件可能已改变,本次未自动回滚。'
605
+ }
606
+
607
+ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node', probe = probeProcesses) {
608
+ if (!idPattern.test(id || '')) throw fail('Invalid worker id')
609
+ const storage = join(dir, '.remote-plugin-center')
610
+ const lock = join(storage, 'lock.json')
611
+ const owner = read(lock)
612
+ if (owner.id !== id || owner.workerPid && owner.workerPid !== process.pid) throw fail('Worker does not own lock')
613
+ atomic(lock, { ...owner, workerPid: process.pid })
614
+ const jobPath = join(storage, 'job-' + id + '.json')
615
+ const job = read(jobPath)
616
+ const manifestPath = join(dir, 'package.json')
617
+ const disabledPath = join(storage, 'disabled.json')
618
+ let disabled
619
+ const save = () => { job.updatedAt = Date.now(); atomic(jobPath, job) }
620
+ const progress = (stage, message) => { job.stage = stage; job.message = message; save() }
621
+ const guarded = async task => {
622
+ const file = join(dir, 'package.json.lock'), owner = String(process.pid)
623
+ try { writeFileSync(file, owner, { flag: 'wx', mode: 0o600 }) }
624
+ catch { throw fail('DSH 配置锁已被其他进程取得,已停止操作;请稍后重试', 409) }
625
+ try { return await task() }
626
+ finally { if (ownershipText(file) === owner) unlinkSync(file) }
627
+ }
628
+ let heartbeat
629
+ try {
630
+ job.phase = 'running'; progress('backup', '正在备份配置文件。')
631
+ heartbeat = setInterval(save, 4000); heartbeat.unref()
632
+ if (job.revision !== revision(manifestPath)) throw fail('任务开始前 profile 已变化,请刷新后重试')
633
+ disabled = new Set(existsSync(disabledPath) ? read(disabledPath) : [])
634
+ if (job.action === 'update-all') for (const target of job.targets) if (!target.enabled) disabled.add(target.name)
635
+ const backup = join(storage, 'backup-' + id)
636
+ mkdirSync(backup, { mode: 0o700 })
637
+ for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml', 'cordis.yml', '.npmrc']) {
638
+ if (existsSync(join(dir, name))) copyFileSync(join(dir, name), join(backup, name))
639
+ }
640
+ if (existsSync(disabledPath)) copyFileSync(disabledPath, join(backup, 'disabled.json'))
641
+ if (job.name === '@hyprnos/dsh-remote-plugin' && !job.plan) cpSync(join(dir, 'node_modules', '@hyprnos/dsh-remote-plugin'), join(backup, 'remote-plugin'), { recursive: true, dereference: true })
642
+ progress('profile-lock', '正在检查 DSH 配置锁。')
643
+ const existingLock = await profileLock(dir, probe)
644
+ if (existingLock) {
645
+ if (existingLock.state !== 'dead') throw fail(existingLock.message, 409)
646
+ // No await between final ownership comparison, backup and removal.
647
+ if (!existsSync(existingLock.path) || readFileSync(existingLock.path, 'utf8') !== existingLock.raw) throw fail('DSH 配置锁已变化,请刷新后重试', 409)
648
+ copyFileSync(existingLock.path, join(backup, 'package.json.lock'))
649
+ unlinkSync(existingLock.path)
650
+ job.log += '已备份并回收确认退出的进程遗留的 DSH 配置锁。\n'
651
+ }
652
+ if (job.revision !== revision(manifestPath)) throw fail('检查配置锁期间 profile 已变化,请刷新后重试')
653
+ if (job.restoreFrom) {
654
+ const sourcePath = join(storage, 'job-' + job.restoreFrom + '.json'), source = read(sourcePath)
655
+ progress('restore', '正在核验并恢复更新前的插件文件和配置。')
656
+ await guarded(() => restoreTransaction(dir, join(storage, 'backup-' + job.restoreFrom), source.recoveryState, backup))
657
+ source.restoredBy = job.id; atomic(sourcePath, source)
658
+ job.phase = 'complete'; job.stage = 'complete'; job.restartRequired = true
659
+ job.message = '已恢复更新前的插件文件和配置,校验通过;请重启 DSH。失败现场副本已保留。'
660
+ return
661
+ }
662
+ if (job.plan) {
663
+ if (job.plan.expiresAt < Date.now() || profileRevision(dir) !== job.plan.revision) throw fail('预检已过期或配置改变,未执行安装,请重新预检')
664
+ progress('snapshot', '正在备份全部插件文件和配置,完成前不会安装。')
665
+ await guarded(async () => {
666
+ await backupTransaction(dir, backup)
667
+ if (profileRevision(dir) !== job.plan.revision) throw fail('备份期间配置发生变化,未执行安装')
668
+ job.transactionStarted = true; save()
669
+ writeWorkspace(dir, job.plan.workspace)
670
+ })
671
+ }
672
+ if (['install', 'update', 'remove', 'update-all'].includes(job.action)) {
673
+ progress('cli', '正在运行 DSH 插件命令,等待主机输出。')
674
+ const targets = job.action === 'update-all' ? job.targets : [job]
675
+ let batchRevision = job.action === 'update-all' ? profileRevision(dir) : null
676
+ for (const target of targets) {
677
+ if (job.action === 'update-all') {
678
+ if (profileRevision(dir) !== batchRevision) throw fail('批量更新期间主机配置已被其他操作改变,已停止后续项。')
679
+ target.phase = 'running'; progress('cli', '正在更新 ' + target.name + '@' + target.version + '(' + (targets.indexOf(target) + 1) + '/' + targets.length + ')。')
680
+ }
681
+ const args = job.action === 'remove' ? ['remove', target.name, '--config.ignore-scripts=true'] : ['add', target.name + '@' + target.version, '--save-exact', '--ignore-scripts', '--registry=' + REGISTRY]
682
+ await execute(cli, ['plugin', '--profile', basename(dir), ...args], dir, chunk => {
683
+ job.lastOutputAt = Date.now()
684
+ job.log = (job.log + chunk.replace(/\x1b\[[0-9;]*m/g, '').replace(/(token|password|authorization)\s*[=:]\s*\S+/gi, '$1=[redacted]')).slice(-12000)
685
+ save()
686
+ }, pid => atomic(lock, { ...read(lock), cliPid: pid }), cliMode)
687
+ if (job.action === 'update-all') await guarded(() => {
688
+ const manifest = read(manifestPath)
689
+ manifest.dsh.profile.bundles = manifest.dsh.profile.bundles.filter(name => !disabled.has(name))
690
+ atomic(manifestPath, manifest); atomic(disabledPath, [...disabled])
691
+ const pkg = read(join(dir, 'node_modules', ...target.name.split('/'), 'package.json'))
692
+ if (pkg.version !== target.version || !pkg.dsh?.bundle?.patch || manifest.dependencies?.[target.name] !== target.version) throw fail('安装后的包版本、精确依赖或 bundle 校验失败:' + target.name)
693
+ verifyInstalled(dir, job)
694
+ batchRevision = profileRevision(dir)
695
+ target.phase = 'complete'; save()
696
+ })
697
+ }
698
+ }
699
+ const verify = () => {
700
+ progress('verify', '正在保存配置并核验插件状态。')
701
+ if (job.action === 'disable') disabled.add(job.name)
702
+ if (job.action === 'enable' || job.action === 'remove') disabled.delete(job.name)
703
+ const manifest = read(manifestPath)
704
+ manifest.dsh.profile.bundles = manifest.dsh.profile.bundles.filter(name => !disabled.has(name))
705
+ if (job.action === 'enable' && !manifest.dsh.profile.bundles.includes(job.name)) manifest.dsh.profile.bundles.push(job.name)
706
+ atomic(manifestPath, manifest)
707
+ atomic(disabledPath, [...disabled])
708
+ const installed = Object.hasOwn(manifest.dependencies || {}, job.name)
709
+ if (job.action !== 'update-all' && (job.action === 'remove' ? installed : !installed)) throw fail('操作后依赖状态与预期不符')
710
+ if (job.action === 'update-all') for (const target of job.targets) {
711
+ const pkg = read(join(dir, 'node_modules', ...target.name.split('/'), 'package.json'))
712
+ if (pkg.version !== target.version || manifest.dependencies?.[target.name] !== target.version) throw fail('批量更新最终版本不一致:' + target.name)
713
+ }
714
+ if (['install', 'update'].includes(job.action)) {
715
+ const pkg = read(join(dir, 'node_modules', ...job.name.split('/'), 'package.json'))
716
+ if (pkg.version !== job.version || !pkg.dsh?.bundle?.patch) throw fail('安装后的包版本或 bundle 校验失败')
717
+ }
718
+ if (job.plan) {
719
+ // pnpm may append the just-approved version again. Consolidate only rules
720
+ // already present in this transaction, preserving the reviewed policy.
721
+ const workspace = join(dir, 'pnpm-workspace.yaml')
722
+ const normalized = mergeReleaseRules(existsSync(workspace) ? readFileSync(workspace, 'utf8') : null).raw
723
+ if (JSON.stringify(releasePolicy(normalized, {})) !== JSON.stringify(releasePolicy(job.plan.workspace, {}))) throw fail('执行后发布年龄策略超出已确认范围,请检查并恢复备份')
724
+ writeWorkspace(dir, normalized)
725
+ verifyInstalled(dir, job)
726
+ }
727
+ }
728
+ if (job.plan) await guarded(verify)
729
+ else verify()
730
+ job.phase = 'complete'; job.stage = 'complete'; job.restartRequired = true
731
+ job.message = '配置已保存;重启 DSH 后生效。安装脚本未执行。'
732
+ } catch (error) {
733
+ job.phase = 'failed'; job.message = String(error.message || error)
734
+ if (job.action === 'update-all') for (const target of job.targets) {
735
+ if (target.phase === 'running') { target.phase = 'failed'; target.message = job.message }
736
+ else if (target.phase === 'queued') { target.phase = 'interrupted'; target.message = '前项失败,未执行;请先核对或恢复本次备份。' }
737
+ }
738
+ if((job.name==='@hyprnos/dsh-remote-plugin' || job.targets?.some(target => target.name === '@hyprnos/dsh-remote-plugin' && target.phase === 'failed')) && /(?:ERR_PNPM_)?(?:EPERM|EBUSY)/.test(job.log) && /rename/i.test(job.log)) {
739
+ job.message = 'Windows 拒绝替换 Remote 插件目录,可能仍有旧网关或 DSH 进程占用。更新未完成,配置和旧包备份已保留;请退出对应 DSH Desktop 及其 Remote 网关后,使用同一 Desktop 安装自带的 CLI 在当前 profile 重装目标版本,再启动 DSH。不要删除插件目录或强行覆盖;不能假定失败后已自动回滚。'
740
+ }
741
+ const policyNotice = job.message === String(error.message || error) ? immatureReleaseNotice(job.log) : null
742
+ if (policyNotice) job.message = policyNotice
743
+ if (job.transactionStarted) {
744
+ try { job.recoveryState = { revision: profileRevision(dir), installed: treeDigest(join(dir, 'node_modules')) }; job.message += ' 可使用“恢复更新前状态”还原插件和配置;恢复前会再次核验文件未被修改。' }
745
+ catch { job.message += ' 无法完整核验失败现场,请在主机退出 DSH 后使用本任务备份恢复。' }
746
+ }
747
+ // A failed package manager may have changed files. Never claim rollback.
748
+ job.restartRequired = true
749
+ } finally {
750
+ clearInterval(heartbeat)
751
+ job.endedAt = Date.now(); save()
752
+ if (existsSync(lock) && read(lock).id === id) unlinkSync(lock)
753
+ }
754
+ }
755
+
756
+ export function cliInvocation(cli, args, dir, cliMode = 'node', runtime = process) {
757
+ if (!['node', 'desktop'].includes(cliMode)) throw fail('Unsupported CLI mode')
758
+ return { command: runtime.execPath, args: [...(cliMode === 'desktop' ? ['--expose-internals'] : []), cli, ...args],
759
+ env: { ...runtime.env, DSH_HOME: dirname(dirname(dir)), npm_config_ignore_scripts: 'true',
760
+ ...(cliMode === 'desktop' ? { ELECTRON_RUN_AS_NODE: '1' } : {}) } }
761
+ }
762
+
763
+ function runCli(cli, args, dir, output, onSpawn, cliMode) {
764
+ return new Promise((resolveRun, reject) => {
765
+ const invocation = cliInvocation(cli, args, dir, cliMode)
766
+ const child = spawn(invocation.command, invocation.args, { cwd: dir, env: invocation.env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
767
+ child.once('spawn', () => onSpawn(child.pid))
768
+ child.stdout.on('data', chunk => output(chunk.toString()))
769
+ child.stderr.on('data', chunk => output(chunk.toString()))
770
+ child.once('error', reject)
771
+ child.once('close', code => code === 0 ? resolveRun() : reject(fail('DSH 插件命令失败,退出码 ' + code)))
772
+ })
773
+ }
774
+
775
+ if (process.argv[2] === '--worker' && process.argv[1] && canonicalPath(process.argv[1]) === canonicalPath(SELF)) {
776
+ await runWorker(process.argv[3], process.argv[4], process.argv[5], undefined, process.argv[6])
777
+ }