dsh-chrome-bridge 1.19.0 → 2.0.0

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 (89) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +37 -16
  14. package/download.js +895 -69
  15. package/drag.js +68 -30
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +312 -16
  22. package/i18n/index.js +17 -0
  23. package/i18n/ru.js +312 -16
  24. package/i18n/zh.js +310 -14
  25. package/image-guard.js +13 -6
  26. package/index.js +21 -1073
  27. package/locale/ru.json +7 -0
  28. package/nav.js +56 -10
  29. package/package.json +8 -1
  30. package/panel.js +14 -4
  31. package/refs.js +293 -240
  32. package/setup.js +248 -74
  33. package/tools/click.js +58 -0
  34. package/tools/devtools.js +61 -0
  35. package/tools/dialog.js +22 -0
  36. package/tools/download.js +50 -0
  37. package/tools/drag.js +61 -0
  38. package/tools/eval.js +22 -0
  39. package/tools/fill.js +77 -0
  40. package/tools/handoff.js +40 -0
  41. package/tools/index.js +38 -0
  42. package/tools/input.js +147 -0
  43. package/tools/nav.js +57 -0
  44. package/tools/read.js +87 -0
  45. package/tools/record.js +120 -0
  46. package/tools/screenshot.js +223 -0
  47. package/tools/tabs.js +131 -0
  48. package/tools/wait.js +56 -0
  49. package/vendor/cb +616 -35
  50. package/vendor/extension/_locales/en/messages.json +3 -0
  51. package/vendor/extension/_locales/ru/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  53. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  54. package/vendor/extension/background.js +2 -1969
  55. package/vendor/extension/confirm.css +148 -0
  56. package/vendor/extension/confirm.html +49 -0
  57. package/vendor/extension/confirm.js +188 -0
  58. package/vendor/extension/in-page-cursor.js +599 -0
  59. package/vendor/extension/manifest.json +11 -2
  60. package/vendor/extension/popup.css +99 -5
  61. package/vendor/extension/popup.html +28 -2
  62. package/vendor/extension/popup.js +430 -45
  63. package/vendor/extension/sw/boot.js +111 -0
  64. package/vendor/extension/sw/cdp.js +411 -0
  65. package/vendor/extension/sw/chooser.js +192 -0
  66. package/vendor/extension/sw/confirm.js +608 -0
  67. package/vendor/extension/sw/cursor.js +241 -0
  68. package/vendor/extension/sw/dispatch.js +129 -0
  69. package/vendor/extension/sw/download.js +279 -0
  70. package/vendor/extension/sw/fetch-hub.js +224 -0
  71. package/vendor/extension/sw/frames.js +651 -0
  72. package/vendor/extension/sw/imaging.js +361 -0
  73. package/vendor/extension/sw/native.js +111 -0
  74. package/vendor/extension/sw/net-tools.js +525 -0
  75. package/vendor/extension/sw/ops.js +829 -0
  76. package/vendor/extension/sw/popup-api.js +303 -0
  77. package/vendor/extension/sw/profile.js +166 -0
  78. package/vendor/extension/sw/record.js +494 -0
  79. package/vendor/extension/sw/state.js +161 -0
  80. package/vendor/extension/sw/tabui.js +219 -0
  81. package/vendor/extension/sw/util.js +166 -0
  82. package/vendor/extension/sw/welcome.js +26 -0
  83. package/vendor/extension/sw/windows.js +94 -0
  84. package/vendor/extension/welcome.css +189 -0
  85. package/vendor/extension/welcome.html +70 -0
  86. package/vendor/extension/welcome.js +157 -0
  87. package/vendor/host/host.js +476 -71
  88. package/vendor/in-page-cursor.js +309 -37
  89. package/vendor/skill/SKILL.md +34 -16
package/setup.js CHANGED
@@ -24,6 +24,7 @@ import path from 'node:path'
24
24
  import crypto from 'node:crypto'
25
25
  import { execFile, execFileSync, spawn } from 'node:child_process'
26
26
  import { fileURLToPath } from 'node:url'
27
+ import { tt } from './i18n/index.js'
27
28
 
28
29
  export const HOST_NAME = 'com.dsh.bridge'
29
30
  export const EXT_DIR_NAME = 'dsh-bridge-extension'
@@ -84,6 +85,25 @@ export function paths(home = os.homedir(), platform = process.platform) {
84
85
  }
85
86
  }
86
87
 
88
+ // Chrome Stable 总是注册。其余浏览器只使用已经存在的用户数据目录。
89
+ function browserDirs(home, platform = process.platform) {
90
+ const stable = paths(home, platform).chromeDir
91
+ const mac = platform === 'darwin'
92
+ const win = platform === 'win32'
93
+ const root = win ? path.dirname(path.dirname(path.dirname(stable))) :
94
+ path.join(home, mac ? 'Library/Application Support' : '.config')
95
+ const names = win ? ['Google/Chrome Beta/User Data', 'Google/Chrome SxS/User Data', 'Google/Chrome Dev/User Data',
96
+ 'Microsoft/Edge/User Data', 'BraveSoftware/Brave-Browser/User Data', 'Chromium/User Data', 'Vivaldi/User Data'] :
97
+ mac ? ['Google/Chrome Beta', 'Google/Chrome Canary', 'Google/Chrome Dev', 'Microsoft Edge',
98
+ 'BraveSoftware/Brave-Browser', 'Arc/User Data', 'Chromium', 'Vivaldi'] :
99
+ ['google-chrome-beta', 'google-chrome-canary', 'google-chrome-unstable', 'microsoft-edge',
100
+ 'BraveSoftware/Brave-Browser', 'arc', 'chromium', 'vivaldi']
101
+ const discovered = names.map((name) => path.join(root, name)).filter((dir) => {
102
+ try { return fs.statSync(dir).isDirectory() } catch { return false }
103
+ })
104
+ return [stable, ...discovered]
105
+ }
106
+
87
107
  /**
88
108
  * 扩展 ID:由 manifest.json 里的公钥(key)推导,每台机器都一样。
89
109
  * 算法与 Chrome / install.sh 一致:sha256(DER) 前 16 字节 → 每个 nibble 映射成 a..p。
@@ -91,14 +111,32 @@ export function paths(home = os.homedir(), platform = process.platform) {
91
111
  */
