dsh-chrome-bridge 1.20.0 → 2.0.1

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 (88) 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 +18 -8
  14. package/download.js +879 -60
  15. package/drag.js +38 -20
  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 +168 -16
  22. package/i18n/ru.js +168 -16
  23. package/i18n/zh.js +168 -16
  24. package/image-guard.js +13 -6
  25. package/index.js +17 -1155
  26. package/locale/ru.json +7 -0
  27. package/nav.js +43 -5
  28. package/package.json +8 -1
  29. package/panel.js +10 -1
  30. package/refs.js +275 -230
  31. package/setup.js +214 -46
  32. package/tools/click.js +58 -0
  33. package/tools/devtools.js +61 -0
  34. package/tools/dialog.js +22 -0
  35. package/tools/download.js +50 -0
  36. package/tools/drag.js +61 -0
  37. package/tools/eval.js +22 -0
  38. package/tools/fill.js +77 -0
  39. package/tools/handoff.js +40 -0
  40. package/tools/index.js +38 -0
  41. package/tools/input.js +147 -0
  42. package/tools/nav.js +57 -0
  43. package/tools/read.js +87 -0
  44. package/tools/record.js +120 -0
  45. package/tools/screenshot.js +231 -0
  46. package/tools/tabs.js +131 -0
  47. package/tools/wait.js +56 -0
  48. package/vendor/cb +616 -35
  49. package/vendor/extension/_locales/en/messages.json +3 -0
  50. package/vendor/extension/_locales/ru/messages.json +3 -0
  51. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  53. package/vendor/extension/background.js +2 -1969
  54. package/vendor/extension/confirm.css +148 -0
  55. package/vendor/extension/confirm.html +49 -0
  56. package/vendor/extension/confirm.js +188 -0
  57. package/vendor/extension/in-page-cursor.js +599 -0
  58. package/vendor/extension/manifest.json +11 -2
  59. package/vendor/extension/popup.css +99 -5
  60. package/vendor/extension/popup.html +28 -2
  61. package/vendor/extension/popup.js +430 -45
  62. package/vendor/extension/sw/boot.js +111 -0
  63. package/vendor/extension/sw/cdp.js +411 -0
  64. package/vendor/extension/sw/chooser.js +192 -0
  65. package/vendor/extension/sw/confirm.js +608 -0
  66. package/vendor/extension/sw/cursor.js +241 -0
  67. package/vendor/extension/sw/dispatch.js +129 -0
  68. package/vendor/extension/sw/download.js +279 -0
  69. package/vendor/extension/sw/fetch-hub.js +224 -0
  70. package/vendor/extension/sw/frames.js +651 -0
  71. package/vendor/extension/sw/imaging.js +439 -0
  72. package/vendor/extension/sw/native.js +111 -0
  73. package/vendor/extension/sw/net-tools.js +525 -0
  74. package/vendor/extension/sw/ops.js +829 -0
  75. package/vendor/extension/sw/popup-api.js +303 -0
  76. package/vendor/extension/sw/profile.js +166 -0
  77. package/vendor/extension/sw/record.js +494 -0
  78. package/vendor/extension/sw/state.js +161 -0
  79. package/vendor/extension/sw/tabui.js +219 -0
  80. package/vendor/extension/sw/util.js +166 -0
  81. package/vendor/extension/sw/welcome.js +26 -0
  82. package/vendor/extension/sw/windows.js +94 -0
  83. package/vendor/extension/welcome.css +189 -0
  84. package/vendor/extension/welcome.html +70 -0
  85. package/vendor/extension/welcome.js +157 -0
  86. package/vendor/host/host.js +476 -71
  87. package/vendor/in-page-cursor.js +309 -37
  88. package/vendor/skill/SKILL.md +34 -16
package/setup.js CHANGED
@@ -85,6 +85,25 @@ export function paths(home = os.homedir(), platform = process.platform) {
85
85
  }
86
86
  }
87
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
+
88
107
  /**
89
108
  * 扩展 ID:由 manifest.json 里的公钥(key)推导,每台机器都一样。
90
109
  * 算法与 Chrome / install.sh 一致:sha256(DER) 前 16 字节 → 每个 nibble 映射成 a..p。
@@ -92,14 +111,32 @@ export function paths(home = os.homedir(), platform = process.platform) {
92
111
  */
