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/index.js CHANGED
@@ -9,499 +9,34 @@
9
9
  * DSH 工具 → socket → 宿主 → 原生消息 → Chrome 扩展 → chrome.debugger → CDP
10
10
  */
11
11
 
12
- import net from 'node:net'
13
- import fs from 'node:fs'
14
- import os from 'node:os'
15
- import path from 'node:path'
16
- import crypto from 'node:crypto'
17
- import { fileURLToPath } from 'node:url'
18
- import { AsyncLocalStorage } from 'node:async_hooks'
19
12
  import { installImageGuard } from './image-guard.js'
20
- import { ensureInstalled, installHint, assistInstall, paths, extensionId, hostProbe } from './setup.js'
21
- import { snapshot, locate, focusShadow, elementBox, selectInPage, frameTexts } from './refs.js'
22
- import { consoleLog, networkLog, responseBody, clearLogs } from './devtools.js'
23
- import { historyNav, waitUntil } from './nav.js'
13
+ import { ensureInstalled, hostProbe } from './setup.js'
24
14
  import { PANEL_ROUTE, panelHandler } from './panel.js'
25
- import { drag } from './drag.js'
26
- import { download, downloadsDir, humanSize } from './download.js'
27
- import { createT, DEFAULT_LOCALE, normalizeLocale } from './i18n/index.js'
28
-
29
- /**
30
- * 这里刻意不 import 任何外部包——不碰 `@deepseek-ai/dsh-tools`。
31
- *
32
- * 原因:profile 上下文里那个包解析不到(裸 node 实测 ERR_MODULE_NOT_FOUND),
33
- * 一旦解析失败,整个插件模块加载失败、行直接挂掉,而且错误只留在 app 进程里,
34
- * 外面完全看不到。所以工具对象在这里按 dsh-tools 的产出形状手搓:
35
- * parameters —— 属性表编译成 JSON Schema(等价 parameterSchemaSpecToJsonSchema)
36
- * output —— { schema, render },schema 直接写成 JSON Schema
37
- */
38
-
39
- // socket / token / 日志都在只有当前用户进得去的 /tmp/dsh-bridge-<uid>/(和宿主、cb 同一个约定):
40
- // /tmp 人人可写,固定文件名会被别的用户抢先占位,或者用软链接把写入引到别处。
41
- // Windows:目录是 %TEMP%\dsh-bridge(本来就只属于当前用户);没有 Unix socket,宿主每次起一个
42
- // 随机名字的命名管道,名字写在 token 文件第二行
43
- const WIN = process.platform === 'win32'
44
- const UID = typeof process.getuid === 'function' ? process.getuid() : null
45
- const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${UID ?? 'user'}`)
46
- const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
47
- const FIXED_SOCK = process.env.DSH_BRIDGE_SOCK || (WIN ? null : path.join(DIR, 'dsh-bridge.sock'))
48
-
49
- function tokenLines() {
50
- try { return fs.readFileSync(TOKEN_FILE, 'utf8').split('\n').map((l) => l.trim()) } catch { return [] }
51
- }
52
- /** 宿主在听的地址(Windows 上每次启动都换) */
53
- function hostSock() { return FIXED_SOCK || tokenLines()[1] || null }
54
- /** 宿主起没起:socket 文件在不在;Windows 看 token 文件里有没有管道名(宿主退出时会删掉) */
55
- function hostUp() { const s = hostSock(); return Boolean(s) && (WIN || fs.existsSync(s)) }
56
- const TRACE = path.join(DIR, 'plugin.log')
57
- const { O_WRONLY, O_CREAT, O_APPEND, O_NOFOLLOW } = fs.constants
58
-
59
- /** 目录必须是自己的真目录(不是软链接)、别人进不去:不然连上的可能是别人摆的假宿主 */
60
- function checkDir(dir) {
61
- const st = fs.lstatSync(dir)
62
- if (!st.isDirectory() || (!WIN && ((UID !== null && st.uid !== UID) || (st.mode & 0o077)))) {
63
- throw new Error(t('err.dirNotOwned', { dir }))
64
- }
65
- }
66
-
67
- let traceOk = null
68
- function trace(line) {
69
- try {
70
- if (traceOk === null) {
71
- traceOk = false
72
- try { fs.mkdirSync(DIR, { mode: 0o700 }) } catch {}
73
- checkDir(DIR)
74
- traceOk = true
75
- }
76
- if (traceOk) {
77
- fs.appendFileSync(TRACE, `${new Date().toISOString()} ${line}\n`, { flag: O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW, mode: 0o600 })
78
- }
79
- } catch {}
80
- }
81
-
82
- /** 属性表 → JSON Schema:{ [name]: { type, required?, description?, ... } } */
83
- function specToJsonSchema(spec) {
84
- const properties = {}
85
- const required = []
86
- for (const [key, node] of Object.entries(spec)) {
87
- const { required: isRequired, ...rest } = node
88
- properties[key] = rest
89
- if (isRequired) required.push(key)
90
- }
91
- return { type: 'object', properties, ...(required.length ? { required } : {}) }
92
- }
93
-
94
- /**
95
- * 每次工具调用的「名片」:哪个 DSH 会话、哪个工具、大概在干嘛。随每个请求带给扩展,
96
- * 扩展弹窗靠它把操作归到会话下面、把一次工具调用的多个底层操作合成一条「最近动作」。
97
- * 用 AsyncLocalStorage 传,工具代码里一层层的 call() 不用改签名。
98
- */
99
- const callInfo = new AsyncLocalStorage()
100
- const BASE_CLIENT = { kind: 'dsh', pid: process.pid }
101
-
102
- /** DSH 没有正式文档说 exec 里有什么,几个可能的位置都试一下;拿不到就按进程算一个会话 */
103
- function sessionOf(exec) {
104
- const a = exec && exec.agent
105
- const v = (exec && exec.sessionId) || (a && (a.sessionId || (a.session && a.session.id) || a.id))
106
- return typeof v === 'string' || typeof v === 'number' ? String(v) : null
107
- }
108
-
109
- let execProbed = false
110
- function probeExec(exec) {
111
- if (execProbed || !exec) return
112
- execProbed = true
113
- try {
114
- const a = exec.agent
115
- trace(`exec 键: ${Object.keys(exec).join(',')}|agent 键: ${a ? Object.keys(a).join(',') : '-'}`)
116
- } catch {}
117
- }
118
-
119
- const short = (v, n = 40) => {
120
- const t = String(v ?? '').replace(/\s+/g, ' ').trim()
121
- return t.length > n ? t.slice(0, n - 1) + '…' : t
122
- }
123
-
124
- /** 一眼看得懂的一句话:「[3]」「「加载完成」」「back」「https://…」 */
125
- function hintOf(name, a = {}) {
126
- const el = (p = '') => {
127
- const ref = a[p ? `${p}Ref` : 'ref']
128
- if (ref !== undefined && ref !== null) return `[${ref}]`
129
- const sel = a[p ? `${p}Selector` : 'selector']
130
- if (sel) return short(sel, 30)
131
- const text = a[p ? `${p}Text` : 'text']
132
- if (text) return `「${short(text, 20)}」`
133
- const x = a[p ? `${p}X` : 'x']
134
- const y = a[p ? `${p}Y` : 'y']
135
- return x !== undefined && y !== undefined ? `(${x}, ${y})` : ''
136
- }
137
- switch (name) {
138
- case 'browser_tabs': return [a.action, short(a.url || a.query || '', 40)].filter(Boolean).join(' ')
139
- case 'browser_read': return [a.what, a.selector ? short(a.selector, 30) : ''].filter(Boolean).join(' ')
140
- case 'browser_click': return el()
141
- case 'browser_input':
142
- // 只记字数:这句会显示在扩展弹窗的「最近动作」里,打的可能是密码
143
- return a.action === 'type' ? `打字 ${String(a.text ?? '').length} 字${a.ref != null || a.selector ? ` → ${el()}` : ''}`
144
- : a.action === 'key' ? `按键 ${a.key || ''}`
145
- : `${a.action} ${el()}`.trim()
146
- case 'browser_nav': return (a.action && a.action !== 'go') ? a.action : short(a.url, 50)
147
- case 'browser_screenshot': return a.mode === 'element' ? `元素 ${el()}` : a.mode || ''
148
- case 'browser_eval': return short(a.expression, 40)
149
- case 'browser_wait':
150
- return `${a.gone ? '等消失 ' : ''}${a.text ? `「${short(a.text, 20)}」` : a.url ? `网址 ${short(a.url, 30)}` : short(a.selector, 30)}`
151
- case 'browser_dialog': return a.action || ''
152
- case 'browser_drag': return `${el('from')} → ${el('to')}`
153
- case 'browser_download': return a.ref !== undefined && a.ref !== null ? `[${a.ref}]` : short(a.selector || a.url || '', 50)
154
- case 'browser_devtools': return [a.action, a.level && a.level !== 'all' ? a.level : '', a.filter ? `「${short(a.filter, 16)}」` : ''].filter(Boolean).join(' ')
155
- default: return ''
156
- }
157
- }
158
-
159
- /** 等价于 dsh-tools 的 defineTool(只用它的产出形状,不依赖它) */
160
- function defineTool(options) {
161
- return {
162
- name: options.name,
163
- description: options.description,
164
- parameters: specToJsonSchema(options.parameters),
165
- output: { schema: options.output.schema, render: options.output.render },
166
- ...(options.presentCall ? { presentCall: options.presentCall } : {}),
167
- execute(args, exec) {
168
- probeExec(exec)
169
- let hint = ''
170
- try { hint = hintOf(options.name, args || {}) } catch {}
171
- const info = {
172
- ...BASE_CLIENT,
173
- session: sessionOf(exec),
174
- tool: options.name,
175
- call: (exec && exec.callId) || crypto.randomUUID(),
176
- hint,
177
- }
178
- return callInfo.run(info, () => options.execute(args, exec))
179
- },
180
- }
181
- }
15
+ import { normalizeLocale } from './i18n/index.js'
16
+ import { setPluginLocale } from './core/locale.js'
17
+ import { call, hostUp, trace } from './core/transport.js'
18
+ import { resolveTab, setProjections } from './core/session.js'
19
+ import { refreshExtension } from './core/ext.js'
20
+ import { cleanOldShots } from './core/shots.js'
21
+ import { buildTools } from './tools/index.js'
182
22
 
183
23
  export const name = 'browser-bridge'
184
24
  export const inject = ['tools']
185
25
 
186
- /**
187
- * 工具描述 / 参数说明 / 报错文案的当前语言。apply 里按 config.locale 换掉;
188
- * 模块级的报错(call、resolveTab、uploadable 这些)也用同一个 t。
189
- * 默认 zh:没配 locale 的安装行为和以前逐字一致。
190
- */
191
- let t = createT(DEFAULT_LOCALE)
192
-
193
- /**
194
- * 第一次发现宿主连不上时,做一次「引导」:把扩展目录塞进剪贴板、后台打开
195
- * chrome://extensions(见 setup.js 的 assistInstall)。每个进程只做一次。
196
- * 那一下点选替不了 —— Chrome 137+ 没有 --load-extension —— 但至少让用户不用自己去翻目录、找页面。
197
- * 宿主连得上就算装好(不管扩展是解压的还是商店的),这里根本不会被调到。
198
- */
199
- let aided = false
200
- function firstAid() {
201
- if (aided) return ''
202
- aided = true
203
- try {
204
- if (hostUp()) return ''
205
- const r = assistInstall()
206
- const notes = []
207
- if (r.opened) notes.push(t('hint.extOpened', { store: r.store ? t('hint.extOpenedStore') : '' }))
208
- if (r.clipboard) notes.push(t('hint.copied', { how: WIN ? t('hint.copiedWin') : t('hint.copiedMac') }))
209
- return notes.length ? t('hint.notes', { notes: notes.join(t('hint.notesSep')) }) : ''
210
- } catch {
211
- return ''
212
- }
213
- }
214
-
215
- /** 报错时带上「还差哪一步」——宿主和 native 注册已由 setup.js 自动装好。 */
216
- const HINT = () => installHint() + firstAid()
217
-
218
- // ── 与宿主通话 ──────────────────────────────────────────────────────────────
219
-
220
- /**
221
- * 一次请求一个连接,协议是换行分隔的 JSON(和 cb CLI 完全一致)。
222
- * quiet:后台自己问的(不是用户/模型要做的事)——出错不带「还差哪一步」,那里面会去打开扩展页、改剪贴板。
223
- */
224
- function call(op, args = {}, timeoutMs = 60000, quiet = false) {
225
- const hint = () => (quiet ? '' : HINT())
226
- return new Promise((resolve, reject) => {
227
- const SOCK = hostSock()
228
- if (!hostUp()) {
229
- return reject(new Error(t('err.bridgeDown', { sock: SOCK || TOKEN_FILE, hint: hint() })))
230
- }
231
- try { checkDir(WIN ? DIR : path.dirname(SOCK)) } catch (e) { return reject(e) }
232
- const token = tokenLines()[0] || null
233
- const id = crypto.randomUUID()
234
- const sock = net.connect(SOCK)
235
- let acc = ''
236
- let done = false
237
- let timer = null
238
- const finish = (fn, v) => {
239
- if (done) return
240
- done = true
241
- clearTimeout(timer)
242
- try { sock.destroy() } catch {}
243
- fn(v)
244
- }
245
- sock.setEncoding('utf8')
246
- const client = callInfo.getStore() || BASE_CLIENT
247
- // timeoutMs 也带给宿主:它按这个等扩展,不再一律 45 秒(等元素、截图这类慢操作以前必定被它掐掉)
248
- sock.on('connect', () => sock.write(JSON.stringify({ token, id, op, args, client, timeoutMs }) + '\n'))
249
- sock.on('data', (d) => {
250
- acc += d
251
- const i = acc.indexOf('\n')
252
- if (i < 0) return
253
- let msg
254
- try { msg = JSON.parse(acc.slice(0, i)) } catch { return finish(reject, new Error(t('err.badJson'))) }
255
- if (msg.ok) finish(resolve, msg.result)
256
- else finish(reject, new Error(msg.error || t('err.unknownHostError')))
257
- })
258
- sock.on('error', (e) => finish(reject, new Error(t('err.connect', { message: e.message, hint: hint() }))))
259
- sock.on('close', () => finish(reject, new Error(t('err.closed'))))
260
- timer = setTimeout(() => finish(reject, new Error(t('err.timeout', { ms: `${timeoutMs}ms` }))), timeoutMs)
261
- })
262
- }
263
-
264
- /**
265
- * 每个会话「正在用的标签页」:它自己打开的,或者它点名操作过的。不传 tab 时就接着用它;
266
- * 一个都没有就报错 —— 绝不默认去动用户正在看的标签页(以前省略等于 active:模型没传 tab,
267
- * 就把用户正在编辑的页面跳走了)。明确传 "active" 照旧:那是模型按用户的话有意要动当前页。
268
- */
269
- const currentTab = new Map() // 会话 → 标签页 id
270
- const sessionKey = () => (callInfo.getStore() || {}).session || 'default'
271
- const rememberTab = (id) => currentTab.set(sessionKey(), Number(id))
272
-
273
- /** 标签页关掉了:谁正在用它,谁就忘掉它 */
274
- function forgetTab(id) {
275
- for (const [k, v] of currentTab) if (v === Number(id)) currentTab.delete(k)
276
- }
277
-
278
26
  /**
279
27
  * 用户正在看的那一页。窗口不止一个时每个窗口都有一个 active:先挑用户最后在用的窗口里的,
280
28
  * 再挑不在 DSH 干活窗口里的。老扩展不给 focused / agentWindow,就退回第一个 active(以前的做法)。
281
29
  */
282
30
  function userTab(tabs) {
283
- return tabs.find((t) => t.active && t.focused) ||
284
- tabs.find((t) => t.active && !t.agentWindow) ||
285
- tabs.find((t) => t.active)
286
- }
287
-
288
- async function resolveTab(tab) {
289
- if (tab !== undefined && tab !== null && tab !== '') {
290
- if (String(tab) === 'active') {
291
- const active = userTab(await call('tabs'))
292
- if (!active) throw new Error(t('err.noActiveTab'))
293
- rememberTab(active.id)
294
- return active.id
295
- }
296
- const id = Number(tab)
297
- if (!Number.isInteger(id)) throw new Error(t('err.badTab', { tab }))
298
- rememberTab(id)
299
- return id
300
- }
301
- const id = currentTab.get(sessionKey())
302
- if (id !== undefined) {
303
- if ((await call('tabs')).some((t) => t.id === id)) return id
304
- currentTab.delete(sessionKey())
305
- }
306
- throw new Error(t('err.noTab'))
307
- }
308
-
309
- /**
310
- * 后台标签页(或者 Chrome 窗口被别的窗口挡住)时页面是 hidden,CDP 发的鼠标/键盘事件
311
- * 会被直接丢掉——工具照样回「已点击」,其实什么都没发生(实测:3 次点击 0 次生效)。
312
- * 打开焦点模拟后事件就能送达(Playwright 对每个页面都这么做)。
313
- * 空闲断开调试会话会清掉它,所以每次动手前补一下,本地一个来回,很便宜。
314
- */
315
- async function emulateFocus(tabId) {
316
- try {
317
- await call('cdp', { tabId, method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } })
318
- } catch (e) {
319
- trace(`焦点模拟失败(忽略): ${e && e.message}`)
320
- }
321
- }
322
-
323
- /**
324
- * 换目录之前的宿主只在 /tmp/dsh-bridge.sock 听:插件升级后它要是还活着,新插件就找不到宿主。
325
- * 只要那个 socket 确实是自己的,就请它让扩展重载一次 —— 扩展重连时 Chrome 会拉起新宿主(新目录)。
326
- * 只发 reload,不发别的。
327
- */
328
- function nudgeLegacyHost() {
329
- if (WIN) return
330
- try {
331
- const legacy = '/tmp/dsh-bridge.sock'
332
- const tokenFile = '/tmp/dsh-bridge.token'
333
- const st = fs.lstatSync(legacy)
334
- const tk = fs.lstatSync(tokenFile)
335
- if (!st.isSocket() || !tk.isFile() || (UID !== null && (st.uid !== UID || tk.uid !== UID))) return
336
- const token = fs.readFileSync(tokenFile, 'utf8').trim()
337
- const s = net.connect(legacy)
338
- s.on('connect', () => s.end(JSON.stringify({ token, id: crypto.randomUUID(), op: 'reload', args: {} }) + '\n'))
339
- s.on('error', () => {})
340
- setTimeout(() => s.destroy(), 3000).unref()
341
- trace('旧宿主还在老地方听:已请扩展重载,换成新宿主')
342
- } catch {}
343
- }
344
-
345
- /**
346
- * 扩展是「已解压」加载的:setup 把新文件拷进扩展目录后,Chrome 不会自己重载,跑的还是旧代码。
347
- * 所以插件启动时对一下版本号,对不上就让扩展自己 chrome.runtime.reload()(一秒内带着新代码回来)。
348
- *
349
- * 只管解压版(ID 和 ~/dsh-bridge-extension 推导出来的一致)。商店版的代码由商店自己更新,
350
- * reload 只会白白掐断宿主一下;而商店版本号常常落后本地,不跳过就会每次启动都重载。
351
- */
352
- async function refreshExtension() {
353
- if (!hostUp()) {
354
- if (!process.env.DSH_BRIDGE_SOCK) nudgeLegacyHost()
355
- return
356
- }
357
- let want, localId
358
- try {
359
- const manifestFile = path.join(paths().extDir, 'manifest.json')
360
- want = JSON.parse(fs.readFileSync(manifestFile, 'utf8')).version
361
- localId = extensionId(manifestFile)
362
- } catch {
363
- return
364
- }
365
- try {
366
- const { version, id } = await call('version', {}, 5000)
367
- if (id && id !== localId) {
368
- trace(`扩展 ${version}(${id})不是本地解压版,不重载`)
369
- return
370
- }
371
- if (version === want) return
372
- await call('reload', {}, 5000)
373
- trace(`扩展 ${version} → ${want}:已让它重载`)
374
- } catch (e) {
375
- trace(`检查扩展版本失败(忽略): ${e && e.message}`)
376
- }
31
+ return tabs.find((tb) => tb.active && tb.focused) ||
32
+ tabs.find((tb) => tb.active && !tb.agentWindow) ||
33
+ tabs.find((tb) => tb.active)
377
34
  }
378
35
 
379
- /** 页内光标脚本:点东西时让用户看得见。读不到就静默降级。 */
380
- let cursorCache
381
- function cursorScript() {
382
- if (cursorCache !== undefined) return cursorCache
383
- // 先用插件自带的那份:版本跟插件走,别的安装脚本往 ~/.dsh/chrome-cursor 里写了旧版也不受影响
384
- const candidates = [
385
- path.join(path.dirname(fileURLToPath(import.meta.url)), 'vendor/in-page-cursor.js'),
386
- path.join(os.homedir(), '.dsh/chrome-cursor/in-page-cursor.js'), // setup.js 落盘的位置(cb 命令行也读它)
387
- ]
388
- cursorCache = ''
389
- for (const file of candidates) {
390
- try { cursorCache = fs.readFileSync(file, 'utf8'); break } catch {}
391
- }
392
- return cursorCache
393
- }
394
- const withCursor = (extra = {}) => {
395
- const script = cursorScript()
396
- return script ? { ...extra, script } : extra
397
- }
398
-
399
- const clip = (s, n = 6000) => (s.length > n ? s.slice(0, n) + `\n…(截断,全文 ${s.length} 字)` : s)
400
-
401
- /** DSH 的会话投影服务(读会话现在的工作目录用);apply 里 inject 到了才有 */
402
- let projections = null
403
-
404
- /**
405
- * 会话现在的工作目录:先看 DSH 的 workingDirectory 投影(会话里切过目录就是新的),没有再用会话头里
406
- * 建会话时的目录。都拿不到返回空串。写法同 dsh-video-preview 的 sessionCwd。
407
- */
408
- function sessionCwd(exec) {
409
- const session = exec && exec.agent && exec.agent.session
410
- let cwd
411
- try {
412
- cwd = projections && session && projections.stateOf(session, 'workingDirectory')
413
- } catch { /* 没装这个投影 */ }
414
- if (typeof cwd !== 'string' || !cwd) cwd = session && session.header && session.header.cwd
415
- return typeof cwd === 'string' && path.isAbsolute(cwd) ? cwd : ''
416
- }
417
-
418
- /**
419
- * 点击 / 按键让页面要选文件时,扩展已把系统的选文件窗口拦下、回一个 id。记在「会话 + 标签页」名下:
420
- * 之后这个会话 upload 不给目标就带着它去,别的会话拿不到(不会把文件塞进人家刚点开的框)。
421
- */
422
- const chooserIds = new Map()
423
- const chooserKey = (tabId) => `${sessionKey()}:${Number(tabId)}`
424
-
425
- /** 点击 / 按键回话后面补的那句。老扩展不回 fileChooser,就什么也不加 */
426
- function chooserNote(r, tabId) {
427
- const c = r && r.fileChooser
428
- if (!c) return ''
429
- if (c.unsupported) return '\n' + t('note.fileChooserUnsupported')
430
- if (c.folder) return '\n' + t('note.fileChooserFolder')
431
- chooserIds.set(chooserKey(tabId), c.id)
432
- return '\n' + t('note.fileChooser', { multi: c.mode === 'selectMultiple' ? t('note.fileChooserMulti') : '' })
433
- }
434
-
435
- /**
436
- * upload 的报错换成说得清的话:
437
- * 没开「允许访问文件网址」:新扩展报 FILE_ACCESS_OFF(带详情页地址),老扩展只回 CDP 的一句 Not allowed(issue #7)
438
- * 单选框给了多个文件 / 页面没在等选文件 / 用户自己已经选好 / 选文件夹的框(新扩展的记号)
439
- * 不给目标时老扩展的参数错(它不认这种用法)→ 还是「要 ref 或 selector」
440
- * 别的错原样抛。
441
- */
442
- function uploadError(e, noTarget) {
443
- const msg = String(e && e.message || e)
444
- if (/FILE_ACCESS_OFF|Not allowed/.test(msg)) {
445
- const url = (/chrome:\/\/extensions\/\?id=[a-p]{32}/.exec(msg) || [])[0] || 'chrome://extensions'
446
- return new Error(t('err.fileAccessOff', { url }))
447
- }
448
- if (msg.includes('MULTI_NOT_ALLOWED')) return new Error(t('err.uploadSingle'))
449
- if (msg.includes('NO_FILE_CHOOSER')) return new Error(t('err.uploadNoChooser'))
450
- if (msg.includes('USER_PICKED')) return new Error(t('err.uploadUserPicked'))
451
- if (msg.includes('FOLDER_INPUT')) return new Error(t('err.uploadFolder'))
452
- if (noTarget && /params\.selector|mandatory field|Invalid parameters|没找到文件输入框/.test(msg)) return new Error(t('err.uploadNeedsTarget'))
453
- return e
454
- }
455
-
456
- /**
457
- * upload 能塞进网页的文件:只限会话工作目录、系统临时目录下的普通文件,路径里任何一段以 . 开头
458
- * (~/.ssh、.env 这类隐藏目录/文件)都不行。按 realpath 判断,软链接绕不过去;交给扩展的也是 realpath。
459
- */
460
- function uploadable(files, cwd) {
461
- const roots = [cwd, os.tmpdir(), '/tmp'].filter(Boolean)
462
- .map((d) => { try { return fs.realpathSync(d) } catch { return null } }).filter(Boolean)
463
- const hidden = (p) => p.split(path.sep).some((seg) => seg.startsWith('.'))
464
- return files.map((f) => {
465
- const raw = String(f)
466
- if (!path.isAbsolute(raw) && !cwd) throw new Error(t('err.uploadAbs', { path: raw }))
467
- const abs = path.resolve(cwd || '/', raw)
468
- let real
469
- try { real = fs.realpathSync(abs) } catch { throw new Error(t('err.uploadMissing', { path: raw })) }
470
- if (hidden(abs) || hidden(real)) throw new Error(t('err.uploadHidden', { path: raw }))
471
- if (!roots.some((r) => real.startsWith(r + path.sep))) {
472
- throw new Error(cwd ? t('err.uploadOutsideCwd', { cwd, path: raw }) : t('err.uploadOutside', { path: raw }))
473
- }
474
- if (!fs.statSync(real).isFile()) throw new Error(t('err.uploadNotFile', { path: raw }))
475
- return real
476
- })
477
- }
478
-
479
- /** browser_wait 最多等多久:再长就该换个思路(或者分几次等),别把一次工具调用挂几分钟 */
480
- const WAIT_MAX_MS = 120_000
481
-
482
- // ── 工具通用外壳 ────────────────────────────────────────────────────────────
483
-
484
- const textOutput = {
485
- schema: {
486
- type: 'object',
487
- additionalProperties: false,
488
- properties: { text: { type: 'string' } },
489
- required: ['text'],
490
- },
491
- render: (_args, value) => [{ type: 'text', text: value.text }],
492
- }
493
-
494
- const present = (title) => (args) => ({ card: 'generic', title, kind: 'other', rawInput: args })
495
-
496
- // ── 截图:把图直接给模型看 ──────────────────────────────────────────────────
497
-
498
- /** render 是同步的,所以 execute 把附件引用存在这里,render 取出来用。 */
499
- const shotRefs = new Map()
500
-
501
36
  export function apply(ctx, config) {
502
37
  // 工具描述是写进模型上下文的那一层,注册那一刻就得是最终语言:
503
38
  // config.locale 给 en / ru,缺省或认不出就是 zh(见 i18n/index.js)。
504
- t = createT(config && config.locale)
39
+ setPluginLocale(config && config.locale)
505
40
  trace(`apply 被调用(locale: ${normalizeLocale(config && config.locale)})`)
506
41
 
507
42
  // 一次性安装:宿主 + native 注册自动落地,用户只剩把扩展装进 Chrome(加载已解压,或商店装)
@@ -515,6 +50,7 @@ export function apply(ctx, config) {
515
50
  trace(`setup 异常(忽略): ${e && e.message}`)
516
51
  }
517
52
  refreshExtension()
53
+ cleanOldShots()
518
54
 
519
55
  // DSH 插件页里的设置卡(client.js)靠这条路由拿状态、按开关。webServer 是可选的:
520
56
  // 没有网页端的 profile(headless)里就不挂,工具照常注册。
@@ -538,606 +74,20 @@ export function apply(ctx, config) {
538
74
  // 会话投影:upload 只放行会话工作目录(和系统临时目录)下的文件,要靠它读工作目录。
539
75
  // 可选的:拿不到就退回会话头里的目录。别直接读 ctx.sessionProjections:没写进 inject 的服务,
540
76
  // DSH(cordis)会直接抛「cannot get property without inject」,整个 apply 就断了
541
- projections = null
77
+ setProjections(null)
542
78
  try {
543
79
  if (typeof ctx.inject === 'function') {
544
- ctx.inject(['sessionProjections'], (sub) => { if (sub && sub.sessionProjections) projections = sub.sessionProjections })
80
+ ctx.inject(['sessionProjections'], (sub) => { if (sub && sub.sessionProjections) setProjections(sub.sessionProjections) })
545
81
  }
546
82
  } catch (e) {
547
83
  trace(`会话投影没拿到(upload 按会话头里的目录算): ${e && e.message}`)
548
84
  }
549
85
 
550
- // 好几处参数说明共用这两段,按当前语言取一次
551
- const TAB = t('param.tab')
552
- const REF = t('param.ref')
553
-
554
- const tools = [
555
- // ── 标签页 ──────────────────────────────────────────────────────────────
556
- defineTool({
557
- name: 'browser_tabs',
558
- description: t('tool.tabs.desc'),
559
- parameters: {
560
- action: {
561
- type: 'string', required: true, enum: ['list', 'find', 'open', 'close', 'activate'],
562
- description: t('tool.tabs.action'),
563
- },
564
- query: { type: 'string', description: t('tool.tabs.query') },
565
- url: { type: 'string', description: t('tool.tabs.url') },
566
- tab: { type: 'string', description: t('tool.tabs.tab') },
567
- },
568
- output: textOutput,
569
- presentCall: present('Browser tabs'),
570
- async execute(args) {
571
- switch (args.action) {
572
- case 'list': {
573
- const tabs = await call('tabs')
574
- const mine = userTab(tabs)
575
- const lines = tabs.map((t) =>
576
- `${t === mine ? '*' : ' '} ${String(t.id).padStart(5)} ${(t.title || '').slice(0, 50)} — ${t.url.slice(0, 80)}${t.agentWindow ? '(DSH 干活窗口)' : ''}`)
577
- const text = lines.join('\n') || '(没有标签页)'
578
- return { text: lines.length ? `${text}\n(* = 用户正在看的页)` : text }
579
- }
580
- case 'find': {
581
- const q = String(args.query || '').toLowerCase()
582
- const tabs = (await call('tabs')).filter((t) =>
583
- (t.title || '').toLowerCase().includes(q) || (t.url || '').toLowerCase().includes(q))
584
- return {
585
- text: tabs.map((t) => `${String(t.id).padStart(5)} ${t.title} — ${t.url}`).join('\n') || '(没有匹配的标签页)',
586
- }
587
- }
588
- case 'open': {
589
- if (!args.url) throw new Error(t('err.openNeedsUrl'))
590
- const r = await call('open', { url: args.url })
591
- rememberTab(r.tabId)
592
- const where = r.window === 'agent' ? '(在单独的 DSH 干活窗口里,后台打开,没打扰用户正在看的页)' : '(后台标签页)'
593
- return { text: `已打开标签页 ${r.tabId}${where}:${r.url}` }
594
- }
595
- case 'close': {
596
- const tabId = await resolveTab(args.tab)
597
- await call('close', { tabId })
598
- forgetTab(tabId)
599
- return { text: `已关闭标签页 ${tabId}` }
600
- }
601
- case 'activate': {
602
- const tabId = await resolveTab(args.tab)
603
- await call('activate', { tabId })
604
- return { text: `已切到标签页 ${tabId}` }
605
- }
606
- default:
607
- throw new Error(t('err.unknownAction', { action: args.action }))
608
- }
609
- },
610
- }),
611
-
612
- // ── 读页面 ──────────────────────────────────────────────────────────────
613
- defineTool({
614
- name: 'browser_read',
615
- description: t('tool.read.desc'),
616
- parameters: {
617
- what: { type: 'string', required: true, enum: ['snapshot', 'text', 'html', 'attr', 'info'], description: t('tool.read.what') },
618
- tab: { type: 'string', description: TAB },
619
- selector: { type: 'string', description: t('tool.read.selector') },
620
- name: { type: 'string', description: t('tool.read.name') },
621
- limit: { type: 'integer', description: t('tool.read.limit') },
622
- },
623
- output: textOutput,
624
- presentCall: present('Read page'),
625
- async execute(args) {
626
- const tabId = await resolveTab(args.tab)
627
- const limit = Number(args.limit || (args.what === 'snapshot' ? 8000 : 6000))
628
- switch (args.what) {
629
- case 'snapshot': {
630
- return { text: await snapshot(call, tabId, { selector: args.selector || undefined, limit }) }
631
- }
632
- case 'text': {
633
- const r = await call('text', { tabId, selector: args.selector || undefined, limit })
634
- let text = r.text || ''
635
- // 整页读时把同源 iframe 里的字接在后面(innerText 不含框架内容);跨站的给一行提示
636
- if (!args.selector) {
637
- for (const f of await frameTexts(call, tabId).catch(() => [])) {
638
- text += f.cross
639
- ? `\n\n[iframe] ${f.src}(跨站框架,读不到里面的字:browser_screenshot 看)`
640
- : f.text ? `\n\n[iframe] ${f.src}\n${f.text}` : ''
641
- }
642
- }
643
- return { text: clip(text.trim(), limit) || '(页面没有可见文字)' }
644
- }
645
- case 'html': {
646
- const r = await call('html', { tabId, selector: args.selector || 'body', limit })
647
- return { text: clip(r.html, limit) }
648
- }
649
- case 'attr': {
650
- if (!args.selector || !args.name) throw new Error(t('err.attrNeeds'))
651
- const r = await call('attr', { tabId, selector: args.selector, name: args.name })
652
- return { text: r.value === null ? '(没有这个属性)' : String(r.value) }
653
- }
654
- case 'info': {
655
- const r = await call('info', { tabId })
656
- const v = r.viewport ? ` | 视口 ${r.viewport.w}×${r.viewport.h},已滚动 ${r.viewport.scrollY}px` : ''
657
- const d = r.pendingDialog
658
- ? `\n⚠️ 有 ${r.pendingDialog.type} 弹窗挡着:「${r.pendingDialog.message}」——先调 browser_dialog 放行`
659
- : ''
660
- return { text: `${r.title}\n${r.url}${v}${d}` }
661
- }
662
- default:
663
- throw new Error(t('err.unknownWhat', { what: args.what }))
664
- }
665
- },
666
- }),
667
-
668
- // ── 点击 ────────────────────────────────────────────────────────────────
669
- defineTool({
670
- name: 'browser_click',
671
- description: t('tool.click.desc'),
672
- parameters: {
673
- tab: { type: 'string', description: TAB },
674
- ref: { type: 'integer', description: REF },
675
- selector: { type: 'string', description: t('tool.click.selector') },
676
- text: { type: 'string', description: t('tool.click.text') },
677
- x: { type: 'integer', description: t('tool.click.x') },
678
- y: { type: 'integer', description: t('tool.click.y') },
679
- count: { type: 'integer', description: t('tool.click.count') },
680
- },
681
- output: textOutput,
682
- presentCall: present('Browser click'),
683
- async execute(args) {
684
- const tabId = await resolveTab(args.tab)
685
- await emulateFocus(tabId)
686
- const count = Number(args.count || 1)
687
- if (args.ref !== undefined && args.ref !== null) {
688
- const el = await locate(call, tabId, args.ref, { wantPoint: count > 1 })
689
- if (el.selector && count === 1) {
690
- const r = await call('clickEl', { tabId, selector: el.selector, ...withCursor(), chooser: true })
691
- return { text: `已点击 [${args.ref}] ${r.target.tag}「${r.target.text}」@ (${r.x}, ${r.y})${chooserNote(r, tabId)}` }
692
- }
693
- // shadow DOM / iframe 里的元素(选择器够不着),或者要双击:按坐标点
694
- const r = await call('click', { tabId, x: el.x, y: el.y, clickCount: count, ...withCursor(), chooser: true })
695
- return { text: `已点击 [${args.ref}] ${el.tag}「${el.text}」@ (${r.x}, ${r.y})${count > 1 ? ` ×${count}` : ''}${chooserNote(r, tabId)}` }
696
- }
697
- if (args.selector) {
698
- const r = await call('clickEl', { tabId, selector: args.selector, ...withCursor(), chooser: true })
699
- return { text: `已点击 ${r.target.tag}「${r.target.text}」@ (${r.x}, ${r.y})${chooserNote(r, tabId)}` }
700
- }
701
- if (args.text) {
702
- const r = await call('clickText', { tabId, text: args.text, exact: false, ...withCursor(), chooser: true })
703
- return { text: `已点击 ${r.target.tag}「${r.target.text}」@ (${r.x}, ${r.y})${chooserNote(r, tabId)}` }
704
- }
705
- if (args.x !== undefined && args.y !== undefined) {
706
- const r = await call('click', { tabId, x: Number(args.x), y: Number(args.y), clickCount: count, ...withCursor(), chooser: true })
707
- return { text: `已点击坐标 (${r.x}, ${r.y})${chooserNote(r, tabId)}` }
708
- }
709
- throw new Error(t('err.clickNeeds'))
710
- },
711
- }),
712
-
713
- // ── 输入 ────────────────────────────────────────────────────────────────
714
- defineTool({
715
- name: 'browser_input',
716
- description: t('tool.input.desc'),
717
- parameters: {
718
- action: {
719
- type: 'string', required: true, enum: ['type', 'key', 'select', 'upload', 'focus', 'hover', 'scroll'],
720
- description: t('tool.input.action'),
721
- },
722
- tab: { type: 'string', description: TAB },
723
- text: { type: 'string', description: t('tool.input.text') },
724
- ref: { type: 'integer', description: t('tool.input.ref', { ref: REF }) },
725
- selector: { type: 'string', description: t('tool.input.selector') },
726
- key: { type: 'string', description: t('tool.input.key') },
727
- value: { type: 'string', description: t('tool.input.value') },
728
- files: { type: 'array', items: { type: 'string' }, description: t('tool.input.files') },
729
- dy: { type: 'integer', description: t('tool.input.dy') },
730
- dx: { type: 'integer', description: t('tool.input.dx') },
731
- x: { type: 'integer', description: t('tool.input.x') },
732
- y: { type: 'integer', description: t('tool.input.y') },
733
- },
734
- output: textOutput,
735
- presentCall: present('Browser input'),
736
- async execute(args, exec) {
737
- const tabId = await resolveTab(args.tab)
738
- if (args.action !== 'scroll') await emulateFocus(tabId)
739
- // 有编号就先把它换成选择器;shadow DOM / iframe 里的元素换不成,下面各自按坐标/页内处理
740
- const hasRef = args.ref !== undefined && args.ref !== null &&
741
- ['type', 'select', 'upload', 'focus', 'hover'].includes(args.action)
742
- const el = hasRef ? await locate(call, tabId, args.ref) : null
743
- const selector = el ? el.selector : args.selector
744
- const target = hasRef ? `[${args.ref}]` : args.selector
745
- const noShadow = (what) => {
746
- if (el && el.shadow) throw new Error(t('err.shadowUnsupported', { ref: args.ref, action: what }))
747
- }
748
- switch (args.action) {
749
- case 'type': {
750
- if (args.text === undefined) throw new Error(t('err.typeNeedsText'))
751
- if (el && el.shadow) {
752
- await call('click', { tabId, x: el.x, y: el.y, ...withCursor() })
753
- const r = await call('type', { tabId, text: args.text })
754
- return { text: `已输入 ${r.typed} 个字符(先点了 ${target})` }
755
- }
756
- const r = await call('type', { tabId, text: args.text, selector: selector || undefined, ...withCursor() })
757
- return { text: `已输入 ${r.typed} 个字符${selector ? `(先聚焦了 ${target})` : ''}` }
758
- }
759
- case 'key': {
760
- if (!args.key) throw new Error(t('err.keyNeedsKey'))
761
- const r = await call('key', { tabId, key: args.key, chooser: true })
762
- return { text: `已按键 ${args.key}${chooserNote(r, tabId)}` }
763
- }
764
- case 'select': {
765
- if (!selector && !el) throw new Error(t('err.selectNeedsTarget'))
766
- if (args.value === undefined) throw new Error(t('err.selectNeedsValue'))
767
- if (el && el.shadow) {
768
- const r = await selectInPage(call, tabId, args.ref, args.value)
769
- return { text: `已选择「${r.label}」(${r.value})` }
770
- }
771
- const r = await call('select', { tabId, selector, value: args.value })
772
- return { text: `已选择「${r.label}」(${r.value})` }
773
- }
774
- case 'upload': {
775
- if (!args.files?.length) throw new Error(t('err.uploadNeedsFiles'))
776
- noShadow('upload')
777
- const files = uploadable(args.files, sessionCwd(exec))
778
- if (!selector && !el) {
779
- // 没给目标:塞给本会话刚才点击时拦下的那个选文件框(带着点击回话里的 id 去,扩展核对)
780
- const key = chooserKey(tabId)
781
- const used = chooserIds.get(key)
782
- let r
783
- try { r = await call('upload', { tabId, files, chooserId: used }) } catch (e) { throw uploadError(e, true) }
784
- if (!r || !r.chooser) throw new Error(t('err.uploadNeedsTarget'))
785
- // 等回包时这个会话可能又点开了新框(存了新 id):只删这次用掉的
786
- if (chooserIds.get(key) === used) chooserIds.delete(key)
787
- return { text: `已把 ${r.files.length} 个文件交给页面刚才打开的选文件框` }
788
- }
789
- let r
790
- try { r = await call('upload', { tabId, selector, files }) } catch (e) { throw uploadError(e) }
791
- return { text: `已把 ${r.files.length} 个文件塞进 ${target}` }
792
- }
793
- case 'focus': {
794
- if (!selector && !el) throw new Error(t('err.focusNeedsTarget'))
795
- if (el && el.shadow) await focusShadow(call, tabId, args.ref)
796
- else await call('focus', { tabId, selector })
797
- return { text: `已聚焦 ${target}` }
798
- }
799
- case 'hover': {
800
- const byPoint = el && el.shadow
801
- if (!selector && !byPoint && (args.x === undefined || args.y === undefined)) {
802
- throw new Error(t('err.hoverNeedsTarget'))
803
- }
804
- const r = await call('hover', {
805
- tabId,
806
- x: byPoint ? el.x : selector ? undefined : Number(args.x),
807
- y: byPoint ? el.y : selector ? undefined : Number(args.y),
808
- selector: byPoint ? undefined : selector || undefined,
809
- ...withCursor(),
810
- })
811
- return { text: `已悬停 @ (${r.x}, ${r.y})${r.target ? ` ${r.target.tag}「${r.target.text}」` : ''}` }
812
- }
813
- case 'scroll': {
814
- const r = await call('scroll', { tabId, deltaY: Number(args.dy ?? 600), deltaX: Number(args.dx || 0) })
815
- return { text: `已滚动 ${r.deltaY}px,当前 scrollY=${r.scrollY} / 页高 ${r.pageHeight}` }
816
- }
817
- default:
818
- throw new Error(t('err.unknownAction', { action: args.action }))
819
- }
820
- },
821
- }),
822
-
823
- // ── 导航 ────────────────────────────────────────────────────────────────
824
- defineTool({
825
- name: 'browser_nav',
826
- description: t('tool.nav.desc'),
827
- parameters: {
828
- action: {
829
- type: 'string', enum: ['go', 'back', 'forward', 'reload'],
830
- description: t('tool.nav.action'),
831
- },
832
- url: { type: 'string', description: t('tool.nav.url') },
833
- tab: { type: 'string', description: TAB },
834
- },
835
- output: textOutput,
836
- presentCall: present('Browser navigate'),
837
- async execute(args) {
838
- const tabId = await resolveTab(args.tab)
839
- const action = args.action || 'go'
840
- if (action === 'go') {
841
- if (!args.url) throw new Error(t('err.navNeedsUrl'))
842
- const r = await call('nav', { tabId, url: args.url, wait: true }, 60000)
843
- const late = r.loaded === false ? '(页面还没加载完,需要的话 browser_wait 等一下)' : ''
844
- return { text: `已到 ${r.url}${r.title ? ` — ${r.title}` : ''}${late}` }
845
- }
846
- const r = await historyNav(call, tabId, action)
847
- const verb = { back: '已后退到', forward: '已前进到', reload: '已刷新' }[action]
848
- if (!verb) throw new Error(t('err.unknownAction', { action }))
849
- const late = r.done ? '' : '(页面还没加载完,需要的话 browser_wait 等一下)'
850
- return { text: `${verb} ${r.url}${r.title ? ` — ${r.title}` : ''}${late}` }
851
- },
852
- }),
853
-
854
- // ── 截图 ────────────────────────────────────────────────────────────────
855
- defineTool({
856
- name: 'browser_screenshot',
857
- description: t('tool.screenshot.desc'),
858
- parameters: {
859
- mode: { type: 'string', required: true, enum: ['viewport', 'full', 'element'], description: t('tool.screenshot.mode') },
860
- tab: { type: 'string', description: TAB },
861
- ref: { type: 'integer', description: t('tool.screenshot.ref', { ref: REF }) },
862
- selector: { type: 'string', description: t('tool.screenshot.selector') },
863
- format: { type: 'string', description: t('tool.screenshot.format') },
864
- },
865
- output: {
866
- schema: {
867
- type: 'object',
868
- additionalProperties: false,
869
- properties: {
870
- text: { type: 'string' },
871
- token: { type: 'string' },
872
- },
873
- required: ['text', 'token'],
874
- },
875
- render: (_args, value) => {
876
- const blocks = [{ type: 'text', text: value.text }]
877
- const ref = shotRefs.get(value.token)
878
- if (ref) {
879
- shotRefs.delete(value.token)
880
- blocks.push({ type: 'image', attachment: ref })
881
- }
882
- return blocks
883
- },
884
- },
885
- presentCall: present('Browser screenshot'),
886
- async execute(args) {
887
- const tabId = await resolveTab(args.tab)
888
- const format = args.format === 'jpeg' ? 'jpeg' : 'png'
889
- let r
890
- if (args.mode === 'element') {
891
- const hasRef = args.ref !== undefined && args.ref !== null
892
- if (!hasRef && !args.selector) throw new Error(t('err.shotNeedsTarget'))
893
- // 自己取框再直接截:扩展的 shot(selector) 取框只等 rAF,后台标签页里会卡满 15 秒
894
- const box = await elementBox(call, tabId, { ref: hasRef ? args.ref : undefined, selector: args.selector })
895
- if (!box || box.width < 1 || box.height < 1) throw new Error(t('err.shotZeroSize'))
896
- const capture = () => call('cdp', {
897
- tabId, method: 'Page.captureScreenshot', params: { format, clip: { ...box, scale: 1 } },
898
- }, 90000)
899
- // Edge 无头偶尔第一次带 clip 的截图一直不回(之后的都正常):15 秒没回就再截一次,先发的那个结果不要了
900
- const first = capture()
901
- first.catch(() => {})
902
- let timer
903
- const late = new Promise((r) => { timer = setTimeout(r, 15000, null) })
904
- const shot = (await Promise.race([first, late]).finally(() => clearTimeout(timer))) || (await capture())
905
- const tabInfo = (await call('tabs')).find((x) => x.id === tabId)
906
- r = { data: shot.result.data, format, url: tabInfo && tabInfo.url, title: tabInfo && tabInfo.title }
907
- } else {
908
- r = await call('shot', { tabId, format, full: args.mode === 'full' }, 90000)
909
- }
910
-
911
- const buf = Buffer.from(r.data, 'base64')
912
- const where = `${r.title || ''} ${r.url || ''}`.trim()
913
- const note = `截图(${args.mode},${Math.round(buf.length / 1024)}KB)— ${where}`
914
-
915
- const attachments = ctx.get('attachments')
916
- if (attachments) {
917
- try {
918
- const fmt = String(args.format || r.format || 'png').toLowerCase()
919
- const isJpeg = fmt === 'jpeg' || fmt === 'jpg'
920
- const [ref] = await attachments.saveImages([{
921
- data: buf,
922
- mediaType: isJpeg ? 'image/jpeg' : 'image/png',
923
- name: `page-${Date.now()}.${isJpeg ? 'jpg' : 'png'}`,
924
- }])
925
- const token = crypto.randomUUID()
926
- shotRefs.set(token, ref)
927
- if (shotRefs.size > 20) shotRefs.delete(shotRefs.keys().next().value)
928
- return { text: note, token }
929
- } catch {
930
- // 存不进附件库就退回文件,别让截图功能整个挂掉
931
- }
932
- }
933
- const file = path.join(os.tmpdir(), `dsh-shot-${Date.now()}.${String(args.format || '').toLowerCase().startsWith('j') ? 'jpg' : 'png'}`)
934
- fs.writeFileSync(file, buf)
935
- return { text: `${note}\n(附件库不可用,已存到 ${file},可以用 read_image 看)`, token: '' }
936
- },
937
- }),
938
-
939
- // ── 跑 JS ───────────────────────────────────────────────────────────────
940
- defineTool({
941
- name: 'browser_eval',
942
- description: t('tool.eval.desc'),
943
- parameters: {
944
- expression: { type: 'string', required: true, description: t('tool.eval.expression') },
945
- tab: { type: 'string', description: TAB },
946
- },
947
- output: textOutput,
948
- presentCall: present('Browser eval'),
949
- async execute(args) {
950
- const tabId = await resolveTab(args.tab)
951
- const r = await call('eval', { tabId, expression: args.expression })
952
- const v = r.value
953
- return { text: typeof v === 'string' ? clip(v) : clip(JSON.stringify(v, null, 2) ?? 'undefined') }
954
- },
955
- }),
956
-
957
- // ── 等元素 ──────────────────────────────────────────────────────────────
958
- defineTool({
959
- name: 'browser_wait',
960
- description: t('tool.wait.desc'),
961
- parameters: {
962
- selector: { type: 'string', description: t('tool.wait.selector') },
963
- text: { type: 'string', description: t('tool.wait.text') },
964
- url: { type: 'string', description: t('tool.wait.url') },
965
- gone: { type: 'boolean', description: t('tool.wait.gone') },
966
- tab: { type: 'string', description: TAB },
967
- timeoutMs: { type: 'integer', description: t('tool.wait.timeoutMs', { max: WAIT_MAX_MS }) },
968
- },
969
- output: textOutput,
970
- presentCall: present('Browser wait'),
971
- async execute(args) {
972
- const tabId = await resolveTab(args.tab)
973
- const timeoutMs = Math.min(Number(args.timeoutMs || 15000), WAIT_MAX_MS)
974
- const has = (v) => v !== undefined && v !== null && v !== ''
975
- const given = [args.selector, args.text, args.url].filter(has).length
976
- if (given !== 1) throw new Error(t('err.waitNeedsOne'))
977
- if (has(args.selector) && !args.gone) {
978
- const r = await call('waitFor', { tabId, selector: args.selector, timeoutMs, visible: true }, timeoutMs + 15000)
979
- return { text: `等到了 ${args.selector} @ (${r.x}, ${r.y})「${r.text}」,用了 ${r.waitedMs}ms` }
980
- }
981
- const text = await waitUntil(call, tabId, {
982
- selector: has(args.selector) ? args.selector : undefined,
983
- text: has(args.text) ? args.text : undefined,
984
- url: has(args.url) ? args.url : undefined,
985
- gone: !!args.gone,
986
- timeoutMs,
987
- })
988
- return { text }
989
- },
990
- }),
991
-
992
- // ── 弹窗 ────────────────────────────────────────────────────────────────
993
- defineTool({
994
- name: 'browser_dialog',
995
- description: t('tool.dialog.desc'),
996
- parameters: {
997
- action: { type: 'string', required: true, enum: ['accept', 'dismiss'], description: t('tool.dialog.action') },
998
- tab: { type: 'string', description: TAB },
999
- text: { type: 'string', description: t('tool.dialog.text') },
1000
- },
1001
- output: textOutput,
1002
- presentCall: present('Browser dialog'),
1003
- async execute(args) {
1004
- const tabId = await resolveTab(args.tab)
1005
- const r = await call('dialog', { tabId, action: args.action, text: args.text || undefined })
1006
- return { text: r.action === 'accept' ? '已放行弹窗' : '已取消弹窗' }
1007
- },
1008
- }),
1009
-
1010
- // ── 拖拽 ────────────────────────────────────────────────────────────────
1011
- defineTool({
1012
- name: 'browser_drag',
1013
- description: t('tool.drag.desc'),
1014
- parameters: {
1015
- tab: { type: 'string', description: TAB },
1016
- fromRef: { type: 'integer', description: t('tool.drag.fromRef', { ref: REF }) },
1017
- fromSelector: { type: 'string', description: t('tool.drag.fromSelector') },
1018
- fromText: { type: 'string', description: t('tool.drag.fromText') },
1019
- fromX: { type: 'integer', description: t('tool.drag.fromX') },
1020
- fromY: { type: 'integer', description: t('tool.drag.fromY') },
1021
- toRef: { type: 'integer', description: t('tool.drag.toRef') },
1022
- toSelector: { type: 'string', description: t('tool.drag.toSelector') },
1023
- toText: { type: 'string', description: t('tool.drag.toText') },
1024
- toX: { type: 'integer', description: t('tool.drag.toX') },
1025
- toY: { type: 'integer', description: t('tool.drag.toY') },
1026
- steps: { type: 'integer', description: t('tool.drag.steps') },
1027
- },
1028
- output: textOutput,
1029
- presentCall: present('Browser drag'),
1030
- async execute(args) {
1031
- const tabId = await resolveTab(args.tab)
1032
- const end = (p) => {
1033
- const ref = args[`${p}Ref`]
1034
- if (ref !== undefined && ref !== null) return { ref: Number(ref) }
1035
- if (args[`${p}Selector`]) return { selector: args[`${p}Selector`] }
1036
- if (args[`${p}Text`]) return { text: args[`${p}Text`] }
1037
- const x = args[`${p}X`]
1038
- const y = args[`${p}Y`]
1039
- if (x !== undefined && x !== null && y !== undefined && y !== null) return { x: Number(x), y: Number(y) }
1040
- throw new Error(t('err.dragNeedsEnd', {
1041
- which: p === 'from' ? t('which.start') : t('which.end'),
1042
- ref: `${p}Ref`, sel: `${p}Selector`, txt: `${p}Text`, xy: `${p}X+${p}Y`,
1043
- }))
1044
- }
1045
- const from = end('from')
1046
- const to = end('to')
1047
- await emulateFocus(tabId)
1048
- // 页内光标跟着走,让用户看得见在拖什么(脚本每次都带,扩展那边注入过就不再执行)
1049
- const script = cursorScript()
1050
- const cursor = script
1051
- ? {
1052
- move: async (x, y, o = {}) => (await call('cursor', {
1053
- tabId, action: 'move', x: Math.round(x), y: Math.round(y), duration: o.duration, straight: o.straight, text: o.label, script,
1054
- })).duration,
1055
- down: () => call('cursor', { tabId, action: 'down', script }),
1056
- up: () => call('cursor', { tabId, action: 'up', script }),
1057
- }
1058
- : undefined
1059
- return { text: await drag(call, tabId, from, to, { steps: args.steps, cursor }) }
1060
- },
1061
- }),
1062
-
1063
- // ── 下载 ────────────────────────────────────────────────────────────────
1064
- defineTool({
1065
- name: 'browser_download',
1066
- description: t('tool.download.desc'),
1067
- parameters: {
1068
- ref: { type: 'integer', description: REF },
1069
- selector: { type: 'string', description: t('tool.download.selector') },
1070
- url: { type: 'string', description: t('tool.download.url') },
1071
- tab: { type: 'string', description: TAB },
1072
- filename: { type: 'string', description: t('tool.download.filename') },
1073
- to: { type: 'string', enum: ['downloads', 'workdir'], description: t('tool.download.to') },
1074
- },
1075
- output: textOutput,
1076
- presentCall: present('Download file'),
1077
- async execute(args, exec) {
1078
- const tabId = await resolveTab(args.tab)
1079
- let dir = downloadsDir()
1080
- if (args.to === 'workdir') {
1081
- dir = sessionCwd(exec)
1082
- if (!dir) throw new Error(t('err.noWorkdir'))
1083
- }
1084
- const r = await download(call, tabId, {
1085
- url: args.url || undefined,
1086
- ref: args.ref ?? undefined,
1087
- selector: args.selector || undefined,
1088
- filename: args.filename || undefined,
1089
- dir,
1090
- })
1091
- const type = (r.type || '').split(';')[0].trim()
1092
- const warn = /^text\/html/i.test(type)
1093
- ? '\n⚠️ 下到的是网页(text/html),多半是登录页或「下载即将开始」的中转页,不是文件本身:打开看看,或者换成真正的文件链接'
1094
- : ''
1095
- return { text: `已下载:${r.file}(${humanSize(r.size)}${type ? `,${type}` : ''})${warn}` }
1096
- },
1097
- }),
1098
-
1099
- // ── 调试:控制台 / 网络 ──────────────────────────────────────────────────
1100
- defineTool({
1101
- name: 'browser_devtools',
1102
- description: t('tool.devtools.desc'),
1103
- parameters: {
1104
- action: {
1105
- type: 'string', required: true, enum: ['console', 'network', 'response', 'clear'],
1106
- description: t('tool.devtools.action'),
1107
- },
1108
- tab: { type: 'string', description: TAB },
1109
- level: {
1110
- type: 'string', enum: ['all', 'warning', 'error'],
1111
- description: t('tool.devtools.level'),
1112
- },
1113
- filter: { type: 'string', description: t('tool.devtools.filter') },
1114
- reload: {
1115
- type: 'boolean',
1116
- description: t('tool.devtools.reload'),
1117
- },
1118
- request: { type: 'string', description: t('tool.devtools.request') },
1119
- limit: { type: 'integer', description: t('tool.devtools.limit') },
1120
- },
1121
- output: textOutput,
1122
- presentCall: present('Browser devtools'),
1123
- async execute(args) {
1124
- const tabId = await resolveTab(args.tab)
1125
- const limit = args.limit ? Number(args.limit) : undefined
1126
- switch (args.action) {
1127
- case 'console':
1128
- return { text: await consoleLog(call, tabId, { level: args.level || 'all', filter: args.filter, limit }) }
1129
- case 'network':
1130
- return { text: await networkLog(call, tabId, { filter: args.filter, reload: !!args.reload, limit }) }
1131
- case 'response':
1132
- return { text: await responseBody(call, tabId, args.request, limit) }
1133
- case 'clear':
1134
- return { text: await clearLogs(call, tabId) }
1135
- default:
1136
- throw new Error(t('err.unknownAction', { action: args.action }))
1137
- }
1138
- },
1139
- }),
1140
- ]
86
+ const tools = buildTools({
87
+ userTab,
88
+ resolveTab: (tab) => resolveTab(tab, userTab),
89
+ getAttachments: () => ctx.get('attachments'),
90
+ })
1141
91
 
1142
92
  for (const tool of tools) {
1143
93
  try {
@@ -1147,12 +97,10 @@ export function apply(ctx, config) {
1147
97
  throw e
1148
98
  }
1149
99
  }
1150
- trace(`已注册 ${tools.length} 个工具: ${tools.map((t) => t.name).join(', ')}`)
100
+ trace(`已注册 ${tools.length} 个工具: ${tools.map((x) => x.name).join(', ')}`)
1151
101
 
1152
102
  // 上游报「图片太多」时卸掉最老的几张再重试(见 image-guard.js)
1153
103
  installImageGuard(ctx, trace)
1154
104
  }
1155
105
 
1156
106
  trace('模块已加载')
1157
-
1158
-