@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
package/index.mjs ADDED
@@ -0,0 +1,1784 @@
1
+ /* dsh-remote DSH 插件 · Node half
2
+ * 在 DSH Web 的 httpServer 上挂 /remote 前缀路由:
3
+ * - /remote/... 移动控制台 + 主机管理页静态资源
4
+ * - /remote/admin/api 管理控制台数据: 优先代理本地网关(完整设备监控/更新检查),
5
+ * 网关不可用时回退到插件模式主机状态
6
+ * 浏览器侧入口由 client half 注册在 DSH「更多」菜单(见 client.js)。
7
+ */
8
+ import { registerFileDeliveryTools } from './file-delivery.mjs'
9
+ import { execFileSync, spawn, spawnSync } from 'node:child_process'
10
+ import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
11
+ import { stat } from 'node:fs/promises'
12
+ import net from 'node:net'
13
+ import { homedir, hostname, networkInterfaces, tmpdir } from 'node:os'
14
+ import { basename, dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { randomUUID } from 'node:crypto'
17
+ import { createPluginCenter, detectProfile } from './plugin-center.mjs'
18
+ import { readCostInsights } from './insights.mjs'
19
+ import { readApprovalSummary } from './approval-summary.mjs'
20
+ import { readTeamInsights } from './teams.mjs'
21
+ import { readTaskBoard } from './task-board.mjs'
22
+ import { readPeakReminders } from './peak-reminders.mjs'
23
+ import { serveSessionFile } from './session-file.mjs'
24
+ import { createSkillsAdapter } from './skills.mjs'
25
+ import { registerDoctorSkill } from './doctor-skill.mjs'
26
+ import { readDoctorTarget, watchDoctorWorkspaces } from './doctor-target.mjs'
27
+
28
+ export const name = 'dsh-remote'
29
+ export const inject = ['webServer', 'commands', 'agents', 'connection']
30
+
31
+ const MOUNT = '/remote'
32
+ const PUBLIC_DIR = fileURLToPath(new URL('./public/', import.meta.url))
33
+ const INDEX_FILE = 'index.html'
34
+ const LONG_RUNNING_COMMAND_TIMEOUT_MS = 120_000
35
+ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000
36
+ const LONG_RUNNING_COMMANDS = new Set(['export'])
37
+ const COMMAND_OPERATION_RETENTION_MS = 10 * 60_000
38
+ // 已登记的命令由 HTTP 请求之外的独立 promise 驱动。这样浏览器断连或等待到期
39
+ // 都不会中止长操作;状态仅保存在进程内,DSH 重启后会话事件重新成为权威来源。
40
+ const commandOperations = new Map()
41
+ const GATEWAY_SCRIPT = fileURLToPath(new URL('./gateway.cjs', import.meta.url))
42
+ const gatewayInstalled = existsSync(GATEWAY_SCRIPT)
43
+ // 本地网关管理 API 代理: 让插件抽屉显示与网关管理页完全一致的数据。
44
+ // 端口读取优先级: DSH_REMOTE_GATEWAY_PORT > ~/.dsh-remote/gateway-port > 8787
45
+ function gatewayPortFile() { return `${homedir()}/.dsh-remote/gateway-port` }
46
+
47
+ function readGatewayPort() {
48
+ const valid = (v) => /^\d+$/.test(String(v)) && Number(v) >= 1 && Number(v) <= 65535
49
+ const envPort = process.env.DSH_REMOTE_GATEWAY_PORT
50
+ if (valid(envPort)) return String(Number(envPort))
51
+ try {
52
+ const filePort = readFileSync(gatewayPortFile(), 'utf8').trim()
53
+ if (valid(filePort)) return String(Number(filePort))
54
+ } catch {}
55
+ return '8787'
56
+ }
57
+
58
+ function gatewayBase() {
59
+ return (process.env.DSH_REMOTE_GATEWAY || upstreamUrlForListener({ host: readGatewayHost(), port: readGatewayPort() })).replace(/\/+$/, '')
60
+ }
61
+
62
+ export function readGatewayHost() {
63
+ if (process.env.DSH_REMOTE_GATEWAY_HOST) return process.env.DSH_REMOTE_GATEWAY_HOST
64
+ if (process.env.HOST) return process.env.HOST
65
+ try {
66
+ const host = readFileSync(`${homedir()}/.dsh-remote/gateway-host`, 'utf8').trim()
67
+ if (host) return host
68
+ } catch {}
69
+ return '0.0.0.0'
70
+ }
71
+
72
+ function gatewayToken() {
73
+ if (process.env.DSH_REMOTE_TOKEN || process.env.TOKEN) return process.env.DSH_REMOTE_TOKEN || process.env.TOKEN
74
+ try {
75
+ return readFileSync(process.env.TOKEN_FILE || `${homedir()}/.dsh-remote/token`, 'utf8').trim() || ''
76
+ } catch {
77
+ return ''
78
+ }
79
+ }
80
+
81
+ const MIME = {
82
+ '.html': 'text/html; charset=utf-8',
83
+ '.js': 'text/javascript; charset=utf-8',
84
+ '.css': 'text/css; charset=utf-8',
85
+ '.json': 'application/json; charset=utf-8',
86
+ '.svg': 'image/svg+xml',
87
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
88
+ '.png': 'image/png',
89
+ '.ico': 'image/x-icon',
90
+ }
91
+
92
+ let version = '0.0.0'
93
+ try {
94
+ const v = JSON.parse(readFileSync(new URL('./public/version.json', import.meta.url), 'utf8'))
95
+ if (v?.version) version = v.version
96
+ } catch {}
97
+
98
+ // DSH 实际监听地址由 apply 时从 webServer 服务读取
99
+ let dshListen = { host: '127.0.0.1', port: 3080 }
100
+ let dshConnection = null
101
+
102
+ // 监听通配地址不是连接目标;保留地址族,避免 IPv6-only 服务退回 IPv4。
103
+ export function upstreamUrlForListener({ host, port }) {
104
+ let target = String(host || '127.0.0.1').replace(/^\[|\]$/g, '')
105
+ if (target === '0.0.0.0') target = '127.0.0.1'
106
+ if (net.isIP(target) === 6 && new URL(`http://[${target}]`).hostname === '[::]') target = '::1'
107
+ return `http://${net.isIP(target) === 6 ? `[${target}]` : target}:${port}`
108
+ }
109
+
110
+ /** Desktop hands a fixed local browser landing to the host's own auth flow. */
111
+ export function browserLaunchUrl(ctx) {
112
+ if (typeof ctx.connection?.authenticatedUrl !== 'function') return null
113
+ const base = new URL(upstreamUrlForListener(ctx.webServer))
114
+ if (ctx.webServer.protocol === 'https:') base.protocol = 'https:'
115
+ if (!['127.0.0.1', '[::1]'].includes(base.hostname)) return null
116
+ const url = new URL(ctx.connection.authenticatedUrl(base.href))
117
+ if (url.origin !== base.origin || url.pathname !== '/' || url.username || url.password) return null
118
+ url.hash = 'dsh-remote-connect'
119
+ return url.href
120
+ }
121
+
122
+ function dshUpstreamCookieFile() {
123
+ return process.env.DSH_REMOTE_DSH_COOKIE_FILE || `${homedir()}/.dsh-remote/dsh-upstream.cookie`
124
+ }
125
+
126
+ /**
127
+ * DSH 0.1.2-alpha.1 起,Host RPC 与 WebSocket 都要求浏览器会话 Cookie。
128
+ * 新版 connection 服务可把仅进程内可见的启动令牌兑换为 Cookie;旧版没有
129
+ * authenticatedUrl,直接跳过即可。文件只让同一用户的独立网关读取。
130
+ */
131
+ async function refreshDshUpstreamCookie() {
132
+ if (typeof dshConnection?.authenticatedUrl !== 'function') return false
133
+ const upstream = upstreamUrlForListener(dshListen)
134
+ try {
135
+ const loginUrl = dshConnection.authenticatedUrl(upstream)
136
+ const response = await fetch(loginUrl, {
137
+ redirect: 'manual',
138
+ signal: AbortSignal.timeout(2500),
139
+ })
140
+ const setCookie = response.headers.get('set-cookie') || ''
141
+ const cookie = setCookie.split(';', 1)[0].trim()
142
+ if (response.status !== 303 || !cookie.includes('=') || cookie.length > 4096 || /[\0\r\n]/.test(cookie)) {
143
+ throw new Error(`认证交换返回 HTTP ${response.status}`)
144
+ }
145
+ const file = dshUpstreamCookieFile()
146
+ mkdirSync(dirname(file), { recursive: true })
147
+ writeFileSync(file, cookie + '\n', { mode: 0o600 })
148
+ chmodSync(file, 0o600)
149
+ return true
150
+ } catch (e) {
151
+ // 禁止记录带启动令牌的 URL 或 Cookie,只保留不含凭据的错误摘要。
152
+ logGateway('刷新 DSH 上游认证失败: ' + (e?.message || String(e)))
153
+ return false
154
+ }
155
+ }
156
+
157
+ function lanIPs() {
158
+ const out = [...configuredAdvertisedHosts()]
159
+ let groups
160
+ try { groups = Object.values(networkInterfaces()) } catch { return out }
161
+ for (const list of groups) {
162
+ for (const it of list ?? []) {
163
+ if (it.family === 'IPv4' && !it.internal && !out.includes(it.address)) out.push(it.address)
164
+ }
165
+ }
166
+ return out
167
+ }
168
+
169
+ function validAdvertisedHost(value) {
170
+ const host = String(value || '').trim()
171
+ if (!host || host.length > 253 || host === '0.0.0.0' || host === '127.0.0.1') return ''
172
+ if (!/^[A-Za-z0-9.-]+$/.test(host) || host.startsWith('.') || host.endsWith('.') || host.includes('..')) return ''
173
+ if (/^\d+(?:\.\d+){3}$/.test(host) && host.split('.').some(part => Number(part) > 255)) return ''
174
+ const labels = host.split('.')
175
+ if (labels.some(label => !label || label.length > 63 || label.startsWith('-') || label.endsWith('-'))) return ''
176
+ return host
177
+ }
178
+
179
+ function configuredAdvertisedHosts() {
180
+ return [...new Set(String(process.env.DSH_REMOTE_ADVERTISE_HOSTS || '')
181
+ .split(/[\s,]+/)
182
+ .map(validAdvertisedHost)
183
+ .filter(Boolean))]
184
+ }
185
+
186
+ function targetPath(pathname) {
187
+ let rel
188
+ try {
189
+ rel = decodeURIComponent(pathname.slice(MOUNT.length)) || '/'
190
+ } catch {
191
+ return null
192
+ }
193
+ const file = rel === '/' ? INDEX_FILE : rel.replace(/^\/+/, '')
194
+ const abs = resolve(PUBLIC_DIR, normalize(file))
195
+ if (abs !== PUBLIC_DIR && !abs.startsWith(PUBLIC_DIR)) return null
196
+ return abs
197
+ }
198
+
199
+ function sendJson(res, status, body) {
200
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
201
+ res.end(JSON.stringify(body))
202
+ }
203
+
204
+ function readBody(req, maxBytes) {
205
+ return new Promise((resolvePromise, reject) => {
206
+ const chunks = []; let size = 0, settled = false
207
+ req.on('data', (chunk) => {
208
+ if (settled) return
209
+ size += chunk.length
210
+ if (size > maxBytes) {
211
+ settled = true; chunks.length = 0
212
+ reject(Object.assign(new Error('body too large'), { status: 413 }))
213
+ return
214
+ }
215
+ chunks.push(chunk)
216
+ })
217
+ req.on('end', () => { if (!settled) { settled = true; resolvePromise(Buffer.concat(chunks).toString('utf8')) } })
218
+ req.on('error', reject)
219
+ req.once('aborted', () => reject(Object.assign(new Error('request aborted'), { status: 400 })))
220
+ })
221
+ }
222
+
223
+ /** 转发到本地网关管理 API;缺少令牌返回 null,超时与连接失败保留具体错误。 */
224
+ async function proxyGateway(path, method, body) {
225
+ const token = gatewayToken()
226
+ if (!token) return null
227
+ try {
228
+ const res = await fetch(`${gatewayBase()}${path}`, {
229
+ method,
230
+ headers: {
231
+ authorization: `Bearer ${token}`,
232
+ 'content-type': 'application/json',
233
+ 'x-dsh-remote-client': 'admin',
234
+ },
235
+ body: method === 'POST' ? body : undefined,
236
+ signal: AbortSignal.timeout(path === '/admin/api/relay' ? 18000 : path.startsWith('/admin/api/dsh') ? 15000 : 5000),
237
+ })
238
+ const json = await res.json().catch(() => ({ ok: false, error: `gateway ${res.status}` }))
239
+ return { status: res.status, json }
240
+ } catch (error) {
241
+ const timeout = error?.name === 'TimeoutError' || error?.name === 'AbortError'
242
+ return { status: timeout ? 504 : 502, json: { ok: false, code: timeout ? 'GATEWAY_TIMEOUT' : 'GATEWAY_UNREACHABLE',
243
+ error: timeout ? '本地网关响应超时,请稍后重试' : '无法连接本地网关,请检查网关运行状态' } }
244
+ }
245
+ }
246
+
247
+ /* ---------- 本地网关开关(持久化 + 自愈) ---------- */
248
+
249
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)) }
250
+
251
+ function runExit(cmd, args) {
252
+ return new Promise((resolvePromise) => {
253
+ let p
254
+ try { p = spawn(cmd, args, { stdio: 'ignore' }) }
255
+ catch { return resolvePromise(1) }
256
+ p.on('error', () => resolvePromise(1))
257
+ p.on('exit', (code) => resolvePromise(code ?? 1))
258
+ })
259
+ }
260
+
261
+ const GATEWAY_ENV_KEYS = [
262
+ 'TOKEN', 'TOKEN_FILE', 'DSH_REMOTE_TOKEN', 'DSH_REMOTE_DEVICE_KEYS', 'DSH_REMOTE_FS_ROOT', 'DSH_REMOTE_FS_WORKSPACE_CACHE_MS', 'DSH_REMOTE_FS_MAX_UPLOAD',
263
+ 'DSH_REMOTE_DSH_COOKIE_FILE',
264
+ 'DSH_REMOTE_NOTES', 'DSH_REMOTE_WORKBENCH', 'DSH_REMOTE_ADVERTISE_HOSTS', 'DSH_REMOTE_DSH_SERVICE', 'DSH_REMOTE_SYSTEMCTL', 'DSH_REMOTE_DSH_CONTROL_MODE',
265
+ 'DSH_REMOTE_AUTO_RESTART', 'DSH_REMOTE_CRASH_LOG_FILE',
266
+ 'DSH_REMOTE_DSH_CONTROL_TIMEOUT_MS', 'DSH_REMOTE_DSH_CONTROL_POLL_MS', 'DSH_REMOTE_FEEDBACK_URL',
267
+ 'UPDATE_CHECK_URL', 'UPDATE_INTERVAL_MS', 'UPDATE_PROXY', 'DSH_HEALTH_PATH',
268
+ 'GATEWAY_WS_IDLE_MS', 'GATEWAY_WS_PING_MS', 'GATEWAY_WS_PONG_TIMEOUT_MS',
269
+ 'GATEWAY_WS_UPGRADE_TIMEOUT_MS', 'GATEWAY_UPSTREAM_TIMEOUT_MS', 'GATEWAY_EVENT_BUFFER_MAX',
270
+ 'GATEWAY_WS_TICKET_TTL_MS',
271
+ 'GATEWAY_HTTP_REQUEST_TIMEOUT_MS', 'GATEWAY_HTTP_HEADERS_TIMEOUT_MS', 'GATEWAY_HTTP_KEEPALIVE_TIMEOUT_MS',
272
+ 'DSH_REMOTE_CORS_ORIGINS',
273
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
274
+ 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'
275
+ ]
276
+
277
+ function gatewaySystemdEnvArgs() {
278
+ const args = []
279
+ for (const key of GATEWAY_ENV_KEYS) {
280
+ const value = process.env[key]
281
+ if (value === undefined || /[\0\r\n]/.test(value)) continue
282
+ args.push('--setenv=' + key + '=' + value)
283
+ }
284
+ return args
285
+ }
286
+
287
+ /** 127.0.0.1 端口占用预检: 能连上=被占用, 连接被拒/超时=可用。 */
288
+ function portInUse(port) {
289
+ return new Promise((resolvePromise) => {
290
+ const host = new URL(upstreamUrlForListener({ host: readGatewayHost(), port })).hostname.replace(/^\[|\]$/g, '')
291
+ const sock = net.connect({ host, port: Number(port) })
292
+ let done = false
293
+ const finish = (used) => {
294
+ if (done) return
295
+ done = true
296
+ sock.destroy()
297
+ resolvePromise(used)
298
+ }
299
+ sock.once('connect', () => finish(true))
300
+ sock.once('error', () => finish(false))
301
+ sock.setTimeout(800, () => finish(false))
302
+ })
303
+ }
304
+
305
+ let gatewayHealthJob = null
306
+ /** Probe a loopback DSH origin with a short timeout; any non-5xx answer proves the listener is up. */
307
+ async function upstreamReachable(url) {
308
+ try {
309
+ const res = await fetch(String(url).replace(/\/+$/, '') + '/', { signal: AbortSignal.timeout(2500), redirect: 'manual' })
310
+ return res.status < 500
311
+ } catch { return false }
312
+ }
313
+ async function gatewayRunning() {
314
+ const base = gatewayBase()
315
+ if (gatewayHealthJob?.base === base) return gatewayHealthJob.promise
316
+ const job = { base }
317
+ gatewayHealthJob = job
318
+ job.promise = probeGatewayRunning(base).finally(() => { if (gatewayHealthJob === job) gatewayHealthJob = null })
319
+ return job.promise
320
+ }
321
+ async function probeGatewayRunning(base) {
322
+ try {
323
+ const res = await fetch(`${base}/health?probe=live`, { signal: AbortSignal.timeout(6000) })
324
+ if (!res.ok) return { running: false }
325
+ const data = await res.json().catch(() => ({}))
326
+ // Early 0.7.x live probes deliberately omit readiness/upstream fields.
327
+ // Recognize that exact compact shape without invoking the old, blocking
328
+ // full health check. Public health never authorizes a PID kill: takeover
329
+ // still requires the existing token and /admin/api/shutdown below.
330
+ const compact = data.ok === true && data.probe === 'live' && data.liveness?.ok === true
331
+ && !Object.hasOwn(data, 'pid') && !Object.hasOwn(data, 'upstream') && !Object.hasOwn(data, 'events')
332
+ const pid = compact ? data.liveness.pid : data.pid
333
+ if (data.service !== 'dsh-remote' || !Number.isInteger(pid) || pid <= 1
334
+ || typeof data.version !== 'string' || !data.version
335
+ || (!compact && (typeof data.upstream !== 'string' || !data.events?.mux || !data.events?.host))) return { running: false }
336
+ return {
337
+ running: true,
338
+ base,
339
+ pid,
340
+ version: typeof data.version === 'string' ? data.version : '',
341
+ upstream: typeof data.upstream === 'string' ? data.upstream : '',
342
+ upstreamOk: data.upstreamOk === true,
343
+ upstreamReachable: data.upstreamReachable !== false,
344
+ upstreamStatus: Number(data.upstreamStatus) || 0,
345
+ upstreamProbe: typeof data.upstreamProbe === 'string' ? data.upstreamProbe : '',
346
+ }
347
+ } catch {
348
+ return { running: false }
349
+ }
350
+ }
351
+
352
+ function gatewayPidFile() { return `${homedir()}/.dsh-remote/plugin-gateway.pid` }
353
+
354
+ function writeGatewayPid(pid) {
355
+ try {
356
+ mkdirSync(`${homedir()}/.dsh-remote`, { recursive: true })
357
+ writeFileSync(gatewayPidFile(), String(pid) + '\n')
358
+ } catch {}
359
+ }
360
+
361
+ function logGateway(msg) {
362
+ try {
363
+ mkdirSync(`${homedir()}/.dsh-remote`, { recursive: true })
364
+ appendFileSync(`${homedir()}/.dsh-remote/plugin-gateway.log`, `[${new Date().toISOString()}] ${msg}\n`)
365
+ } catch {}
366
+ }
367
+
368
+ async function killGateway(health) {
369
+ // PID 文件和公开健康响应不能证明进程归属;仅走网关认证关闭接口。
370
+ if (!health?.running || !Number.isInteger(health.pid) || health.pid <= 1) return false
371
+ const token = gatewayToken()
372
+ if (!token) return false
373
+ try {
374
+ const res = await fetch(`${health.base || gatewayBase()}/admin/api/shutdown`, {
375
+ method: 'POST', headers: { authorization: `Bearer ${token}`, 'x-dsh-remote-client': 'admin' },
376
+ signal: AbortSignal.timeout(2000),
377
+ })
378
+ const body = await res.json().catch(() => ({}))
379
+ if (!res.ok || body.ok !== true || body.bye !== true) return false
380
+ logGateway('已请求旧网关认证关闭')
381
+ await sleep(300)
382
+ return true
383
+ } catch (e) {
384
+ logGateway('认证关闭旧网关失败: ' + (e?.message || String(e)))
385
+ return false
386
+ }
387
+ }
388
+
389
+ /** 用户意图持久化在 ~/.dsh-remote/gateway.enabled: on=跟随 DSH 自启/自愈, off=手动停止。 */
390
+ function gatewayStateFile() { return `${homedir()}/.dsh-remote/gateway.enabled` }
391
+
392
+ function gatewayAutostart() {
393
+ if (process.env.DSH_REMOTE_AUTOSTART === '0') return false
394
+ try {
395
+ const v = readFileSync(gatewayStateFile(), 'utf8').trim()
396
+ return v !== 'off'
397
+ } catch {
398
+ return true // 全新安装: 默认自动拉起网关, 抽屉打开即有网关模式
399
+ }
400
+ }
401
+
402
+ function setGatewayEnabled(on) {
403
+ try {
404
+ mkdirSync(`${homedir()}/.dsh-remote`, { recursive: true })
405
+ writeFileSync(gatewayStateFile(), on ? 'on\n' : 'off\n')
406
+ } catch {}
407
+ }
408
+
409
+ /* ---------- 网关解释器解析 ----------
410
+ * Windows 不允许覆盖正在运行的可执行文件,而 DSH Desktop 的 NSIS 更新器会原地替换整棵
411
+ * 安装目录。旧实现用 process.execPath(桌面版即 DeepSeek Harness.exe) + detached 启动
412
+ * 常驻网关,等于让插件进程长期占用 DSH 安装目录,导致 DSH 自更新失败。因此网关解释器
413
+ * 必须位于安装目录之外,同时保留「网关活过 DSH 退出/重启」的既有设计。
414
+ *
415
+ * 选择顺序(取第一个通过校验的候选):
416
+ * 1. DSH_REMOTE_NODE: 绝对路径, -v 可执行且主版本 >= 18
417
+ * 2. PATH 中的 node: 同样校验
418
+ * 3. DSH Desktop 自带 runtime, 复制到 ~/.dsh-remote/runtime/node-<ver>(.exe)
419
+ * 4. process.execPath 兜底: 显式标记 runtimeInsideInstallDir 并写警告, 不允许静默降级
420
+ * 所有被跳过的候选及原因都会写进 ~/.dsh-remote/plugin-gateway.log。
421
+ */
422
+ export const GATEWAY_RUNTIME_MIN_MAJOR = 18
423
+ const GATEWAY_RUNTIME_DIR = ['.dsh-remote', 'runtime']
424
+
425
+ function runtimeProbeEnv() {
426
+ // 桌面版宿主进程的 process.execPath 是 Electron 可执行文件;探测它需要 node 语义。
427
+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
428
+ delete env.NODE_CHANNEL_FD
429
+ delete env.NODE_CHANNEL_SERIALIZATION_MODE
430
+ return env
431
+ }
432
+
433
+ /** 默认探测: 执行 `<candidate> -v`。返回 {ok, version, major, code, detail},绝不抛错。 */
434
+ let probeSequence = 0
435
+ function probeNodeVersion(file) {
436
+ // 用临时文件接收 stdout 而不是管道:受限环境/沙箱下 Node 无法创建管道句柄
437
+ // (spawn stdio:'pipe' 会 EPERM),写文件在各权限模式下都可用。
438
+ let fd = null
439
+ const outputFile = join(tmpdir(), 'dsh-remote-probe-' + process.pid + '-' + randomUUID().slice(0, 8) + '-' + (++probeSequence) + '.txt')
440
+ try {
441
+ fd = openSync(outputFile, 'w')
442
+ const spawned = spawnSync(file, ['-v'], {
443
+ timeout: 5000, windowsHide: true, env: runtimeProbeEnv(),
444
+ stdio: ['ignore', fd, 'ignore'],
445
+ })
446
+ try { closeSync(fd); fd = null } catch {}
447
+ if (spawned.error) {
448
+ return { ok: false, code: 'PROBE_FAILED', detail: String(spawned.error.code || spawned.error.message).slice(0, 160) }
449
+ }
450
+ const output = readFileSync(outputFile, 'utf8')
451
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(output || '').trim())
452
+ if (!match) return { ok: false, code: 'PROBE_FAILED', detail: '无法解析 node -v 输出' }
453
+ return { ok: true, version: `${match[1]}.${match[2]}.${match[3]}`, major: Number(match[1]) }
454
+ } catch (error) {
455
+ if (fd !== null) { try { closeSync(fd) } catch {} }
456
+ const detail = String(error?.code ? error.code + ' ' : '') + String(error?.message || error)
457
+ return { ok: false, code: 'PROBE_FAILED', detail: detail.slice(0, 160) }
458
+ } finally {
459
+ try { rmSync(outputFile, { force: true }) } catch {}
460
+ }
461
+ }
462
+
463
+ function normalizeNodeVersion(value) {
464
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value || '').trim())
465
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : ''
466
+ }
467
+
468
+ /** 比较真实路径;不存在的复制目标也解析最近的既有父目录,避免 junction 绕过边界。 */
469
+ function normalizeRuntimePath(value, platform) {
470
+ let text = String(value || '')
471
+ if (!text) return ''
472
+ try {
473
+ text = resolve(text)
474
+ let ancestor = text
475
+ const suffix = []
476
+ for (;;) {
477
+ try { text = join(realpathSync.native(ancestor), ...suffix); break } catch {}
478
+ const parent = dirname(ancestor)
479
+ if (parent === ancestor) break
480
+ suffix.unshift(basename(ancestor))
481
+ ancestor = parent
482
+ }
483
+ } catch { /* 无法规范化时保留原文;候选另有存在/可执行性校验。 */ }
484
+ if (platform === 'win32') text = text.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
485
+ if (platform === 'win32') text = text.toLowerCase().replaceAll('/', '\\')
486
+ return text.replace(/[\\/]+$/, '') || text
487
+ }
488
+
489
+ function isPathInsideDir(parent, child, platform) {
490
+ const parentPath = normalizeRuntimePath(parent, platform)
491
+ const childPath = normalizeRuntimePath(child, platform)
492
+ if (!parentPath || !childPath) return false
493
+ const separator = platform === 'win32' ? '\\' : '/'
494
+ return childPath === parentPath || childPath.startsWith(parentPath.endsWith(separator) ? parentPath : parentPath + separator)
495
+ }
496
+
497
+ function desktopBundledNodePath(installDir, platform) {
498
+ return join(installDir, 'resources', 'runtime', 'primary-runtime', 'dependencies', 'node', 'bin', platform === 'win32' ? 'node.exe' : 'node')
499
+ }
500
+
501
+ function runtimeCopyTarget(home, version, platform) {
502
+ return join(home, ...GATEWAY_RUNTIME_DIR, 'node-' + version + (platform === 'win32' ? '.exe' : ''))
503
+ }
504
+
505
+ function envPathValue(env) {
506
+ if (!env || typeof env !== 'object') return ''
507
+ const key = Object.keys(env).find(name => name.toLowerCase() === 'path')
508
+ const value = key ? env[key] : ''
509
+ return typeof value === 'string' ? value : ''
510
+ }
511
+
512
+ /** 按 PATH 顺序列出真实存在的 node 可执行文件;Windows 只看 node.exe(不解析 .cmd 垫片)。 */
513
+ function findPathNodeCandidates(env, platform) {
514
+ const names = platform === 'win32' ? ['node.exe'] : ['node']
515
+ const found = []
516
+ for (const rawEntry of envPathValue(env).split(platform === 'win32' ? ';' : ':')) {
517
+ const entry = rawEntry.trim().replace(/^"(.*)"$/, '$1')
518
+ if (!entry) continue
519
+ for (const name of names) {
520
+ const file = join(entry, name)
521
+ try { if (statSync(file).isFile()) found.push(file) } catch {}
522
+ }
523
+ }
524
+ return found
525
+ }
526
+
527
+ /** 默认复制实现: 先写 *.partial, 校验大小后原子 rename;失败清理半成品。 */
528
+ function copyNodeRuntimeFile(source, target) {
529
+ const dir = dirname(target)
530
+ const partial = target + '.' + process.pid + '.partial'
531
+ try {
532
+ const sourceStat = statSync(source)
533
+ if (!sourceStat.isFile() || sourceStat.size <= 0) return { ok: false, error: '源文件不可用' }
534
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
535
+ // 清理上次失败留下的半成品, 避免 90MB 级文件无限堆积。
536
+ try {
537
+ for (const name of readdirSync(dir)) {
538
+ if (name.startsWith(basename(target) + '.') && name.endsWith('.partial')) rmSync(join(dir, name), { force: true })
539
+ }
540
+ } catch {}
541
+ copyFileSync(source, partial)
542
+ try { chmodSync(partial, 0o755) } catch {}
543
+ const copiedStat = statSync(partial)
544
+ if (copiedStat.size !== sourceStat.size) throw new Error('复制后大小校验失败')
545
+ rmSync(target, { force: true })
546
+ renameSync(partial, target)
547
+ return { ok: true, bytes: copiedStat.size }
548
+ } catch (error) {
549
+ try { rmSync(partial, { force: true }) } catch {}
550
+ return { ok: false, error: error?.code || error?.message || 'COPY_FAILED' }
551
+ }
552
+ }
553
+
554
+ function insideInstallDirWarning(platform) {
555
+ return platform === 'win32'
556
+ ? '本次网关解释器位于 DSH 安装目录内,DSH 更新可能失败;请安装 Node.js 18+ 到系统 PATH,或设置 DSH_REMOTE_NODE 指向安装目录外的 node。'
557
+ : '本次网关解释器位于 DSH 安装目录内;建议设置 DSH_REMOTE_NODE 或安装系统 Node.js 18+,避免网关占用安装目录。'
558
+ }
559
+
560
+ /**
561
+ * 解析并校验网关解释器。永远返回可用结果(最差为 process.execPath 兜底),不抛错。
562
+ * 全部选项均可注入,便于在临时目录中测试真实的启动策略。
563
+ */
564
+ export async function resolveGatewayRuntime(options = {}) {
565
+ const env = options.env && typeof options.env === 'object' ? options.env : process.env
566
+ const platform = options.platform || process.platform
567
+ const home = options.home || homedir()
568
+ const execPath = resolve(typeof options.execPath === 'string' && options.execPath ? options.execPath : process.execPath)
569
+ const installDir = dirname(execPath)
570
+ const desktopHost = options.desktopHost === undefined
571
+ ? Boolean(process.versions.electron) || existsSync(join(installDir, 'resources', 'app.asar'))
572
+ : options.desktopHost === true
573
+ const probe = typeof options.probe === 'function' ? options.probe : probeNodeVersion
574
+ const copyRuntime = typeof options.copyRuntime === 'function' ? options.copyRuntime : copyNodeRuntimeFile
575
+ const log = typeof options.log === 'function' ? options.log : logGateway
576
+
577
+ const attempts = []
578
+ const candidates = []
579
+ const seen = new Set()
580
+ let copy = null
581
+
582
+ const addAttempt = (source, candidate, ok, code, detail) => {
583
+ attempts.push({ source, candidate: candidate || '', ok: !!ok, code, detail: detail || '' })
584
+ }
585
+ const skip = (source, candidate, code, detail) => {
586
+ addAttempt(source, candidate, false, code, detail)
587
+ log('网关解释器候选跳过: ' + source + ' ' + (candidate || '(未提供)') + ' - ' + (detail || code))
588
+ return null
589
+ }
590
+ const runProbe = async (file) => {
591
+ try {
592
+ const result = await Promise.resolve(probe(file))
593
+ return result && typeof result === 'object' ? result : { ok: false, code: 'PROBE_FAILED', detail: '无效的探测结果' }
594
+ } catch (error) {
595
+ return { ok: false, code: 'PROBE_FAILED', detail: String(error?.message || error).slice(0, 160) }
596
+ }
597
+ }
598
+ const accept = (source, executable, version, major, reused) => {
599
+ const key = normalizeRuntimePath(executable, platform)
600
+ if (seen.has(key)) return false
601
+ seen.add(key)
602
+ candidates.push({ executable, source, version, major, insideInstallDir: false, reused: !!reused, valid: true })
603
+ addAttempt(source, executable, true, 'OK', reused ? '复用已存在的 node ' + version + ' 副本' : '')
604
+ log('网关解释器: ' + source + ' -> ' + executable + ' (node ' + version + ')')
605
+ return true
606
+ }
607
+ /** 校验一个 node 候选: 绝对路径/存在/边界/probe/版本。boundary=false 用于安装目录内的复制源。 */
608
+ const checkNode = async (source, rawCandidate, { boundary = true } = {}) => {
609
+ if (typeof rawCandidate !== 'string' || !rawCandidate.trim()) return skip(source, '', 'MISSING', '路径为空')
610
+ if (!isAbsolute(rawCandidate)) return skip(source, rawCandidate, 'NOT_ABSOLUTE', '不是绝对路径')
611
+ const candidate = resolve(rawCandidate)
612
+ if (!existsSync(candidate)) return skip(source, candidate, 'MISSING', '文件不存在')
613
+ try { if (!statSync(candidate).isFile()) return skip(source, candidate, 'MISSING', '不是文件') } catch { return skip(source, candidate, 'MISSING', '无法读取文件信息') }
614
+ if (boundary && desktopHost && isPathInsideDir(installDir, candidate, platform)) {
615
+ return skip(source, candidate, 'INSIDE_INSTALL_DIR', '位于 DSH 安装目录内, 会阻止 DSH 原地更新')
616
+ }
617
+ const probed = await runProbe(candidate)
618
+ if (!probed.ok) return skip(source, candidate, 'PROBE_FAILED', '无法执行 -v: ' + (probed.detail || '未知错误'))
619
+ const version = normalizeNodeVersion(probed.version)
620
+ const major = Number(probed.major) || Number((/(\d+)\./.exec(version) || [])[1]) || 0
621
+ if (!version || !Number.isFinite(major) || major < GATEWAY_RUNTIME_MIN_MAJOR) {
622
+ return skip(source, candidate, 'VERSION_TOO_OLD', 'node ' + (version || String(probed.version || '?')) + ' < ' + GATEWAY_RUNTIME_MIN_MAJOR)
623
+ }
624
+ return { executable: candidate, version, major }
625
+ }
626
+
627
+ // 1) DSH_REMOTE_NODE
628
+ const envNode = typeof env.DSH_REMOTE_NODE === 'string' ? env.DSH_REMOTE_NODE.trim() : ''
629
+ if (envNode) {
630
+ const checked = await checkNode('env', envNode)
631
+ if (checked) accept('env', checked.executable, checked.version, checked.major, false)
632
+ }
633
+
634
+ // 2) PATH 中的 node
635
+ const pathCandidates = findPathNodeCandidates(env, platform)
636
+ if (!pathCandidates.length) skip('path', '', 'NOT_FOUND', 'PATH 中没有找到 node')
637
+ for (const file of pathCandidates) {
638
+ const checked = await checkNode('path', file)
639
+ if (checked && accept('path', checked.executable, checked.version, checked.major, false)) break
640
+ }
641
+
642
+ // 3) 按需准备内置副本:没有外部候选,或外部候选实际启动失败时才复制。
643
+ let desktopPrepared = false
644
+ const prepareDesktopRuntime = async () => {
645
+ if (!desktopHost || desktopPrepared) return null
646
+ desktopPrepared = true
647
+ const previousCount = candidates.length
648
+ const source = desktopBundledNodePath(installDir, platform)
649
+ if (!existsSync(source)) {
650
+ skip('desktop-runtime', source, 'SOURCE_MISSING', '未找到桌面版自带 node 运行时')
651
+ } else {
652
+ const sourceChecked = await checkNode('desktop-runtime', source, { boundary: false })
653
+ if (sourceChecked) {
654
+ const target = runtimeCopyTarget(home, sourceChecked.version, platform)
655
+ if (desktopHost && isPathInsideDir(installDir, target, platform)) {
656
+ skip('desktop-runtime', target, 'INSIDE_INSTALL_DIR', 'node 副本目标位于 DSH 安装目录内')
657
+ } else {
658
+ const existingProbe = existsSync(target) ? await runProbe(target) : null
659
+ if (existingProbe?.ok && normalizeNodeVersion(existingProbe.version) === sourceChecked.version) {
660
+ copy = { source, target, version: sourceChecked.version, reused: true, bytes: safeFileSize(target) }
661
+ accept('desktop-runtime', target, sourceChecked.version, sourceChecked.major, true)
662
+ } else {
663
+ let copied = null
664
+ try { copied = await copyRuntime(source, target) } catch (error) { copied = { ok: false, error: error?.message || String(error) } }
665
+ if (!copied?.ok) {
666
+ skip('desktop-runtime', target, 'COPY_FAILED', '复制 node 运行时失败: ' + (copied?.error || '未知错误'))
667
+ } else {
668
+ const verified = await runProbe(target)
669
+ if (!verified?.ok || normalizeNodeVersion(verified.version) !== sourceChecked.version) {
670
+ try { rmSync(target, { force: true }) } catch {}
671
+ skip('desktop-runtime', target, 'COPY_PROBE_FAILED', '副本无法执行或版本不符: ' + (verified?.detail || normalizeNodeVersion(verified?.version) || '未知错误'))
672
+ } else {
673
+ const bytes = Number(copied.bytes) || safeFileSize(target)
674
+ copy = { source, target, version: sourceChecked.version, reused: false, bytes }
675
+ log('已复制网关解释器: ' + source + ' -> ' + target + ' (' + bytes + ' B)')
676
+ accept('desktop-runtime', target, sourceChecked.version, sourceChecked.major, false)
677
+ }
678
+ }
679
+ }
680
+ }
681
+ }
682
+ }
683
+ return candidates[previousCount] || null
684
+ }
685
+ if (!candidates.length) await prepareDesktopRuntime()
686
+
687
+ // 4) 兜底 process.execPath: 即使探测失败也保留为最后尝试,但必须显式记录
688
+ const hostKey = normalizeRuntimePath(execPath, platform)
689
+ if (!seen.has(hostKey)) {
690
+ const probed = await runProbe(execPath)
691
+ const version = probed.ok ? normalizeNodeVersion(probed.version) : ''
692
+ const major = probed.ok ? (Number(probed.major) || Number((/(\d+)\./.exec(version) || [])[1]) || 0) : 0
693
+ const insideInstallDir = desktopHost && isPathInsideDir(installDir, execPath, platform)
694
+ candidates.push({ executable: execPath, source: 'host', version, major, insideInstallDir, reused: false, valid: probed.ok })
695
+ seen.add(hostKey)
696
+ addAttempt('host', execPath, probed.ok, probed.ok ? 'OK' : 'PROBE_FAILED', probed.ok ? '' : '无法执行 -v: ' + (probed.detail || '未知错误'))
697
+ if (probed.ok) log('网关解释器兜底: host -> ' + execPath + ' (node ' + version + ')')
698
+ else log('网关解释器兜底: host -> ' + execPath + ' (探测失败, 仍作为最后尝试)')
699
+ }
700
+
701
+ const selected = candidates[0]
702
+ const warning = selected?.insideInstallDir ? insideInstallDirWarning(platform) : ''
703
+ if (warning) log('警告: ' + warning)
704
+ const plan = {
705
+ executable: selected.executable,
706
+ source: selected.source,
707
+ version: selected.version,
708
+ major: selected.major,
709
+ installDir,
710
+ desktopHost,
711
+ platform,
712
+ insideInstallDir: !!selected.insideInstallDir,
713
+ // 提示词/文档使用的显式标记名;insideInstallDir 是内部与状态字段名,二者保持同义。
714
+ runtimeInsideInstallDir: !!selected.insideInstallDir,
715
+ warning,
716
+ candidates,
717
+ attempts,
718
+ copy,
719
+ }
720
+ plan.prepareDesktopFallback = async () => {
721
+ const candidate = await prepareDesktopRuntime()
722
+ plan.copy = copy
723
+ if (candidate) {
724
+ // accept() 追加的新候选应排在 host 兜底之前。
725
+ candidates.splice(candidates.indexOf(candidate), 1)
726
+ const hostIndex = candidates.findIndex(entry => entry.source === 'host')
727
+ candidates.splice(hostIndex < 0 ? candidates.length : hostIndex, 0, candidate)
728
+ }
729
+ return candidate
730
+ }
731
+ return plan
732
+ }
733
+
734
+ function safeFileSize(file) {
735
+ try { return statSync(file).size } catch { return 0 }
736
+ }
737
+
738
+ function gatewayRuntimeSummary(plan) {
739
+ if (!plan) return null
740
+ return {
741
+ executable: plan.executable,
742
+ source: plan.source,
743
+ version: plan.version,
744
+ major: plan.major,
745
+ installDir: plan.installDir,
746
+ desktopHost: plan.desktopHost,
747
+ insideInstallDir: plan.insideInstallDir,
748
+ runtimeInsideInstallDir: plan.runtimeInsideInstallDir ?? plan.insideInstallDir,
749
+ warning: plan.warning,
750
+ copy: plan.copy ? { target: plan.copy.target, version: plan.copy.version, reused: plan.copy.reused } : null,
751
+ attempts: plan.attempts.map(entry => ({ source: entry.source, ok: entry.ok, code: entry.code, detail: entry.detail })),
752
+ }
753
+ }
754
+
755
+ let gatewayRuntimePlanPromise = null
756
+ let gatewayRuntimeState = null
757
+ let gatewayRuntimeStartedPid = 0
758
+ let gatewayRuntimeSupervisorPid = 0
759
+
760
+ /** 解析结果按进程缓存(环境变量变化需重启 DSH);解析失败也回退为显式警告而不是静默。 */
761
+ function gatewayRuntimePlan() {
762
+ if (!gatewayRuntimePlanPromise) {
763
+ gatewayRuntimePlanPromise = (async () => {
764
+ let plan
765
+ try {
766
+ plan = await resolveGatewayRuntime()
767
+ } catch (error) {
768
+ const installDir = dirname(resolve(process.execPath))
769
+ const warning = '网关解释器解析失败,回退到 DSH 可执行文件,DSH 更新可能失败: ' + (error?.message || error)
770
+ logGateway('警告: ' + warning)
771
+ plan = {
772
+ executable: process.execPath, source: 'host', version: '', major: 0, installDir,
773
+ desktopHost: Boolean(process.versions.electron), insideInstallDir: true, warning,
774
+ candidates: [{ executable: process.execPath, source: 'host', version: '', major: 0, insideInstallDir: true, reused: false, valid: false }],
775
+ attempts: [], copy: null,
776
+ }
777
+ }
778
+ return plan
779
+ })()
780
+ }
781
+ return gatewayRuntimePlanPromise
782
+ }
783
+
784
+ /** 仅报告绑定到当前 worker PID 的实际解释器;解析计划不能证明现存网关用了它。 */
785
+ async function gatewayRuntimeForStatus(reported, health) {
786
+ const current = health || await gatewayRunning()
787
+ if (!current.running) return null
788
+ if (gatewayRuntimeState?.pid === current.pid) return gatewayRuntimeState
789
+ if (reported === undefined) {
790
+ const response = await proxyGateway('/admin/api/runtime', 'GET', '')
791
+ reported = response?.status === 200 && response.json.ok === true ? response.json.gatewayRuntime : null
792
+ }
793
+ if (reported?.pid !== current.pid || typeof reported.executable !== 'string' || !isAbsolute(reported.executable)) {
794
+ return { source: 'unknown', pid: current.pid, executable: '', version: '', insideInstallDir: null,
795
+ runtimeInsideInstallDir: null, warning: '当前网关未报告实际解释器;请停止并重新启动网关后确认。' }
796
+ }
797
+ const plan = await gatewayRuntimePlan()
798
+ if (gatewayRuntimeSupervisorPid && reported.supervisorPid === gatewayRuntimeSupervisorPid) gatewayRuntimeStartedPid = current.pid
799
+ const matched = plan.candidates.find(candidate => normalizeRuntimePath(candidate.executable, process.platform) === normalizeRuntimePath(reported.executable, process.platform))
800
+ const version = normalizeNodeVersion(reported.version)
801
+ const actual = { executable: reported.executable, source: matched?.source || 'external', version,
802
+ major: Number(version.split('.')[0]) || 0, insideInstallDir: plan.desktopHost && isPathInsideDir(plan.installDir, reported.executable, process.platform) }
803
+ gatewayRuntimeState = { ...gatewayRuntimeStateFor(plan, actual), pid: current.pid }
804
+ return gatewayRuntimeState
805
+ }
806
+
807
+ function gatewayRuntimeStateFor(plan, candidate) {
808
+ const used = { ...plan, executable: candidate.executable, source: candidate.source, version: candidate.version, major: candidate.major,
809
+ insideInstallDir: !!candidate.insideInstallDir, runtimeInsideInstallDir: !!candidate.insideInstallDir }
810
+ // 实际启动可能回退到 host(安装目录内)候选: 必须重新给出对应警告,不能沿用首选候选的空 warning。
811
+ const usedWarning = used.insideInstallDir ? (plan.warning || insideInstallDirWarning(plan.platform || process.platform)) : ''
812
+ if (usedWarning) logGateway('警告: ' + usedWarning)
813
+ return { ...gatewayRuntimeSummary({ ...used, warning: usedWarning }), at: Date.now() }
814
+ }
815
+
816
+ /** 启动随插件分发的 gateway.cjs; 已运行则直接返回。 */
817
+ const GATEWAY_AUTH_HINT = '网关正在运行,但管理认证不可用。请检查 TOKEN_FILE、TOKEN / DSH_REMOTE_TOKEN 与文件权限;若旧网关无法恢复令牌,请在主机上确认进程归属后手动重启网关,再刷新此页。'
818
+
819
+ async function startGateway() {
820
+ const upstream = upstreamUrlForListener(dshListen)
821
+ const health = await gatewayRunning()
822
+ if (health.running) {
823
+ const auth = await proxyGateway('/admin/api/state', 'GET', '')
824
+ if (!auth || auth.status !== 200 || auth.json.ok !== true) {
825
+ return { ok: false, running: true, started: false, error: auth?.status === 401 || auth?.status === 403 ? GATEWAY_AUTH_HINT : auth?.json?.error || '本地网关管理接口响应异常,请稍后重试' }
826
+ }
827
+ await gatewayRuntimeForStatus(auth.json.gatewayRuntime ?? null, health)
828
+ setGatewayEnabled(true)
829
+ return { ok: true, running: true, started: false }
830
+ }
831
+ const script = GATEWAY_SCRIPT
832
+ if (!existsSync(script)) {
833
+ return { ok: false, running: false, error: '插件包缺少 gateway.cjs, 请升级插件' }
834
+ }
835
+ const port = readGatewayPort()
836
+ const host = readGatewayHost()
837
+ if (await portInUse(port)) {
838
+ logGateway(`端口 ${port} 已被占用, 拒绝启动`)
839
+ return { ok: false, running: false, error: `端口 ${port} 已被占用,请在插件页修改网关端口后重试` }
840
+ }
841
+ // Windows 上运行中的 exe 不能被覆盖,网关解释器必须位于 DSH 安装目录之外,
842
+ // 否则 DSH 原地更新(NSIS 替换整棵安装目录)会被插件进程挡住。
843
+ // 顺序: DSH_REMOTE_NODE > PATH node > 桌面版内置 runtime 副本 > process.execPath(显式警告)。
844
+ const runtime = await gatewayRuntimePlan()
845
+ logGateway('启动网关, 端口: ' + port + ', 上游: ' + upstream + ', 解释器: ' + runtime.executable
846
+ + ' (' + runtime.source + (runtime.version ? ', node ' + runtime.version : '') + ')')
847
+
848
+ // Windows locks a process's current directory. Keep both supervisor and
849
+ // worker outside the replaceable node_modules package during self-update.
850
+ const gatewayCwd = `${homedir()}/.dsh-remote`
851
+ let cwdReady = false
852
+ try { mkdirSync(gatewayCwd, { recursive: true }); cwdReady = true } catch {}
853
+
854
+ /** 最多等 4 秒; 超过可能是端口冲突或首次初始化, 前端稍后刷新即可。 */
855
+ const waitGatewayReady = async () => {
856
+ for (let i = 0; i < 16; i++) {
857
+ await sleep(250)
858
+ const healthNow = await gatewayRunning()
859
+ if (healthNow.running) return healthNow
860
+ }
861
+ return null
862
+ }
863
+ const startedResult = (candidate, healthNow) => {
864
+ if (healthNow.pid) writeGatewayPid(healthNow.pid)
865
+ gatewayRuntimeStartedPid = healthNow.pid
866
+ gatewayRuntimeState = { ...gatewayRuntimeStateFor(runtime, candidate), pid: healthNow.pid }
867
+ setGatewayEnabled(true)
868
+ return { ok: true, running: true, started: true, runtime: gatewayRuntimeState }
869
+ }
870
+
871
+ // 逐个候选尝试: 解释器立即退出/无法执行时回退下一候选,绝不静默改回 process.execPath。
872
+ const failures = []
873
+ async function* runtimeCandidates() {
874
+ // 快照防止按需准备副本时修改 candidates,导致重复启动或漏掉候选。
875
+ for (const candidate of [...runtime.candidates]) {
876
+ if (candidate.source === 'host' && runtime.prepareDesktopFallback) {
877
+ const fallback = await runtime.prepareDesktopFallback()
878
+ if (fallback) yield fallback
879
+ }
880
+ yield candidate
881
+ }
882
+ }
883
+ for await (const candidate of runtimeCandidates()) {
884
+ // 首选 systemd-run: 网关成为独立 user 单元, DSH 重启/升级不会连带杀掉它
885
+ let sysd = false
886
+ try {
887
+ await runExit('systemctl', ['--user', 'reset-failed', 'dsh-remote-gateway'])
888
+ sysd = (await runExit('systemd-run', [
889
+ '--user', '--unit=dsh-remote-gateway', '--service-type=exec',
890
+ ...gatewaySystemdEnvArgs(),
891
+ '--setenv=PORT=' + port, '--setenv=HOST=' + host, '--setenv=DSH_UPSTREAM=' + upstream,
892
+ '--', candidate.executable, script, '--supervise',
893
+ ])) === 0
894
+ } catch {}
895
+ if (sysd) {
896
+ try {
897
+ const pid = Number(execFileSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', 'dsh-remote-gateway'], { encoding: 'utf8' }).trim())
898
+ if (Number.isFinite(pid) && pid > 1) { writeGatewayPid(pid); gatewayRuntimeSupervisorPid = pid }
899
+ } catch {}
900
+ const healthNow = await waitGatewayReady()
901
+ if (healthNow) return startedResult(candidate, healthNow)
902
+ // 单元立即失败(解释器不可执行等)才换候选;仍在启动时可能只是慢,不重复拉起。
903
+ const unitState = gatewaySystemdUnitState()
904
+ failures.push({ executable: candidate.executable, reason: 'systemd 单元 ' + (unitState || '未就绪') })
905
+ logGateway('解释器 ' + candidate.executable + ' 的 systemd 单元未就绪(' + (unitState || '未知状态') + '), 尝试下一候选')
906
+ if (unitState === 'activating' || unitState === 'active') return { ok: true, running: false, pending: true, hint: '网关启动中, 稍后刷新' }
907
+ continue
908
+ }
909
+
910
+ // 无 systemd 的机器回退: detached 子进程
911
+ if (!cwdReady) return { ok: false, running: false, error: '无法创建网关运行目录,请检查用户目录权限' }
912
+ let logFd = null
913
+ try {
914
+ logFd = openSync(`${homedir()}/.dsh-remote/plugin-gateway.log`, 'a')
915
+ } catch {}
916
+ const gatewayEnv = { ...process.env, PORT: port, HOST: host, DSH_UPSTREAM: upstream }
917
+ delete gatewayEnv.NODE_CHANNEL_FD
918
+ delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
919
+ let child = null
920
+ try {
921
+ // Windows: a detached console child gets its own console window. Without
922
+ // windowsHide the user sees a stray black window, and closing that window
923
+ // terminates the gateway. Keep the supervisor invisible and log-only.
924
+ child = spawn(candidate.executable, [script, '--supervise'], {
925
+ cwd: gatewayCwd,
926
+ detached: true,
927
+ windowsHide: true,
928
+ stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
929
+ env: gatewayEnv,
930
+ })
931
+ } catch (error) {
932
+ failures.push({ executable: candidate.executable, reason: 'spawn 失败: ' + (error?.message || error) })
933
+ logGateway('解释器 ' + candidate.executable + ' 无法启动网关: ' + (error?.message || error) + ', 尝试下一候选')
934
+ continue
935
+ } finally {
936
+ if (logFd !== null) { try { closeSync(logFd) } catch {} }
937
+ }
938
+ let exited = null
939
+ child.once('exit', (code, signal) => { exited = { code, signal } })
940
+ child.once('error', (error) => { exited = { code: null, error: error?.message || String(error) } })
941
+ child.unref()
942
+ if (Number.isInteger(child.pid) && child.pid > 1) { writeGatewayPid(child.pid); gatewayRuntimeSupervisorPid = child.pid }
943
+ let healthNow = null
944
+ for (let i = 0; i < 16; i++) {
945
+ await sleep(250)
946
+ const healthProbe = await gatewayRunning()
947
+ if (healthProbe.running) { healthNow = healthProbe; break }
948
+ if (exited) break
949
+ }
950
+ if (healthNow) return startedResult(candidate, healthNow)
951
+ if (exited) {
952
+ const detail = 'code=' + exited.code + (exited.signal ? ' signal=' + exited.signal : '') + (exited.error ? ' error=' + exited.error : '')
953
+ failures.push({ executable: candidate.executable, reason: '立即退出(' + detail + ')' })
954
+ logGateway('解释器 ' + candidate.executable + ' 启动的网关立即退出(' + detail + '), 尝试下一候选')
955
+ continue
956
+ }
957
+ // 进程仍活着但 4 秒内未就绪: 保持原行为等待前端刷新,不重复启动第二个网关。
958
+ return { ok: true, running: false, pending: true, hint: '网关启动中, 稍后刷新' }
959
+ }
960
+ const failureDetail = failures.map(item => item.executable + ' (' + item.reason + ')').join('; ')
961
+ logGateway('网关启动失败: 所有解释器候选均未成功: ' + failureDetail)
962
+ return {
963
+ ok: false, running: false,
964
+ error: '网关启动失败: ' + failures.length + ' 个解释器候选均未成功' + (runtime.warning ? ';' + runtime.warning : ''),
965
+ runtime: gatewayRuntimeState || gatewayRuntimeSummary(runtime),
966
+ }
967
+ }
968
+
969
+ function gatewaySystemdUnitState() {
970
+ try {
971
+ return String(execFileSync('systemctl', ['--user', 'show', '-p', 'ActiveState', '--value', 'dsh-remote-gateway'], {
972
+ encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'],
973
+ })).trim()
974
+ } catch { return '' }
975
+ }
976
+
977
+ let ensurePromise = null
978
+ /** 自愈入口: 状态轮询/DSH 启动时调用。开关为 on 且网关没起来, 就自动拉起(并发只拉一次)。 */
979
+ function ensureGateway() {
980
+ if (!gatewayAutostart()) return Promise.resolve(false)
981
+ if (ensurePromise) return ensurePromise
982
+ ensurePromise = (async () => {
983
+ try {
984
+ // 提前解析解释器(结果缓存):即使网关已在运行,插件页也能显示实际选择与理由。
985
+ const runtime = await gatewayRuntimePlan()
986
+ await refreshDshUpstreamCookie()
987
+ const health = await gatewayRunning()
988
+ if (!health.running) {
989
+ const out = await startGateway()
990
+ return !!out.running
991
+ }
992
+ const upstream = upstreamUrlForListener(dshListen)
993
+ const oldUpstream = health.upstream || ''
994
+ const oldVersion = health.version || '?'
995
+ const versionMismatch = oldVersion !== version
996
+ const actualRuntime = runtime.desktopHost ? await gatewayRuntimeForStatus(undefined, health) : null
997
+ // DSH 重启后接管遗留的宿主解释器,或应用新的外部解释器配置。
998
+ // 本进程已尝试并回退的实例不再反复重启,避免坏候选导致重启风暴。
999
+ const runtimeMismatch = runtime.desktopHost && gatewayRuntimeStartedPid !== health.pid
1000
+ && !runtime.insideInstallDir && actualRuntime?.executable
1001
+ && normalizeRuntimePath(actualRuntime.executable, process.platform) !== normalizeRuntimePath(runtime.executable, process.platform)
1002
+ // 上游暂时不可达不应重启网关: VPN/DSH 重启/短暂网络抖动时,
1003
+ // 重启只能制造额外断线,网关应保持运行并通过 /health 暴露 degraded 状态。
1004
+ const upstreamChanged = (oldUpstream && oldUpstream !== upstream) || (!oldUpstream && upstream)
1005
+ if (versionMismatch || runtimeMismatch || upstreamChanged) {
1006
+ logGateway(`网关需刷新: 版本 ${oldVersion} -> ${version}, 上游 ${oldUpstream || '?'} -> ${upstream}`)
1007
+ if (runtimeMismatch) logGateway('网关解释器需迁移: ' + actualRuntime.executable + ' -> ' + runtime.executable)
1008
+ // DSH desktop restarts on a new loopback port. A live gateway can repoint its
1009
+ // upstream in place, which keeps the relay control channel and public path up;
1010
+ // only a version/runtime change still needs a gateway restart.
1011
+ if (upstreamChanged && oldUpstream && !versionMismatch && !runtimeMismatch) {
1012
+ const reachable = await upstreamReachable(upstream)
1013
+ const swapped = reachable ? await proxyGateway('/admin/api/upstream', 'POST', JSON.stringify({ url: upstream })) : null
1014
+ if (swapped?.status === 200 && swapped.json?.ok === true) {
1015
+ logGateway(`上游已热切换: ${oldUpstream} -> ${upstream}`)
1016
+ return true
1017
+ }
1018
+ logGateway(`上游热切换未生效(${reachable ? swapped?.json?.error || swapped?.status || 'unknown' : '上游暂不可达'}), 回退重启网关`)
1019
+ }
1020
+ if (!await killGateway(health)) {
1021
+ logGateway('拒绝自动重启: 无法通过认证关闭旧网关,请检查令牌或端口占用')
1022
+ return false
1023
+ }
1024
+ for (let i = 0; i < 10; i++) {
1025
+ if (!(await gatewayRunning()).running) break
1026
+ await sleep(200)
1027
+ }
1028
+ const out = await startGateway()
1029
+ return !!out.running
1030
+ }
1031
+ return true
1032
+ } finally {
1033
+ setTimeout(() => { ensurePromise = null }, 4000)
1034
+ }
1035
+ })()
1036
+ return ensurePromise
1037
+ }
1038
+
1039
+ /** 通过网关自身的 /admin/api/shutdown 优雅停止(不管它当初是谁拉起的); 并写入 off 防自愈拉起。 */
1040
+ async function stopGateway() {
1041
+ const health = await gatewayRunning()
1042
+ if (!await killGateway(health)) return { ok: false, running: health.running, error: health.running ? GATEWAY_AUTH_HINT : '网关未运行' }
1043
+ setGatewayEnabled(false)
1044
+ return { ok: true, running: false, bye: true }
1045
+ }
1046
+
1047
+ // ---------- 统计事件投递(实时 assistant/message + usage -> 网关 /stats/ingest) ----------
1048
+ // 网关未运行时静默失败: 网关启动后会按 seq 游标扫描 session.jsonl.zstd 补齐。
1049
+ const statsQueues = new Map() // sessionId -> Promise 串行队列(保证 seq 顺序)
1050
+
1051
+ function statsSend(session, event) {
1052
+ if (event.type !== 'assistant/message') return
1053
+ const usage = event.data?.usage
1054
+ if (!usage || typeof usage !== 'object') return
1055
+ const token = gatewayToken()
1056
+ if (!token) return
1057
+ let fallbackModel = ''
1058
+ try { fallbackModel = session.requestContext?.()?.model || '' } catch {}
1059
+ const payload = {
1060
+ sessionId: session.id,
1061
+ fallbackModel,
1062
+ event: {
1063
+ type: 'assistant/message',
1064
+ seq: event.seq,
1065
+ time: event.time,
1066
+ data: {
1067
+ usage: {
1068
+ inputTokens: usage.inputTokens,
1069
+ outputTokens: usage.outputTokens,
1070
+ cacheReadTokens: usage.cacheReadTokens,
1071
+ cacheWriteTokens: usage.cacheWriteTokens,
1072
+ },
1073
+ message: { source: { model: event.data?.message?.source?.model || '' } },
1074
+ },
1075
+ },
1076
+ }
1077
+ const prev = statsQueues.get(session.id) || Promise.resolve()
1078
+ const next = prev.then(async () => {
1079
+ try {
1080
+ await fetch(`${gatewayBase()}/stats/ingest`, {
1081
+ method: 'POST',
1082
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
1083
+ body: JSON.stringify(payload),
1084
+ signal: AbortSignal.timeout(2000),
1085
+ })
1086
+ } catch {}
1087
+ }).finally(() => {
1088
+ if (statsQueues.get(session.id) === next) statsQueues.delete(session.id)
1089
+ })
1090
+ statsQueues.set(session.id, next)
1091
+ }
1092
+
1093
+ /** 从 sessionId 解析 DSH Agent:优先取已发布 live agent,否则走 resume。返回 { agent, resolvePath } 便于定位。 */
1094
+ async function resolveAgent(ctx, sessionId) {
1095
+ if (!ctx.agents) return { agent: null, resolvePath: 'no-agents-service' }
1096
+ let live
1097
+ try {
1098
+ live = ctx.agents.get(sessionId)
1099
+ } catch (e) {
1100
+ live = undefined
1101
+ }
1102
+ if (live) return { agent: live, resolvePath: 'live' }
1103
+ try {
1104
+ const handle = await ctx.agents.resume({ resumeSessionId: sessionId })
1105
+ if (!handle || !handle.agent) return { agent: null, resolvePath: 'resume-empty-handle' }
1106
+ return { agent: handle.agent, resolvePath: 'resume' }
1107
+ } catch (e) {
1108
+ return { agent: null, resolvePath: 'resume-error' }
1109
+ }
1110
+ }
1111
+
1112
+ function commandHead(line) {
1113
+ const match = /^\/+(\S+)/.exec(String(line || '').trim())
1114
+ return match ? match[1].replace(/^\/+/, '') : ''
1115
+ }
1116
+
1117
+ function commandEntryName(entry) {
1118
+ const value = typeof entry === 'string' ? entry : entry?.name
1119
+ return String(value || '').trim().replace(/^\/+/, '')
1120
+ }
1121
+
1122
+ function commandWasExecuted(result) {
1123
+ // DSH 0.1.x 的 commands.execute() 成功时可以返回 void。只要 Promise 正常
1124
+ // 完成,就不应把同一条 /command 再降级为 session.prompt 的普通文本;只有
1125
+ // 执行器明确返回 false / { executed: false } 才表示未处理。
1126
+ return result !== false && result?.executed !== false
1127
+ }
1128
+
1129
+ function remoteCommandAuthorized(req) {
1130
+ const expected = gatewayToken()
1131
+ return !!expected && req.headers.authorization === `Bearer ${expected}`
1132
+ }
1133
+
1134
+ function commandOperationSnapshot(operation) {
1135
+ if (!operation) return { active: false, phase: 'idle', command: '', startedAt: 0, endedAt: 0, message: '' }
1136
+ return {
1137
+ id: operation.id,
1138
+ active: operation.active === true,
1139
+ phase: operation.phase || 'idle',
1140
+ command: String(operation.command || ''),
1141
+ startedAt: Number(operation.startedAt) || 0,
1142
+ endedAt: Number(operation.endedAt) || 0,
1143
+ message: String(operation.message || ''),
1144
+ ...(typeof operation.executed === 'boolean' ? { executed: operation.executed } : {}),
1145
+ }
1146
+ }
1147
+
1148
+ async function executeRegisteredCommand(ctx, agent, line, signal) {
1149
+ return ctx.commands.execute.length === 3
1150
+ ? ctx.commands.execute(agent, line, signal)
1151
+ : ctx.commands.execute(agent, line, [], signal)
1152
+ }
1153
+
1154
+ function beginCommandOperation(ctx, agent, sessionId, line, command) {
1155
+ const existing = commandOperations.get(sessionId)
1156
+ if (existing?.active) {
1157
+ if (existing.line !== line) throw new Error('当前会话已有命令正在执行,请等待完成后再提交。')
1158
+ return { operation: existing, reused: true }
1159
+ }
1160
+ const operation = { id: randomUUID(), active: true, phase: 'running', command, line, startedAt: Date.now(), endedAt: 0, message: '' }
1161
+ commandOperations.set(sessionId, operation)
1162
+ // 不把已登记命令绑定到 HTTP 超时:真实 command/done 才是完成边界。
1163
+ // 处理器仍接收可用 AbortSignal,以符合命令执行器的契约。
1164
+ const signal = new AbortController().signal
1165
+ void executeRegisteredCommand(ctx, agent, line, signal).then((result) => {
1166
+ operation.active = false
1167
+ operation.endedAt = Date.now()
1168
+ operation.executed = commandWasExecuted(result)
1169
+ operation.phase = !operation.executed || result?.result?.kind === 'error' ? 'failed' : 'complete'
1170
+ operation.message = operation.phase === 'failed' ? (operation.executed ? 'command-failed' : 'command-not-executed') : String(result?.result?.text || '').slice(0, 2000)
1171
+ }, (error) => {
1172
+ operation.active = false
1173
+ operation.endedAt = Date.now()
1174
+ operation.phase = 'failed'
1175
+ operation.message = 'command-failed'
1176
+ }).finally(() => {
1177
+ const cleanup = setTimeout(() => {
1178
+ if (commandOperations.get(sessionId) === operation && !operation.active) commandOperations.delete(sessionId)
1179
+ }, COMMAND_OPERATION_RETENTION_MS)
1180
+ cleanup.unref?.()
1181
+ })
1182
+ return { operation, reused: false }
1183
+ }
1184
+
1185
+ async function resolveFile(pathname) {
1186
+ // 安装包在 public/ 之外,精确映射此文件,不能开放整个插件目录。
1187
+ let abs = pathname === `${MOUNT}/dsh-remote.apk`
1188
+ ? fileURLToPath(new URL('./apk/dsh-remote.apk', import.meta.url)) : targetPath(pathname)
1189
+ if (abs === null) return null
1190
+ try {
1191
+ let info = await stat(abs)
1192
+ if (info.isDirectory()) {
1193
+ abs = resolve(abs, INDEX_FILE)
1194
+ info = await stat(abs)
1195
+ }
1196
+ if (!info.isFile() && !extname(abs)) {
1197
+ abs = abs + '.html' // /remote/admin -> admin.html
1198
+ info = await stat(abs)
1199
+ }
1200
+ return info.isFile() ? { abs, info } : null
1201
+ } catch {
1202
+ if (!extname(abs)) {
1203
+ // /remote/admin 无此裸文件 -> 再试 admin.html
1204
+ try {
1205
+ const alt = abs + '.html'
1206
+ const info = await stat(alt)
1207
+ return info.isFile() ? { abs: alt, info } : null
1208
+ } catch {
1209
+ return null
1210
+ }
1211
+ }
1212
+ return null
1213
+ }
1214
+ }
1215
+
1216
+ // Read metadata inside the actual DSH Host, never from the gateway's cwd/version.
1217
+ export function hostDescription(ctx, runtime = process) {
1218
+ let dshVersion = null, attachedSessions = null
1219
+ const profile = detectProfile(ctx, runtime.argv[1], runtime)
1220
+ if (profile?.cli) {
1221
+ try {
1222
+ const pkg = JSON.parse(readFileSync(resolve(dirname(profile.cli), '../package.json'), 'utf8'))
1223
+ const expected = profile.cliMode === 'desktop' ? '@deepseek-ai/dsh-desktop-host' : '@deepseek-ai/dsh'
1224
+ if (pkg.name === expected && typeof pkg.version === 'string') dshVersion = pkg.version.slice(0, 100)
1225
+ } catch {}
1226
+ }
1227
+ try {
1228
+ const agents = ctx.agents.list()
1229
+ if (Array.isArray(agents)) attachedSessions = agents.length
1230
+ } catch {}
1231
+ return { version: dshVersion, cwd: runtime.cwd(), attachedSessions, home: homedir(), canOpenPath: false, metadataOnly: true }
1232
+ }
1233
+
1234
+ async function serveStatic(req, res, ctx) {
1235
+ const pathname = new URL(req.url ?? '/', 'http://x').pathname
1236
+ if (pathname === `${MOUNT}/admin/api/browser-launch`) {
1237
+ res.setHeader('cache-control', 'no-store')
1238
+ res.setHeader('referrer-policy', 'no-referrer')
1239
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
1240
+ if (req.headers['x-dsh-remote-client'] !== 'entry') return sendJson(res, 403, { ok: false, code: 'explicit-entry-required' })
1241
+ if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1242
+ // Prefix routes are not automatically authenticated by DSH. Require its
1243
+ // signed browser cookie before minting a browser launch URL.
1244
+ if (typeof ctx.connection?.authorizeIndex !== 'function') return sendJson(res, 503, { ok: false, code: 'browser-auth-unavailable' })
1245
+ if (!ctx.connection.authorizeIndex(req, res)) return
1246
+ // Never accept a destination/Host header or expose a Remote gateway token.
1247
+ let url
1248
+ try { url = browserLaunchUrl(ctx) } catch (_) {}
1249
+ return sendJson(res, url ? 200 : 503, url ? { ok: true, url } : { ok: false, code: 'browser-auth-unavailable' })
1250
+ }
1251
+ if (pathname === `${MOUNT}/api/doctor/target` || pathname === `${MOUNT}/admin/api/doctor-target`) {
1252
+ res.setHeader('cache-control','no-store')
1253
+ if(pathname===`${MOUNT}/api/doctor/target` && !remoteCommandAuthorized(req))return sendJson(res,401,{ok:false,code:'unauthorized'})
1254
+ if(req.method!=='GET')return sendJson(res,405,{ok:false,code:'read-only'})
1255
+ if([...new URL(req.url,'http://x').searchParams].length)return sendJson(res,400,{ok:false,code:'invalid-query'})
1256
+ return sendJson(res,200,readDoctorTarget(ctx))
1257
+ }
1258
+ if (pathname === `${MOUNT}/api/host-description`) {
1259
+ res.setHeader('cache-control', 'no-store')
1260
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1261
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
1262
+ return sendJson(res, 200, { ok: true, ...hostDescription(ctx) })
1263
+ }
1264
+ if (pathname.startsWith(`${MOUNT}/api/skills/`)) {
1265
+ res.setHeader('cache-control', 'no-store')
1266
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1267
+ const adapter = createSkillsAdapter(async path => {
1268
+ // Use this host's listener, never a URL, origin or cookie supplied by the caller.
1269
+ const base = upstreamUrlForListener({ host: ctx.webServer.host, port: ctx.webServer.port })
1270
+ let cookie = ''
1271
+ try { cookie = readFileSync(dshUpstreamCookieFile(), 'utf8').trim() } catch {}
1272
+ const response = await fetch(base + path, { headers: cookie ? { cookie } : {}, redirect: 'error', signal: AbortSignal.timeout(10000) })
1273
+ if (!response.ok) { await response.body?.cancel(); throw Object.assign(new Error('native-read-failed'), { status: response.status }) }
1274
+ const chunks = []; let bytes = 0
1275
+ for await (const chunk of response.body) {
1276
+ bytes += chunk.length
1277
+ if (bytes > 2 * 1024 * 1024) throw new Error('response-too-large')
1278
+ chunks.push(chunk)
1279
+ }
1280
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new Error('unsupported') }
1281
+ })
1282
+ const url = new URL(req.url, 'http://x')
1283
+ const result = await adapter.handle(req.method, pathname.slice(`${MOUNT}/api/skills`.length), url.searchParams)
1284
+ return sendJson(res, result.status, result.body)
1285
+ }
1286
+ if (pathname === `${MOUNT}/api/task-board`) {
1287
+ res.setHeader('cache-control', 'no-store')
1288
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1289
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
1290
+ const result = await readTaskBoard(ctx, new URL(req.url, 'http://x').searchParams)
1291
+ return sendJson(res, result.status, result.body)
1292
+ }
1293
+ if (pathname === `${MOUNT}/api/teams`) {
1294
+ res.setHeader('cache-control', 'no-store')
1295
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1296
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
1297
+ const result = await readTeamInsights(ctx, new URL(req.url, 'http://x').searchParams, async archived => {
1298
+ let cookie = ''
1299
+ try { cookie = readFileSync(dshUpstreamCookieFile(), 'utf8').trim() } catch {}
1300
+ if (cookie.length > 4096 || /[\x00-\x1f]/.test(cookie)) cookie = ''
1301
+ return fetch(upstreamUrlForListener(dshListen) + '/plugins/dsh-agent-teams/state' + (archived ? '?archived=1' : ''), {
1302
+ headers: cookie ? { cookie } : {}, redirect: 'error', signal: AbortSignal.timeout(20000)
1303
+ })
1304
+ })
1305
+ return sendJson(res, result.status, result.body)
1306
+ }
1307
+ if (pathname === `${MOUNT}/api/insights/peak-reminders`) {
1308
+ res.setHeader('cache-control', 'no-store')
1309
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1310
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
1311
+ if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1312
+ const result = await readPeakReminders(ctx)
1313
+ return sendJson(res, result.status, result.body)
1314
+ }
1315
+ if (pathname === `${MOUNT}/api/insights/cost`) {
1316
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1317
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
1318
+ const query = new URL(req.url, 'http://x').searchParams
1319
+ if ([...query.keys()].some(key => key !== 'sessionId') || query.getAll('sessionId').length > 1) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1320
+ const result = await readCostInsights(ctx, query.get('sessionId') || '')
1321
+ res.setHeader('cache-control', 'no-store')
1322
+ return sendJson(res, result.status, result.body)
1323
+ }
1324
+ if (pathname === `${MOUNT}/api/approval-summary`) {
1325
+ res.setHeader('cache-control', 'no-store')
1326
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1327
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
1328
+ if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1329
+ let body
1330
+ try { body = JSON.parse(await readBody(req, 4096)) }
1331
+ catch { return sendJson(res, 400, { ok: false, code: 'invalid-body' }) }
1332
+ const result = await readApprovalSummary(ctx, body)
1333
+ return sendJson(res, result.status, result.body)
1334
+ }
1335
+ if (pathname.startsWith(`${MOUNT}/api/plugins/`)) {
1336
+ res.setHeader('cache-control', 'no-store')
1337
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, message: 'unauthorized' })
1338
+ try {
1339
+ const url = new URL(req.url, 'http://x')
1340
+ const body = req.method === 'POST' ? JSON.parse((await readBody(req, 8192)) || '{}') : {}
1341
+ const result = await pluginCenters.get(ctx).handle(req.method, pathname.slice(`${MOUNT}/api/plugins`.length), body, url.searchParams)
1342
+ return sendJson(res, req.method === 'POST' ? 202 : 200, result)
1343
+ } catch (error) {
1344
+ return sendJson(res, error.status || (error instanceof SyntaxError ? 400 : 500), { ok: false, message: error.message || 'Plugin operation failed' })
1345
+ }
1346
+ }
1347
+
1348
+ // 无尾斜杠的入口重定向到带斜杠版本:
1349
+ // 否则相对资源 styles.css/app.js 会按 URL 规则解析到上级路径 /styles.css,
1350
+ // 被 DSH 的 SPA fallback 返回 HTML, 表现为白底 + 脚本不运行。
1351
+ if (pathname === MOUNT) {
1352
+ res.writeHead(302, { location: `${MOUNT}/` })
1353
+ res.end()
1354
+ return
1355
+ }
1356
+ if (pathname === `${MOUNT}/admin`) {
1357
+ res.writeHead(302, { location: `${MOUNT}/admin/` })
1358
+ res.end()
1359
+ return
1360
+ }
1361
+
1362
+ // The embedded panel is already authenticated by the DSH web listener,
1363
+ // like the adjacent admin/state route. Read cost-meter without a gateway.
1364
+ if (pathname === `${MOUNT}/admin/api/cost`) {
1365
+ res.setHeader('cache-control', 'no-store')
1366
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
1367
+ const result = await readCostInsights(ctx)
1368
+ return sendJson(res, result.status, result.body)
1369
+ }
1370
+
1371
+ // Legacy stats API retained for older clients.
1372
+ if (pathname === `${MOUNT}/admin/api/stats/summary` || pathname === `${MOUNT}/admin/api/stats/detail`) {
1373
+ const query = new URL(req.url ?? '/', 'http://x').search
1374
+ const sub = pathname.slice(`${MOUNT}/admin/api/stats`.length)
1375
+ const proxied = await proxyGateway(`/stats${sub}${query}`, 'GET', '')
1376
+ if (proxied !== null) {
1377
+ sendJson(res, proxied.status, proxied.json)
1378
+ } else {
1379
+ sendJson(res, 502, { ok: false, error: '本地网关不可用, Token 统计需要网关运行' })
1380
+ }
1381
+ return
1382
+ }
1383
+
1384
+ // 管理控制台数据: 优先代理本地网关(设备监控/更新检查完整), 网关不可用回退插件状态
1385
+ if (pathname === `${MOUNT}/admin/api/state`) {
1386
+ void ensureGateway() // 自愈: 开关为 on 而网关没起来时, 后台拉起, 下个轮询即可见网关
1387
+ const health = await gatewayRunning() // 新网关可在健康探测时恢复缺失的令牌文件
1388
+ const localToken = gatewayToken()
1389
+ const proxied = await proxyGateway('/admin/api/state', 'GET', '')
1390
+ if (proxied?.status === 200 && proxied.json.ok === true) {
1391
+ // 主机端 DSH 面板本身已登录本机用户, 管理页无需令牌门禁;
1392
+ // 把真实网关令牌一并返回, 抽屉里直接显示并允许复制(供手机 App 使用)。
1393
+ sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled, gatewayRuntime: await gatewayRuntimeForStatus(proxied.json.gatewayRuntime ?? null, health) })
1394
+ return
1395
+ }
1396
+ if (health.running && proxied?.status >= 500) {
1397
+ sendJson(res, proxied.status, { ...proxied.json, gatewayRunning: true })
1398
+ return
1399
+ }
1400
+ sendJson(res, 200, {
1401
+ ok: true,
1402
+ mode: 'plugin',
1403
+ gatewayRunning: health.running,
1404
+ gatewayAuthError: health.running && (!localToken || proxied?.status === 401 || proxied?.status === 403) ? GATEWAY_AUTH_HINT : '',
1405
+ gatewayVersion: health.version || '',
1406
+ gatewayRuntime: await gatewayRuntimeForStatus(null, health),
1407
+ version,
1408
+ token: health.running ? '' : localToken || '',
1409
+ gatewayInstalled,
1410
+ platform: process.platform,
1411
+ hostname: hostname(),
1412
+ lanIPs: lanIPs(),
1413
+ startedAt: Date.now() - Math.floor(process.uptime() * 1000),
1414
+ uptimeSec: Math.floor(process.uptime()),
1415
+ host: dshListen.host,
1416
+ port: dshListen.port,
1417
+ protocol: { version: 1 },
1418
+ capabilities: {
1419
+ wsTicket: 0,
1420
+ eventPolling: 0,
1421
+ workspaceFiles: 0,
1422
+ imagePromptTransport: 0,
1423
+ dshLifecycle: 0,
1424
+ centralAnnouncements: 0,
1425
+ feedback: 0,
1426
+ deviceKeys: 0,
1427
+ },
1428
+ dshControl: { supported: false, code: 'EXTERNAL_LIFECYCLE', message: '插件内嵌模式不负责管理 DSH 自身进程' },
1429
+ deviceKeys: { supported: false, enabled: false, entries: [] },
1430
+ upstream: { url: 'DSH 内嵌(同进程, 无需网关)', reachable: true },
1431
+ latest: { version, newer: false },
1432
+ onlineCount: 0,
1433
+ deviceCount: 0,
1434
+ totalRequests: 0,
1435
+ authFailures: 0,
1436
+ events: {
1437
+ mux: { connected: false, attempt: 0, lastError: '网关未运行' },
1438
+ host: { connected: false, attempt: 0, lastError: '网关未运行' },
1439
+ },
1440
+ devices: [],
1441
+ })
1442
+ return
1443
+ }
1444
+ const gatewayAdminMutations = new Map([
1445
+ [`${MOUNT}/admin/api/note`, '/note'],
1446
+ [`${MOUNT}/admin/api/kick`, '/kick'],
1447
+ [`${MOUNT}/admin/api/token/rotate`, '/token/rotate'],
1448
+ [`${MOUNT}/admin/api/device-keys/mode`, '/device-keys/mode'],
1449
+ [`${MOUNT}/admin/api/device-keys/create`, '/device-keys/create'],
1450
+ [`${MOUNT}/admin/api/device-keys/note`, '/device-keys/note'],
1451
+ [`${MOUNT}/admin/api/device-keys/rotate`, '/device-keys/rotate'],
1452
+ [`${MOUNT}/admin/api/device-keys/revoke`, '/device-keys/revoke'],
1453
+ ])
1454
+ if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart` || pathname === `${MOUNT}/admin/api/lan`) {
1455
+ if (!['GET', 'POST'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST' }); res.end(); return }
1456
+ const body = req.method === 'POST' ? await readBody(req, 4096) : undefined
1457
+ const proxied = await proxyGateway('/admin/api/' + pathname.split('/').pop(), req.method, body)
1458
+ sendJson(res, proxied?.status || 502, proxied?.json || { error: 'GATEWAY_UNAVAILABLE' })
1459
+ return
1460
+ }
1461
+ if (gatewayAdminMutations.has(pathname)) {
1462
+ if (req.method !== 'POST') {
1463
+ res.writeHead(405, { allow: 'POST' })
1464
+ res.end()
1465
+ return
1466
+ }
1467
+ const body = await readBody(req, 4096)
1468
+ const sub = gatewayAdminMutations.get(pathname)
1469
+ const proxied = await proxyGateway(`/admin/api${sub}`, 'POST', body)
1470
+ if (proxied !== null) {
1471
+ sendJson(res, proxied.status, proxied.json)
1472
+ } else {
1473
+ sendJson(res, 502, { ok: false, error: '本地网关不可用, 设备管理需在网关模式操作' })
1474
+ }
1475
+ return
1476
+ }
1477
+
1478
+ // 网关端口配置(仅插件内嵌页使用): GET 当前生效端口 / PUT 修改端口
1479
+ if (pathname === `${MOUNT}/admin/api/config`) {
1480
+ if (req.method === 'GET') {
1481
+ const h = await gatewayRunning()
1482
+ sendJson(res, 200, {
1483
+ ok: true,
1484
+ port: Number(readGatewayPort()),
1485
+ running: h.running,
1486
+ source: process.env.DSH_REMOTE_GATEWAY_PORT ? 'env' : existsSync(gatewayPortFile()) ? 'file' : 'default',
1487
+ })
1488
+ return
1489
+ }
1490
+ if (req.method === 'PUT') {
1491
+ let body = {}
1492
+ try {
1493
+ body = JSON.parse((await readBody(req, 4096)) || '{}')
1494
+ } catch {}
1495
+ const port = Number(body.port)
1496
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1497
+ sendJson(res, 400, { ok: false, error: '端口必须是 1-65535 的整数' })
1498
+ return
1499
+ }
1500
+ const oldPort = Number(readGatewayPort())
1501
+ // 先在切换配置前读取旧端口上的健康状态;写入新端口后 gatewayRunning()
1502
+ // 只会探测新端口,否则旧网关会变成孤儿进程继续占用旧端口。
1503
+ const oldHealth = process.env.DSH_REMOTE_GATEWAY ? { running: false } : await gatewayRunning()
1504
+ if (!process.env.DSH_REMOTE_GATEWAY_PORT && port !== oldPort && oldHealth.running && !await killGateway(oldHealth)) {
1505
+ sendJson(res, 409, { ok: false, error: '无法通过认证关闭旧网关,端口配置未修改' })
1506
+ return
1507
+ }
1508
+ try {
1509
+ mkdirSync(`${homedir()}/.dsh-remote`, { recursive: true })
1510
+ writeFileSync(gatewayPortFile(), String(port) + '\n')
1511
+ } catch (e) {
1512
+ sendJson(res, 500, { ok: false, error: '写入端口配置失败: ' + (e?.message || String(e)) })
1513
+ return
1514
+ }
1515
+ const effectivePort = Number(readGatewayPort())
1516
+ let running = (await gatewayRunning()).running
1517
+ if (gatewayAutostart()) {
1518
+ const startOut = await startGateway()
1519
+ running = !!startOut.running || (await gatewayRunning()).running
1520
+ }
1521
+ sendJson(res, 200, { ok: true, port: Number(port), effectivePort, running })
1522
+ return
1523
+ }
1524
+ res.writeHead(405, { allow: 'GET, PUT' })
1525
+ res.end()
1526
+ return
1527
+ }
1528
+
1529
+ // 本地网关开关(仅插件内嵌页使用): GET 状态 / POST {action:'start'|'stop'}
1530
+ if (pathname === `${MOUNT}/admin/api/gateway`) {
1531
+ if (req.method === 'GET') {
1532
+ const h = await gatewayRunning()
1533
+ sendJson(res, 200, {
1534
+ ok: true, running: h.running, version: h.version || '', upstream: h.upstream || '', upstreamOk: h.upstreamOk === true,
1535
+ runtime: await gatewayRuntimeForStatus(undefined, h),
1536
+ })
1537
+ return
1538
+ }
1539
+ if (req.method === 'POST') {
1540
+ let action = ''
1541
+ try {
1542
+ const raw = await readBody(req, 4096)
1543
+ action = JSON.parse(raw || '{}').action
1544
+ } catch {}
1545
+ if (action === 'start') sendJson(res, 200, await startGateway())
1546
+ else if (action === 'stop') sendJson(res, 200, await stopGateway())
1547
+ else sendJson(res, 400, { ok: false, error: 'action 必须是 start 或 stop' })
1548
+ return
1549
+ }
1550
+ res.writeHead(405, { allow: 'GET, POST' })
1551
+ res.end()
1552
+ return
1553
+ }
1554
+
1555
+ // 远程启动/重启 DSH: 内嵌抽屉通过插件前缀转发到独立网关。
1556
+ if (pathname === `${MOUNT}/admin/api/dsh`) {
1557
+ if (req.method !== 'GET' && req.method !== 'POST') {
1558
+ res.writeHead(405, { allow: 'GET, POST' })
1559
+ res.end()
1560
+ return
1561
+ }
1562
+ const body = req.method === 'POST' ? await readBody(req, 4096) : ''
1563
+ const query = new URL(req.url, 'http://x').search
1564
+ const proxied = await proxyGateway('/admin/api/dsh' + query, req.method, body)
1565
+ if (proxied !== null) {
1566
+ sendJson(res, proxied.status, proxied.json)
1567
+ } else {
1568
+ sendJson(res, 502, { ok: false, error: '本地网关不可用,无法控制 DSH' })
1569
+ }
1570
+ return
1571
+ }
1572
+
1573
+ if (pathname === `${MOUNT}/api/session-file`) {
1574
+ if (!remoteCommandAuthorized(req)) { sendJson(res,401,{ok:false,message:'unauthorized'});return }
1575
+ return serveSessionFile(ctx, req, res, new URL(req.url, 'http://host'))
1576
+ }
1577
+ // 命令状态:由插件进程跟踪长期操作,客户端重连后可恢复可见状态。
1578
+ if (pathname === `${MOUNT}/api/command-status`) {
1579
+ if (req.method !== 'GET') {
1580
+ res.writeHead(405, { allow: 'GET' })
1581
+ res.end()
1582
+ return
1583
+ }
1584
+ if (!remoteCommandAuthorized(req)) {
1585
+ sendJson(res, 401, { ok: false, message: 'unauthorized' })
1586
+ return
1587
+ }
1588
+ const sessionId = new URL(req.url ?? '/', 'http://x').searchParams.get('sessionId') || ''
1589
+ if (!sessionId) {
1590
+ sendJson(res, 400, { ok: false, message: 'sessionId required' })
1591
+ return
1592
+ }
1593
+ const operation = commandOperationSnapshot(commandOperations.get(sessionId))
1594
+ // compact 为上一版客户端保留,新的客户端统一读取 operation。
1595
+ sendJson(res, 200, { ok: true, operation, compact: operation.command === 'compact' ? operation : commandOperationSnapshot(null) })
1596
+ return
1597
+ }
1598
+
1599
+ // 斜杠命令桥接:客户端 → 网关 → 插件端点 → ctx.commands.execute
1600
+ if (pathname === `${MOUNT}/api/command`) {
1601
+ if (req.method !== 'POST') {
1602
+ res.writeHead(405, { allow: 'POST' })
1603
+ res.end()
1604
+ return
1605
+ }
1606
+ if (!remoteCommandAuthorized(req)) {
1607
+ sendJson(res, 401, { ok: false, message: 'unauthorized' })
1608
+ return
1609
+ }
1610
+ let body
1611
+ try {
1612
+ body = JSON.parse((await readBody(req, 8192)) || '{}')
1613
+ } catch (error) {
1614
+ sendJson(res, error.status === 413 ? 413 : 400, { ok: false, message: error.status === 413 ? 'body too large' : 'invalid json' })
1615
+ return
1616
+ }
1617
+ const { sessionId, line } = body || {}
1618
+ if (!sessionId || typeof line !== 'string') {
1619
+ sendJson(res, 400, { ok: false, message: 'sessionId and line required' })
1620
+ return
1621
+ }
1622
+ try {
1623
+ const { agent, resolvePath } = await resolveAgent(ctx, sessionId)
1624
+ if (!agent) {
1625
+ sendJson(res, 200, { ok: false, message: 'agent not found', debug: { resolvePath, commandNames: [] } })
1626
+ return
1627
+ }
1628
+ let commandEntries = null
1629
+ let commandNames = []
1630
+ try {
1631
+ const listed = await ctx.commands.list(agent)
1632
+ commandEntries = Array.isArray(listed) ? listed : null
1633
+ commandNames = commandEntries ? commandEntries.map(commandEntryName).filter(Boolean) : []
1634
+ } catch (e) {
1635
+ commandNames = ['list-error']
1636
+ }
1637
+ const name = commandHead(line)
1638
+ if (commandEntries && (!name || !commandEntries.some(entry => commandEntryName(entry) === name))) {
1639
+ // 仅把 DSH 已登记的 slash command 截留到命令服务。未知 /xxx 仍让客户端
1640
+ // 按普通文本发送,保持 DSH 自己处理自定义提示词的兼容行为。
1641
+ sendJson(res, 200, { ok: true, executed: false, debug: { resolvePath, commandNames, reason: 'unknown-command' } })
1642
+ return
1643
+ }
1644
+ // /export 的成功结果必须先回到客户端,由客户端再发起 ZIP 下载;其他已登记
1645
+ // 命令统一异步受理,避免把未知耗时绑定到一条 HTTP 请求。
1646
+ if (name && (name !== 'export' || body.async === true)) {
1647
+ const { operation, reused } = beginCommandOperation(ctx, agent, sessionId, line, name)
1648
+ sendJson(res, 202, {
1649
+ ok: true,
1650
+ executed: true,
1651
+ accepted: true,
1652
+ operation: commandOperationSnapshot(operation),
1653
+ compact: name === 'compact' ? commandOperationSnapshot(operation) : undefined,
1654
+ debug: { resolvePath, commandNames, reused },
1655
+ })
1656
+ return
1657
+ }
1658
+ // /export 在持久化历史较大时会等待刷新;其他同步命令沿用较短超时。
1659
+ const signal = AbortSignal.timeout(LONG_RUNNING_COMMANDS.has(name)
1660
+ ? LONG_RUNNING_COMMAND_TIMEOUT_MS
1661
+ : DEFAULT_COMMAND_TIMEOUT_MS)
1662
+ const result = await executeRegisteredCommand(ctx, agent, line, signal)
1663
+ sendJson(res, 200, { ok: true, executed: commandWasExecuted(result), debug: { resolvePath, commandNames } })
1664
+ } catch (e) {
1665
+ sendJson(res, 200, { ok: false, message: 'command-failed' })
1666
+ }
1667
+ return
1668
+ }
1669
+
1670
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
1671
+ res.writeHead(405, { allow: 'GET, HEAD' })
1672
+ res.end()
1673
+ return
1674
+ }
1675
+ const found = await resolveFile(pathname)
1676
+ if (found === null) {
1677
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
1678
+ res.end('not found')
1679
+ return
1680
+ }
1681
+ const { abs, info } = found
1682
+ const lastModified = info.mtime.toUTCString()
1683
+ const mtimeSec = Math.floor(info.mtime.getTime() / 1000) * 1000
1684
+ const ims = req.headers['if-modified-since']
1685
+ if (ims && new Date(ims).getTime() >= mtimeSec) {
1686
+ res.writeHead(304, { 'last-modified': lastModified })
1687
+ res.end()
1688
+ return
1689
+ }
1690
+ res.writeHead(200, {
1691
+ 'content-type': extname(abs) === '.apk' ? 'application/vnd.android.package-archive' : MIME[extname(abs)] ?? 'application/octet-stream',
1692
+ ...(extname(abs) === '.apk' ? { 'content-disposition': 'attachment; filename="dsh-remote.apk"', 'x-content-type-options': 'nosniff' } : {}),
1693
+ 'content-length': info.size,
1694
+ 'cache-control': 'no-cache',
1695
+ 'last-modified': lastModified,
1696
+ })
1697
+ if (req.method === 'HEAD') {
1698
+ res.end()
1699
+ return
1700
+ }
1701
+ const stream = createReadStream(abs)
1702
+ stream.on('error', () => res.destroy())
1703
+ res.on('close', () => stream.destroy())
1704
+ stream.pipe(res)
1705
+ }
1706
+
1707
+ const pluginCenters = new WeakMap()
1708
+ export function desktopLaunchConfig(ctx) {
1709
+ if (process.platform !== 'win32' || !process.versions.electron) return null
1710
+ const profile = detectProfile(ctx)
1711
+ const hostScript = process.argv[1] || ''
1712
+ if (profile?.name !== 'desktop' || !/[\\/]@deepseek-ai[\\/]dsh-desktop-host[\\/]lib[\\/]index\.js$/.test(hostScript)) return null
1713
+ const pid = process.pid, parent = process.ppid
1714
+ try {
1715
+ const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); @(' + [pid,parent].map(id =>
1716
+ "Get-CimInstance Win32_Process -Filter 'ProcessId=" + id + "' | ForEach-Object { @{pid=$_.ProcessId;parent=$_.ParentProcessId;executable=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')} }").join('; ') + ') | ConvertTo-Json -Compress'
1717
+ const rows = JSON.parse(execFileSync('powershell.exe', ['-NoLogo','-NoProfile','-NonInteractive','-Command',script], { encoding:'utf8', timeout:8000, windowsHide:true }))
1718
+ const host = rows.find(row => row.pid === pid), root = rows.find(row => row.pid === parent)
1719
+ if (!host || !root || host.parent !== root.pid || resolve(root.executable) !== resolve(process.execPath) || resolve(host.executable) !== resolve(process.execPath) || /--(?:type|expose-internals)\b/.test(root.command)) return null
1720
+ return { version:1, kind:'desktop', executable:process.execPath, args:[], cwd:dirname(process.execPath), profile:'desktop', env:{DSH_HOME:profile.home},
1721
+ upstream:upstreamUrlForListener(ctx.webServer), desktop:{root:{pid:root.pid,started:root.started},host:{pid:host.pid,started:host.started},hostScript,profilePath:profile.dir} }
1722
+ } catch (error) { logGateway('Desktop 启动信息核验失败: ' + error.message); return null }
1723
+ }
1724
+
1725
+ export function saveDshLaunchConfig(ctx) {
1726
+ if (process.platform !== 'win32') return false
1727
+ const desktop = desktopLaunchConfig(ctx)
1728
+ if (process.versions.electron && !desktop) return false
1729
+ const profile = detectProfile(ctx)
1730
+ if (!desktop && (!profile?.cli || profile.name === 'desktop' || resolve(process.argv[1] || '') !== resolve(profile.cli))) return false
1731
+ const env = { DSH_HOME: profile.home }
1732
+ for (const key of ['HOME', 'USERPROFILE', 'PATH', 'NODE_OPTIONS']) {
1733
+ if (process.env[key] !== undefined) env[key] = process.env[key]
1734
+ }
1735
+ const args = desktop ? [] : [profile.cli, ...process.argv.slice(2)]
1736
+ if (!desktop && !args.includes('--no-open')) args.push('--no-open')
1737
+ const config = desktop || { version: 1, executable: process.execPath, args, cwd: process.cwd(),
1738
+ env, profile: profile.name, upstream: upstreamUrlForListener({ host: ctx.webServer.host, port: ctx.webServer.port }) }
1739
+ const file = process.env.DSH_REMOTE_DSH_LAUNCH_FILE || `${homedir()}/.dsh-remote/dsh-launch.json`
1740
+ const tmp = `${file}.${process.pid}.tmp`
1741
+ try {
1742
+ mkdirSync(dirname(file), { recursive: true })
1743
+ writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 })
1744
+ renameSync(tmp, file)
1745
+ return true
1746
+ } catch (err) {
1747
+ logGateway('无法保存 DSH 启动配置: ' + err.message)
1748
+ return false
1749
+ }
1750
+ }
1751
+
1752
+ export function apply(ctx) {
1753
+ pluginCenters.set(ctx, createPluginCenter(ctx))
1754
+ dshListen = { host: ctx.webServer.host, port: ctx.webServer.port }
1755
+ dshConnection = ctx.connection
1756
+ saveDshLaunchConfig(ctx)
1757
+ // Optional on older DSH: register the packaged read-only doctor skill when
1758
+ // the host exposes a skill registry. Failure never blocks the plugin.
1759
+ registerDoctorSkill(ctx)
1760
+ registerFileDeliveryTools(ctx, { gatewayBase, gatewayToken })
1761
+ watchDoctorWorkspaces(ctx)
1762
+ ctx.effect(() => ctx.webServer.register({
1763
+ kind: 'prefix',
1764
+ path: MOUNT,
1765
+ handler: (req, res) => serveStatic(req, res, ctx).catch(error => {
1766
+ if (res.writableEnded || res.destroyed) return
1767
+ if (res.headersSent) return res.destroy()
1768
+ if (error.status === 413) res.setHeader('connection', 'close')
1769
+ sendJson(res, error.status || (error instanceof SyntaxError ? 400 : 500), { ok: false, message: error.status === 413 ? 'body too large' : 'request-failed' })
1770
+ }),
1771
+ }), 'dsh-remote: /remote route')
1772
+ // 实时统计: 监听 DSH 会话事件流, 把带 usage 的 assistant/message 投递到网关聚合
1773
+ ctx.on('session/event', (session, event) => {
1774
+ statsSend(session, event)
1775
+ })
1776
+ // DSH 启动/重启后自愈: 用户没关过网关就自动拉起(默认开, DSH_REMOTE_AUTOSTART=0 关闭)
1777
+ void ensureGateway()
1778
+ // apply 可能早于 Web 监听完成;延迟再交换一次新版 DSH 的会话 Cookie。
1779
+ ctx.effect(() => {
1780
+ const timer = setTimeout(() => { void ensureGateway() }, 5000)
1781
+ timer.unref?.()
1782
+ return () => clearTimeout(timer)
1783
+ }, 'dsh-remote: refresh upstream authentication')
1784
+ }