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

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