93
112
  export function extensionId(manifestFile) {
94
113
  const key = JSON.parse(fs.readFileSync(manifestFile, 'utf8')).key
114
+ if (!key || typeof key !== 'string') return null
95
115
  const hex = crypto.createHash('sha256').update(Buffer.from(key, 'base64')).digest('hex').slice(0, 32)
96
116
  return [...hex].map((c) => String.fromCharCode(97 + parseInt(c, 16))).join('')
97
117
  }
98
118
 
99
- function copyFile(src, dest, mode) {
119
+ function atomicWrite(dest, body, mode = 0o644) {
100
120
  fs.mkdirSync(path.dirname(dest), { recursive: true })
101
- fs.copyFileSync(src, dest)
102
- 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 }
103
140
  }
104
141
 
105
142
  /** vendor 树的内容指纹:内容没变就整段跳过,插件每次启动都调它也不会抖动。 */
@@ -134,15 +171,16 @@ function allPresent(src, dest) {
134
171
  * 最终还是看宿主连不连得上。返回 { id, profile, version } 或 null;读不到就当没装。
135
172
  */
136
173
  export function storeExtension(home = os.homedir()) {
137
- const { chromeDir } = paths(home)
138
- let profiles = []
139
- try { profiles = fs.readdirSync(chromeDir).filter((n) => n === 'Default' || /^Profile \d+$/.test(n)) } catch {}
140
- for (const profile of profiles) {
141
- for (const id of STORE_EXT_IDS) {
142
- try {
143
- const vers = fs.readdirSync(path.join(chromeDir, profile, 'Extensions', id)).filter((v) => !v.startsWith('.'))
144
- if (vers.length) return { id, profile, version: vers.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).pop().replace(/_\d+$/, '') }
145
- } 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
+ }
146
184
  }
147
185
  }
148
186
  return null
@@ -178,17 +216,24 @@ const bat = (s) => String(s).replace(/%/g, '%%')
178
216
  * primary 用 %~dp0 拼:用户目录带中文时,脚本里直接写中文路径 cmd 会读错(CI 实测),%~dp0 是 cmd 自己算的,不会错。
179
217
  * DSH 升级换了路径,插件下次加载会重写这个文件。路径可能带中文,先把代码页切到 UTF-8 再读后面的行。
180
218
  */
181
- 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) {
182
220
  return [
183
221
  '@echo off',
184
222
  'chcp 65001 >nul',
185
- 'setlocal',
223
+ 'setlocal DisableDelayedExpansion',
224
+ 'set "FOUND_NODE="',
186
225
  ...(electron ? ['set ELECTRON_RUN_AS_NODE=1'] : []),
187
226
  ...(primary ? [`set "N=%~dp0${primary}"`, `if not exist "%N%" set "N=${bat(execPath)}"`] : [`set "N=${bat(execPath)}"`]),
188
227
  'if defined DSH_BRIDGE_NODE set "N=%DSH_BRIDGE_NODE%"',
189
- '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',
190
235
  // 宿主退出后马上 exit /b:cmd 不再回头读这个文件(文件可能已被改写,见 restartStaleHosts)
191
- '"%N%" "%~dp0host.js" %* & exit /b',
236
+ `"%N%" "%~dp0${cli ? 'cb' : 'host.js'}" %* & exit /b`,
192
237
  '',
193
238
  ].join('\r\n')
194
239
  }
