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