dsh-embedded-browser-next 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/tools.js ADDED
@@ -0,0 +1,740 @@
1
+ /**
2
+ * The model-facing tool set.
3
+ *
4
+ * Every tool works on **the calling session's own tab**: the handler reads the
5
+ * session id off its execution context, so the model never has to know that
6
+ * sessions exist, and two sessions can never steer each other's page. They do
7
+ * share the Chrome profile — and therefore the login state — on purpose.
8
+ *
9
+ * Names are prefixed `browser_embedded_` on purpose: the BrowserSkill plugin
10
+ * owns `browser_*` for the user's real browser, this suite drives the Chrome
11
+ * that lives inside the container, and a duplicate tool name aborts plugin load.
12
+ * The prefix is what the `browser-use` skill routes on, so keep the two in step.
13
+ *
14
+ * Registration is lazy (see `./lazy.js`): nothing here is published until the
15
+ * `browser-use` skill has been invoked, so this module *builds* the suite and
16
+ * the caller decides when it goes live.
17
+ *
18
+ * @module dsh-embedded-browser/tools
19
+ */
20
+
21
+ import { writeFile } from 'node:fs/promises'
22
+ import { tmpdir } from 'node:os'
23
+ import { join } from 'node:path'
24
+ import { defineTool } from '@deepseek-ai/dsh-tools'
25
+ import { SNAPSHOT_BUDGET_CHARS, SNAPSHOT_CAP, SNAPSHOT_FLOOR } from './snapshot-window.js'
26
+
27
+ /** Canonical values must be lossless JSON: drop `undefined` and functions. */
28
+ const clean = (value) => JSON.parse(JSON.stringify(value ?? null))
29
+
30
+ /** Render one canonical value as a single text block. */
31
+ const asText = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, undefined, 1) }]
32
+
33
+ /** Unconstrained JSON output plus the plugin's own text projection. */
34
+ const jsonOutput = () => ({ schema: { type: 'json' }, render: (_args, value) => asText(value) })
35
+
36
+ /**
37
+ * The session a tool call belongs to.
38
+ *
39
+ * `exec.agent` is absent on agentless dispatches (service-internal, UI, command
40
+ * paths), and a browser without an owner would be shared state again — so that
41
+ * case is an error rather than a silent fallback.
42
+ */
43
+ function sessionOf(exec) {
44
+ const sessionId = exec?.agent?.id
45
+ if (typeof sessionId !== 'string' || sessionId === '') {
46
+ throw new Error('browser_embedded_* tools require a calling agent session; this call has no owning session')
47
+ }
48
+ return sessionId
49
+ }
50
+
51
+ /**
52
+ * Name one element the way the manager expects: a snapshot index, or a CSS
53
+ * selector.
54
+ *
55
+ * Snapshot indices are positional — any DOM change between the read and the
56
+ * action invalidates them, which is what "element #14 is gone" means. A selector
57
+ * is resolved fresh at action time, so prefer it for anything but a one-shot.
58
+ */
59
+ function targetOf(args, label = 'element') {
60
+ if (typeof args.index === 'number') return { index: args.index }
61
+ if (typeof args.selector === 'string' && args.selector.trim() !== '') return { selector: args.selector.trim() }
62
+ throw new Error(`name the ${label} with index (from browser_embedded_snapshot) or selector (a CSS selector)`)
63
+ }
64
+
65
+ /** Human-readable snapshot: header, numbered inventory, then page text. */
66
+ function formatSnapshot(value) {
67
+ const lines = []
68
+ if (value.collapsed === true) {
69
+ lines.push('⚠ 面板现在是 0×0(被折叠或隐藏):页面能读,但点击、输入、拖动都到不了页面。先让面板可见或展开右侧栏。', '')
70
+ }
71
+ if (value.title !== undefined || value.url !== undefined) lines.push(`${value.title ?? ''}`.trim(), `${value.url ?? ''}`.trim(), '')
72
+ if (Array.isArray(value.elements) && value.elements.length > 0) {
73
+ // Say which slice this is and what follows. A bare count reads as "the page
74
+ // is nearly empty"; worse, the agent stops looking for the element it needs
75
+ // instead of paging to it.
76
+ const total = typeof value.total === 'number' ? value.total : value.elements.length
77
+ const start = typeof value.offset === 'number' ? value.offset : 0
78
+ const last = start + value.elements.length
79
+ const more = value.more === true || last < total
80
+ const span = total > value.elements.length ? `第 ${start + 1}–${last} 个 / 共 ${total}` : `${total} 个`
81
+ lines.push(`可交互元素 (${span}${more ? `,继续用 offset=${last}` : ''}):`)
82
+ for (const element of value.elements) {
83
+ const bits = [`[${element.index}]`, `<${element.tag}>`]
84
+ if (element.type !== undefined) bits.push(`type=${element.type}`)
85
+ if (element.label !== undefined && element.label !== '') bits.push(`"${element.label}"`)
86
+ if (element.value !== undefined && element.value !== '') bits.push(`值="${element.value}"`)
87
+ // What is on screen, without reordering the list: the caller can prefer these
88
+ // without paging losing entries behind them.
89
+ if (element.onScreen === true) bits.push('屏内')
90
+ if (element.disabled === true) bits.push('(disabled)')
91
+ lines.push(` ${bits.join(' ')}`)
92
+ }
93
+ lines.push('')
94
+ } else if (typeof value.total === 'number' && value.total > 0) {
95
+ // Paged past the end. Saying so beats printing nothing and leaving the caller
96
+ // to conclude the page changed under it.
97
+ lines.push(`可交互元素:共 ${value.total} 个,offset=${value.offset ?? 0} 已经超过末尾`, '')
98
+ }
99
+ if (Array.isArray(value.frames) && value.frames.length > 0) {
100
+ // Say plainly which frames are opaque. An agent that is not told "this is a
101
+ // cross-origin frame, use coordinates" concludes that clicking is impossible
102
+ // and hands the job back to the human — which is what used to happen.
103
+ lines.push(`内嵌框架 (${value.frames.length}):`)
104
+ for (const [index, frame] of value.frames.entries()) {
105
+ const bits = [`[${index}]`, `@${frame.x},${frame.y} ${frame.w}x${frame.h}`]
106
+ if (frame.origin === 'same') bits.push('同源')
107
+ else if (typeof frame.origin === 'string' && frame.origin !== '') bits.push(`来自 ${frame.origin}`)
108
+ if (frame.readable === true) bits.push('顶层可读')
109
+ else bits.push('跨域:DOM 读不到;坐标点,或用 browser_embedded_frame op=open index=' + index + ' 单独打开读(会丢原页面状态)')
110
+ if (typeof frame.src === 'string' && frame.src !== '') bits.push(frame.src)
111
+ lines.push(` ${bits.join(' ')}`)
112
+ }
113
+ lines.push('')
114
+ }
115
+ if (typeof value.text === 'string' && value.text !== '') lines.push('页面正文:', value.text)
116
+ return lines.join('\n')
117
+ }
118
+
119
+ /**
120
+ * Build every tool this plugin registers.
121
+ *
122
+ * @param deps - browser manager, human broker, screencast hub, config, and the
123
+ * optional attachment service used to hand screenshots back to the model.
124
+ * @returns tool definitions to register inside one effect.
125
+ */
126
+ export function defineTools({ manager, human, hub, config, getAttachments, logger, getPanelAvailable = () => true }) {
127
+ const screenshotRefs = new Map()
128
+ let screenshotSequence = 0
129
+ const askHumanTimeoutMs = Math.max(10_000, (config.askHumanTimeoutSeconds ?? 600) * 1000)
130
+
131
+ const status = defineTool({
132
+ name: 'browser_embedded_status',
133
+ description:
134
+ "Report this session's browser tab: whether the browser is running, this tab's URL/title, the persistent profile directory, and whether the human has a pending action. " +
135
+ "It also reports `layer` — where the human can see this page right now: `sidebar` (docked in the right Sidebar), `float` (a floating panel inside the DSH window: draggable, lost when switching conversation), `window` (a separate visible browser window), or `headless` (nothing on screen — no human logins, nobody watching). " +
136
+ "When the page has moved since your last call the answer also carries `layerChanged` (`sidebar → float`) and a one-line `layerNote`; coordinates and logins mean different things on each layer. Call this first when unsure about browser state.",
137
+ parameters: {},
138
+ output: jsonOutput(),
139
+ execute: async (_args, exec) => clean(await manager.status(sessionOf(exec))),
140
+ })
141
+
142
+ const navigate = defineTool({
143
+ name: 'browser_embedded_navigate',
144
+ description:
145
+ "Open a URL in this session's browser tab (starting the browser if needed). Each session has its own tab, and the human can watch or take over yours from a right-sidebar tab in the DSH Web UI — it opens by itself once this session has a browser. All sessions share one login profile, so a login done once works everywhere.",
146
+ parameters: {
147
+ url: { type: 'string', required: true, description: 'Absolute http(s) URL to open.' },
148
+ newTab: { type: 'boolean', description: "Discard this session's current page and open the URL in a fresh tab." },
149
+ },
150
+ output: jsonOutput(),
151
+ execute: async (args, exec) => {
152
+ const sessionId = sessionOf(exec)
153
+ const url = String(args.url)
154
+ if (!/^https?:\/\//i.test(url)) throw new Error('url must start with http:// or https://')
155
+ return clean(
156
+ args.newTab === true
157
+ ? await manager.replaceTab(sessionId, url)
158
+ : await manager.navigate(sessionId, url),
159
+ )
160
+ },
161
+ })
162
+
163
+ const frame = defineTool({
164
+ name: 'browser_embedded_frame',
165
+ description:
166
+ "Read a cross-origin iframe by opening its URL as the page itself. A cross-origin frame's DOM cannot be read from the parent page (browser security), so snapshot cannot see inside it; navigating to the frame's src makes it the top document, where snapshot/click/type work normally. " +
167
+ 'DESTRUCTIVE for the parent page: form fields, scroll position, open dropdowns and anything not yet submitted are LOST — the frame open navigates the tab away. op=back only reloads the original URL; it does not restore the previous form or scroll state. ' +
168
+ 'Only use this when snapshot said the frame is cross-origin and you actually need what is inside it; for a single click inside the frame, coordinates are cheaper. Report the state loss to the human when it matters.',
169
+ parameters: {
170
+ op: {
171
+ type: 'string',
172
+ required: true,
173
+ description:
174
+ 'open: load the frame as the page (needs index from the snapshot frames list, or url). back: return to the page that was open when op=open ran (reloads its URL; state is NOT restored).',
175
+ },
176
+ index: { type: 'number', description: 'op=open: frame number from browser_embedded_snapshot’s 内嵌框架 list.' },
177
+ url: { type: 'string', description: 'op=open: the frame src instead of an index.' },
178
+ },
179
+ output: jsonOutput(),
180
+ execute: async (args, exec) => {
181
+ const sessionId = sessionOf(exec)
182
+ const op = String(args.op ?? '')
183
+ if (op === 'open') return clean(await manager.frameOpen(sessionId, { index: args.index, url: args.url }))
184
+ if (op === 'back') return clean(await manager.frameBack(sessionId))
185
+ throw new Error('op must be "open" or "back"')
186
+ },
187
+ })
188
+
189
+ const snapshot = defineTool({
190
+ name: 'browser_embedded_snapshot',
191
+ description:
192
+ "Read this session's page as structured text: title, URL, a numbered inventory of clickable/typable elements, and the visible text. Pass an element number to browser_embedded_click or browser_embedded_type. " +
193
+ "How many elements come back depends on the page (80 minimum, 240 maximum, and a character budget), and what is on screen is listed first when the list has to be cut. " +
194
+ "The header says which slice this is and whether more follow — when it does, call again with `offset` set to the number after the last one to page through the rest. " +
195
+ "A truncated list is not a dead end: click/type by selector or by visible text still find elements that were not listed.",
196
+ parameters: {
197
+ maxChars: { type: 'number', description: 'Truncate the page text at this many characters (default 4000).' },
198
+ maxElements: { type: 'number', description: 'Exact number of interactive elements to list, instead of the automatic size.' },
199
+ offset: { type: 'number', description: 'Skip this many entries before listing — page through a long inventory. Use the number in the header.' },
200
+ },
201
+ output: {
202
+ schema: { type: 'json' },
203
+ render: (_args, value) => asText(formatSnapshot(value)),
204
+ },
205
+ execute: async (args, exec) =>
206
+ clean(
207
+ await manager.snapshot(sessionOf(exec), {
208
+ maxChars: args.maxChars,
209
+ maxElements: args.maxElements,
210
+ offset: args.offset,
211
+ floor: SNAPSHOT_FLOOR,
212
+ cap: SNAPSHOT_CAP,
213
+ budget: SNAPSHOT_BUDGET_CHARS,
214
+ }),
215
+ ),
216
+ })
217
+
218
+ const click = defineTool({
219
+ name: 'browser_embedded_click',
220
+ description:
221
+ "Click something in this session's page: an element number from browser_embedded_snapshot, a stable loc/selector, a visible text label, or raw x/y viewport coordinates. Real input events are dispatched, so hover/focus behaviour matches a human click. Set double=true for a double-click. Use x/y for content inside a cross-origin iframe (a payment/consent dialog, a captcha widget): no selector can reach in there, but a click at the coordinates does — snapshot lists those frames with their rect.",
222
+ parameters: {
223
+ index: { type: 'number', description: 'Element number from the latest browser_embedded_snapshot.' },
224
+ selector: { type: 'string', description: 'CSS selector — stable across snapshots, unlike element numbers.' },
225
+ text: { type: 'string', description: 'Visible text of the element to click (exact match first, then substring). Semantic controls are tried first, then any visible element whose text matches, so a button built out of a span is found too. A match that does not look clickable is reported with its selector instead of being clicked blind.' },
226
+ x: { type: 'number', description: 'Viewport CSS x for a coordinate click — the only way into a cross-origin iframe. Take it from the frame rect in snapshot, or from a screenshot.' },
227
+ y: { type: 'number', description: 'Viewport CSS y, with x.' },
228
+ double: { type: 'boolean', description: 'Double-click instead of a single click.' },
229
+ },
230
+ output: jsonOutput(),
231
+ execute: async (args, exec) => {
232
+ const sessionId = sessionOf(exec)
233
+ const double = args.double === true
234
+ if (typeof args.index === 'number') return clean(await manager.click(sessionId, args.index, { double }))
235
+ if (typeof args.selector === 'string' && args.selector !== '') {
236
+ return clean(await manager.clickSelector(sessionId, args.selector, { double }))
237
+ }
238
+ if (typeof args.x === 'number' && typeof args.y === 'number') {
239
+ return clean(await manager.clickPoint(sessionId, { x: args.x, y: args.y }, { double }))
240
+ }
241
+ if (typeof args.text === 'string' && args.text !== '') {
242
+ if (double) throw new Error('text matching supports single clicks only; pass index or selector for a double-click')
243
+ return clean(await manager.clickText(sessionId, args.text))
244
+ }
245
+ throw new Error('provide index, selector, text, or x and y')
246
+ },
247
+ })
248
+
249
+ const type = defineTool({
250
+ name: 'browser_embedded_type',
251
+ description:
252
+ "Focus a field and insert text (works with React/Vue controlled inputs). Set submit=true to press Enter afterwards, e.g. to submit a login form. The click it performs is required: without a focused field the browser silently drops inserted text. Name the field with index, selector, or x/y viewport coordinates (the only way to type into a cross-origin iframe).",
253
+ parameters: {
254
+ index: { type: 'number', description: 'Field element number from the latest snapshot.' },
255
+ selector: { type: 'string', description: 'CSS selector for the field — stable across snapshots.' },
256
+ x: { type: 'number', description: 'Viewport CSS x to click first, for a field inside a cross-origin iframe.' },
257
+ y: { type: 'number', description: 'Viewport CSS y, with x.' },
258
+ text: { type: 'string', required: true, description: 'Text to insert.' },
259
+ submit: { type: 'boolean', description: 'Press Enter after typing.' },
260
+ },
261
+ output: jsonOutput(),
262
+ execute: async (args, exec) => {
263
+ const sessionId = sessionOf(exec)
264
+ const submit = args.submit === true
265
+ if (typeof args.x === 'number' && typeof args.y === 'number') {
266
+ return clean(await manager.typePoint(sessionId, { x: args.x, y: args.y }, String(args.text), { submit }))
267
+ }
268
+ return clean(await manager.type(sessionId, targetOf(args, 'field'), String(args.text), { submit }))
269
+ },
270
+ })
271
+
272
+ const press = defineTool({
273
+ name: 'browser_embedded_press',
274
+ description: "Press one key in this session's page (Enter, Tab, Escape, Backspace, Delete, ArrowUp/Down/Left/Right, Home, End, PageUp, PageDown, Space).",
275
+ parameters: {
276
+ key: { type: 'string', required: true, description: 'Key name, e.g. Enter.' },
277
+ },
278
+ output: jsonOutput(),
279
+ execute: async (args, exec) => clean(await manager.press(sessionOf(exec), String(args.key))),
280
+ })
281
+
282
+ const scroll = defineTool({
283
+ name: 'browser_embedded_scroll',
284
+ description: "Scroll this session's page viewport: down, up, left, right, top, or bottom.",
285
+ parameters: {
286
+ direction: { type: 'string', required: true, description: 'One of down, up, left, right, top, bottom.' },
287
+ pixels: { type: 'number', description: 'Explicit scroll distance instead of one page.' },
288
+ },
289
+ output: jsonOutput(),
290
+ execute: async (args, exec) => clean(await manager.scroll(sessionOf(exec), String(args.direction), { pixels: args.pixels })),
291
+ })
292
+
293
+ const screenshot = defineTool({
294
+ name: 'browser_embedded_screenshot',
295
+ description:
296
+ "Capture this session's page as an image so you can see the rendering (layout, CAPTCHA, QR codes, charts). Pass selector to clip a single element. Prefer browser_embedded_snapshot for reading text.",
297
+ parameters: {
298
+ fullPage: { type: 'boolean', description: 'Capture the whole scrollable page instead of the viewport.' },
299
+ selector: { type: 'string', description: 'CSS selector of one element to capture instead of the page.' },
300
+ },
301
+ output: {
302
+ schema: { type: 'json' },
303
+ render: (_args, value) => {
304
+ try {
305
+ const ref = value.attachmentId !== undefined ? screenshotRefs.get(value.attachmentId) : undefined
306
+ if (ref !== undefined) {
307
+ return [{ type: 'text', text: `屏幕截图 ${value.mediaType} ${value.bytes} 字节` }, { type: 'image', attachment: ref }]
308
+ }
309
+ return asText(value)
310
+ } catch (error) {
311
+ return asText({ error: `screenshot render failed: ${error.message}` })
312
+ }
313
+ },
314
+ },
315
+ execute: async (args, exec) => {
316
+ const shot = await manager.screenshot(sessionOf(exec), {
317
+ fullPage: args.fullPage === true,
318
+ selector: typeof args.selector === 'string' && args.selector !== '' ? args.selector : undefined,
319
+ })
320
+ const attachments = getAttachments?.()
321
+ if (attachments !== undefined) {
322
+ try {
323
+ const ref = await attachments.saveImage({ data: shot.data, mediaType: shot.mediaType })
324
+ const attachmentId = `embedded-browser-shot-${++screenshotSequence}`
325
+ screenshotRefs.set(attachmentId, ref)
326
+ if (screenshotRefs.size > 8) screenshotRefs.delete(screenshotRefs.keys().next().value)
327
+ return { attachmentId, bytes: shot.data.length, mediaType: shot.mediaType }
328
+ } catch (error) {
329
+ logger?.debug?.(`attachment save failed: ${error.message}`)
330
+ }
331
+ }
332
+ const file = join(tmpdir(), `dsh-embedded-browser-${Date.now()}.png`)
333
+ await writeFile(file, shot.data)
334
+ return { path: file, bytes: shot.data.length, mediaType: shot.mediaType }
335
+ },
336
+ })
337
+
338
+ /**
339
+ * Whether the human lets the agent move their view on its own.
340
+ *
341
+ * Moving the page is cheap and sometimes the only way to get a login done, but it
342
+ * rearranges someone else's screen — so it is the human's switch, not ours, and a
343
+ * refusal has to read like a setting rather than a bug.
344
+ */
345
+ const presentRefusal = (mode) => {
346
+ if (config.aiPresent === 'off') return 'the human turned off agent-initiated surface changes (aiPresent: off)'
347
+ if (mode === 'float' && config.aiPresentFloat === false) return 'the human turned off agent-initiated floating (aiPresentFloat: false)'
348
+ if (mode === 'window' && config.aiPresentWindow === false) return 'the human turned off agent-initiated windows (aiPresentWindow: false)'
349
+ return undefined
350
+ }
351
+
352
+ const present = defineTool({
353
+ name: 'browser_embedded_present',
354
+ description:
355
+ "Move the page onto another surface — where the human can see or touch it — and report the layer that is now in force. " +
356
+ "Use it when a person must look at the page (login, QR code, CAPTCHA, 'does this look right?') and the page is not already in front of them, or to put it back when they are done. " +
357
+ 'Modes: `float` — a floating panel inside the DSH window (draggable, resizable, and hidden when the conversation changes); `sidebar` — dock it back into the right Sidebar; `window` — a real, separate browser window. ' +
358
+ '`window` is the escape hatch when the panel cannot do the job (a cross-origin frame inside the panel gets no input) or when logins must survive quitting the app: it may restart the browser once with a visible window (the profile and every login are kept, and each conversation’s page reopens on its own URL), then brings that window to the front. The answer says `restarted` when that happened. ' +
359
+ 'The live page is moved, not reloaded: same tab, same scroll position, same logins. A request that moves nothing (the page was already on that layer) comes back with `moved: false` and a `note` — that is not a successful switch, so say so rather than claiming it worked. ' +
360
+ 'The reverse direction works too: while the page is in the real window, asking for `sidebar` or `float` brings it back — the window is closed, the page is reopened in the panel, and the answer carries `restored: true`. That is the only way back that does not throw the window away by hand. ' +
361
+ 'The human can refuse agent-initiated moves in settings; a refusal is a fact about their configuration, so report it rather than retrying.',
362
+ parameters: {
363
+ mode: { type: 'string', required: true, description: 'sidebar | float | window' },
364
+ },
365
+ output: jsonOutput(),
366
+ execute: async (args, exec) => {
367
+ const sessionId = sessionOf(exec)
368
+ const mode = String(args.mode ?? '').trim()
369
+ if (mode !== 'sidebar' && mode !== 'float' && mode !== 'window') {
370
+ throw new Error(`present needs mode: sidebar, float or window (got ${JSON.stringify(args.mode)})`)
371
+ }
372
+ const refused = presentRefusal(mode)
373
+ if (refused !== undefined) throw new Error(`present refused: ${refused}`)
374
+ return clean(await manager.present(sessionId, mode))
375
+ },
376
+ })
377
+
378
+ const askHuman = defineTool({
379
+ name: 'browser_embedded_ask_human',
380
+ description:
381
+ "Hand this session's browser tab to the person in front of the DSH Web UI and wait. Use this whenever you hit something only a human can do: entering credentials, scanning a QR code, a one-time passcode from a phone, a CAPTCHA, or a hardware/SSO step. The browser tab is brought up in the right Sidebar of this conversation and comes back to the front even if the human had closed it; this call returns as soon as they press 完成, or on timeout. " +
382
+ 'It can only reach the Sidebar panel: if the browser tab was never opened, nobody can see the request — the answer then carries `via: "headless"` and an `advice` field. Do not retry in that case; tell the human in chat (or use browser_embedded_present({ mode: "window" }) first to put the page in a real window they can see).',
383
+ parameters: {
384
+ instruction: { type: 'string', required: true, description: 'What the human should do, in their language, e.g. 请在浏览器面板里登录腾讯云控制台(账号密码或扫码),完成后点「我已完成」。' },
385
+ timeoutSeconds: { type: 'number', description: 'How long to wait for the human (default from plugin config).' },
386
+ url: { type: 'string', description: 'Optional URL to open before handing over.' },
387
+ },
388
+ output: jsonOutput(),
389
+ timeoutMs: askHumanTimeoutMs + 60_000,
390
+ execute: async (args, exec) => {
391
+ const sessionId = sessionOf(exec)
392
+ if (getPanelAvailable() !== true) {
393
+ throw new Error('this deployment has no DSH Web UI, so the browser tab cannot be shown to a human; ask the human to supply the value directly')
394
+ }
395
+ const instruction = String(args.instruction ?? '请在浏览器面板里完成操作,然后点「我已完成」。')
396
+ const timeoutMs = args.timeoutSeconds !== undefined ? Math.max(5_000, Number(args.timeoutSeconds) * 1000) : askHumanTimeoutMs
397
+ // A conversation waiting on a person is the one thing that must not be
398
+ // reclaimed while it waits: closing the page mid-hand-over would leave the
399
+ // human looking at nothing after being told to look at something.
400
+ hub.residency?.setPinned?.(sessionId, true)
401
+ if (typeof args.url === 'string' && args.url !== '') await manager.navigate(sessionId, args.url)
402
+ else await manager.ensureSession(sessionId)
403
+ await hub.pushState({ force: true })
404
+ // Give the sidebar tab a moment to mount and announce its guest. Without this
405
+ // wait the branch above lands on the headless tab for the rest of the call,
406
+ // and the human ends up operating a *different* browser — the exact failure
407
+ // this tool exists to prevent.
408
+ const watching = await hub.waitForGuest(sessionId, 4_000)
409
+ const onAbort = () => human.cancel(sessionId, 'cancelled')
410
+ exec?.signal?.addEventListener?.('abort', onAbort, { once: true })
411
+ try {
412
+ const outcome = await human.ask(sessionId, instruction, { timeoutMs })
413
+ // `watching` is a 4 s snapshot taken *before* the hand-over, and the panel
414
+ // routinely finishes mounting after it — measured 2026-11-27: the human
415
+ // pressed 我已完成 on a banner they could see, and the answer said
416
+ // `via: "headless"`. Ask again now that the exchange actually happened; the
417
+ // question "did a person see this page" has a better answer after it than
418
+ // before it.
419
+ const seen = watching === true || (hub?.guestAvailable?.(sessionId) === true)
420
+ // Nothing else happens here on purpose. This used to follow up with a status
421
+ // read and a snapshot, and on the panel route those are guest round-trips with
422
+ // a 30 s ceiling — so a click that settled the request instantly could still be
423
+ // followed by half a minute of nothing before the agent said anything. The
424
+ // human pressed a button; the tool answers now. The page is one call away.
425
+ logger?.debug?.(`ask_human settled: ${outcome.status} after ${outcome.waitedMs}ms via=${seen ? 'panel' : 'headless'}`)
426
+ return clean({
427
+ ...outcome,
428
+ sessionId,
429
+ // Which browser the human was actually shown. `headless` is an honest
430
+ // failure, not a silent one: the page they operated was not the agent's.
431
+ via: seen ? 'panel' : 'headless',
432
+ hint: seen
433
+ ? undefined
434
+ : 'the sidebar browser did not open, so the human could not see the page; their confirmation may describe a different page — re-read it with browser_embedded_snapshot',
435
+ /**
436
+ * What to do next when the human saw nothing.
437
+ *
438
+ * A closed browser tab is the one case this tool cannot fix: the panel is
439
+ * the only surface it can reach, and a tab nobody opened has no socket to
440
+ * receive the request. Retrying would burn another timeout in silence, so
441
+ * the answer says what the options are instead of leaving the model to
442
+ * guess at an empty `via`.
443
+ */
444
+ advice: seen
445
+ ? undefined
446
+ : 'The human never saw this page: with the browser tab closed there is no surface to push it to. Ask them in chat to open it (right Sidebar → guide → 内嵌浏览器), or on a headed deployment call browser_embedded_present({ mode: "window" }) to show the page in a real window — then ask in chat rather than waiting on this tool again.',
447
+ })
448
+ } finally {
449
+ exec?.signal?.removeEventListener?.('abort', onAbort)
450
+ }
451
+ },
452
+ })
453
+
454
+ const js = defineTool({
455
+ name: 'browser_embedded_js',
456
+ description:
457
+ "Evaluate one JavaScript expression in this session's page and return its value. The escape hatch: read data the snapshot misses, inspect app state, compute something. Only JSON-serializable results survive — a DOM node comes back as null, so return primitives or plain objects.",
458
+ parameters: {
459
+ expression: { type: 'string', required: true, description: 'Expression to evaluate, e.g. "document.querySelectorAll(\'a\').length".' },
460
+ awaitPromise: { type: 'boolean', description: 'Await a returned promise (default true).' },
461
+ },
462
+ output: jsonOutput(),
463
+ execute: async (args, exec) =>
464
+ clean(await manager.evalJs(sessionOf(exec), String(args.expression), { awaitPromise: args.awaitPromise !== false })),
465
+ })
466
+
467
+ const wait = defineTool({
468
+ name: 'browser_embedded_wait',
469
+ description:
470
+ 'Wait for a page condition instead of guessing with fixed delays: a CSS selector to appear, the URL to match, a JS expression to become truthy, or the document to finish loading. Use after navigation and after anything that triggers async rendering.',
471
+ parameters: {
472
+ op: { type: 'string', required: true, description: 'One of selector, url, function, load, delay.' },
473
+ selector: { type: 'string', description: 'op=selector: CSS selector that must become visible.' },
474
+ pattern: { type: 'string', description: 'op=url: substring, or /regex/ form.' },
475
+ expression: { type: 'string', description: 'op=function: JS expression that must become truthy.' },
476
+ timeoutMs: { type: 'number', description: 'Budget in ms (default 10000).' },
477
+ ms: { type: 'number', description: 'op=delay: fixed milliseconds to wait.' },
478
+ },
479
+ output: jsonOutput(),
480
+ execute: async (args, exec) =>
481
+ clean(
482
+ await manager.waitFor(sessionOf(exec), {
483
+ op: String(args.op ?? 'delay'),
484
+ selector: args.selector,
485
+ pattern: args.pattern,
486
+ expression: args.expression,
487
+ timeoutMs: args.timeoutMs,
488
+ ms: args.ms,
489
+ }),
490
+ ),
491
+ })
492
+
493
+ const pageInfo = defineTool({
494
+ name: 'browser_embedded_page_info',
495
+ description:
496
+ 'Cheap page state without reading the content: URL, title, readyState, viewport, scroll offsets, and a coarse human-verification (CAPTCHA) signal. Use it to check whether the page really changed.',
497
+ parameters: {},
498
+ output: jsonOutput(),
499
+ execute: async (_args, exec) => clean(await manager.pageInfo(sessionOf(exec))),
500
+ })
501
+
502
+ const readElement = defineTool({
503
+ name: 'browser_embedded_read_element',
504
+ description:
505
+ 'Read one element by CSS selector without taking a whole snapshot: its text, HTML, current value, an attribute, or whether it is visible/enabled. Also returns how many elements the selector matched.',
506
+ parameters: {
507
+ selector: { type: 'string', required: true, description: 'CSS selector (first match is read).' },
508
+ what: { type: 'string', description: 'One of text (default), html, value, attribute, visible, enabled, count.' },
509
+ attribute: { type: 'string', description: 'Attribute name when what=attribute.' },
510
+ },
511
+ output: jsonOutput(),
512
+ execute: async (args, exec) =>
513
+ clean(await manager.readElement(sessionOf(exec), String(args.selector), args.what ?? 'text', args.attribute)),
514
+ })
515
+
516
+ const hover = defineTool({
517
+ name: 'browser_embedded_hover',
518
+ description:
519
+ 'Move the pointer over an element without clicking. Required before clicking anything inside a CSS :hover dropdown or menu — those items do not exist in the DOM (or are not clickable) until the pointer has moved over their parent. Pass x/y viewport coordinates to hover inside a cross-origin iframe.',
520
+ parameters: {
521
+ index: { type: 'number', description: 'Element number from the latest snapshot.' },
522
+ selector: { type: 'string', description: 'CSS selector — stable across snapshots, unlike element numbers.' },
523
+ x: { type: 'number', description: 'Viewport CSS x to hover, for content inside a cross-origin iframe.' },
524
+ y: { type: 'number', description: 'Viewport CSS y, with x.' },
525
+ },
526
+ output: jsonOutput(),
527
+ execute: async (args, exec) => {
528
+ const sessionId = sessionOf(exec)
529
+ if (typeof args.x === 'number' && typeof args.y === 'number') {
530
+ return clean(await manager.hoverPoint(sessionId, { x: args.x, y: args.y }))
531
+ }
532
+ return clean(await manager.hover(sessionId, targetOf(args)))
533
+ },
534
+ })
535
+
536
+ const tab = defineTool({
537
+ name: 'browser_embedded_tab',
538
+ description:
539
+ "Inspect or rearrange the tabs of this session's browser. list reports every page target with its owning session; switch rebinds this session to an existing tab; close shuts one down. Each session normally drives its own tab — use switch only when you deliberately need a different page.",
540
+ parameters: {
541
+ op: { type: 'string', required: true, description: 'One of list, switch, close.' },
542
+ targetId: { type: 'string', description: 'op=switch/close: target id from op=list.' },
543
+ },
544
+ output: jsonOutput(),
545
+ execute: async (args, exec) => {
546
+ const sessionId = sessionOf(exec)
547
+ const op = String(args.op ?? 'list')
548
+ if (op === 'list') return clean({ tabs: await manager.listTabs() })
549
+ if (op === 'switch') {
550
+ if (typeof args.targetId !== 'string' || args.targetId === '') throw new Error('op=switch needs targetId')
551
+ return clean(await manager.bindTab(sessionId, args.targetId))
552
+ }
553
+ if (op === 'close') {
554
+ if (typeof args.targetId !== 'string' || args.targetId === '') throw new Error('op=close needs targetId')
555
+ return clean({ closed: await manager.closeTab(args.targetId) })
556
+ }
557
+ throw new Error(`unsupported tab op ${JSON.stringify(op)}; use list, switch or close`)
558
+ },
559
+ })
560
+
561
+ const select = defineTool({
562
+ name: 'browser_embedded_select',
563
+ description:
564
+ 'Choose an option in a native <select> dropdown, firing the input/change events a human choice sends. Accepts the option value or its visible text.',
565
+ parameters: {
566
+ index: { type: 'number', description: 'Element number of the <select>.' },
567
+ selector: { type: 'string', description: 'CSS selector for the <select> — stable across snapshots.' },
568
+ value: { type: 'string', required: true, description: 'Option value or visible label.' },
569
+ },
570
+ output: jsonOutput(),
571
+ execute: async (args, exec) => clean(await manager.select(sessionOf(exec), targetOf(args, 'select'), String(args.value))),
572
+ })
573
+
574
+ const check = defineTool({
575
+ name: 'browser_embedded_check',
576
+ description:
577
+ 'Set a checkbox or radio to a wanted state. Does nothing when it is already in that state, so it is safe to call without inspecting first.',
578
+ parameters: {
579
+ index: { type: 'number', description: 'Element number of the box.' },
580
+ selector: { type: 'string', description: 'CSS selector for the box — stable across snapshots.' },
581
+ checked: { type: 'boolean', description: 'Target state (default true).' },
582
+ },
583
+ output: jsonOutput(),
584
+ execute: async (args, exec) => clean(await manager.check(sessionOf(exec), targetOf(args, 'checkbox'), args.checked !== false)),
585
+ })
586
+
587
+ const dialog = defineTool({
588
+ name: 'browser_embedded_dialog',
589
+ description:
590
+ 'Answer the alert/confirm/prompt the page is blocking on. A page-level dialog freezes every later call on that tab, so call this before anything else when a previous action seems to have hung. Accept or dismiss, optionally filling a prompt.',
591
+ parameters: {
592
+ accept: { type: 'boolean', description: 'true (default) accepts/OK, false cancels.' },
593
+ text: { type: 'string', description: 'Text for a prompt dialog.' },
594
+ },
595
+ output: jsonOutput(),
596
+ execute: async (args, exec) =>
597
+ clean(await manager.dialog(sessionOf(exec), { accept: args.accept !== false, text: args.text })),
598
+ })
599
+
600
+ const http = defineTool({
601
+ name: 'browser_embedded_http',
602
+ description:
603
+ "Fetch a URL from inside the page, so the request carries this profile's cookies and login state. Bound by the page's CORS rules — same-origin always works, cross-origin only where the page itself could. The body is truncated at maxBytes rather than refused. For public pages prefer a purpose-built HTTP tool.",
604
+ parameters: {
605
+ url: { type: 'string', required: true, description: 'Absolute http(s) URL.' },
606
+ method: { type: 'string', description: 'HTTP method (default GET).' },
607
+ headers: { type: 'object', additionalProperties: true, description: 'Request headers as a plain object.' },
608
+ body: { type: 'string', description: 'Request body for POST/PUT.' },
609
+ maxBytes: { type: 'number', description: 'Response body cap in bytes (default 200000).' },
610
+ },
611
+ output: jsonOutput(),
612
+ execute: async (args, exec) =>
613
+ clean(
614
+ await manager.httpFetch(sessionOf(exec), {
615
+ url: String(args.url),
616
+ method: args.method,
617
+ headers: args.headers,
618
+ body: args.body,
619
+ maxBytes: args.maxBytes,
620
+ }),
621
+ ),
622
+ })
623
+
624
+ const upload = defineTool({
625
+ name: 'browser_embedded_upload',
626
+ description:
627
+ 'Attach local files to a file input, bypassing the native file picker. The element must be an <input type=file> from the latest snapshot. Credentials folders (~/.ssh, ~/.dsh, ~/.gemini and friends) and operating-system directories are refused.',
628
+ parameters: {
629
+ index: { type: 'number', description: 'Element number of the file input.' },
630
+ selector: { type: 'string', description: 'CSS selector for the file input — stable across snapshots.' },
631
+ files: { type: 'string', required: true, description: 'One absolute path, or several separated by newlines.' },
632
+ },
633
+ output: jsonOutput(),
634
+ execute: async (args, exec) => {
635
+ const files = String(args.files)
636
+ .split(/\r?\n/)
637
+ .map((file) => file.trim())
638
+ .filter((file) => file !== '')
639
+ return clean(await manager.upload(sessionOf(exec), targetOf(args, 'file input'), files))
640
+ },
641
+ })
642
+
643
+ const download = defineTool({
644
+ name: 'browser_embedded_download',
645
+ description:
646
+ "Save a file: either point downloads at a directory, or fetch one URL and write it there. In the side panel the host cancels real browser downloads, so a URL is fetched inside the page (carrying that page's cookies) and written by the node half — which also means a download link the human clicks now produces a file instead of nothing.",
647
+ parameters: {
648
+ downloadPath: { type: 'string', description: 'Directory to save into; must be inside ~/Downloads/dsh-embedded-browser (omit for that default). Anything else is refused rather than clamped.' },
649
+ url: { type: 'string', description: 'Optional: fetch this URL now and save it into that directory.' },
650
+ maxBytes: { type: 'number', description: 'Refuse a body larger than this (default 32MB).' },
651
+ },
652
+ output: jsonOutput(),
653
+ execute: async (args, exec) =>
654
+ clean(
655
+ await manager.download(sessionOf(exec), {
656
+ downloadPath: args.downloadPath,
657
+ url: args.url,
658
+ maxBytes: args.maxBytes,
659
+ }),
660
+ ),
661
+ })
662
+
663
+ const drag = defineTool({
664
+ name: 'browser_embedded_drag',
665
+ description:
666
+ 'Drag one element onto another. A `draggable` source gets a synthesized drag event sequence — the panel cannot start an OS drag, so those events carry isTrusted=false; anything else gets a real pointer path (sliders, canvas, custom mousedown handlers). Both endpoints are element numbers from the latest snapshot.',
667
+ parameters: {
668
+ from: { type: 'number', description: 'Element number to pick up.' },
669
+ fromSelector: { type: 'string', description: 'CSS selector for what to pick up (alternative to from).' },
670
+ to: { type: 'number', description: 'Element number to drop on.' },
671
+ toSelector: { type: 'string', description: 'CSS selector for where to drop (alternative to to).' },
672
+ },
673
+ output: jsonOutput(),
674
+ execute: async (args, exec) =>
675
+ clean(
676
+ await manager.drag(
677
+ sessionOf(exec),
678
+ targetOf({ index: args.from, selector: args.fromSelector }, 'drag source'),
679
+ targetOf({ index: args.to, selector: args.toSelector }, 'drop target'),
680
+ ),
681
+ ),
682
+ })
683
+
684
+ const fill = defineTool({
685
+ name: 'browser_embedded_fill',
686
+ description:
687
+ "Replace a field's value outright, including React/Vue controlled inputs (the framework sees the change). Use this to set an input; use browser_embedded_type when you need real keystrokes or Enter-to-submit.",
688
+ parameters: {
689
+ index: { type: 'number', description: 'Field element number from the latest snapshot.' },
690
+ selector: { type: 'string', description: 'CSS selector for the field — stable across snapshots.' },
691
+ text: { type: 'string', required: true, description: 'The value to end up with (empty string clears the field).' },
692
+ },
693
+ output: jsonOutput(),
694
+ execute: async (args, exec) => clean(await manager.fill(sessionOf(exec), targetOf(args, 'field'), String(args.text))),
695
+ })
696
+
697
+ const close = defineTool({
698
+ name: 'browser_embedded_close',
699
+ description:
700
+ "Close this session's browser tab and free its memory. The shared profile keeps every login, so the next call opens a fresh tab already authenticated. The human can close it from the sidebar tab too, in which case the next tool call simply opens a new one.",
701
+ parameters: {},
702
+ output: jsonOutput(),
703
+ execute: async (_args, exec) => {
704
+ const sessionId = sessionOf(exec)
705
+ const closed = await manager.closeSession(sessionId, { reason: 'closed by the agent' })
706
+ await hub.sync()
707
+ await hub.pushState({ force: true })
708
+ return { closed, sessionId }
709
+ },
710
+ })
711
+
712
+ return [
713
+ status,
714
+ pageInfo,
715
+ navigate,
716
+ frame,
717
+ snapshot,
718
+ js,
719
+ readElement,
720
+ wait,
721
+ click,
722
+ type,
723
+ fill,
724
+ press,
725
+ hover,
726
+ select,
727
+ check,
728
+ scroll,
729
+ drag,
730
+ screenshot,
731
+ upload,
732
+ download,
733
+ http,
734
+ dialog,
735
+ tab,
736
+ present,
737
+ askHuman,
738
+ close,
739
+ ]
740
+ }