@@ -355,6 +400,7 @@ export async function restartStaleHosts(hostDir, keep, {
355
400
  const { pid, exe } = host
356
401
  const until = Date.now() + waitMs
357
402
  let idleSince = null
403
+ let delay = pollMs
358
404
  let foreign = 0
359
405
  const ask = async () => {
360
406
  const st = await probe(host)
@@ -364,7 +410,7 @@ export async function restartStaleHosts(hostDir, keep, {
364
410
  }
365
411
  const ready = () => idleSince !== null && Date.now() - idleSince >= idleMs
366
412
  while (Date.now() < until) {
367
- await ask()
413
+ let status = await ask()
368
414
  if (foreign >= foreignTries) { log(`问不到旧宿主 ${pid},这次不动它(${exe}),下次加载再看`); return false }
369
415
  if (ready()) {
370
416
  // 慢的(PowerShell 列进程)放在前面,最后一次问和结束之间不夹别的
@@ -376,13 +422,16 @@ export async function restartStaleHosts(hostDir, keep, {
376
422
  if (!fresh) return true // 自己走了
377
423
  if (fresh.hosts > 1) { log(multi(fresh)); return false }
378
424
  await sleep(1000)
379
- if (await ask() === 'idle' && ready()) {
425
+ status = await ask()
426
+ if (status === 'idle' && ready()) {
380
427
  const ok = await kill(fresh)
381
428
  log(ok ? `换下了还在用旧程序跑的宿主 ${pid}(${exe})` : `结束旧宿主 ${pid} 失败(${exe})`)
382
429
  return ok
383
430
  }
384
431
  }
385
- 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)
386
435
  }
387
436
  log(`旧宿主 ${pid} 一直没空,这次不换(${exe}),下次加载再试`)
388
437
  return false
@@ -415,14 +464,35 @@ export function unixLauncher(execPath = process.execPath, electron = Boolean(pro
415
464
  'if [ -n "$DSH_BRIDGE_NODE" ] && [ -x "$DSH_BRIDGE_NODE" ]; then go "$DSH_BRIDGE_NODE" "$@"; fi',
416
465
  `if [ -x "$DSH_NODE" ]; then ${electron ? 'export ELECTRON_RUN_AS_NODE=1; ' : ''}go "$DSH_NODE" "$@"; fi`,
417
466
  '',
418
- 'for N in /usr/local/bin/node "$HOME/.local/bin/node" /opt/homebrew/bin/node /usr/bin/node \\',
419
- ' "$HOME/.volta/bin/node" "$HOME/.asdf/shims/node" "$HOME/.local/share/mise/shims/node"; do',
420
- ' 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',
421
492
  'done',
422
- 'for N in "$HOME"/.nvm/versions/node/*/bin/node; do',
423
- ' 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',
424
495
  'done',
425
- 'if [ -n "$LAST" ]; then go "$LAST" "$@"; fi',
426
496
  'N="$(command -v node 2>/dev/null)"',
427
497
  'if [ -n "$N" ]; then go "$N" "$@"; fi',
428
498
  '',
@@ -434,20 +504,77 @@ export function unixLauncher(execPath = process.execPath, electron = Boolean(pro
434
504
  ].join('\n')
435
505
  }
436
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
+
437
558
  /** 装好了没有(只看落盘结果,不管 Chrome 有没有加载扩展)。 */
559
+ const stateCache = new Map()
560
+
438
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 }
439
564
  const p = paths(home)
440
565
  let extId = null
441
566
  try { extId = extensionId(path.join(p.extDir, 'manifest.json')) } catch {}
442
- return {
567
+ const state = {
443
568
  ...p,
444
569
  extId,
445
- extensionCopied: !!extId,
570
+ extensionCopied: fs.existsSync(path.join(p.extDir, 'manifest.json')),
446
571
  hostCopied: fs.existsSync(p.launcher),
447
- 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),
448
573
  vendor: fs.existsSync(vendorDir()),
449
574
  store: storeExtension(home),
450
575
  }
576
+ stateCache.set(home, { state, at: Date.now() })
577
+ return { ...state }
451
578
  }
452
579
 
453
580
  /**
@@ -457,10 +584,11 @@ export function installState(home = os.homedir()) {
457
584
  * 1. 扩展 → ~/dsh-bridge-extension(Chrome「加载已解压」要选它,所以必须可见、稳定)
458
585
  * 2. 原生宿主 → ~/.dsh/chrome-bridge/host/(注册文件指向这里)
459
586
  * 3. 写注册文件 NativeMessagingHosts/com.dsh.bridge.json(allowed_origins 绑定固定扩展 ID)
460
- * 4. 顺带落一个 cb CLI + 页内光标脚本(可选,失败不影响主流程;不碰 ~/.dsh/skills)
587
+ * 4. 同步浏览器技能、cb CLI 和页内光标脚本
461
588
  */
462
589
  export function ensureInstalled(options = {}) {
463
590
  const home = options.home || os.homedir()
591
+ stateCache.delete(home)
464
592
  const vendor = options.vendor || vendorDir()
465
593
  const p = paths(home)
466
594
  const out = { ok: false, changed: false, home, vendor, ...p }
@@ -486,11 +614,10 @@ export function ensureInstalled(options = {}) {
486
614
  description: 'dsh-chrome-bridge native host (local browser control)',
487
615
  path: p.launcher,
488
616
  type: 'stdio',
489
- 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}/`),
490
618
  }, null, 2)}\n`
491
619
 
492
- let nmPrev = null
493
- 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'))
494
621
  // 桌面版(Electron)在 Windows 上:宿主改用复制到宿主目录的独立 node,别占着 DSH 安装目录(issue #3)
495
622
  const primary = win && process.versions.electron ? hostNode(p.hostDir) : null
496
623
  const launcherBody = win ? winLauncher(process.execPath, Boolean(process.versions.electron), primary && path.basename(primary)) : unixLauncher()
@@ -498,26 +625,24 @@ export function ensureInstalled(options = {}) {
498
625
  try { launcherPrev = fs.readFileSync(p.launcher, 'utf8') } catch {}
499
626
  const restartMark = path.join(p.hostDir, 'restart-hosts.pending')
500
627
  const regOk = !win || REG_KEYS.every((k) => regValue(k) === p.nmFile)
501
- const upToDate = prev === stamp && nmPrev === nmBody && launcherPrev === launcherBody && regOk
502
- && 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'))
503
630
  if (!upToDate) {
504
631
  fs.mkdirSync(p.extDir, { recursive: true })
505
632
  fs.cpSync(vExt, p.extDir, { recursive: true, force: true })
506
633
  fs.mkdirSync(p.hostDir, { recursive: true })
507
- fs.cpSync(vHost, p.hostDir, { recursive: true, force: true })
634
+ atomicWrite(path.join(p.hostDir, 'host.js'), fs.readFileSync(path.join(vHost, 'host.js')))
508
635
  // 换了 node:先记一笔「还有旧宿主要换」再写启动脚本(后面哪步失败了,下次加载也还记得要换),换完才删
509
636
  if (primary && launcherPrev !== launcherBody) fs.writeFileSync(restartMark, `${primary}\n`)
510
- fs.writeFileSync(p.launcher, launcherBody)
511
- if (!win) fs.chmodSync(p.launcher, 0o755)
637
+ atomicWrite(p.launcher, launcherBody, win ? 0o644 : 0o755)
512
638
  fs.rmSync(path.join(p.hostDir, 'launch-error.txt'), { force: true }) // 上回拉不起来的原因:脚本重写了就作废
513
- fs.mkdirSync(p.nmDir, { recursive: true })
514
- fs.writeFileSync(p.nmFile, nmBody)
639
+ for (const file of manifests) atomicWrite(file, nmBody)
515
640
  if (win) {
516
641
  for (const k of REG_KEYS) {
517
642
  execFileSync('reg', ['add', k, '/ve', '/t', 'REG_SZ', '/d', p.nmFile, '/f'], { stdio: 'ignore', windowsHide: true })
518
643
  }
519
644
  }
520
- fs.writeFileSync(p.stampFile, `${stamp}\n`)
645
+ atomicWrite(p.stampFile, `${stamp}\n`)
521
646
  out.changed = true
522
647
  }
523
648
  if (primary && fs.existsSync(restartMark)) {
@@ -528,12 +653,17 @@ export function ensureInstalled(options = {}) {
528
653
  }
529
654
 
530
655
  // ── 可选件:cb CLI、页内光标脚本 —— 失败只是少个便利,不该让安装失败 ──
531
- // 刻意不动 ~/.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
+ }
532
661
  try {
533
- copyFile(path.join(vendor, 'cb'), p.cb, win ? undefined : 0o755)
662
+ syncFile(path.join(vendor, 'cb'), p.cb, win ? 0o644 : 0o755)
534
663
  if (win) {
535
- // Windows 没有 shebang:旁边放个 cb.cmd(用 PATH 里的 node),也不去建 ~/.local/bin 的软链接
536
- 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)
537
667
  } else {
538
668
  fs.mkdirSync(path.dirname(p.cbLink), { recursive: true })
539
669
  // ~/.local/bin/cb 可能是用户自己的另一个 cb:只在还没有时建链接;指向我们的链接本来就对,
@@ -544,7 +674,7 @@ export function ensureInstalled(options = {}) {
544
674
  }
545
675
  } catch {}
546
676
  try {
547
- copyFile(path.join(vendor, 'in-page-cursor.js'), p.cursorFile)
677
+ syncFile(path.join(vendor, 'in-page-cursor.js'), p.cursorFile)
548
678
  } catch {}
549
679
 
550
680
  return { ...out, ok: true, changed: out.changed, extId, nmFile: p.nmFile }
@@ -553,6 +683,44 @@ export function ensureInstalled(options = {}) {
553
683
  }
554
684
  }
555
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
+
556
724
  /**
557
725
  * 出错时给模型/用户看的话(只在宿主连不上时才会走到这里)。宿主和注册已经自动装好了,
558
726
  * 所以只剩 Chrome 那一下 —— 那一下谁都替不了(Chrome 137+ 移除了 --load-extension),
@@ -665,7 +833,7 @@ export function assistInstall(home = os.homedir(), { viaStore = false } = {}) {
665
833
  // 剪贴板:macOS 用 pbcopy,Windows 用 clip(Linux 不一定有 xclip,就不塞了)
666
834
  if (!store && process.platform !== 'linux') {
667
835
  try {
668
- 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 })
669
837
  else execFileSync('/usr/bin/pbcopy', [], { input: `${p.extDir}\n` })
670
838
  out.clipboard = true
671
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
+ }
@@ -0,0 +1,22 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput } from '../core/tooldef.js'
4
+
5
+ export function buildDialog({ resolveTab, TAB }) {
6
+ return defineTool({
7
+ name: 'browser_dialog',
8
+ description: t('tool.dialog.desc'),
9
+ parameters: {
10
+ action: { type: 'string', required: true, enum: ['accept', 'dismiss'], description: t('tool.dialog.action') },
11
+ tab: { type: 'string', description: TAB },
12
+ text: { type: 'string', description: t('tool.dialog.text') },
13
+ },
14
+ output: textOutput,
15
+ presentCall: present('dialog', 'browser_dialog'),
16
+ async execute(args) {
17
+ const tabId = await resolveTab(args.tab)
18
+ const r = await call('dialog', { tabId, action: args.action, text: args.text || undefined })
19
+ return { text: r.action === 'accept' ? t('res.dialog.accepted') : t('res.dialog.dismissed') }
20
+ },
21
+ })
22
+ }
@@ -0,0 +1,50 @@
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 { sessionCwd } from '../core/session.js'
5
+ import { download, downloadsDir, humanSize } from '../download.js'
6
+
7
+ export function buildDownload({ resolveTab, TAB, REF }) {
8
+ return defineTool({
9
+ name: 'browser_download',
10
+ description: t('tool.download.desc'),
11
+ parameters: {
12
+ ref: { type: 'integer', description: REF },
13
+ selector: { type: 'string', description: t('tool.download.selector') },
14
+ url: { type: 'string', description: t('tool.download.url') },
15
+ tab: { type: 'string', description: TAB },
16
+ filename: { type: 'string', description: t('tool.download.filename') },
17
+ click: { type: 'boolean', description: t('tool.download.click') },
18
+ to: { type: 'string', enum: ['downloads', 'workdir'], description: t('tool.download.to') },
19
+ },
20
+ output: textOutput,
21
+ presentCall: present('download', 'browser_download'),
22
+ async execute(args, exec) {
23
+ const tabId = await resolveTab(args.tab)
24
+ let dir = downloadsDir()
25
+ if (args.to === 'workdir') {
26
+ dir = sessionCwd(exec)
27
+ if (!dir) throw new Error(t('err.noWorkdir'))
28
+ }
29
+ const r = await download(call, tabId, {
30
+ url: args.url || undefined,
31
+ ref: args.ref ?? undefined,
32
+ selector: args.selector || undefined,
33
+ filename: args.filename || undefined,
34
+ click: args.click,
35
+ dir,
36
+ })
37
+ const type = (r.type || '').split(';')[0].trim()
38
+ const warn = (/^text\/html/i.test(type) ? t('res.dl.warnHtml') : '') +
39
+ (r.cookieDegraded ? t('res.dl.cookieDegraded') : '')
40
+ return {
41
+ text: t('res.dl.done', {
42
+ file: r.file,
43
+ size: humanSize(r.size),
44
+ type: type ? t('res.dl.typePart', { type }) : '',
45
+ warn,
46
+ }),
47
+ }
48
+ },
49
+ })
50
+ }