dsh-shared-browser 0.0.0-stage → 0.6.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.
- package/LICENSE +21 -0
- package/README.md +132 -2
- package/README.zh.md +127 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +10 -0
- package/index.js +825 -0
- package/lib/bridge.mjs +372 -0
- package/lib/client.cjs +2712 -0
- package/lib/external.mjs +641 -0
- package/locale/en.json +9 -0
- package/locale/zh.json +9 -0
- package/package.json +78 -3
package/index.js
ADDED
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-shared-browser — one browser, shared by the user and the agent.
|
|
3
|
+
*
|
|
4
|
+
* Two halves, one product:
|
|
5
|
+
*
|
|
6
|
+
* - **Client half** (`lib/client.cjs`) takes over DSH's own Browser tab through
|
|
7
|
+
* the public `sidebarRightTabs` registry (`priority: 'extension'`, same
|
|
8
|
+
* `kind: 'browser'`), then draws the full desktop-browser chrome around the
|
|
9
|
+
* Electron `<webview>` the shell already owns: back/forward/reload, zoom,
|
|
10
|
+
* find-in-page, device emulation, history, bookmarks, permissions, storage
|
|
11
|
+
* clearing, screenshots, region screenshots, element picking, element
|
|
12
|
+
* comments, a DevTools panel, and the context menu the product menu shows.
|
|
13
|
+
*
|
|
14
|
+
* - **Host half** (this file) exposes the same browser to the agent as tools,
|
|
15
|
+
* relays commands over an authenticated SSE/POST bridge, and owns everything
|
|
16
|
+
* that must survive a tab: the console log, the network log, element
|
|
17
|
+
* comments, and screenshots written to disk.
|
|
18
|
+
*
|
|
19
|
+
* Because the tab type is a registration and the bridge is a route pair, the
|
|
20
|
+
* bundle needs no edit to DSH: unloading it restores the stock browser.
|
|
21
|
+
* @module dsh-shared-browser
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
25
|
+
import { randomUUID } from 'node:crypto'
|
|
26
|
+
import { homedir } from 'node:os'
|
|
27
|
+
import { join } from 'node:path'
|
|
28
|
+
import { Hub, BridgeError, ROUTE_BASE, fence, readJson, replyError, replyJson } from './lib/bridge.mjs'
|
|
29
|
+
import { ExternalBrowser, detectBrowsers, profileRoot } from './lib/external.mjs'
|
|
30
|
+
|
|
31
|
+
export const name = 'dsh-shared-browser'
|
|
32
|
+
export const inject = ['tools']
|
|
33
|
+
|
|
34
|
+
const VERSION = '0.6.0'
|
|
35
|
+
const ATTACHMENT_PREFIX = `${ROUTE_BASE}/attachment?path=`
|
|
36
|
+
|
|
37
|
+
/** Tool output envelope: JSON text plus a generic card. */
|
|
38
|
+
const json = () => ({
|
|
39
|
+
schema: { type: 'object', additionalProperties: true },
|
|
40
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value ?? null) }],
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/** Present-call descriptor for the tool card. */
|
|
44
|
+
const present = (title, args) => ({ card: 'generic', title, kind: 'other', rawInput: args || {} })
|
|
45
|
+
|
|
46
|
+
/** Directory where screenshots and captured payloads are stored. */
|
|
47
|
+
const SETTINGS_FILE = 'settings.json'
|
|
48
|
+
const settingsRoot = () => join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'shared-browser')
|
|
49
|
+
|
|
50
|
+
/** Read the small JSON settings file; defaults keep the in-app browser. */
|
|
51
|
+
async function readSettings() {
|
|
52
|
+
try {
|
|
53
|
+
const raw = await readFile(join(settingsRoot(), SETTINGS_FILE), 'utf8')
|
|
54
|
+
const parsed = JSON.parse(raw)
|
|
55
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
56
|
+
} catch {
|
|
57
|
+
return {}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Persist a partial settings patch. */
|
|
62
|
+
async function writeSettings(patch) {
|
|
63
|
+
const next = { ...(await readSettings()), ...patch }
|
|
64
|
+
await mkdir(settingsRoot(), { recursive: true })
|
|
65
|
+
await writeFile(join(settingsRoot(), SETTINGS_FILE), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
66
|
+
return next
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function attachmentsRoot() {
|
|
70
|
+
const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
71
|
+
return join(home, 'shared-browser', 'attachments')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Ensure the attachments directory exists. @returns {Promise<string>} absolute path. */
|
|
75
|
+
async function ensureAttachments() {
|
|
76
|
+
const dir = attachmentsRoot()
|
|
77
|
+
await mkdir(dir, { recursive: true })
|
|
78
|
+
return dir
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Decode a data URL produced by the browser into raw bytes.
|
|
83
|
+
* @param {string} dataUrl - `data:image/png;base64,…`.
|
|
84
|
+
* @returns {{ bytes: Buffer, mime: string, ext: string }} decoded payload.
|
|
85
|
+
*/
|
|
86
|
+
function decodeDataUrl(dataUrl) {
|
|
87
|
+
const match = /^data:([^;,]+)?(?:;base64)?,(.*)$/su.exec(String(dataUrl ?? ''))
|
|
88
|
+
if (match === null) throw new BridgeError('截图数据不是合法的 data URL。', 'bad-image')
|
|
89
|
+
const mime = match[1] ?? 'image/png'
|
|
90
|
+
const bytes = Buffer.from(match[2], 'base64')
|
|
91
|
+
const ext = mime === 'image/jpeg' ? 'jpg' : mime === 'image/webp' ? 'webp' : 'png'
|
|
92
|
+
return { bytes, mime, ext }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Persist one browser capture and describe it for the tool result.
|
|
97
|
+
* @param {{ dataUrl: string, name?: string }} capture - client payload.
|
|
98
|
+
* @param {string} kind - `screenshot` | `region` | `element`.
|
|
99
|
+
* @returns {Promise<Record<string, unknown>>} stored file facts.
|
|
100
|
+
*/
|
|
101
|
+
async function storeCapture(capture, kind) {
|
|
102
|
+
const dir = await ensureAttachments()
|
|
103
|
+
const { bytes, mime, ext } = decodeDataUrl(capture.dataUrl)
|
|
104
|
+
const stamp = new Date().toISOString().replace(/[:.]/gu, '-')
|
|
105
|
+
const base = String(capture.name ?? kind).replace(/[^\w.-]+/gu, '-').slice(0, 40) || kind
|
|
106
|
+
const file = join(dir, `${stamp}-${base}-${randomUUID().slice(0, 8)}.${ext}`)
|
|
107
|
+
await writeFile(file, bytes)
|
|
108
|
+
return {
|
|
109
|
+
path: file,
|
|
110
|
+
bytes: bytes.length,
|
|
111
|
+
mime,
|
|
112
|
+
url: `${ATTACHMENT_PREFIX}${encodeURIComponent(file.slice(dir.length + 1).replace(/\\/gu, '/'))}`,
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Mount the routes and tools.
|
|
118
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - plugin context.
|
|
119
|
+
*/
|
|
120
|
+
export function apply(ctx) {
|
|
121
|
+
const hub = new Hub({ attachmentsDir: attachmentsRoot() })
|
|
122
|
+
/* Real Chromium channel: the user's own Edge/Chrome over CDP, used when the
|
|
123
|
+
built-in webview cannot do the job (Cloudflare-class challenges, logins
|
|
124
|
+
that must survive restarts, downloads, DevTools). */
|
|
125
|
+
const external = new ExternalBrowser(() => {})
|
|
126
|
+
/** @type {Array<() => void>} */
|
|
127
|
+
const disposers = []
|
|
128
|
+
|
|
129
|
+
// Routes exist only once the Host has a web server. Waiting for the service keeps
|
|
130
|
+
// the tools usable on carriers without one (a plain CLI session, for example).
|
|
131
|
+
ctx.inject(['webServer'], (injected) => {
|
|
132
|
+
const webServer = injected.webServer
|
|
133
|
+
const origin = (() => {
|
|
134
|
+
try { return webServer.getOrigin() } catch { return undefined }
|
|
135
|
+
})()
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Wrap a route handler with the same-origin fence and uniform error replies.
|
|
139
|
+
* @param {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void>} handler - body.
|
|
140
|
+
* @returns {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => void} guarded handler.
|
|
141
|
+
*/
|
|
142
|
+
const route = handler => (req, res) => {
|
|
143
|
+
const refusal = fence(req, origin)
|
|
144
|
+
if (refusal !== null) {
|
|
145
|
+
replyError(res, 403, refusal, 'forbidden')
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
handler(req, res).catch((error) => {
|
|
149
|
+
if (error instanceof BridgeError) replyError(res, 400, error.message, error.code)
|
|
150
|
+
else replyError(res, 500, error instanceof Error ? error.message : String(error), 'internal')
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
disposers.push(webServer.register({
|
|
155
|
+
kind: 'exact',
|
|
156
|
+
path: `${ROUTE_BASE}/state`,
|
|
157
|
+
handler: route(async (_req, res) => {
|
|
158
|
+
replyJson(res, { ok: true, version: VERSION, ...hub.status() })
|
|
159
|
+
}),
|
|
160
|
+
}))
|
|
161
|
+
|
|
162
|
+
disposers.push(webServer.register({
|
|
163
|
+
kind: 'exact',
|
|
164
|
+
path: `${ROUTE_BASE}/events`,
|
|
165
|
+
handler: route(async (req, res) => {
|
|
166
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
167
|
+
hub.attach(res, { sessionId: url.searchParams.get('sessionId'), version: url.searchParams.get('version') })
|
|
168
|
+
req.on('close', () => { /* stream close is handled by the response */ })
|
|
169
|
+
}),
|
|
170
|
+
}))
|
|
171
|
+
|
|
172
|
+
disposers.push(webServer.register({
|
|
173
|
+
kind: 'exact',
|
|
174
|
+
path: `${ROUTE_BASE}/report`,
|
|
175
|
+
handler: route(async (req, res) => {
|
|
176
|
+
if (req.method !== 'POST') { replyError(res, 405, 'POST only', 'method'); return }
|
|
177
|
+
const type = String(req.headers['content-type'] ?? '')
|
|
178
|
+
if (!type.toLowerCase().includes('application/json')) {
|
|
179
|
+
replyError(res, 415, 'report 必须是 application/json。', 'content-type')
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
const body = await readJson(req)
|
|
183
|
+
replyJson(res, hub.ingest(body))
|
|
184
|
+
}),
|
|
185
|
+
}))
|
|
186
|
+
|
|
187
|
+
// Opt-in debugging hook. It lets a local script drive the same host → client
|
|
188
|
+
// command path the tools use, without spending a model turn. Never
|
|
189
|
+
// registered unless the Host process was started with the flag.
|
|
190
|
+
if (process.env.DSH_SHARED_BROWSER_DEV === '1') {
|
|
191
|
+
disposers.push(webServer.register({
|
|
192
|
+
kind: 'exact',
|
|
193
|
+
path: `${ROUTE_BASE}/debug/command`,
|
|
194
|
+
handler: route(async (req, res) => {
|
|
195
|
+
if (req.method !== 'POST') { replyError(res, 405, 'POST only', 'method'); return }
|
|
196
|
+
const body = await readJson(req)
|
|
197
|
+
const name = String(body.tool ?? body.op ?? '')
|
|
198
|
+
const run = tools.get(name)
|
|
199
|
+
if (run === undefined) throw new BridgeError(`unknown tool: ${name}`, 'tool')
|
|
200
|
+
const value = await run(body.args ?? {})
|
|
201
|
+
replyJson(res, { ok: true, value })
|
|
202
|
+
}),
|
|
203
|
+
}))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/* The sidebar mirror polls these two routes: a PNG of the real page and a
|
|
207
|
+
channel for pointer/keyboard events coming back from the pane. */
|
|
208
|
+
disposers.push(webServer.register({
|
|
209
|
+
kind: 'exact',
|
|
210
|
+
path: `${ROUTE_BASE}/external/frame`,
|
|
211
|
+
handler: route(async (req, res) => {
|
|
212
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
213
|
+
const tabId = url.searchParams.get('tab') ?? ''
|
|
214
|
+
const capture = await external.command('screenshot', {}, tabId)
|
|
215
|
+
const bytes = Buffer.from(String(capture.dataUrl ?? '').split(',')[1] ?? '', 'base64')
|
|
216
|
+
if (bytes.length === 0) { replyError(res, 409, '外部页签没有画面。', 'empty'); return }
|
|
217
|
+
res.writeHead(200, { 'content-type': capture.mime ?? 'image/png', 'cache-control': 'no-store', 'content-length': bytes.length })
|
|
218
|
+
res.end(bytes)
|
|
219
|
+
}),
|
|
220
|
+
}))
|
|
221
|
+
|
|
222
|
+
disposers.push(webServer.register({
|
|
223
|
+
kind: 'exact',
|
|
224
|
+
path: `${ROUTE_BASE}/external/command`,
|
|
225
|
+
handler: route(async (req, res) => {
|
|
226
|
+
if (req.method !== 'POST') { replyError(res, 405, 'POST only', 'method'); return }
|
|
227
|
+
const body = await readJson(req)
|
|
228
|
+
const tabId = String(body.tab ?? '')
|
|
229
|
+
const value = await run(String(body.op ?? ''), { ...(body.args ?? {}), tabId })
|
|
230
|
+
replyJson(res, { ok: true, value })
|
|
231
|
+
}),
|
|
232
|
+
}))
|
|
233
|
+
|
|
234
|
+
disposers.push(webServer.register({
|
|
235
|
+
kind: 'exact',
|
|
236
|
+
path: `${ROUTE_BASE}/external/input`,
|
|
237
|
+
handler: route(async (req, res) => {
|
|
238
|
+
if (req.method !== 'POST') { replyError(res, 405, 'POST only', 'method'); return }
|
|
239
|
+
const body = await readJson(req)
|
|
240
|
+
replyJson(res, { ok: true, ...(await external.input(String(body.tab ?? ''), body)) })
|
|
241
|
+
}),
|
|
242
|
+
}))
|
|
243
|
+
|
|
244
|
+
disposers.push(webServer.register({
|
|
245
|
+
kind: 'exact',
|
|
246
|
+
path: `${ROUTE_BASE}/attachment`,
|
|
247
|
+
handler: route(async (req, res) => {
|
|
248
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
249
|
+
const requested = url.searchParams.get('path') ?? ''
|
|
250
|
+
const dir = await ensureAttachments()
|
|
251
|
+
const resolved = join(dir, requested)
|
|
252
|
+
if (!resolved.startsWith(dir)) { replyError(res, 400, '非法附件路径。', 'path'); return }
|
|
253
|
+
const { readFile } = await import('node:fs/promises')
|
|
254
|
+
const bytes = await readFile(resolved).catch(() => null)
|
|
255
|
+
if (bytes === null) { replyError(res, 404, '附件不存在。', 'missing'); return }
|
|
256
|
+
const mime = resolved.endsWith('.jpg') ? 'image/jpeg' : resolved.endsWith('.webp') ? 'image/webp' : 'image/png'
|
|
257
|
+
res.writeHead(200, { 'content-type': mime, 'cache-control': 'no-store', 'content-length': bytes.length })
|
|
258
|
+
res.end(bytes)
|
|
259
|
+
}),
|
|
260
|
+
}))
|
|
261
|
+
|
|
262
|
+
injected.effect(() => () => {
|
|
263
|
+
hub.detach()
|
|
264
|
+
for (const off of disposers) {
|
|
265
|
+
try { off() } catch { /* route already gone */ }
|
|
266
|
+
}
|
|
267
|
+
}, 'dsh-shared-browser routes')
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
/* ------------------------------------------------------------------ tools */
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Register one agent tool with a uniform envelope.
|
|
274
|
+
* @param {string} toolName - `bb_*` name.
|
|
275
|
+
* @param {string} description - model-facing contract.
|
|
276
|
+
* @param {Record<string, unknown>} properties - JSON schema properties.
|
|
277
|
+
* @param {(args: any) => Promise<unknown>} execute - implementation.
|
|
278
|
+
* @param {string} title - card title.
|
|
279
|
+
* @param {string[]} [required] - required properties.
|
|
280
|
+
*/
|
|
281
|
+
/** Tool table, reused by the opt-in debug route. */
|
|
282
|
+
const tools = new Map()
|
|
283
|
+
|
|
284
|
+
const tool = (toolName, description, properties, execute, title, required = []) => {
|
|
285
|
+
tools.set(toolName, execute)
|
|
286
|
+
ctx.tools.register({
|
|
287
|
+
name: toolName,
|
|
288
|
+
description,
|
|
289
|
+
parameters: {
|
|
290
|
+
type: 'object',
|
|
291
|
+
additionalProperties: false,
|
|
292
|
+
properties,
|
|
293
|
+
...(required.length === 0 ? {} : { required }),
|
|
294
|
+
},
|
|
295
|
+
output: json(),
|
|
296
|
+
execute,
|
|
297
|
+
presentCall: args => present(title, args),
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const tabArg = { type: 'string', description: 'Tab id from bb_tabs. Defaults to the active tab.' }
|
|
302
|
+
|
|
303
|
+
/** Built-in tabs known to sit on a challenge page. */
|
|
304
|
+
const walledTabs = new Set()
|
|
305
|
+
|
|
306
|
+
/** Guidance repeated in every result that lands on a bot wall. */
|
|
307
|
+
const WALL_POLICY = '这是 Cloudflare/DataDome 等防自动程序页面:不要尝试完成或绕过人机验证,也不要点击验证控件。请把情况告诉用户,让用户在弹出的真实浏览器窗口里自行验证,或改用其它数据源。'
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Flag a challenge page from its title or body text.
|
|
311
|
+
* @param {object|null} value - snapshot or text result.
|
|
312
|
+
* @returns {{wall: boolean, hint: string}} wall flag plus guidance.
|
|
313
|
+
*/
|
|
314
|
+
const wallInfo = (value) => {
|
|
315
|
+
const title = String(value?.title ?? '')
|
|
316
|
+
const body = String(value?.text ?? '')
|
|
317
|
+
const wall = CHALLENGE.test(title) === true || CHALLENGE.test(body) === true
|
|
318
|
+
return { wall, hint: WALL_POLICY }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Bot walls that never clear inside an Electron webview. */
|
|
322
|
+
const CHALLENGE = /请稍候|正在进行安全验证|访问暂时受限|Just a moment|Verify you are human|challenge-platform|\bcf-\w+/i
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* True when the built-in tab is sitting on a challenge page.
|
|
326
|
+
* @param {unknown} opened - result of the built-in open command.
|
|
327
|
+
* @returns {Promise<boolean>} whether the page is a bot wall.
|
|
328
|
+
*/
|
|
329
|
+
const looksLikeChallenge = async (opened) => {
|
|
330
|
+
const tabId = opened !== null && typeof opened === 'object' ? opened.tabId : null
|
|
331
|
+
const title = String(opened?.title ?? '')
|
|
332
|
+
if (CHALLENGE.test(title) === true) return true
|
|
333
|
+
const probe = await hub.command('text', { tabId, maxChars: 600 }, { timeoutMs: 8000 }).catch(() => null)
|
|
334
|
+
const text = String(probe?.text ?? '')
|
|
335
|
+
return text !== '' && CHALLENGE.test(text)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Move a walled page into the user's real browser, mirror it into the sidebar,
|
|
340
|
+
* and report the new tab.
|
|
341
|
+
* @param {string} target - address that hit the wall.
|
|
342
|
+
* @returns {Promise<object>} external tab descriptor.
|
|
343
|
+
*/
|
|
344
|
+
/** Compare addresses ignoring a trailing slash, which Edge adds on its own. */
|
|
345
|
+
const normaliseUrl = value => String(value ?? '').replace(/\/+$/, '')
|
|
346
|
+
/** Pick the tab that actually shows the target, else the newest one. */
|
|
347
|
+
const pickTab = (tabs, target) => tabs.find(entry => normaliseUrl(entry.url) === normaliseUrl(target)) ?? tabs[tabs.length - 1]
|
|
348
|
+
|
|
349
|
+
const handOff = async (target) => {
|
|
350
|
+
const state = await external.ensure({ url: target })
|
|
351
|
+
const tabs = await external.listTabs()
|
|
352
|
+
const tab = pickTab(tabs, target)
|
|
353
|
+
const tabId = tab === undefined ? 'ext:unknown' : `ext:${tab.id}`
|
|
354
|
+
hub.command('ensure', { url: target, external: tabId }, { timeoutMs: 8000 }).catch(() => {})
|
|
355
|
+
return { channel: 'external', handoff: 'challenge', tabId, url: tab?.url ?? target, title: tab?.title ?? '', browser: state.browser?.name ?? null, note: '内置浏览器被 Cloudflare 类防护拦截,已自动切换到外部浏览器。', hint: `${WALL_POLICY}验证请在已弹出的外部浏览器窗口里由用户完成。` }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Route a command to the external channel when the tab id says so. */
|
|
359
|
+
const isExternal = tabId => typeof tabId === 'string' && tabId.startsWith('ext:')
|
|
360
|
+
const run = (op, args = {}, options) => {
|
|
361
|
+
const tabId = args !== null && typeof args === 'object' ? args.tabId : undefined
|
|
362
|
+
if (isExternal(tabId)) return external.command(op, args, tabId)
|
|
363
|
+
return hub.command(op, args, options)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
tool('bb_status',
|
|
367
|
+
'Read the shared-browser state: whether a Browser tab is attached, every open tab, and how much console/network/comment data is held. Read-only; start here when something looks disconnected.',
|
|
368
|
+
{},
|
|
369
|
+
async () => ({ version: VERSION, ...hub.status(), attachmentsDir: attachmentsRoot(), wallPolicy: WALL_POLICY }),
|
|
370
|
+
'Shared browser status')
|
|
371
|
+
|
|
372
|
+
tool('bb_tabs',
|
|
373
|
+
'List, activate, open, reload or close shared-browser tabs. The tab list is the same one the user sees in the right sidebar.',
|
|
374
|
+
{
|
|
375
|
+
action: { type: 'string', enum: ['list', 'activate', 'open', 'reload', 'close'], description: 'Operation. Default list.' },
|
|
376
|
+
tabId: tabArg,
|
|
377
|
+
url: { type: 'string', description: 'For action=open: address to open in a new tab.' },
|
|
378
|
+
background: { type: 'boolean', description: 'For action=open: open without stealing focus.' },
|
|
379
|
+
},
|
|
380
|
+
async (a) => {
|
|
381
|
+
const action = a.action ?? 'list'
|
|
382
|
+
if (action === 'list') {
|
|
383
|
+
const externalTabs = external.running === true ? (await external.command('tabs', {}).catch(() => ({ tabs: [] }))).tabs : []
|
|
384
|
+
return { tabs: [...hub.tabs, ...externalTabs], activeTabId: hub.activeTabId, external: external.summary() }
|
|
385
|
+
}
|
|
386
|
+
if (isExternal(a.tabId)) return external.command(action === 'activate' ? 'tabs' : action, { tabId: a.tabId, url: a.url })
|
|
387
|
+
const value = await hub.command('tabs', { action, tabId: a.tabId ?? null, url: a.url ?? null, background: a.background === true })
|
|
388
|
+
return value
|
|
389
|
+
},
|
|
390
|
+
'Shared browser tabs',
|
|
391
|
+
[])
|
|
392
|
+
|
|
393
|
+
tool('bb_open',
|
|
394
|
+
'Open an address in the shared browser and wait until it is usable. If no Browser tab exists yet, this opens one. Returns the tab id, final URL and title. Cloudflare-class challenges are handed to the external browser automatically; never try to solve the verification, ask the user to finish it in the real window.',
|
|
395
|
+
{
|
|
396
|
+
url: { type: 'string', description: 'http(s) address to open.' },
|
|
397
|
+
newTab: { type: 'boolean', description: 'Open in a new tab instead of the active one.' },
|
|
398
|
+
channel: { type: 'string', enum: ['builtin', 'external'], description: 'Which browser drives the page. builtin is the in-app webview; external is the user own Edge/Chrome over CDP, with real fingerprints, persistent logins and working DevTools.' },
|
|
399
|
+
waitMs: { type: 'number', description: 'How long to wait for load. Default 15000.' },
|
|
400
|
+
},
|
|
401
|
+
async (a) => {
|
|
402
|
+
const target = String(a.url ?? '')
|
|
403
|
+
const waitMs = a.waitMs ?? 15000
|
|
404
|
+
const settings = await readSettings()
|
|
405
|
+
const channel = a.channel ?? (settings.channel === 'external' ? 'external' : 'builtin')
|
|
406
|
+
if (channel === 'external') {
|
|
407
|
+
const state = await external.ensure({ url: target })
|
|
408
|
+
const tabs = await external.listTabs()
|
|
409
|
+
const tab = pickTab(tabs, target)
|
|
410
|
+
const tabId = tab === undefined ? 'ext:unknown' : `ext:${tab.id}`
|
|
411
|
+
/* Mirror the tab into the sidebar so the user can watch the same page. */
|
|
412
|
+
hub.command('ensure', { url: target, external: tabId }, { timeoutMs: 8000 }).catch(() => {})
|
|
413
|
+
return { channel: 'external', tabId, url: tab?.url ?? target, title: tab?.title ?? '', browser: state.browser?.name ?? null, profileDir: state.profileDir }
|
|
414
|
+
}
|
|
415
|
+
/* Ask the page to open a pane first: the user should not have to open the
|
|
416
|
+
browser before an Agent can use it. */
|
|
417
|
+
const ensured = await hub.command('ensure', { url: target }, { timeoutMs: 8000 }).catch(error => ({ opened: false, reason: String(error && error.message ? error.message : error) }))
|
|
418
|
+
if (ensured !== null && ensured.opened === true) {
|
|
419
|
+
/* The new pane loads `params.url` by itself; give it a moment, then report
|
|
420
|
+
the tab the client registered. */
|
|
421
|
+
const deadline = Date.now() + waitMs
|
|
422
|
+
while (Date.now() < deadline) {
|
|
423
|
+
await new Promise(resolve => setTimeout(resolve, 400))
|
|
424
|
+
const tab = hub.status().tabs.find(entry => entry.visible === true)
|
|
425
|
+
if (tab !== undefined) {
|
|
426
|
+
if (settings.autoLaunch !== false && (await looksLikeChallenge({ tabId: tab.id, title: tab.title })) === true) {
|
|
427
|
+
await hub.command('tabs', { action: 'close', tabId: tab.id }).catch(() => {})
|
|
428
|
+
return await handOff(target)
|
|
429
|
+
}
|
|
430
|
+
return { tabId: tab.id, url: tab.url || target, title: tab.title ?? '', opened: true }
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return { opened: true, url: target, pending: true }
|
|
434
|
+
}
|
|
435
|
+
const opened = await hub.command('open', { url: target, newTab: a.newTab === true, waitMs }, { timeoutMs: waitMs + 10000 })
|
|
436
|
+
/* Cloudflare-class walls never resolve inside the Electron webview. Hand the
|
|
437
|
+
page to the user's real browser instead of leaving a dead tab behind. */
|
|
438
|
+
const wall = await looksLikeChallenge(opened)
|
|
439
|
+
if (wall === true) {
|
|
440
|
+
await hub.command('tabs', { action: 'close', tabId: opened?.tabId ?? null }).catch(() => {})
|
|
441
|
+
if (settings.autoLaunch === false) {
|
|
442
|
+
if (typeof opened?.tabId === 'string') walledTabs.add(opened.tabId)
|
|
443
|
+
return { channel: 'builtin', wall: true, ...opened, hint: WALL_POLICY, note: '页面被 Cloudflare 类防护拦截;在 bb_settings 里打开 autoLaunch 可自动切换外部浏览器。' }
|
|
444
|
+
}
|
|
445
|
+
return await handOff(target)
|
|
446
|
+
}
|
|
447
|
+
return opened
|
|
448
|
+
},
|
|
449
|
+
'Open in shared browser',
|
|
450
|
+
['url'])
|
|
451
|
+
|
|
452
|
+
tool('bb_settings',
|
|
453
|
+
'Read or change how the browser is driven: default channel (builtin|external), preferred external browser, and the profile folder used for persistent logins.',
|
|
454
|
+
{
|
|
455
|
+
action: { type: 'string', enum: ['get', 'set'], description: 'Operation. Default get.' },
|
|
456
|
+
channel: { type: 'string', enum: ['builtin', 'external'], description: 'Default channel for bb_open.' },
|
|
457
|
+
browser: { type: 'string', enum: ['msedge', 'chrome'], description: 'Preferred external browser.' },
|
|
458
|
+
profileDir: { type: 'string', description: 'Folder for the external profile. Empty restores the default.' },
|
|
459
|
+
autoLaunch: { type: 'boolean', description: 'Switch to the external browser automatically when the built-in one hits a bot wall. Default true.' },
|
|
460
|
+
},
|
|
461
|
+
async (a) => {
|
|
462
|
+
if (a.action === 'set') {
|
|
463
|
+
const patch = {}
|
|
464
|
+
if (a.channel !== undefined) patch.channel = a.channel
|
|
465
|
+
if (a.browser !== undefined) patch.browser = a.browser
|
|
466
|
+
if (a.profileDir !== undefined) patch.profileDir = a.profileDir
|
|
467
|
+
if (a.autoLaunch !== undefined) patch.autoLaunch = a.autoLaunch === true
|
|
468
|
+
const settings = await writeSettings(patch)
|
|
469
|
+
return { settings, path: join(settingsRoot(), SETTINGS_FILE) }
|
|
470
|
+
}
|
|
471
|
+
return { settings: await readSettings(), path: join(settingsRoot(), SETTINGS_FILE), profileRoot: profileRoot(), candidates: detectBrowsers() }
|
|
472
|
+
},
|
|
473
|
+
'Browser settings')
|
|
474
|
+
|
|
475
|
+
tool('bb_external',
|
|
476
|
+
'Manage the external Chromium channel: report which Edge/Chrome is installed, launch it with a persistent profile, or close it. Use this when a site rejects the built-in browser (Cloudflare-class challenges, downloads, logins that must survive restarts).',
|
|
477
|
+
{
|
|
478
|
+
action: { type: 'string', enum: ['status', 'launch', 'close'], description: 'Operation. Default status.' },
|
|
479
|
+
browser: { type: 'string', enum: ['msedge', 'chrome'], description: 'Preferred browser for launch.' },
|
|
480
|
+
url: { type: 'string', description: 'Address for action=launch.' },
|
|
481
|
+
},
|
|
482
|
+
async (a) => {
|
|
483
|
+
const action = a.action ?? 'status'
|
|
484
|
+
if (action === 'launch') {
|
|
485
|
+
const settings = await readSettings()
|
|
486
|
+
await external.ensure({ url: a.url ?? 'about:blank', browser: a.browser ?? settings.browser, profileDir: settings.profileDir || undefined })
|
|
487
|
+
return { launched: true, ...external.summary(), candidates: detectBrowsers() }
|
|
488
|
+
}
|
|
489
|
+
if (action === 'close') {
|
|
490
|
+
await external.shutdown(true)
|
|
491
|
+
return { running: false }
|
|
492
|
+
}
|
|
493
|
+
return { ...external.summary(), candidates: detectBrowsers(), profileRoot: profileRoot() }
|
|
494
|
+
},
|
|
495
|
+
'External browser channel')
|
|
496
|
+
|
|
497
|
+
tool('bb_navigate',
|
|
498
|
+
'Navigate the active tab (or tabId) to an address, with optional back/forward/reload.',
|
|
499
|
+
{
|
|
500
|
+
url: { type: 'string', description: 'Address to load. Omit for a history move.' },
|
|
501
|
+
action: { type: 'string', enum: ['goto', 'back', 'forward', 'reload', 'stop'], description: 'Default goto when url is given, otherwise reload.' },
|
|
502
|
+
tabId: tabArg,
|
|
503
|
+
waitMs: { type: 'number', description: 'How long to wait for load. Default 15000.' },
|
|
504
|
+
},
|
|
505
|
+
async (a) => run('navigate', { ...a }, { timeoutMs: (a.waitMs ?? 15000) + 10000 }),
|
|
506
|
+
'Navigate shared browser')
|
|
507
|
+
|
|
508
|
+
tool('bb_snapshot',
|
|
509
|
+
'Read the page as an accessibility-style tree with stable element refs (e1, e2, …). Use the refs with bb_click/bb_type instead of guessing selectors. A result carrying wall:true is an anti-bot challenge: never try to solve it.',
|
|
510
|
+
{
|
|
511
|
+
tabId: tabArg,
|
|
512
|
+
interactiveOnly: { type: 'boolean', description: 'Only interactive and labeled elements. Default false.' },
|
|
513
|
+
maxChars: { type: 'number', description: 'Budget for the returned text. Default 20000.' },
|
|
514
|
+
maxDepth: { type: 'number', description: 'DOM depth cap. Default 12.' },
|
|
515
|
+
},
|
|
516
|
+
async (a) => {
|
|
517
|
+
try {
|
|
518
|
+
const value = await run('snapshot', { ...a }, { timeoutMs: 15000 })
|
|
519
|
+
return { ...value, ...wallInfo(value) }
|
|
520
|
+
} catch (error) {
|
|
521
|
+
const tabId = typeof a.tabId === 'string' ? a.tabId : hub.status().activeTabId
|
|
522
|
+
const tab = hub.status().tabs.find(entry => entry.id === tabId)
|
|
523
|
+
const walled = walledTabs.has(tabId) || CHALLENGE.test(String(tab?.title ?? '')) === true
|
|
524
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
525
|
+
throw new Error(walled === true ? `${message} ${WALL_POLICY}` : message)
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
'Snapshot page')
|
|
529
|
+
|
|
530
|
+
tool('bb_text',
|
|
531
|
+
'Extract readable text from the page (main content first), optionally limited to one element. A result carrying wall:true is an anti-bot challenge: never try to solve it.',
|
|
532
|
+
{
|
|
533
|
+
tabId: tabArg,
|
|
534
|
+
selector: { type: 'string', description: 'Optional CSS selector to read instead of the whole page.' },
|
|
535
|
+
maxChars: { type: 'number', description: 'Default 20000.' },
|
|
536
|
+
},
|
|
537
|
+
async (a) => {
|
|
538
|
+
try {
|
|
539
|
+
const value = await run('text', { ...a }, { timeoutMs: 15000 })
|
|
540
|
+
return { ...value, ...wallInfo(value) }
|
|
541
|
+
} catch (error) {
|
|
542
|
+
const tabId = typeof a.tabId === 'string' ? a.tabId : hub.status().activeTabId
|
|
543
|
+
const tab = hub.status().tabs.find(entry => entry.id === tabId)
|
|
544
|
+
const walled = walledTabs.has(tabId) || CHALLENGE.test(String(tab?.title ?? '')) === true
|
|
545
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
546
|
+
throw new Error(walled === true ? `${message} ${WALL_POLICY}` : message)
|
|
547
|
+
}
|
|
548
|
+
},
|
|
549
|
+
'Read page text')
|
|
550
|
+
|
|
551
|
+
tool('bb_click',
|
|
552
|
+
'Click an element in the shared browser: by ref from bb_snapshot, by CSS selector, or at viewport coordinates. The user sees the real click. Do not use it on anti-bot verification widgets (Cloudflare, DataDome, I-am-not-a-robot): hand those to the user instead.',
|
|
553
|
+
{
|
|
554
|
+
ref: { type: 'string', description: 'Element ref from bb_snapshot (e12).' },
|
|
555
|
+
selector: { type: 'string', description: 'CSS selector, or text= prefix for text match.' },
|
|
556
|
+
x: { type: 'number', description: 'Viewport X for a coordinate click.' },
|
|
557
|
+
y: { type: 'number', description: 'Viewport Y for a coordinate click.' },
|
|
558
|
+
button: { type: 'string', enum: ['left', 'right', 'middle'], description: 'Default left.' },
|
|
559
|
+
clickCount: { type: 'number', description: 'Default 1; 2 double-clicks.' },
|
|
560
|
+
tabId: tabArg,
|
|
561
|
+
},
|
|
562
|
+
async (a) => {
|
|
563
|
+
const tabId = typeof a.tabId === 'string' ? a.tabId : hub.status().activeTabId
|
|
564
|
+
if (walledTabs.has(tabId) === true) return { clicked: false, wall: true, hint: WALL_POLICY }
|
|
565
|
+
return run('click', { ...a }, { timeoutMs: 15000 })
|
|
566
|
+
},
|
|
567
|
+
'Click in shared browser')
|
|
568
|
+
|
|
569
|
+
tool('bb_type',
|
|
570
|
+
'Type text into a focused or selected control (ref/selector), optionally pressing Enter. Fires real input events, so site listeners run.',
|
|
571
|
+
{
|
|
572
|
+
ref: { type: 'string', description: 'Element ref from bb_snapshot.' },
|
|
573
|
+
selector: { type: 'string', description: 'CSS selector or text= match.' },
|
|
574
|
+
text: { type: 'string', description: 'Text to type.' },
|
|
575
|
+
clear: { type: 'boolean', description: 'Clear the field first. Default true.' },
|
|
576
|
+
submit: { type: 'boolean', description: 'Press Enter afterwards.' },
|
|
577
|
+
delayMs: { type: 'number', description: 'Per-character delay. Default 8.' },
|
|
578
|
+
tabId: tabArg,
|
|
579
|
+
},
|
|
580
|
+
async (a) => run('type', { ...a }, { timeoutMs: 20000 }),
|
|
581
|
+
'Type in shared browser',
|
|
582
|
+
['text'])
|
|
583
|
+
|
|
584
|
+
tool('bb_press',
|
|
585
|
+
'Press a key or chord in the page (Enter, Tab, Escape, Control+A, Meta+K, ArrowDown, F5 …).',
|
|
586
|
+
{
|
|
587
|
+
keys: { type: 'string', description: 'Key or chord, e.g. "Control+Shift+R".' },
|
|
588
|
+
tabId: tabArg,
|
|
589
|
+
},
|
|
590
|
+
async (a) => run('press', { ...a }, { timeoutMs: 10000 }),
|
|
591
|
+
'Press keys',
|
|
592
|
+
['keys'])
|
|
593
|
+
|
|
594
|
+
tool('bb_wait',
|
|
595
|
+
'Wait for a selector, a text snippet, or the document to reach readyState complete.',
|
|
596
|
+
{
|
|
597
|
+
selector: { type: 'string', description: 'CSS selector to wait for.' },
|
|
598
|
+
text: { type: 'string', description: 'Visible text to wait for.' },
|
|
599
|
+
state: { type: 'string', enum: ['visible', 'hidden'], description: 'Default visible.' },
|
|
600
|
+
timeoutMs: { type: 'number', description: 'Default 10000.' },
|
|
601
|
+
tabId: tabArg,
|
|
602
|
+
},
|
|
603
|
+
async (a) => run('wait', { ...a }, { timeoutMs: (a.timeoutMs ?? 10000) + 5000 }),
|
|
604
|
+
'Wait for page state')
|
|
605
|
+
|
|
606
|
+
tool('bb_eval',
|
|
607
|
+
'Evaluate JavaScript in the page main world and return its value. Use for data the snapshot cannot express; prefer bb_text/bb_snapshot for reading.',
|
|
608
|
+
{
|
|
609
|
+
expression: { type: 'string', description: 'Expression or body to evaluate. A Promise is awaited.' },
|
|
610
|
+
awaitPromise: { type: 'boolean', description: 'Default true.' },
|
|
611
|
+
tabId: tabArg,
|
|
612
|
+
},
|
|
613
|
+
async (a) => run('evaluate', { ...a }, { timeoutMs: 20000 }),
|
|
614
|
+
'Evaluate in page',
|
|
615
|
+
['expression'])
|
|
616
|
+
|
|
617
|
+
tool('bb_screenshot',
|
|
618
|
+
'Capture the visible tab (or one element) as a PNG and save it under the DSH home. Returns the absolute path, so you can attach it or read it back.',
|
|
619
|
+
{
|
|
620
|
+
selector: { type: 'string', description: 'Capture only this element.' },
|
|
621
|
+
fullPage: { type: 'boolean', description: 'Capture the whole scrollable page. Default false.' },
|
|
622
|
+
name: { type: 'string', description: 'File name prefix.' },
|
|
623
|
+
tabId: tabArg,
|
|
624
|
+
},
|
|
625
|
+
async (a) => {
|
|
626
|
+
const capture = await run('screenshot', { ...a }, { timeoutMs: 30000 })
|
|
627
|
+
const value = await storeCapture(capture, 'screenshot')
|
|
628
|
+
const tabId = typeof a.tabId === 'string' ? a.tabId : hub.status().activeTabId
|
|
629
|
+
const title = String(hub.status().tabs.find(entry => entry.id === tabId)?.title ?? '')
|
|
630
|
+
return { ...value, ...wallInfo({ title }) }
|
|
631
|
+
},
|
|
632
|
+
'Screenshot shared browser')
|
|
633
|
+
|
|
634
|
+
tool('bb_region_screenshot',
|
|
635
|
+
'Capture a rectangle of the tab (viewport coordinates, CSS pixels) as a PNG. Use it for a region the user is talking about.',
|
|
636
|
+
{
|
|
637
|
+
x: { type: 'number', description: 'Left edge in CSS pixels.' },
|
|
638
|
+
y: { type: 'number', description: 'Top edge in CSS pixels.' },
|
|
639
|
+
width: { type: 'number', description: 'Width in CSS pixels.' },
|
|
640
|
+
height: { type: 'number', description: 'Height in CSS pixels.' },
|
|
641
|
+
name: { type: 'string', description: 'File name prefix.' },
|
|
642
|
+
tabId: tabArg,
|
|
643
|
+
},
|
|
644
|
+
async (a) => {
|
|
645
|
+
const capture = await run('regionScreenshot', { ...a }, { timeoutMs: 30000 })
|
|
646
|
+
return storeCapture(capture, 'region')
|
|
647
|
+
},
|
|
648
|
+
'Region screenshot',
|
|
649
|
+
['x', 'y', 'width', 'height'])
|
|
650
|
+
|
|
651
|
+
tool('bb_console',
|
|
652
|
+
'Read console output (console.* calls, page errors and unhandled rejections) captured from the shared browser. Newest last.',
|
|
653
|
+
{
|
|
654
|
+
level: { type: 'string', enum: ['error', 'warning', 'info', 'debug', 'verbose'], description: 'Only this level.' },
|
|
655
|
+
levelAtLeast: { type: 'string', enum: ['error', 'warning', 'info', 'debug'], description: 'This level or more severe.' },
|
|
656
|
+
limit: { type: 'number', description: 'Default 100, max 1000.' },
|
|
657
|
+
since: { type: 'number', description: 'Only entries at or after this epoch millisecond.' },
|
|
658
|
+
tabId: tabArg,
|
|
659
|
+
clear: { type: 'boolean', description: 'Drop the buffer after reading.' },
|
|
660
|
+
},
|
|
661
|
+
async (a) => {
|
|
662
|
+
const rank = { error: 0, warning: 1, info: 2, debug: 3, verbose: 4 }
|
|
663
|
+
let entries = isExternal(a.tabId)
|
|
664
|
+
? (await external.command('console', {})).entries ?? []
|
|
665
|
+
: hub.console({ level: a.level, limit: a.limit, tabId: a.tabId, since: a.since })
|
|
666
|
+
if (typeof a.levelAtLeast === 'string') {
|
|
667
|
+
const floor = rank[a.levelAtLeast] ?? 0
|
|
668
|
+
entries = entries.filter(entry => (rank[entry.level] ?? 9) <= floor)
|
|
669
|
+
}
|
|
670
|
+
if (a.clear === true) hub.clear()
|
|
671
|
+
return { count: entries.length, entries }
|
|
672
|
+
},
|
|
673
|
+
'Console log')
|
|
674
|
+
|
|
675
|
+
tool('bb_network',
|
|
676
|
+
'Read network activity captured from the page (fetch/XHR, method, status, duration, failures). Newest last.',
|
|
677
|
+
{
|
|
678
|
+
limit: { type: 'number', description: 'Default 50.' },
|
|
679
|
+
failedOnly: { type: 'boolean', description: 'Only failed requests.' },
|
|
680
|
+
filter: { type: 'string', description: 'Substring of the URL.' },
|
|
681
|
+
},
|
|
682
|
+
async (a) => {
|
|
683
|
+
const entries = isExternal(a.tabId)
|
|
684
|
+
? (await external.command('network', { failedOnly: a.failedOnly === true, filter: a.filter })).entries ?? []
|
|
685
|
+
: hub.network({ limit: a.limit, failedOnly: a.failedOnly === true, filter: a.filter })
|
|
686
|
+
return { count: entries.length, entries }
|
|
687
|
+
},
|
|
688
|
+
'Network log')
|
|
689
|
+
|
|
690
|
+
tool('bb_comment',
|
|
691
|
+
'Attach a comment to an element of the shared browser, exactly as the user\'s comment tool does. Omit ref/selector to comment on the element the user picked last.',
|
|
692
|
+
{
|
|
693
|
+
ref: { type: 'string', description: 'Element ref from bb_snapshot or from bb_comments.' },
|
|
694
|
+
selector: { type: 'string', description: 'CSS selector.' },
|
|
695
|
+
note: { type: 'string', description: 'Comment body.' },
|
|
696
|
+
tabId: tabArg,
|
|
697
|
+
},
|
|
698
|
+
async (a) => {
|
|
699
|
+
const comment = await run('comment', { ...a }, { timeoutMs: 15000 })
|
|
700
|
+
hub.ingest({ type: 'comment', comment })
|
|
701
|
+
return comment
|
|
702
|
+
},
|
|
703
|
+
'Comment element',
|
|
704
|
+
['note'])
|
|
705
|
+
|
|
706
|
+
tool('bb_comments',
|
|
707
|
+
'List element comments the user left in the shared browser (and any the agent added): selector, element text, the comment body, and the screenshot when captured.',
|
|
708
|
+
{
|
|
709
|
+
selector: { type: 'string', description: 'Only comments on this selector.' },
|
|
710
|
+
tabId: tabArg,
|
|
711
|
+
limit: { type: 'number', description: 'Default 50.' },
|
|
712
|
+
},
|
|
713
|
+
async (a) => {
|
|
714
|
+
const comments = hub.commentsFor({ selector: a.selector, tabId: a.tabId, limit: a.limit })
|
|
715
|
+
return { count: comments.length, comments }
|
|
716
|
+
},
|
|
717
|
+
'Element comments')
|
|
718
|
+
|
|
719
|
+
tool('bb_find',
|
|
720
|
+
'Find text in the page and scroll to the first match, like Ctrl+F. Returns the match count and a short excerpt.',
|
|
721
|
+
{
|
|
722
|
+
text: { type: 'string', description: 'Text to find.' },
|
|
723
|
+
action: { type: 'string', enum: ['find', 'next', 'previous', 'stop'], description: 'Default find.' },
|
|
724
|
+
tabId: tabArg,
|
|
725
|
+
},
|
|
726
|
+
async (a) => run('find', { ...a }, { timeoutMs: 10000 }),
|
|
727
|
+
'Find in page',
|
|
728
|
+
['text'])
|
|
729
|
+
|
|
730
|
+
tool('bb_zoom',
|
|
731
|
+
'Set or reset the page zoom factor, like Ctrl+= / Ctrl+- / Ctrl+NumPad0.',
|
|
732
|
+
{
|
|
733
|
+
action: { type: 'string', enum: ['in', 'out', 'reset', 'set'], description: 'Default reset.' },
|
|
734
|
+
factor: { type: 'number', description: 'For action=set: 0.25 … 5.' },
|
|
735
|
+
tabId: tabArg,
|
|
736
|
+
},
|
|
737
|
+
async (a) => run('zoom', { ...a }, { timeoutMs: 8000 }),
|
|
738
|
+
'Zoom page')
|
|
739
|
+
|
|
740
|
+
tool('bb_devtools',
|
|
741
|
+
'Open or close the shared browser\'s DevTools panel (console, elements, network, eval). The panel belongs to the browser UI, so the user sees the same window.',
|
|
742
|
+
{
|
|
743
|
+
action: { type: 'string', enum: ['open', 'close', 'toggle', 'status'], description: 'Default toggle.' },
|
|
744
|
+
panel: { type: 'string', enum: ['console', 'elements', 'network', 'eval'], description: 'Panel to focus.' },
|
|
745
|
+
tabId: tabArg,
|
|
746
|
+
},
|
|
747
|
+
async (a) => run('devtools', { ...a }, { timeoutMs: 8000 }),
|
|
748
|
+
'DevTools panel')
|
|
749
|
+
|
|
750
|
+
tool('bb_storage',
|
|
751
|
+
'Inspect or clear the site storage of the shared browser: cookies, localStorage, sessionStorage, caches and IndexedDB for the current origin (or every origin with scope=all).',
|
|
752
|
+
{
|
|
753
|
+
action: { type: 'string', enum: ['status', 'clear'], description: 'Default status.' },
|
|
754
|
+
scope: { type: 'string', enum: ['origin', 'all'], description: 'Default all, matching the menu item.' },
|
|
755
|
+
tabId: tabArg,
|
|
756
|
+
},
|
|
757
|
+
async (a) => run('storage', { ...a }, { timeoutMs: 15000 }),
|
|
758
|
+
'Site storage')
|
|
759
|
+
|
|
760
|
+
tool('bb_permissions',
|
|
761
|
+
'Report which site permissions the shared browser grants (camera, microphone, notifications, geolocation, popups, downloads) and why they are refused, plus the site the tab is on.',
|
|
762
|
+
{ tabId: tabArg },
|
|
763
|
+
async (a) => run('permissions', { ...a }, { timeoutMs: 8000 }),
|
|
764
|
+
'Site permissions')
|
|
765
|
+
|
|
766
|
+
tool('bb_history',
|
|
767
|
+
'Read or clear the shared browser history (the same list the browser menu shows).',
|
|
768
|
+
{
|
|
769
|
+
action: { type: 'string', enum: ['list', 'clear'], description: 'Default list.' },
|
|
770
|
+
query: { type: 'string', description: 'Filter by URL or title substring.' },
|
|
771
|
+
limit: { type: 'number', description: 'Default 50.' },
|
|
772
|
+
},
|
|
773
|
+
async (a) => run('history', { ...a }, { timeoutMs: 8000 }),
|
|
774
|
+
'Browser history')
|
|
775
|
+
|
|
776
|
+
tool('bb_emulate',
|
|
777
|
+
'Switch the shared browser into device emulation (viewport size, device pixel ratio, touch, user agent) or leave it with mode=none. Used by the menu item 设备仿真.',
|
|
778
|
+
{
|
|
779
|
+
device: { type: 'string', enum: ['none', 'iphone-14', 'pixel-7', 'ipad-mini', 'galaxy-s23', 'desktop-720'], description: 'Preset. Default none.' },
|
|
780
|
+
width: { type: 'number', description: 'Custom width in CSS pixels.' },
|
|
781
|
+
height: { type: 'number', description: 'Custom height in CSS pixels.' },
|
|
782
|
+
tabId: tabArg,
|
|
783
|
+
},
|
|
784
|
+
async (a) => run('emulate', { ...a }, { timeoutMs: 10000 }),
|
|
785
|
+
'Device emulation')
|
|
786
|
+
|
|
787
|
+
tool('bb_add_to_chat',
|
|
788
|
+
'Put something from the browser into the conversation as a draft attachment the user can review and send: a screenshot, a region, the picked element, or the console tail. Returns what was inserted.',
|
|
789
|
+
{
|
|
790
|
+
kind: { type: 'string', enum: ['screenshot', 'region', 'element', 'console'], description: 'What to add.' },
|
|
791
|
+
note: { type: 'string', description: 'Optional sentence to insert with it.' },
|
|
792
|
+
selector: { type: 'string', description: 'For kind=element: element to describe.' },
|
|
793
|
+
ref: { type: 'string', description: 'For kind=element: ref from bb_snapshot.' },
|
|
794
|
+
x: { type: 'number', description: 'For kind=region: left edge.' },
|
|
795
|
+
y: { type: 'number', description: 'For kind=region: top edge.' },
|
|
796
|
+
width: { type: 'number', description: 'For kind=region: width.' },
|
|
797
|
+
height: { type: 'number', description: 'For kind=region: height.' },
|
|
798
|
+
tabId: tabArg,
|
|
799
|
+
},
|
|
800
|
+
async (a) => run('addToChat', { ...a }, { timeoutMs: 30000 }),
|
|
801
|
+
'Add browser content to chat',
|
|
802
|
+
['kind'])
|
|
803
|
+
|
|
804
|
+
tool('bb_open_devtools_native',
|
|
805
|
+
'Explain how to reach the real Chromium DevTools for the app window, and report whether a remote debugging port is already reachable. Read-only.',
|
|
806
|
+
{},
|
|
807
|
+
async () => {
|
|
808
|
+
const probe = async (port) => fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(800) })
|
|
809
|
+
.then(async response => (response.ok ? { port, ok: true, info: await response.json() } : { port, ok: false }))
|
|
810
|
+
.catch(() => ({ port, ok: false }))
|
|
811
|
+
const [first, second] = await Promise.all([probe(9223), probe(9222)])
|
|
812
|
+
const reachable = [first, second].filter(entry => entry.ok)
|
|
813
|
+
return {
|
|
814
|
+
reachable,
|
|
815
|
+
note: reachable.length === 0
|
|
816
|
+
? 'The packaged app disables guest DevTools (devTools: !app.isPackaged). Use the in-app panel from bb_devtools; a native window needs a launch with --remote-debugging-port=9222.'
|
|
817
|
+
: 'A debugging endpoint is reachable; open chrome://inspect or connect Playwright to it.',
|
|
818
|
+
inAppPanel: 'bb_devtools action=open',
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
'Native DevTools availability')
|
|
822
|
+
|
|
823
|
+
// Keep the module importable in tests without a Cordis context.
|
|
824
|
+
return { hub, version: VERSION }
|
|
825
|
+
}
|