dsh-chrome-bridge 1.16.3 → 1.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/image-guard.js +5 -99
- package/index.js +14 -7
- package/package.json +1 -1
- package/setup.js +223 -7
package/image-guard.js
CHANGED
|
@@ -8,10 +8,10 @@
|
|
|
8
8
|
* 只按字节数预检、不管张数,于是错误直接砸到会话上,且每次重发还是那么多张 ——
|
|
9
9
|
* 会话就此卡死,只能新开会话。
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* 这个模块只补一件事:自己认这个错,记一条 `image/offload` 决策(卸掉最老的 N 张),让 loop 重试。
|
|
12
|
+
* 解释这条决策的投影由内置 dsh-compaction-image-offload 注册(dsh-base 里一定有)。我们不再自己注册:
|
|
13
|
+
* 以前抢先注册了同名投影,内置插件注册时撞名、整个没启动,它的两个兜底监听也跟着没了(issue #4)。
|
|
14
|
+
* 万一真没有这个投影,append 会抛错,下面接住、交给下游,和没装这个插件一样。
|
|
15
15
|
*
|
|
16
16
|
* 不 import 任何外部包:profile 上下文里 `@deepseek-ai/*` 解析不可靠(踩过)。
|
|
17
17
|
*/
|
|
@@ -22,48 +22,6 @@ const OFFLOAD_MARGIN = 8
|
|
|
22
22
|
|
|
23
23
|
// ── 选谁卸:按请求顺序找最老的、还没卸下的图片出现位置 ──────────────────────
|
|
24
24
|
|
|
25
|
-
function isRecord(value) {
|
|
26
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function isIndex(value) {
|
|
30
|
-
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0)
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function deepFreeze(value) {
|
|
34
|
-
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
35
|
-
Object.freeze(value)
|
|
36
|
-
for (const child of Object.values(value)) deepFreeze(child)
|
|
37
|
-
}
|
|
38
|
-
return value
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** 把一条消息里指定的图片出现位置标成已卸下(索引要数上已卸下的那些)。 */
|
|
42
|
-
function offloadMessageImages(message, indexes) {
|
|
43
|
-
let imageIndex = 0
|
|
44
|
-
let selected = 0
|
|
45
|
-
const visit = (blocks) => {
|
|
46
|
-
let next
|
|
47
|
-
for (const [index, block] of blocks.entries()) {
|
|
48
|
-
let projected = block
|
|
49
|
-
if (block.type === 'image') {
|
|
50
|
-
if (imageIndex === indexes[selected]) {
|
|
51
|
-
if (block.offloaded === true) throw new Error(`image/offload: image index ${imageIndex} is already offloaded`)
|
|
52
|
-
projected = { ...block, offloaded: true }
|
|
53
|
-
selected += 1
|
|
54
|
-
}
|
|
55
|
-
imageIndex += 1
|
|
56
|
-
}
|
|
57
|
-
if (projected !== block) next ??= blocks.slice(0, index)
|
|
58
|
-
if (next) next.push(projected)
|
|
59
|
-
}
|
|
60
|
-
return next ?? blocks
|
|
61
|
-
}
|
|
62
|
-
const content = visit(message.content)
|
|
63
|
-
if (selected !== indexes.length) throw new Error(`image/offload: image index ${indexes[selected]} does not exist`)
|
|
64
|
-
return deepFreeze({ ...message, content })
|
|
65
|
-
}
|
|
66
|
-
|
|
67
25
|
/** 这次失败要卸下几张图;不是图片超限就返回 0。 */
|
|
68
26
|
export function imagesToOffload(failure) {
|
|
69
27
|
const text = `${(failure && failure.message) || ''} ${(failure && failure.code) || ''}`
|
|
@@ -102,66 +60,14 @@ export function offloadOldestImages(session, count) {
|
|
|
102
60
|
return marked
|
|
103
61
|
}
|
|
104
62
|
|
|
105
|
-
// ── 投影:和内置 dsh-compaction-image-offload 的纯定义同语义 ────────────────
|
|
106
|
-
|
|
107
|
-
/** 实时创建 / 恢复 / fork 都用它解释 `image/offload` 事件。 */
|
|
108
|
-
export const imageOffloadProjection = {
|
|
109
|
-
type: 'image/offload',
|
|
110
|
-
project(event, context) {
|
|
111
|
-
const data = event.data
|
|
112
|
-
if (!isRecord(data) || Object.keys(data).length !== 1 || !Array.isArray(data.targets) || data.targets.length === 0) {
|
|
113
|
-
throw new Error('image/offload: data must contain a nonempty targets array')
|
|
114
|
-
}
|
|
115
|
-
const messages = new Map()
|
|
116
|
-
const nodes = new Set(context.nodes)
|
|
117
|
-
for (const target of data.targets) {
|
|
118
|
-
if (!isRecord(target) || Object.keys(target).length !== 2 || !isIndex(target.seq) ||
|
|
119
|
-
!Array.isArray(target.imageIndexes) || target.imageIndexes.length === 0) {
|
|
120
|
-
throw new Error('image/offload: each target must contain a seq and nonempty imageIndexes')
|
|
121
|
-
}
|
|
122
|
-
const seq = target.seq
|
|
123
|
-
if (messages.has(seq)) throw new Error(`image/offload: duplicate target seq ${seq}`)
|
|
124
|
-
if (!nodes.has(seq)) throw new Error(`image/offload: target seq ${seq} is not a current surface node`)
|
|
125
|
-
const source = context.events[seq - context.baseSeq]
|
|
126
|
-
if (source?.type !== 'user/message' && source?.type !== 'tool/result') {
|
|
127
|
-
throw new Error(`image/offload: target seq ${seq} must be user/message or tool/result`)
|
|
128
|
-
}
|
|
129
|
-
let previous = -1
|
|
130
|
-
for (const index of target.imageIndexes) {
|
|
131
|
-
if (!isIndex(index) || index <= previous) {
|
|
132
|
-
throw new Error('image/offload: imageIndexes must be strictly increasing non-negative safe integers')
|
|
133
|
-
}
|
|
134
|
-
previous = index
|
|
135
|
-
}
|
|
136
|
-
const message = context.messages.get(seq) ?? (source.type === 'user/message' ? source.data : source.data.message)
|
|
137
|
-
messages.set(seq, offloadMessageImages(message, target.imageIndexes))
|
|
138
|
-
}
|
|
139
|
-
return messages
|
|
140
|
-
},
|
|
141
|
-
}
|
|
142
|
-
|
|
143
63
|
// ── 挂上去 ──────────────────────────────────────────────────────────────────
|
|
144
64
|
|
|
145
65
|
/**
|
|
146
|
-
*
|
|
66
|
+
* 挂 request-error 监听器(投影交给内置插件,见文件头)。
|
|
147
67
|
* @param ctx 插件上下文
|
|
148
68
|
* @param trace 日志函数
|
|
149
69
|
*/
|
|
150
70
|
export function installImageGuard(ctx, trace = () => {}) {
|
|
151
|
-
const registerProjection = (sctx) => {
|
|
152
|
-
const sessions = sctx.get ? sctx.get('sessions') : sctx.sessions
|
|
153
|
-
if (!sessions || typeof sessions.registerMessageProjection !== 'function') return
|
|
154
|
-
try {
|
|
155
|
-
sessions.registerMessageProjection(imageOffloadProjection)
|
|
156
|
-
trace('已注册 image/offload 投影(内置插件没挂,自己补一份)')
|
|
157
|
-
} catch (e) {
|
|
158
|
-
// 内置 dsh-compaction-image-offload 已经注册过,那就用它的
|
|
159
|
-
trace(`image/offload 投影已存在,用内置的: ${e && e.message}`)
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
if (typeof ctx.inject === 'function') ctx.inject(['sessions'], registerProjection)
|
|
163
|
-
else registerProjection(ctx)
|
|
164
|
-
|
|
165
71
|
ctx.on('agent/request-error', ({ agent, failure }, next) => {
|
|
166
72
|
const count = imagesToOffload(failure)
|
|
167
73
|
if (count <= 0) return next()
|
package/index.js
CHANGED
|
@@ -17,7 +17,7 @@ import crypto from 'node:crypto'
|
|
|
17
17
|
import { fileURLToPath } from 'node:url'
|
|
18
18
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
19
19
|
import { installImageGuard } from './image-guard.js'
|
|
20
|
-
import { ensureInstalled, installHint, assistInstall, paths, extensionId } from './setup.js'
|
|
20
|
+
import { ensureInstalled, installHint, assistInstall, paths, extensionId, hostProbe } from './setup.js'
|
|
21
21
|
import { snapshot, locate, focusShadow, elementBox, selectInPage, frameTexts } from './refs.js'
|
|
22
22
|
import { consoleLog, networkLog, responseBody, clearLogs } from './devtools.js'
|
|
23
23
|
import { historyNav, waitUntil } from './nav.js'
|
|
@@ -209,12 +209,16 @@ const HINT = () => installHint() + firstAid()
|
|
|
209
209
|
|
|
210
210
|
// ── 与宿主通话 ──────────────────────────────────────────────────────────────
|
|
211
211
|
|
|
212
|
-
/**
|
|
213
|
-
|
|
212
|
+
/**
|
|
213
|
+
* 一次请求一个连接,协议是换行分隔的 JSON(和 cb CLI 完全一致)。
|
|
214
|
+
* quiet:后台自己问的(不是用户/模型要做的事)——出错不带「还差哪一步」,那里面会去打开扩展页、改剪贴板。
|
|
215
|
+
*/
|
|
216
|
+
function call(op, args = {}, timeoutMs = 60000, quiet = false) {
|
|
217
|
+
const hint = () => (quiet ? '' : HINT())
|
|
214
218
|
return new Promise((resolve, reject) => {
|
|
215
219
|
const SOCK = hostSock()
|
|
216
220
|
if (!hostUp()) {
|
|
217
|
-
return reject(new Error(`浏览器桥没在跑(找不到 ${SOCK || TOKEN_FILE}):Chrome 没开,或扩展还没加载。\n${
|
|
221
|
+
return reject(new Error(`浏览器桥没在跑(找不到 ${SOCK || TOKEN_FILE}):Chrome 没开,或扩展还没加载。\n${hint()}`))
|
|
218
222
|
}
|
|
219
223
|
try { checkDir(WIN ? DIR : path.dirname(SOCK)) } catch (e) { return reject(e) }
|
|
220
224
|
const token = tokenLines()[0] || null
|
|
@@ -243,7 +247,7 @@ function call(op, args = {}, timeoutMs = 60000) {
|
|
|
243
247
|
if (msg.ok) finish(resolve, msg.result)
|
|
244
248
|
else finish(reject, new Error(msg.error || '未知错误'))
|
|
245
249
|
})
|
|
246
|
-
sock.on('error', (e) => finish(reject, new Error(`连不上浏览器桥:${e.message}\n${
|
|
250
|
+
sock.on('error', (e) => finish(reject, new Error(`连不上浏览器桥:${e.message}\n${hint()}`)))
|
|
247
251
|
sock.on('close', () => finish(reject, new Error('浏览器桥连接被关掉了')))
|
|
248
252
|
timer = setTimeout(() => finish(reject, new Error(`等浏览器桥超时(${timeoutMs}ms)`)), timeoutMs)
|
|
249
253
|
})
|
|
@@ -457,8 +461,11 @@ export function apply(ctx, config) {
|
|
|
457
461
|
|
|
458
462
|
// 一次性安装:宿主 + native 注册自动落地,用户只剩把扩展装进 Chrome(加载已解压,或商店装)
|
|
459
463
|
try {
|
|
460
|
-
|
|
461
|
-
|
|
464
|
+
// Windows 换旧宿主前问一下占着管道的宿主(DSH 和 cb 只连它):是不是那个旧宿主、手上有没有活(见 hostProbe)。
|
|
465
|
+
// 悄悄问:问不到不能去打开扩展页、改剪贴板
|
|
466
|
+
const probe = hostProbe(() => call('status', {}, 5000, true))
|
|
467
|
+
const s = ensureInstalled({ log: trace, probe })
|
|
468
|
+
trace(s.ok ? `setup:${s.changed ? '已落盘' : '已是最新'} ext=${s.extId}` : `setup 跳过: ${s.reason}`)
|
|
462
469
|
} catch (e) {
|
|
463
470
|
trace(`setup 异常(忽略): ${e && e.message}`)
|
|
464
471
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-chrome-bridge",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.4",
|
|
4
4
|
"description": "DSH plugin: native browser_* tools that drive the Chrome you are already using, over native messaging + CDP. No WebSocket, no port, no Connect button. The native host and the MV3 extension ship inside this package and are installed automatically on first load; the one step left is adding the DSH Bridge extension to Chrome, from the Chrome Web Store or as the bundled unpacked copy. Until then browser_* tools fail loudly with those exact steps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/setup.js
CHANGED
|
@@ -22,7 +22,7 @@ import fs from 'node:fs'
|
|
|
22
22
|
import os from 'node:os'
|
|
23
23
|
import path from 'node:path'
|
|
24
24
|
import crypto from 'node:crypto'
|
|
25
|
-
import { execFileSync, spawn } from 'node:child_process'
|
|
25
|
+
import { execFile, execFileSync, spawn } from 'node:child_process'
|
|
26
26
|
import { fileURLToPath } from 'node:url'
|
|
27
27
|
|
|
28
28
|
export const HOST_NAME = 'com.dsh.bridge'
|
|
@@ -167,25 +167,230 @@ export function parseRegExport(text) {
|
|
|
167
167
|
return m ? m[1].replace(/\\(.)/g, '$1') : null
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
+
/** 批处理里原样写路径:% 要写成 %%,不然会被当成变量展开(引号挡不住) */
|
|
171
|
+
const bat = (s) => String(s).replace(/%/g, '%%')
|
|
172
|
+
|
|
170
173
|
/**
|
|
171
174
|
* Windows 的宿主启动脚本。Chrome 用 cmd 跑它,stdout 就是 native messaging 管道,所以脚本自己一个字都不能往外打。
|
|
172
|
-
* node
|
|
173
|
-
*
|
|
175
|
+
* node 先用 primary(桌面版:复制到宿主目录、和这个脚本放一起的那份独立 node,只给文件名,见 hostNode),
|
|
176
|
+
* 没有再用 DSH 自己的程序(桌面版是 Electron,要 ELECTRON_RUN_AS_NODE;对真 node 这个变量没影响),都没了再找 PATH 里的。
|
|
177
|
+
* primary 用 %~dp0 拼:用户目录带中文时,脚本里直接写中文路径 cmd 会读错(CI 实测),%~dp0 是 cmd 自己算的,不会错。
|
|
178
|
+
* DSH 升级换了路径,插件下次加载会重写这个文件。路径可能带中文,先把代码页切到 UTF-8 再读后面的行。
|
|
174
179
|
*/
|
|
175
|
-
export function winLauncher(execPath = process.execPath, electron = Boolean(process.versions.electron)) {
|
|
180
|
+
export function winLauncher(execPath = process.execPath, electron = Boolean(process.versions.electron), primary = null) {
|
|
176
181
|
return [
|
|
177
182
|
'@echo off',
|
|
178
183
|
'chcp 65001 >nul',
|
|
179
184
|
'setlocal',
|
|
180
185
|
...(electron ? ['set ELECTRON_RUN_AS_NODE=1'] : []),
|
|
181
|
-
`set "N=${execPath}"
|
|
186
|
+
...(primary ? [`set "N=%~dp0${primary}"`, `if not exist "%N%" set "N=${bat(execPath)}"`] : [`set "N=${bat(execPath)}"`]),
|
|
182
187
|
'if defined DSH_BRIDGE_NODE set "N=%DSH_BRIDGE_NODE%"',
|
|
183
188
|
'if not exist "%N%" for %%I in (node.exe) do set "N=%%~$PATH:I"',
|
|
184
|
-
|
|
189
|
+
// 宿主退出后马上 exit /b:cmd 不再回头读这个文件(文件可能已被改写,见 restartStaleHosts)
|
|
190
|
+
'"%N%" "%~dp0host.js" %* & exit /b',
|
|
185
191
|
'',
|
|
186
192
|
].join('\r\n')
|
|
187
193
|
}
|
|
188
194
|
|
|
195
|
+
/**
|
|
196
|
+
* Windows 桌面版:给宿主复制一份独立的 node,放在宿主目录里(issue #3)。
|
|
197
|
+
* 宿主由 Chrome 拉起、一直开着;用 DSH 安装目录里的 DeepSeek Harness.exe 跑的话,它会一直占着安装目录,
|
|
198
|
+
* DSH 升级要把整个目录换名,就会失败(Windows 错误 32),安装器悄悄回滚。
|
|
199
|
+
* DSH 自带一份独立的 node(primary runtime:~/.dsh/dsh-runtimes 里一份,安装目录 resources/runtime 里是源头),
|
|
200
|
+
* 复制过来用,只占我们自己的目录。不直接用 ~/.dsh/dsh-runtimes 里那份:DSH 换新 runtime 时也要给那个目录换名。
|
|
201
|
+
* 文件名带 node 版本:换版本写新文件,旧的删得掉就删(正在跑的删不掉,下次再删)。
|
|
202
|
+
* 找不到、复制失败都返回 null,照旧用 DSH 的程序。
|
|
203
|
+
*/
|
|
204
|
+
export function hostNode(hostDir, { execPath = process.execPath, dshHome = process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), now = Date.now() } = {}) {
|
|
205
|
+
const roots = [
|
|
206
|
+
path.join(dshHome, 'dsh-runtimes', 'dsh-primary-runtime'),
|
|
207
|
+
path.join(path.dirname(execPath), 'resources', 'runtime', 'primary-runtime'),
|
|
208
|
+
]
|
|
209
|
+
for (const root of roots) {
|
|
210
|
+
const src = path.join(root, 'dependencies', 'node', 'bin', 'node.exe')
|
|
211
|
+
let st
|
|
212
|
+
try { st = fs.statSync(src) } catch { continue }
|
|
213
|
+
if (!st.isFile() || st.size === 0) continue
|
|
214
|
+
let ver = ''
|
|
215
|
+
try { const m = JSON.parse(fs.readFileSync(path.join(root, 'runtime.json'), 'utf8')); ver = String((m.components || m).node || '') } catch {}
|
|
216
|
+
const name = `node-${/^[\w.+-]+$/.test(ver) ? `v${ver}` : st.size}.exe`
|
|
217
|
+
const dest = path.join(hostDir, name)
|
|
218
|
+
let have = null
|
|
219
|
+
try { have = fs.statSync(dest) } catch {}
|
|
220
|
+
// 接着用已有的副本:刷一下修改时间,免得另一个 DSH 按「一小时前的旧副本」把它清掉
|
|
221
|
+
if (have && have.size === st.size) { try { fs.utimesSync(dest, new Date(now), new Date(now)) } catch {} }
|
|
222
|
+
if (!have || have.size !== st.size) {
|
|
223
|
+
const tmp = `${dest}.${process.pid}.tmp`
|
|
224
|
+
try {
|
|
225
|
+
fs.mkdirSync(hostDir, { recursive: true })
|
|
226
|
+
fs.copyFileSync(src, tmp)
|
|
227
|
+
fs.renameSync(tmp, dest)
|
|
228
|
+
} catch {
|
|
229
|
+
try { fs.rmSync(tmp, { force: true }) } catch {}
|
|
230
|
+
continue
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// 旧版本的副本、没挪成的临时文件:一小时内没建过也没用过的才删(同时起来的另一个 DSH 可能刚复制好或刚用上、还没写启动脚本)
|
|
234
|
+
// Windows 复制文件会带上源文件的修改时间,所以创建时间和修改时间取晚的那个
|
|
235
|
+
try {
|
|
236
|
+
for (const f of fs.readdirSync(hostDir)) {
|
|
237
|
+
if (f === name || !/^node-[\w.+-]+\.exe(\.\d+\.tmp)?$/.test(f)) continue
|
|
238
|
+
const abs = path.join(hostDir, f)
|
|
239
|
+
try { const fst = fs.statSync(abs); if (now - Math.max(fst.birthtimeMs, fst.mtimeMs) > 3600_000) fs.rmSync(abs) } catch {}
|
|
240
|
+
}
|
|
241
|
+
} catch {}
|
|
242
|
+
return dest
|
|
243
|
+
}
|
|
244
|
+
return null
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Windows:列出还在用别的程序跑着的宿主 [{ pid, cmd, created, exe }]。认得严:命令行里得有我们的 host.js(长路径或 8.3 短路径)
|
|
249
|
+
* 和 Chrome 传给原生宿主的 chrome-extension:// 参数(记事本开着 host.js 不算),程序不是 keep(长短路径都比),
|
|
250
|
+
* 也不是宿主目录里我们自己复制的 node(换了 node 版本时旧副本上的宿主不占 DSH 安装目录,不用去动它)。
|
|
251
|
+
* cmd:拉起它的那个正在跑 run.bat 的 cmd.exe 的 pid(没有就是 0),见 restartStaleHosts 为什么要连它一起结束。
|
|
252
|
+
* created:进程创建时刻(毫秒),复查时和 pid 一起认「还是不是那个进程」。
|
|
253
|
+
* hosts:浏览器拉起的我们的宿主一共几个(新旧都算)——不止一个就是几个浏览器 / 用户都连着,见 restartStaleHosts。
|
|
254
|
+
* 查询出任何错(WMI 坏了之类)都当失败抛出,不能当成「没有旧宿主」。
|
|
255
|
+
*/
|
|
256
|
+
export function listStaleHosts(hostDir, keep) {
|
|
257
|
+
const script = [
|
|
258
|
+
"$ErrorActionPreference = 'Stop'",
|
|
259
|
+
'[Console]::OutputEncoding = [Text.Encoding]::UTF8',
|
|
260
|
+
'$fso = $null; try { $fso = New-Object -ComObject Scripting.FileSystemObject } catch {}',
|
|
261
|
+
'function Short($p) { if (-not $fso) { return $null }; try { $fso.GetFile($p).ShortPath } catch { $null } }',
|
|
262
|
+
'$h = $env:DSH_BRIDGE_HOSTJS; $hs = Short $h',
|
|
263
|
+
'$b = $env:DSH_BRIDGE_RUNBAT; $bs = Short $b',
|
|
264
|
+
'$k = $env:DSH_BRIDGE_KEEP; $ks = Short $k',
|
|
265
|
+
'$d = $env:DSH_BRIDGE_HOSTDIR + [IO.Path]::DirectorySeparatorChar; $ds = $null; if ($fso) { try { $ds = $fso.GetFolder($env:DSH_BRIDGE_HOSTDIR).ShortPath + [IO.Path]::DirectorySeparatorChar } catch {} }',
|
|
266
|
+
'$ic = [StringComparison]::OrdinalIgnoreCase',
|
|
267
|
+
'function Has($s, $x) { $x -and $s.IndexOf($x, $ic) -ge 0 }',
|
|
268
|
+
'$all = @(Get-CimInstance Win32_Process)',
|
|
269
|
+
'$byId = @{}; foreach ($p in $all) { $byId[[int]$p.ProcessId] = $p }',
|
|
270
|
+
'$mine = @($all | Where-Object { $_.CommandLine -and (Has $_.CommandLine \'chrome-extension://\') -and ((Has $_.CommandLine $h) -or (Has $_.CommandLine $hs)) })',
|
|
271
|
+
"'OK'",
|
|
272
|
+
'"HOSTS`t$($mine.Count)"',
|
|
273
|
+
'foreach ($p in $mine) {',
|
|
274
|
+
' $c = $p.CommandLine; $e = $p.ExecutablePath',
|
|
275
|
+
' if (-not $e) { continue }',
|
|
276
|
+
' if ([string]::Equals($e, $k, $ic) -or ($ks -and [string]::Equals($e, $ks, $ic))) { continue }',
|
|
277
|
+
' if ($e.StartsWith($d, $ic) -or ($ds -and $e.StartsWith($ds, $ic))) { continue }',
|
|
278
|
+
' $par = $byId[[int]$p.ParentProcessId]; $cmd = 0',
|
|
279
|
+
" if ($par -and $par.Name -ieq 'cmd.exe' -and $par.CommandLine -and ((Has $par.CommandLine $b) -or (Has $par.CommandLine $bs))) { $cmd = $par.ProcessId }",
|
|
280
|
+
' $t = 0; if ($p.CreationDate) { $t = ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() }',
|
|
281
|
+
' "$($p.ProcessId)`t$cmd`t$t`t$e"',
|
|
282
|
+
'}',
|
|
283
|
+
].join('\n')
|
|
284
|
+
const env = { ...process.env, DSH_BRIDGE_HOSTJS: path.join(hostDir, 'host.js'), DSH_BRIDGE_RUNBAT: path.join(hostDir, 'run.bat'), DSH_BRIDGE_HOSTDIR: hostDir, DSH_BRIDGE_KEEP: keep }
|
|
285
|
+
return new Promise((resolve, reject) => {
|
|
286
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
|
|
287
|
+
{ env, windowsHide: true, timeout: 60000, encoding: 'utf8' }, (err, stdout) => {
|
|
288
|
+
if (err) return reject(err)
|
|
289
|
+
const lines = String(stdout).split(/\r?\n/).map((l) => l.trim())
|
|
290
|
+
// 查询本身跑完了才会先打 OK:没有这行就是半路出错了
|
|
291
|
+
const total = (/^HOSTS\t(\d+)$/m.exec(lines.join('\n')) || [])[1]
|
|
292
|
+
if (!lines.includes('OK') || total === undefined) return reject(new Error('列进程没有跑完'))
|
|
293
|
+
resolve(lines.map((l) => l.split('\t'))
|
|
294
|
+
.filter(([pid, cmd, t]) => /^\d+$/.test(pid) && /^\d+$/.test(cmd || '') && /^\d+$/.test(t || ''))
|
|
295
|
+
.map(([pid, cmd, t, exe]) => ({ pid: Number(pid), cmd: Number(cmd), created: Number(t), hosts: Number(total), exe })))
|
|
296
|
+
})
|
|
297
|
+
})
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 结束旧宿主:有拉起它的 cmd 就连 cmd 带它一起结束(/T),没有就只结束它 */
|
|
301
|
+
function killHost({ pid, cmd }) {
|
|
302
|
+
const args = cmd ? ['/pid', String(cmd), '/T', '/F'] : ['/pid', String(pid), '/F']
|
|
303
|
+
return new Promise((r) => execFile('taskkill', args, { windowsHide: true, timeout: 15000 }, (e) => r(!e)))
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 问占着管道的宿主(DSH 和 cb 只连它)现在能不能换掉旧宿主 h:
|
|
308
|
+
* 'idle' 就是它,手上没有在途的操作,而且最近 5 秒没收到扩展的消息——扩展的回话一到它就开始往客户端写,
|
|
309
|
+
* 老宿主的 status 不报「还在写」,所以等最后一条回话过去 5 秒(本机管道上早写完了);
|
|
310
|
+
* 'busy' 就是它,但有在途的操作、或刚收到扩展的消息;
|
|
311
|
+
* 'foreign' 不是它,或者问不到。
|
|
312
|
+
* getStatus:问宿主 status 的函数(插件里悄悄问,e2e 里用 cb)。
|
|
313
|
+
*/
|
|
314
|
+
export function hostProbe(getStatus, { extQuietMs = 5000 } = {}) {
|
|
315
|
+
return async (h) => {
|
|
316
|
+
let st = null
|
|
317
|
+
try { st = await getStatus() } catch {}
|
|
318
|
+
if (!st || st.pid !== h.pid) return 'foreign'
|
|
319
|
+
if (st.pending > 0 || Date.now() - (Number(st.lastExtMsg) || 0) < extQuietMs) return 'busy'
|
|
320
|
+
return 'idle'
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Windows:启动脚本换了 node 之后,把还在用别的程序跑着的宿主换下来(比如老版本用 DSH 安装目录里的程序拉起的)。
|
|
326
|
+
* 不换的话它要等 Chrome 完全退出才会走,这期间照样占着 DSH 安装目录。结束掉之后扩展马上重连,Chrome 按新脚本拉起新宿主。
|
|
327
|
+
*
|
|
328
|
+
* 别的 DSH / cb 可能正通过它操作浏览器,老宿主在 Windows 上又不会自己排空退出,只能从外面结束,所以只换「占着管道、闲着」的:
|
|
329
|
+
* probe(见 hostProbe)连续答 'idle' 够 idleMs,再列一遍进程确认它还在(pid 和创建时刻都对得上),隔一秒再问一次还闲,马上结束。
|
|
330
|
+
* 答案一变计时重来(末次复查也算)。几个旧宿主同时等,互不耽误。
|
|
331
|
+
* 浏览器拉起的宿主不止一个(Chrome 和 Edge / 两个 Chrome 用户都装了扩展)就整个不换:结束哪个都可能让另一个接过管道
|
|
332
|
+
* (被结束的重连后变成最新的那个,或者后台那个在空档里按自愈逻辑把 token 改成自己的),DSH 接下来的操作就跑到另一个浏览器去了。
|
|
333
|
+
* 这种只能等用户重启浏览器;记号留着,下次加载只剩一个时再换。问不到 / 不是它('foreign')连着几次也放弃这次。
|
|
334
|
+
* 有没换下的就不调 done:记号留着,下次加载再试。
|
|
335
|
+
* 连拉起它的 cmd 一起结束:cmd 跑批处理是一行一行现读的,宿主一退它会按原来的位置接着读 run.bat——
|
|
336
|
+
* 而 run.bat 刚被我们改写过,接着读到的正是新脚本里拉宿主的那行,变量还是旧的,于是又用 DSH 的程序拉起一个宿主,
|
|
337
|
+
* 还接在 Chrome 原来那条管道上(CI 实测)。cmd 一走管道就断了,扩展重连,Chrome 按新脚本拉起新宿主。
|
|
338
|
+
* 剩下的风险:「最后一次问还闲」和「结束」之间几十毫秒里正好进来的操作、或者一个卡住 5 秒以上不读回话的客户端,会断掉
|
|
339
|
+
* (客户端看到连接被关)。只在第一次换宿主时有这么一下,老宿主没有别的办法让它排空。
|
|
340
|
+
*/
|
|
341
|
+
export async function restartStaleHosts(hostDir, keep, {
|
|
342
|
+
log = () => {}, probe = async () => 'foreign', list = listStaleHosts, kill = killHost,
|
|
343
|
+
done = () => {}, waitMs = 15 * 60_000, idleMs = 5000, pollMs = 2000, foreignTries = 3,
|
|
344
|
+
} = {}) {
|
|
345
|
+
// 计时器不拖住进程:DSH 命令行这类很快就退出的场合,等不完就算了(记号还在,下次再来)
|
|
346
|
+
const sleep = (ms) => new Promise((r) => { const t = setTimeout(r, ms); if (t.unref) t.unref() })
|
|
347
|
+
let stale
|
|
348
|
+
try { stale = await list(hostDir, keep) } catch (e) { return log(`查旧宿主失败:${e.message}`) }
|
|
349
|
+
const multi = (h) => `有 ${h.hosts} 个浏览器(或用户)连着宿主,这次不换旧宿主:结束一个的空档里另一个可能接过管道,`
|
|
350
|
+
+ 'DSH 的操作就跑到别的浏览器去了。把浏览器都重启一次就好'
|
|
351
|
+
if (stale.some((h) => h.hosts > 1)) return log(multi(stale.find((h) => h.hosts > 1)))
|
|
352
|
+
|
|
353
|
+
const one = async (host) => {
|
|
354
|
+
const { pid, exe } = host
|
|
355
|
+
const until = Date.now() + waitMs
|
|
356
|
+
let idleSince = null
|
|
357
|
+
let foreign = 0
|
|
358
|
+
const ask = async () => {
|
|
359
|
+
const st = await probe(host)
|
|
360
|
+
idleSince = st === 'idle' ? (idleSince ?? Date.now()) : null
|
|
361
|
+
foreign = st === 'foreign' ? foreign + 1 : 0
|
|
362
|
+
return st
|
|
363
|
+
}
|
|
364
|
+
const ready = () => idleSince !== null && Date.now() - idleSince >= idleMs
|
|
365
|
+
while (Date.now() < until) {
|
|
366
|
+
await ask()
|
|
367
|
+
if (foreign >= foreignTries) { log(`问不到旧宿主 ${pid},这次不动它(${exe}),下次加载再看`); return false }
|
|
368
|
+
if (ready()) {
|
|
369
|
+
// 慢的(PowerShell 列进程)放在前面,最后一次问和结束之间不夹别的
|
|
370
|
+
let fresh
|
|
371
|
+
try { fresh = (await list(hostDir, keep)).find((h) => h.pid === pid && h.created === host.created) } catch (e) {
|
|
372
|
+
log(`复查旧宿主 ${pid} 失败,这次不结束:${e.message}`)
|
|
373
|
+
return false
|
|
374
|
+
}
|
|
375
|
+
if (!fresh) return true // 自己走了
|
|
376
|
+
if (fresh.hosts > 1) { log(multi(fresh)); return false }
|
|
377
|
+
await sleep(1000)
|
|
378
|
+
if (await ask() === 'idle' && ready()) {
|
|
379
|
+
const ok = await kill(fresh)
|
|
380
|
+
log(ok ? `换下了还在用旧程序跑的宿主 ${pid}(${exe})` : `结束旧宿主 ${pid} 失败(${exe})`)
|
|
381
|
+
return ok
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
await sleep(pollMs)
|
|
385
|
+
}
|
|
386
|
+
log(`旧宿主 ${pid} 一直没空,这次不换(${exe}),下次加载再试`)
|
|
387
|
+
return false
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const results = await Promise.all(stale.map((h) => one(h).catch((e) => { log(`换旧宿主 ${h.pid} 出错:${e.message}`); return false })))
|
|
391
|
+
if (results.every(Boolean)) done()
|
|
392
|
+
}
|
|
393
|
+
|
|
189
394
|
/** 单引号包起来给 sh 用(路径里的单引号拆开转义) */
|
|
190
395
|
const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
|
|
191
396
|
|
|
@@ -285,9 +490,12 @@ export function ensureInstalled(options = {}) {
|
|
|
285
490
|
|
|
286
491
|
let nmPrev = null
|
|
287
492
|
try { nmPrev = fs.readFileSync(p.nmFile, 'utf8') } catch {}
|
|
288
|
-
|
|
493
|
+
// 桌面版(Electron)在 Windows 上:宿主改用复制到宿主目录的独立 node,别占着 DSH 安装目录(issue #3)
|
|
494
|
+
const primary = win && process.versions.electron ? hostNode(p.hostDir) : null
|
|
495
|
+
const launcherBody = win ? winLauncher(process.execPath, Boolean(process.versions.electron), primary && path.basename(primary)) : unixLauncher()
|
|
289
496
|
let launcherPrev = null
|
|
290
497
|
try { launcherPrev = fs.readFileSync(p.launcher, 'utf8') } catch {}
|
|
498
|
+
const restartMark = path.join(p.hostDir, 'restart-hosts.pending')
|
|
291
499
|
const regOk = !win || REG_KEYS.every((k) => regValue(k) === p.nmFile)
|
|
292
500
|
const upToDate = prev === stamp && nmPrev === nmBody && launcherPrev === launcherBody && regOk
|
|
293
501
|
&& allPresent(vExt, p.extDir) && allPresent(vHost, p.hostDir)
|
|
@@ -296,6 +504,8 @@ export function ensureInstalled(options = {}) {
|
|
|
296
504
|
fs.cpSync(vExt, p.extDir, { recursive: true, force: true })
|
|
297
505
|
fs.mkdirSync(p.hostDir, { recursive: true })
|
|
298
506
|
fs.cpSync(vHost, p.hostDir, { recursive: true, force: true })
|
|
507
|
+
// 换了 node:先记一笔「还有旧宿主要换」再写启动脚本(后面哪步失败了,下次加载也还记得要换),换完才删
|
|
508
|
+
if (primary && launcherPrev !== launcherBody) fs.writeFileSync(restartMark, `${primary}\n`)
|
|
299
509
|
fs.writeFileSync(p.launcher, launcherBody)
|
|
300
510
|
if (!win) fs.chmodSync(p.launcher, 0o755)
|
|
301
511
|
fs.rmSync(path.join(p.hostDir, 'launch-error.txt'), { force: true }) // 上回拉不起来的原因:脚本重写了就作废
|
|
@@ -309,6 +519,12 @@ export function ensureInstalled(options = {}) {
|
|
|
309
519
|
fs.writeFileSync(p.stampFile, `${stamp}\n`)
|
|
310
520
|
out.changed = true
|
|
311
521
|
}
|
|
522
|
+
if (primary && fs.existsSync(restartMark)) {
|
|
523
|
+
restartStaleHosts(p.hostDir, primary, {
|
|
524
|
+
log: options.log || undefined, probe: options.probe,
|
|
525
|
+
done: () => { try { fs.rmSync(restartMark, { force: true }) } catch {} },
|
|
526
|
+
}).catch((e) => options.log && options.log(`换旧宿主出错:${e.message}`))
|
|
527
|
+
}
|
|
312
528
|
|
|
313
529
|
// ── 可选件:cb CLI、页内光标脚本 —— 失败只是少个便利,不该让安装失败 ──
|
|
314
530
|
// 刻意不动 ~/.dsh/skills:那是全局 agent 行为,装了插件就有原生 browser_* 工具,不需要它。
|