92
112
  export function extensionId(manifestFile) {
93
113
  const key = JSON.parse(fs.readFileSync(manifestFile, 'utf8')).key
114
+ if (!key || typeof key !== 'string') return null
94
115
  const hex = crypto.createHash('sha256').update(Buffer.from(key, 'base64')).digest('hex').slice(0, 32)
95
116
  return [...hex].map((c) => String.fromCharCode(97 + parseInt(c, 16))).join('')
96
117
  }
97
118
 
98
- function copyFile(src, dest, mode) {
119
+ function atomicWrite(dest, body, mode = 0o644) {
99
120
  fs.mkdirSync(path.dirname(dest), { recursive: true })
100
- fs.copyFileSync(src, dest)
101
- if (mode) fs.chmodSync(dest, mode)
121
+ const tmp = `${dest}.tmp.${process.pid}`
122
+ const fd = fs.openSync(tmp, 'wx', mode)
123
+ try {
124
+ try { fs.writeFileSync(fd, body) } finally { fs.closeSync(fd) }
125
+ fs.renameSync(tmp, dest)
126
+ } finally { fs.rmSync(tmp, { force: true }) }
127
+ }
128
+
129
+ function syncFile(src, dest, mode = 0o644) {
130
+ const body = fs.readFileSync(src)
131
+ try {
132
+ if (fs.readFileSync(dest).equals(body) &&
133
+ (process.platform === 'win32' || (fs.statSync(dest).mode & 0o777) === mode)) return
134
+ } catch (e) { if (e.code !== 'ENOENT') throw e }
135
+ atomicWrite(dest, body, mode)
136
+ }
137
+
138
+ function readText(file) {
139
+ try { return fs.readFileSync(file, 'utf8') } catch (e) { if (e.code !== 'ENOENT') throw e; return null }
102
140
  }
103
141
 
104
142
  /** vendor 树的内容指纹:内容没变就整段跳过,插件每次启动都调它也不会抖动。 */
@@ -133,15 +171,16 @@ function allPresent(src, dest) {
133
171
  * 最终还是看宿主连不连得上。返回 { id, profile, version } 或 null;读不到就当没装。
134
172
  */
135
173
  export function storeExtension(home = os.homedir()) {
136
- const { chromeDir } = paths(home)
137
- let profiles = []
138
- try { profiles = fs.readdirSync(chromeDir).filter((n) => n === 'Default' || /^Profile \d+$/.test(n)) } catch {}
139
- for (const profile of profiles) {
140
- for (const id of STORE_EXT_IDS) {
141
- try {
142
- const vers = fs.readdirSync(path.join(chromeDir, profile, 'Extensions', id)).filter((v) => !v.startsWith('.'))
143
- if (vers.length) return { id, profile, version: vers.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).pop().replace(/_\d+$/, '') }
144
- } catch {}
174
+ for (const chromeDir of browserDirs(home)) {
175
+ let profiles = []
176
+ try { profiles = fs.readdirSync(chromeDir).filter((n) => n === 'Default' || /^Profile \d+$/.test(n)) } catch {}
177
+ for (const profile of profiles) {
178
+ for (const id of STORE_EXT_IDS) {
179
+ try {
180
+ const vers = fs.readdirSync(path.join(chromeDir, profile, 'Extensions', id)).filter((v) => !v.startsWith('.'))
181
+ if (vers.length) return { id, profile, version: vers.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).pop().replace(/_\d+$/, '') }
182
+ } catch {}
183
+ }
145
184
  }
146
185
  }
147
186
  return null
@@ -177,17 +216,24 @@ const bat = (s) => String(s).replace(/%/g, '%%')
177
216
  * primary 用 %~dp0 拼:用户目录带中文时,脚本里直接写中文路径 cmd 会读错(CI 实测),%~dp0 是 cmd 自己算的,不会错。
178
217
  * DSH 升级换了路径,插件下次加载会重写这个文件。路径可能带中文,先把代码页切到 UTF-8 再读后面的行。
179
218
  */
180
- export function winLauncher(execPath = process.execPath, electron = Boolean(process.versions.electron), primary = null) {
219
+ export function winLauncher(execPath = process.execPath, electron = Boolean(process.versions.electron), primary = null, cli = false) {
181
220
  return [
182
221
  '@echo off',
183
222
  'chcp 65001 >nul',
184
- 'setlocal',
223
+ 'setlocal DisableDelayedExpansion',
224
+ 'set "FOUND_NODE="',
185
225
  ...(electron ? ['set ELECTRON_RUN_AS_NODE=1'] : []),
186
226
  ...(primary ? [`set "N=%~dp0${primary}"`, `if not exist "%N%" set "N=${bat(execPath)}"`] : [`set "N=${bat(execPath)}"`]),
187
227
  'if defined DSH_BRIDGE_NODE set "N=%DSH_BRIDGE_NODE%"',
188
- 'if not exist "%N%" for %%I in (node.exe) do set "N=%%~$PATH:I"',
228
+ ...(cli ? ['if not exist "%N%" for %%I in ("%USERPROFILE%\\.dsh\\chrome-bridge\\host\\node-*.exe") do if exist "%%~fI" set "N=%%~fI"'] : []),
229
+ ...['%ProgramFiles%\\nodejs', '%LOCALAPPDATA%\\Programs\\nodejs', '%VOLTA_HOME%', '%NVM_SYMLINK%'].map((dir) =>
230
+ `if not exist "%N%" if defined ${dir.split('%')[1]} if exist "${dir}\\node.exe" set "N=${dir}\\node.exe"`),
231
+ 'if not exist "%N%" for /f "delims=" %%I in (\'where node.exe 2^>nul\') do if not defined FOUND_NODE set "FOUND_NODE=%%I"',
232
+ 'if not exist "%N%" if defined FOUND_NODE set "N=%FOUND_NODE%"',
233
+ 'if not exist "%N%" (>"%~dp0launch-error.txt" echo Node.js not found. Set DSH_BRIDGE_NODE. & exit /b 1)',
234
+ 'if exist "%~dp0launch-error.txt" del /q "%~dp0launch-error.txt" >nul 2>&1',
189
235
  // 宿主退出后马上 exit /b:cmd 不再回头读这个文件(文件可能已被改写,见 restartStaleHosts)
190
- '"%N%" "%~dp0host.js" %* & exit /b',
236
+ `"%N%" "%~dp0${cli ? 'cb' : 'host.js'}" %* & exit /b`,
191
237
  '',
192
238
  ].join('\r\n')
193
239
  }
@@ -289,7 +335,7 @@ export function listStaleHosts(hostDir, keep) {
289
335
  const lines = String(stdout).split(/\r?\n/).map((l) => l.trim())
290
336
  // 查询本身跑完了才会先打 OK:没有这行就是半路出错了
291
337
  const total = (/^HOSTS\t(\d+)$/m.exec(lines.join('\n')) || [])[1]
292
- if (!lines.includes('OK') || total === undefined) return reject(new Error('列进程没有跑完'))
338
+ if (!lines.includes('OK') || total === undefined) return reject(new Error(tt('err.setupProcList')))
293
339
  resolve(lines.map((l) => l.split('\t'))
294
340
  .filter(([pid, cmd, t]) => /^\d+$/.test(pid) && /^\d+$/.test(cmd || '') && /^\d+$/.test(t || ''))
295
341
  .map(([pid, cmd, t, exe]) => ({ pid: Number(pid), cmd: Number(cmd), created: Number(t), hosts: Number(total), exe })))
@@ -354,6 +400,7 @@ export async function restartStaleHosts(hostDir, keep, {
354
400
  const { pid, exe } = host
355
401
  const until = Date.now() + waitMs
356
402
  let idleSince = null
403
+ let delay = pollMs
357
404
  let foreign = 0
358
405
  const ask = async () => {
359
406
  const st = await probe(host)
@@ -363,7 +410,7 @@ export async function restartStaleHosts(hostDir, keep, {
363
410
  }
364
411
  const ready = () => idleSince !== null && Date.now() - idleSince >= idleMs
365
412
  while (Date.now() < until) {
366
- await ask()
413
+ let status = await ask()
367
414
  if (foreign >= foreignTries) { log(`问不到旧宿主 ${pid},这次不动它(${exe}),下次加载再看`); return false }
368
415
  if (ready()) {
369
416
  // 慢的(PowerShell 列进程)放在前面,最后一次问和结束之间不夹别的
@@ -375,13 +422,16 @@ export async function restartStaleHosts(hostDir, keep, {
375
422
  if (!fresh) return true // 自己走了
376
423
  if (fresh.hosts > 1) { log(multi(fresh)); return false }
377
424
  await sleep(1000)
378
- if (await ask() === 'idle' && ready()) {
425
+ status = await ask()
426
+ if (status === 'idle' && ready()) {
379
427
  const ok = await kill(fresh)
380
428
  log(ok ? `换下了还在用旧程序跑的宿主 ${pid}(${exe})` : `结束旧宿主 ${pid} 失败(${exe})`)
381
429
  return ok
382
430
  }
383
431
  }
384
- await sleep(pollMs)
432
+ if (status !== 'busy') delay = pollMs
433
+ await sleep(Math.min(delay, Math.max(0, until - Date.now())))
434
+ if (status === 'busy') delay = Math.min(30_000, delay * 2)
385
435
  }
386
436
  log(`旧宿主 ${pid} 一直没空,这次不换(${exe}),下次加载再试`)
387
437
  return false
@@ -414,14 +464,35 @@ export function unixLauncher(execPath = process.execPath, electron = Boolean(pro
414
464
  'if [ -n "$DSH_BRIDGE_NODE" ] && [ -x "$DSH_BRIDGE_NODE" ]; then go "$DSH_BRIDGE_NODE" "$@"; fi',
415
465
  `if [ -x "$DSH_NODE" ]; then ${electron ? 'export ELECTRON_RUN_AS_NODE=1; ' : ''}go "$DSH_NODE" "$@"; fi`,
416
466
  '',
417
- 'for N in /usr/local/bin/node "$HOME/.local/bin/node" /opt/homebrew/bin/node /usr/bin/node \\',
418
- ' "$HOME/.volta/bin/node" "$HOME/.asdf/shims/node" "$HOME/.local/share/mise/shims/node"; do',
419
- ' if [ -x "$N" ]; then go "$N" "$@"; fi',
467
+ 'latest_node() {',
468
+ ' base="$1"; suffix="$2"; prefix="${3#v}"',
469
+ ' for dir in "$base"/v[0-9]*; do',
470
+ ' ver="${dir##*/v}"',
471
+ ' case "$ver." in "$prefix".*) ;; *) [ -z "$prefix" ] || continue ;; esac',
472
+ ' [ -x "$dir/$suffix" ] && printf \'%s\\n\' "$ver"',
473
+ ' done | LC_ALL=C sort -t. -k1,1nr -k2,2nr -k3,3nr | head -n 1',
474
+ '}',
475
+ 'NVM="${NVM_DIR:-$HOME/.nvm}"',
476
+ 'alias=$(cat "$NVM/alias/default" 2>/dev/null)',
477
+ 'depth=0',
478
+ 'while [ "$depth" -lt 8 ]; do',
479
+ ' case "$alias" in lts/*) ;; *[!a-zA-Z0-9_-]*|\'\') break ;; esac',
480
+ ' case "$alias" in *..*) break ;; esac',
481
+ ' [ -f "$NVM/alias/$alias" ] || break',
482
+ ' alias=$(cat "$NVM/alias/$alias"); depth=$((depth + 1))',
483
+ 'done',
484
+ 'base="$NVM/versions/node"',
485
+ 'ver=$(latest_node "$base" bin/node "$alias")',
486
+ '[ -n "$ver" ] || ver=$(latest_node "$base" bin/node "")',
487
+ 'if [ -n "$ver" ]; then go "$base/v$ver/bin/node" "$@"; fi',
488
+ 'for base in "${FNM_DIR:-$HOME/.local/share/fnm}" "$HOME/Library/Application Support/fnm"; do',
489
+ ' if [ -x "$base/aliases/default/bin/node" ]; then go "$base/aliases/default/bin/node" "$@"; fi',
490
+ ' ver=$(latest_node "$base/node-versions" installation/bin/node "")',
491
+ ' if [ -n "$ver" ]; then go "$base/node-versions/v$ver/installation/bin/node" "$@"; fi',
420
492
  'done',
421
- 'for N in "$HOME"/.nvm/versions/node/*/bin/node; do',
422
- ' if [ -x "$N" ]; then LAST="$N"; fi',
493
+ 'for N in /usr/local/bin/node "$HOME/.local/bin/node" /opt/homebrew/bin/node /usr/bin/node /opt/local/bin/node "$HOME/.nodenv/shims/node" "$HOME/.nix-profile/bin/node" "$HOME/.volta/bin/node" "$HOME/.asdf/shims/node" "$HOME/.local/share/mise/shims/node"; do',
494
+ ' if [ -x "$N" ]; then go "$N" "$@"; fi',
423
495
  'done',
424
- 'if [ -n "$LAST" ]; then go "$LAST" "$@"; fi',
425
496
  'N="$(command -v node 2>/dev/null)"',
426
497
  'if [ -n "$N" ]; then go "$N" "$@"; fi',
427
498
  '',
@@ -433,20 +504,77 @@ export function unixLauncher(execPath = process.execPath, electron = Boolean(pro
433
504
  ].join('\n')
434
505
  }
435
506
 
507
+ export const STALE_MS = 120_000
508
+
509
+ /**
510
+ * 列出 DIR/hosts/ 下所有存活的宿主注册项(只读,供插件多宿主路由和 cb CLI 复用)。
511
+ * 校验 DIR 和 DIR/hosts/ 为当前用户自有真目录(防软链接/宽松权限),过滤死 PID、过期心跳和缺 socket 的残留。
512
+ */
513
+ export function listHostEntries(dir = process.env.DSH_BRIDGE_DIR || (process.platform === 'win32' ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)) {
514
+ const win = process.platform === 'win32'
515
+ const safeDir = (d) => {
516
+ try {
517
+ const st = fs.lstatSync(d)
518
+ if (!st.isDirectory()) return false
519
+ if (!win && (st.uid !== process.getuid() || (st.mode & 0o077) !== 0)) return false
520
+ return true
521
+ } catch { return false }
522
+ }
523
+ const hostsDir = path.join(dir, 'hosts')
524
+ if (!safeDir(dir) || !safeDir(hostsDir)) return []
525
+ const alive = (pid) => {
526
+ if (!Number.isInteger(pid) || pid <= 0) return false
527
+ try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
528
+ }
529
+ const hasUnixSocket = (sockPath) => {
530
+ if (win) return true
531
+ try { return fs.lstatSync(sockPath).isSocket() } catch { return false }
532
+ }
533
+ const now = Date.now()
534
+ const entries = []
535
+ let files = []
536
+ try { files = fs.readdirSync(hostsDir) } catch { return [] }
537
+ for (const name of files) {
538
+ if (!name.endsWith('.json')) continue
539
+ const full = path.join(hostsDir, name)
540
+ try {
541
+ const st = fs.lstatSync(full)
542
+ if (!st.isFile() || (!win && st.uid !== process.getuid())) continue
543
+ const data = JSON.parse(fs.readFileSync(full, 'utf8'))
544
+ if (!data || typeof data !== 'object') continue
545
+ if (!alive(data.pid)) continue
546
+ const ts = Number(data.lastSeenAt || data.startedAt || 0)
547
+ if (!Number.isFinite(ts) || ts <= 0 || now - ts > STALE_MS || ts - now > STALE_MS) continue
548
+ if (typeof data.socket !== 'string' || !data.socket || typeof data.token !== 'string' || !data.token) continue
549
+ if (!hasUnixSocket(data.socket)) continue
550
+ entries.push({ ...data, registryFile: full })
551
+ } catch {}
552
+ }
553
+ return entries.sort((a, b) => (Number(b.focusedAt) || 0) - (Number(a.focusedAt) || 0)
554
+ || (Number(b.lastSeenAt) || 0) - (Number(a.lastSeenAt) || 0)
555
+ || (Number(a.startedAt) || 0) - (Number(b.startedAt) || 0))
556
+ }
557
+
436
558
  /** 装好了没有(只看落盘结果,不管 Chrome 有没有加载扩展)。 */
559
+ const stateCache = new Map()
560
+
437
561
  export function installState(home = os.homedir()) {
562
+ const cached = stateCache.get(home)
563
+ if (cached && Date.now() - cached.at < 30_000) return { ...cached.state }
438
564
  const p = paths(home)
439
565
  let extId = null
440
566
  try { extId = extensionId(path.join(p.extDir, 'manifest.json')) } catch {}
441
- return {
567
+ const state = {
442
568
  ...p,
443
569
  extId,
444
- extensionCopied: !!extId,
570
+ extensionCopied: fs.existsSync(path.join(p.extDir, 'manifest.json')),
445
571
  hostCopied: fs.existsSync(p.launcher),
446
- registered: fs.existsSync(p.nmFile) && (process.platform !== 'win32' || regValue(REG_KEYS[0]) !== null),
572
+ registered: fs.existsSync(p.nmFile) && (process.platform !== 'win32' || regValue(REG_KEYS[0]) === p.nmFile),
447
573
  vendor: fs.existsSync(vendorDir()),
448
574
  store: storeExtension(home),
449
575
  }
576
+ stateCache.set(home, { state, at: Date.now() })
577
+ return { ...state }
450
578
  }
451
579
 
452
580
  /**
@@ -456,10 +584,11 @@ export function installState(home = os.homedir()) {
456
584
  * 1. 扩展 → ~/dsh-bridge-extension(Chrome「加载已解压」要选它,所以必须可见、稳定)
457
585
  * 2. 原生宿主 → ~/.dsh/chrome-bridge/host/(注册文件指向这里)
458
586
  * 3. 写注册文件 NativeMessagingHosts/com.dsh.bridge.json(allowed_origins 绑定固定扩展 ID)
459
- * 4. 顺带落一个 cb CLI + 页内光标脚本(可选,失败不影响主流程;不碰 ~/.dsh/skills)
587
+ * 4. 同步浏览器技能、cb CLI 和页内光标脚本
460
588
  */
461
589
  export function ensureInstalled(options = {}) {
462
590
  const home = options.home || os.homedir()
591
+ stateCache.delete(home)
463
592
  const vendor = options.vendor || vendorDir()
464
593
  const p = paths(home)
465
594
  const out = { ok: false, changed: false, home, vendor, ...p }
@@ -485,11 +614,10 @@ export function ensureInstalled(options = {}) {
485
614
  description: 'dsh-chrome-bridge native host (local browser control)',
486
615
  path: p.launcher,
487
616
  type: 'stdio',
488
- allowed_origins: [extId, ...STORE_EXT_IDS].map((id) => `chrome-extension://${id}/`),
617
+ allowed_origins: [extId, ...STORE_EXT_IDS].filter(Boolean).map((id) => `chrome-extension://${id}/`),
489
618
  }, null, 2)}\n`
490
619
 
491
- let nmPrev = null
492
- try { nmPrev = fs.readFileSync(p.nmFile, 'utf8') } catch {}
620
+ const manifests = win ? [p.nmFile] : browserDirs(home).map((dir) => path.join(dir, 'NativeMessagingHosts', HOST_NAME + '.json'))
493
621
  // 桌面版(Electron)在 Windows 上:宿主改用复制到宿主目录的独立 node,别占着 DSH 安装目录(issue #3)
494
622
  const primary = win && process.versions.electron ? hostNode(p.hostDir) : null
495
623
  const launcherBody = win ? winLauncher(process.execPath, Boolean(process.versions.electron), primary && path.basename(primary)) : unixLauncher()
@@ -497,26 +625,24 @@ export function ensureInstalled(options = {}) {
497
625
  try { launcherPrev = fs.readFileSync(p.launcher, 'utf8') } catch {}
498
626
  const restartMark = path.join(p.hostDir, 'restart-hosts.pending')
499
627
  const regOk = !win || REG_KEYS.every((k) => regValue(k) === p.nmFile)
500
- const upToDate = prev === stamp && nmPrev === nmBody && launcherPrev === launcherBody && regOk
501
- && allPresent(vExt, p.extDir) && allPresent(vHost, p.hostDir)
628
+ const upToDate = !options.force && prev === stamp && manifests.every((f) => readText(f) === nmBody) && launcherPrev === launcherBody && regOk
629
+ && allPresent(vExt, p.extDir) && fs.existsSync(path.join(p.hostDir, 'host.js'))
502
630
  if (!upToDate) {
503
631
  fs.mkdirSync(p.extDir, { recursive: true })
504
632
  fs.cpSync(vExt, p.extDir, { recursive: true, force: true })
505
633
  fs.mkdirSync(p.hostDir, { recursive: true })
506
- fs.cpSync(vHost, p.hostDir, { recursive: true, force: true })
634
+ atomicWrite(path.join(p.hostDir, 'host.js'), fs.readFileSync(path.join(vHost, 'host.js')))
507
635
  // 换了 node:先记一笔「还有旧宿主要换」再写启动脚本(后面哪步失败了,下次加载也还记得要换),换完才删
508
636
  if (primary && launcherPrev !== launcherBody) fs.writeFileSync(restartMark, `${primary}\n`)
509
- fs.writeFileSync(p.launcher, launcherBody)
510
- if (!win) fs.chmodSync(p.launcher, 0o755)
637
+ atomicWrite(p.launcher, launcherBody, win ? 0o644 : 0o755)
511
638
  fs.rmSync(path.join(p.hostDir, 'launch-error.txt'), { force: true }) // 上回拉不起来的原因:脚本重写了就作废
512
- fs.mkdirSync(p.nmDir, { recursive: true })
513
- fs.writeFileSync(p.nmFile, nmBody)
639
+ for (const file of manifests) atomicWrite(file, nmBody)
514
640
  if (win) {
515
641
  for (const k of REG_KEYS) {
516
642
  execFileSync('reg', ['add', k, '/ve', '/t', 'REG_SZ', '/d', p.nmFile, '/f'], { stdio: 'ignore', windowsHide: true })
517
643
  }
518
644
  }
519
- fs.writeFileSync(p.stampFile, `${stamp}\n`)
645
+ atomicWrite(p.stampFile, `${stamp}\n`)
520
646
  out.changed = true
521
647
  }
522
648
  if (primary && fs.existsSync(restartMark)) {
@@ -527,12 +653,17 @@ export function ensureInstalled(options = {}) {
527
653
  }
528
654
 
529
655
  // ── 可选件:cb CLI、页内光标脚本 —— 失败只是少个便利,不该让安装失败 ──
530
- // 刻意不动 ~/.dsh/skills:那是全局 agent 行为,装了插件就有原生 browser_* 工具,不需要它。
656
+ const skill = readText(path.join(vendor, 'skill/SKILL.md'))
657
+ if (skill !== null && fs.existsSync(p.skillFile) && skill !== readText(p.skillFile)) {
658
+ atomicWrite(p.skillFile, skill)
659
+ out.changed = true
660
+ }
531
661
  try {
532
- copyFile(path.join(vendor, 'cb'), p.cb, win ? undefined : 0o755)
662
+ syncFile(path.join(vendor, 'cb'), p.cb, win ? 0o644 : 0o755)
533
663
  if (win) {
534
- // Windows 没有 shebang:旁边放个 cb.cmd(用 PATH 里的 node),也不去建 ~/.local/bin 的软链接
535
- fs.writeFileSync(`${p.cb}.cmd`, '@echo off\r\nnode "%~dp0cb" %*\r\n')
664
+ // Windows 通过同目录的 cb.cmd 查找 node 并执行 cb。
665
+ const shim = winLauncher(process.execPath, Boolean(process.versions.electron), primary && `..\\chrome-bridge\\host\\${path.basename(primary)}`, true)
666
+ if (readText(p.cb + '.cmd') !== shim) atomicWrite(p.cb + '.cmd', shim)
536
667
  } else {
537
668
  fs.mkdirSync(path.dirname(p.cbLink), { recursive: true })
538
669
  // ~/.local/bin/cb 可能是用户自己的另一个 cb:只在还没有时建链接;指向我们的链接本来就对,
@@ -543,7 +674,7 @@ export function ensureInstalled(options = {}) {
543
674
  }
544
675
  } catch {}
545
676
  try {
546
- copyFile(path.join(vendor, 'in-page-cursor.js'), p.cursorFile)
677
+ syncFile(path.join(vendor, 'in-page-cursor.js'), p.cursorFile)
547
678
  } catch {}
548
679
 
549
680
  return { ...out, ok: true, changed: out.changed, extId, nmFile: p.nmFile }
@@ -552,6 +683,44 @@ export function ensureInstalled(options = {}) {
552
683
  }
553
684
  }
554
685
 
686
+ export function uninstall(home = os.homedir()) {
687
+ const p = paths(home)
688
+ const win = process.platform === 'win32'
689
+ stateCache.delete(home)
690
+ if (win) {
691
+ for (const key of REG_KEYS) {
692
+ if (regValue(key) === p.nmFile) execFileSync('reg', ['delete', key, '/f'], { stdio: 'ignore', windowsHide: true })
693
+ }
694
+ } else {
695
+ for (const dir of browserDirs(home)) fs.rmSync(path.join(dir, 'NativeMessagingHosts', HOST_NAME + '.json'), { force: true })
696
+ }
697
+ for (const name of ['cb', 'dsh-chrome-bridge']) {
698
+ const target = path.join(home, '.dsh/bin', name)
699
+ const link = path.join(home, '.local/bin', name)
700
+ if (fs.lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink() &&
701
+ path.resolve(path.dirname(link), fs.readlinkSync(link)) === target) fs.unlinkSync(link)
702
+ fs.rmSync(target, { force: true })
703
+ }
704
+ for (const file of [p.cb + '.cmd', p.skillFile, p.cursorFile]) fs.rmSync(file, { force: true })
705
+ for (const dir of [path.dirname(p.skillFile), path.dirname(p.cursorFile)]) {
706
+ try { fs.rmdirSync(dir) } catch (e) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(e.code)) throw e }
707
+ }
708
+ for (const dir of [p.bridge, p.extDir]) fs.rmSync(dir, { recursive: true, force: true })
709
+ if (path.resolve(home) === path.resolve(os.homedir())) {
710
+ const dir = process.env.DSH_BRIDGE_DIR || (win ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)
711
+ const st = fs.lstatSync(dir, { throwIfNoEntry: false })
712
+ if (st?.isDirectory() && (win || st.uid === process.getuid())) {
713
+ for (const item of ['dsh-bridge.sock', 'dsh-bridge.token', 'dsh-bridge.log', 'dsh-bridge.log.1', 'plugin.log']) {
714
+ fs.rmSync(path.join(dir, item), { force: true })
715
+ }
716
+ if (!process.env.DSH_BRIDGE_DIR) {
717
+ try { fs.rmdirSync(dir) } catch (e) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(e.code)) throw e }
718
+ }
719
+ }
720
+ }
721
+ return { ok: true }
722
+ }
723
+
555
724
  /**
556
725
  * 出错时给模型/用户看的话(只在宿主连不上时才会走到这里)。宿主和注册已经自动装好了,
557
726
  * 所以只剩 Chrome 那一下 —— 那一下谁都替不了(Chrome 137+ 移除了 --load-extension),
@@ -560,48 +729,53 @@ export function ensureInstalled(options = {}) {
560
729
  */
561
730
  export function installHint(home = os.homedir()) {
562
731
  const s = installState(home)
563
- if (!s.vendor) return '插件包里没有自带宿主:请重新用 release tarball 安装本插件(README 的 Install 一节)。'
732
+ if (!s.vendor) return tt('setup.noVendor')
564
733
  if (!PLATFORMS.includes(process.platform)) {
565
- return `浏览器桥暂不支持 ${process.platform}(只支持 macOS、Windows、Linux)。`
734
+ return tt('setup.unsupportedPlatform', { platform: process.platform })
566
735
  }
736
+ const mark = (ok) => (ok ? ' ✅' : ' ❌')
567
737
  if (!s.hostCopied || !s.registered) {
568
738
  return [
569
- '宿主或 native messaging 注册没写成功(多半是权限问题):',
570
- `宿主目录 ${s.hostDir}${s.hostCopied ? ' ✅' : ' ❌'}`,
571
- `注册${process.platform === 'win32' ? '(注册表 + 文件)' : '文件'} ${s.nmFile}${s.registered ? ' ✅' : ' ❌'}`,
572
- '重启一次 DSH 会再试一遍;还不行就在 GitHub 提 issue。',
739
+ tt('setup.regHead'),
740
+ tt('setup.regHostDir', { dir: s.hostDir, mark: mark(s.hostCopied) }),
741
+ tt('setup.regNm', {
742
+ kind: process.platform === 'win32' ? tt('setup.nmKindWin') : tt('setup.nmKindFile'),
743
+ file: s.nmFile,
744
+ mark: mark(s.registered),
745
+ }),
746
+ tt('setup.regTail'),
573
747
  ].join('\n')
574
748
  }
575
749
  let launchErr = ''
576
750
  try { launchErr = fs.readFileSync(path.join(s.hostDir, 'launch-error.txt'), 'utf8').trim() } catch {}
577
- if (launchErr) return `Chrome 拉起宿主失败:${launchErr}\n重启 DSH 之后,完全退出 Chrome 再打开一次。`
751
+ if (launchErr) return tt('setup.launchFailed', { err: launchErr })
578
752
  if (s.store) {
579
753
  return [
580
- `扩展已经从 Chrome 应用商店装好了(DSH Bridge ${s.store.version}),但宿主没连上:`,
581
- '1. 确认 Chrome 开着',
582
- '2. chrome://extensions 里 DSH Bridge 是启用状态',
583
- '3. 还不行就完全退出 Chrome 再打开一次',
584
- '不用再「加载已解压」;宿主和 native 注册已经自动装好了。',
754
+ tt('setup.storeHead', { version: s.store.version }),
755
+ tt('setup.storeStep1'),
756
+ tt('setup.storeStep2'),
757
+ tt('setup.storeStep3'),
758
+ tt('setup.storeTail'),
585
759
  ].join('\n')
586
760
  }
587
761
  return [
588
- '浏览器桥还差最后一步(一次性),两种装法选一个:',
589
- '· 最省事:从 Chrome 应用商店装 DSH Bridge(不用开发者模式):',
590
- ` ${STORE_URL}`,
591
- '· 或者加载已解压的扩展:',
592
- ' 1. Chrome 打开 chrome://extensions',
593
- ' 2. 右上角打开「开发者模式」',
594
- ` 3. 点「加载已解压的扩展程序」,${PASTE_TIP[process.platform] || PASTE_TIP.darwin},选这个文件夹:`,
595
- ` ${s.extDir}`,
596
- '装好后回到这里重试;宿主和 native 注册已经自动装好了,不用再跑任何脚本。',
762
+ tt('setup.manualHead'),
763
+ tt('setup.manualStore'),
764
+ tt('setup.storeUrl', { url: STORE_URL }),
765
+ tt('setup.manualUnpacked'),
766
+ tt('setup.manualStep1'),
767
+ tt('setup.manualStep2'),
768
+ tt('setup.manualStep3', { paste: pasteTip() }),
769
+ tt('setup.manualDir', { dir: s.extDir }),
770
+ tt('setup.manualTail'),
597
771
  ].join('\n')
598
772
  }
599
773
 
600
- /** 文件框里怎么直接粘路径 */
601
- const PASTE_TIP = {
602
- darwin: '在文件框里按 ⌘⇧G、粘贴、回车',
603
- win32: '把路径粘进文件框顶上的地址栏、回车',
604
- linux: '在文件框里按 Ctrl+L、粘贴、回车',
774
+ /** 文件框里怎么直接粘路径(按当前语言取,别在模块加载时就定死) */
775
+ function pasteTip() {
776
+ if (process.platform === 'win32') return tt('setup.pasteWin')
777
+ if (process.platform === 'linux') return tt('setup.pasteLinux')
778
+ return tt('setup.pasteDarwin')
605
779
  }
606
780
 
607
781
  /** Chrome 在不在跑(决定要不要顺手把设置页打开)。 */
@@ -632,7 +806,7 @@ function openInChrome(url, { background = false } = {}) {
632
806
  return
633
807
  }
634
808
  const bin = chromeBin()
635
- if (!bin) throw new Error('找不到 Chrome')
809
+ if (!bin) throw new Error(tt('err.chromeNotFound'))
636
810
  spawn(bin, [url], { detached: true, stdio: 'ignore', windowsHide: false }).unref()
637
811
  }
638
812
 
@@ -659,7 +833,7 @@ export function assistInstall(home = os.homedir(), { viaStore = false } = {}) {
659
833
  // 剪贴板:macOS 用 pbcopy,Windows 用 clip(Linux 不一定有 xclip,就不塞了)
660
834
  if (!store && process.platform !== 'linux') {
661
835
  try {
662
- if (process.platform === 'win32') execFileSync('clip', [], { input: p.extDir, windowsHide: true })
836
+ if (process.platform === 'win32') execFileSync('clip', [], { input: Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(p.extDir, 'utf16le')]), windowsHide: true })
663
837
  else execFileSync('/usr/bin/pbcopy', [], { input: `${p.extDir}\n` })
664
838
  out.clipboard = true
665
839
  } catch {}
package/tools/click.js ADDED
@@ -0,0 +1,58 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput } from '../core/tooldef.js'
4
+ import { recordAction } from '../core/session.js'
5
+ import { cursorReady, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
6
+ import { probeState, actionReceipt } from '../core/receipt.js'
7
+ import { chooserNote } from '../core/upload.js'
8
+ import { locate } from '../refs.js'
9
+
10
+ export function buildClick({ resolveTab, TAB, REF }) {
11
+ return defineTool({
12
+ name: 'browser_click',
13
+ description: t('tool.click.desc'),
14
+ parameters: {
15
+ tab: { type: 'string', description: TAB },
16
+ ref: { type: 'integer', description: REF },
17
+ selector: { type: 'string', description: t('tool.click.selector') },
18
+ text: { type: 'string', description: t('tool.click.text') },
19
+ x: { type: 'integer', description: t('tool.click.x') },
20
+ y: { type: 'integer', description: t('tool.click.y') },
21
+ count: { type: 'integer', description: t('tool.click.count') },
22
+ button: { type: 'string', enum: ['left', 'right', 'middle'], description: t('tool.click.button') },
23
+ },
24
+ output: textOutput,
25
+ presentCall: present('click', 'browser_click'),
26
+ async execute(args) {
27
+ const tabId = await resolveTab(args.tab)
28
+ recordAction(tabId)
29
+ await cursorReady()
30
+ await emulateFocus(tabId)
31
+ const count = Number(args.count || 1)
32
+ const options = { tabId, clickCount: count, button: args.button, ...withCursor(), chooser: true }
33
+ const before = await probeState(tabId)
34
+ const done = async (text, r) => ({ text: text + chooserNote(r, tabId) + await actionReceipt(tabId, before, r) })
35
+ if (args.ref != null) {
36
+ const legacyPoint = !hasBuiltinCursor() && (count > 1 || (args.button && args.button !== 'left'))
37
+ const el = await locate(call, tabId, args.ref, { wantPoint: legacyPoint })
38
+ const r = el.selector && !legacyPoint
39
+ ? await call('clickEl', { ...options, selector: el.selector })
40
+ : await call('click', { ...options, x: el.x, y: el.y })
41
+ const target = r.target || el
42
+ const details = { ref: args.ref, tag: target.tag, text: target.text, x: r.x, y: r.y, count }
43
+ return done(count > 1 ? t('res.click.atRefCount', details) : t('res.click.atRef', details), r)
44
+ }
45
+ if (args.selector || args.text) {
46
+ const r = args.selector
47
+ ? await call('clickEl', { ...options, selector: args.selector })
48
+ : await call('clickText', { ...options, text: args.text, exact: false })
49
+ return done(t('res.click.byTag', { tag: r.target.tag, text: r.target.text, x: r.x, y: r.y }), r)
50
+ }
51
+ if (args.x !== undefined && args.y !== undefined) {
52
+ const r = await call('click', { ...options, x: Number(args.x), y: Number(args.y) })
53
+ return done(t('res.click.atCoords', { x: r.x, y: r.y }), r)
54
+ }
55
+ throw new Error(t('err.clickNeeds'))
56
+ },
57
+ })
58
+ }
@@ -0,0 +1,61 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput, WAIT_MAX_MS } from '../core/tooldef.js'
4
+ import { consoleLog, networkLog, responseBody, clearLogs, mockHarAction } from '../devtools.js'
5
+
6
+ export function buildDevtools({ resolveTab, TAB }) {
7
+ return defineTool({
8
+ name: 'browser_devtools',
9
+ description: t('tool.devtools.desc'),
10
+ parameters: {
11
+ action: {
12
+ type: 'string', required: true, enum: ['console', 'network', 'response', 'clear', 'mock', 'unmock', 'mocks', 'har_start', 'har_export'],
13
+ description: t('tool.devtools.action'),
14
+ },
15
+ tab: { type: 'string', description: TAB },
16
+ level: {
17
+ type: 'string', enum: ['all', 'warning', 'error'],
18
+ description: t('tool.devtools.level'),
19
+ },
20
+ filter: { type: 'string', description: t('tool.devtools.filter') },
21
+ reload: {
22
+ type: 'boolean',
23
+ description: t('tool.devtools.reload'),
24
+ },
25
+ waitMs: { type: 'integer', minimum: 0, maximum: WAIT_MAX_MS, description: t('tool.devtools.waitMs') },
26
+ request: { type: 'string', description: t('tool.devtools.request') },
27
+ limit: { type: 'integer', description: t('tool.devtools.limit') },
28
+ urlPattern: { type: 'string', description: t('tool.devtools.urlPattern') },
29
+ method: { type: 'string', description: t('tool.devtools.method') },
30
+ status: { type: 'integer', minimum: 200, maximum: 599, description: t('tool.devtools.status') },
31
+ body: { type: 'string', description: t('tool.devtools.body') },
32
+ contentType: { type: 'string', description: t('tool.devtools.contentType') },
33
+ headers: { type: 'object', additionalProperties: { type: 'string' }, description: t('tool.devtools.headers') },
34
+ delayMs: { type: 'integer', minimum: 0, maximum: 30_000, description: t('tool.devtools.delayMs') },
35
+ abort: { type: 'boolean', description: t('tool.devtools.abort') },
36
+ mockId: { type: 'string', description: t('tool.devtools.mockId') },
37
+ to: { type: 'string', enum: ['downloads', 'workdir'], description: t('tool.download.to') },
38
+ filename: { type: 'string', description: t('tool.devtools.filename') },
39
+ includeBodies: { type: 'boolean', description: t('tool.devtools.includeBodies') },
40
+ clear: { type: 'boolean', description: t('tool.devtools.harClear') },
41
+ },
42
+ output: textOutput,
43
+ presentCall: present('devtools', 'browser_devtools'),
44
+ async execute(args, exec) {
45
+ const tabId = await resolveTab(args.tab)
46
+ const limit = args.limit ? Number(args.limit) : undefined
47
+ switch (args.action) {
48
+ case 'console':
49
+ return { text: await consoleLog(call, tabId, { level: args.level || 'all', filter: args.filter, limit }) }
50
+ case 'network':
51
+ return { text: await networkLog(call, tabId, { filter: args.filter, reload: !!args.reload, waitMs: args.waitMs, limit }) }
52
+ case 'response':
53
+ return { text: await responseBody(call, tabId, args.request, limit) }
54
+ case 'clear':
55
+ return { text: await clearLogs(call, tabId) }
56
+ default:
57
+ return { text: await mockHarAction(call, tabId, args, exec) }
58
+ }
59
+ },
60
+ })
61
+ }