dsh-builtin-browser 0.5.6 → 0.5.8
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/CHANGELOG.md +148 -0
- package/README.en.md +75 -81
- package/README.md +75 -82
- package/client.js +831 -384
- package/desktop-bridge/install-and-start.cmd +4 -5
- package/desktop-bridge/install.mjs +322 -141
- package/desktop-bridge/maintenance-progress.ps1 +166 -0
- package/desktop-bridge/plugin-browser-bridge.js +157 -19
- package/desktop-bridge/request-desktop-quit.ps1 +170 -0
- package/docs/tool-reference.md +20 -1
- package/docs/user-guide.md +28 -4
- package/lib/browser/runtime.d.ts +3 -1
- package/lib/browser/runtime.js +9 -0
- package/lib/browser/types.d.ts +42 -0
- package/lib/browser-electron/authenticated-route.d.ts +27 -0
- package/lib/browser-electron/authenticated-route.js +39 -0
- package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
- package/lib/browser-electron/automatic-maintenance.js +426 -0
- package/lib/browser-electron/bridge-auto.d.ts +93 -0
- package/lib/browser-electron/bridge-auto.js +113 -0
- package/lib/browser-electron/bridge-connection.d.ts +0 -2
- package/lib/browser-electron/bridge-connection.js +2 -4
- package/lib/browser-electron/bridge-endpoint.js +8 -19
- package/lib/browser-electron/bridge-install.d.ts +85 -0
- package/lib/browser-electron/bridge-install.js +211 -0
- package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
- package/lib/browser-electron/bridge-maintenance.js +125 -0
- package/lib/browser-electron/bridge-status.d.ts +10 -3
- package/lib/browser-electron/bridge-status.js +74 -24
- package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
- package/lib/browser-electron/desktop-bridge-host.js +67 -25
- package/lib/browser-electron/desktop-identity.js +21 -9
- package/lib/browser-electron/electron-provision.d.ts +1 -1
- package/lib/browser-electron/electron-provision.js +36 -13
- package/lib/browser-electron/entry.js +173 -67
- package/lib/browser-electron/ephemeral-profile.js +67 -26
- package/lib/browser-electron/history-store.js +2 -2
- package/lib/browser-electron/host-main.js +48 -38
- package/lib/browser-electron/http-body.d.ts +24 -0
- package/lib/browser-electron/http-body.js +33 -0
- package/lib/browser-electron/json-reply.d.ts +13 -1
- package/lib/browser-electron/json-reply.js +16 -2
- package/lib/browser-electron/maintenance-broker.d.ts +35 -0
- package/lib/browser-electron/maintenance-broker.js +114 -0
- package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
- package/lib/browser-electron/maintenance-lifecycle.js +67 -0
- package/lib/browser-electron/maintenance-route.d.ts +18 -0
- package/lib/browser-electron/maintenance-route.js +75 -0
- package/lib/browser-electron/paths.d.ts +4 -0
- package/lib/browser-electron/paths.js +19 -0
- package/lib/browser-electron/process.d.ts +14 -0
- package/lib/browser-electron/process.js +24 -0
- package/lib/browser-electron/provider.d.ts +16 -9
- package/lib/browser-electron/provider.js +87 -18
- package/lib/browser-electron/remote-host.js +22 -20
- package/lib/browser-electron/runtime-route.d.ts +3 -5
- package/lib/browser-electron/runtime-status.d.ts +27 -13
- package/lib/browser-electron/runtime-status.js +28 -6
- package/lib/browser-electron/settings-route.d.ts +5 -18
- package/lib/browser-electron/settings-route.js +4 -14
- package/lib/browser-electron/settings-store.d.ts +28 -0
- package/lib/browser-electron/settings-store.js +32 -2
- package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
- package/lib/browser-electron/sidebar-only-host.js +192 -0
- package/lib/browser-electron/system-browser.d.ts +6 -11
- package/lib/browser-electron/system-browser.js +29 -24
- package/lib/browser-electron/timing.d.ts +8 -0
- package/lib/browser-electron/timing.js +13 -0
- package/lib/browser-electron/windows-system.d.ts +3 -0
- package/lib/browser-electron/windows-system.js +19 -0
- package/lib/tool-browser/index.js +1045 -7
- package/lib/tool-browser/page-probe.d.ts +86 -0
- package/lib/tool-browser/page-probe.js +460 -0
- package/package.json +5 -3
- package/scripts/run-tests.mjs +32 -0
- package/scripts/verify-preview-route.mjs +19 -1
- package/scripts/verify-runtime-status.mjs +14 -0
- package/skills/dsh-builtin-browser/SKILL.md +64 -0
- package/skills/dsh-builtin-browser/references/batch.md +23 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/src/browser/runtime.ts +11 -0
- package/src/browser/types.ts +19 -0
- package/src/browser-electron/authenticated-route.ts +56 -0
- package/src/browser-electron/automatic-maintenance.ts +414 -0
- package/src/browser-electron/bridge-auto.ts +158 -0
- package/src/browser-electron/bridge-connection.ts +2 -4
- package/src/browser-electron/bridge-endpoint.ts +8 -18
- package/src/browser-electron/bridge-install.ts +253 -0
- package/src/browser-electron/bridge-maintenance.ts +161 -0
- package/src/browser-electron/bridge-status.ts +76 -26
- package/src/browser-electron/desktop-bridge-host.ts +60 -26
- package/src/browser-electron/desktop-identity.ts +18 -9
- package/src/browser-electron/electron-provision.ts +35 -14
- package/src/browser-electron/entry.ts +152 -62
- package/src/browser-electron/ephemeral-profile.ts +65 -28
- package/src/browser-electron/history-store.ts +2 -2
- package/src/browser-electron/host-main.ts +40 -34
- package/src/browser-electron/http-body.ts +42 -0
- package/src/browser-electron/json-reply.ts +18 -3
- package/src/browser-electron/maintenance-broker.ts +142 -0
- package/src/browser-electron/maintenance-lifecycle.ts +86 -0
- package/src/browser-electron/maintenance-route.ts +64 -0
- package/src/browser-electron/paths.ts +21 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/provider.ts +106 -22
- package/src/browser-electron/remote-host.ts +23 -23
- package/src/browser-electron/runtime-route.ts +3 -5
- package/src/browser-electron/runtime-status.ts +56 -19
- package/src/browser-electron/settings-route.ts +9 -32
- package/src/browser-electron/settings-store.ts +59 -3
- package/src/browser-electron/sidebar-only-host.ts +199 -0
- package/src/browser-electron/system-browser.ts +26 -23
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/windows-system.ts +23 -0
- package/src/tool-browser/index.ts +995 -10
- package/src/tool-browser/page-probe.ts +474 -0
|
@@ -15,9 +15,12 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import type { Context } from '@deepseek-ai/cordis'
|
|
18
|
-
import {
|
|
18
|
+
import { statSync } from 'node:fs'
|
|
19
|
+
import { defineTool, type JsonValue } from '@deepseek-ai/dsh-tools'
|
|
20
|
+
import { pageOperationScript } from './page-probe.js'
|
|
21
|
+
import { SettingsStore } from '../browser-electron/settings-store.js'
|
|
19
22
|
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
20
|
-
import type { BrowserSessionId } from '../browser/types.js'
|
|
23
|
+
import type { BrowserSessionId, BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.js'
|
|
21
24
|
import {
|
|
22
25
|
ELEMENT_ITEM_SCHEMA,
|
|
23
26
|
NODE_ITEM_SCHEMA,
|
|
@@ -106,6 +109,13 @@ export const READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
|
|
|
106
109
|
'dsh_browser_snapshot', 'dsh_browser_a11y', 'dsh_browser_content', 'dsh_browser_scrape',
|
|
107
110
|
'dsh_browser_screenshot', 'dsh_browser_get_value', 'dsh_browser_wait', 'dsh_browser_challenge',
|
|
108
111
|
'dsh_browser_list_tabs', 'dsh_browser_session', 'dsh_browser_history', 'dsh_browser_visited',
|
|
112
|
+
// Observation added in 0.5.7: console lines, network responses, an assertion, a self-check and the
|
|
113
|
+
// help index. All five only read (the probe's buffers belong to the page, not to the task), so an
|
|
114
|
+
// allow-list must not blind a task that restricted itself.
|
|
115
|
+
'dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response',
|
|
116
|
+
'dsh_browser_assert', 'dsh_browser_doctor', 'dsh_browser_help',
|
|
117
|
+
// Reading the page's own digest and searching its text: observation like the rest.
|
|
118
|
+
'dsh_browser_find', 'dsh_browser_state',
|
|
109
119
|
// dsh_browser_auth reads cookies out of the browser: an observation, and one the
|
|
110
120
|
// credentials switch gates on its own (see credentials.allowRead in the settings).
|
|
111
121
|
// dsh_browser_auth is deliberately NOT here. It reads cookies on "flush" but WRITES them on
|
|
@@ -358,7 +368,7 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
358
368
|
// Tool guidance band is 100-199; 150 keeps clear of the common 110/120
|
|
359
369
|
// tool sections so ordering does not depend on plugin load sequence.
|
|
360
370
|
order: 150,
|
|
361
|
-
text: 'Use
|
|
371
|
+
text: 'Use dsh_browser_* tools to operate the built-in browser. Each task has its own session and window (real toolbar): the human can watch and take over, and other tasks\' pages are not visible to you. Map a page with dsh_browser_a11y (semantic roles/names/states) or dsh_browser_snapshot (numbered elements), then drive it: dsh_browser_click/dsh_browser_type take a target {by: css|text|xpath, value}, or coordinates from dsh_browser_screenshot. Prefer dsh_browser_fill (batch) or dsh_browser_set_value/check/select/clear for forms; verify with dsh_browser_get_value. Use dsh_browser_scrape (not hand-written dsh_browser_execute) for list pages; dsh_browser_wait after slow navigation. Use dsh_browser_do for a run of steps, dsh_browser_assert to check results, and dsh_browser_console/network when the screen is unclear. Say what you are doing on the page. On a CAPTCHA (dsh_browser_challenge), stop retrying and ask the human to solve it in the browser window, then re-check.',
|
|
362
372
|
})
|
|
363
373
|
|
|
364
374
|
/**
|
|
@@ -373,6 +383,9 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
373
383
|
* A name this plugin cannot have is worth a sentence in the log, not the toolset.
|
|
374
384
|
* @param definition - the tool to register.
|
|
375
385
|
*/
|
|
386
|
+
// One store for this apply: it caches by mtime, so reading it per download is a stat, not a parse.
|
|
387
|
+
const settingsStore = new SettingsStore()
|
|
388
|
+
|
|
376
389
|
const registerSafely = (definition: ReturnType<typeof defineTool>): void => {
|
|
377
390
|
try {
|
|
378
391
|
ctx.tools.register(definition)
|
|
@@ -420,7 +433,7 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
420
433
|
// dsh_browser_open is an overview of what just loaded, not a locator: it has no
|
|
421
434
|
// `coords` parameter, so coordinates stay off here (dsh_browser_snapshot owns
|
|
422
435
|
// that switch for callers that actually target pixels).
|
|
423
|
-
render: (
|
|
436
|
+
render: (_args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
|
|
424
437
|
},
|
|
425
438
|
timeoutMs,
|
|
426
439
|
isConcurrencySafe: () => false, // opens tabs / navigates; exclusive within a task
|
|
@@ -561,8 +574,9 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
561
574
|
return `${indent}[${n.ref}] ${n.role} "${n.name}"${valuePart}${coordsPart}${statePart}${selectorPart}${n.frame === true ? ' (iframe)' : ''}`
|
|
562
575
|
})
|
|
563
576
|
const header = `URL: ${value.url}${value.title !== undefined ? `\nTitle: ${value.title}` : ''}`
|
|
564
|
-
|
|
565
|
-
|
|
577
|
+
// The "coords: true" hint used to be appended to EVERY a11y result. It already lives in
|
|
578
|
+
// the parameter description, so repeating it in each model turn was pure token cost.
|
|
579
|
+
return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}` }]
|
|
566
580
|
},
|
|
567
581
|
},
|
|
568
582
|
timeoutMs,
|
|
@@ -1738,8 +1752,22 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
1738
1752
|
savePath: { type: 'string', required: true, description: 'Absolute path of the file to write. Must resolve inside the configured downloadDir (default: the system Downloads folder, localized names such as ~/下载 included); an existing file is never overwritten.' },
|
|
1739
1753
|
},
|
|
1740
1754
|
output: {
|
|
1741
|
-
schema: {
|
|
1742
|
-
|
|
1755
|
+
schema: {
|
|
1756
|
+
type: 'object',
|
|
1757
|
+
additionalProperties: false,
|
|
1758
|
+
properties: {
|
|
1759
|
+
path: { type: 'string', required: true },
|
|
1760
|
+
handoff: { type: 'object', additionalProperties: true },
|
|
1761
|
+
remoteError: { type: 'string' },
|
|
1762
|
+
remoteResult: { type: 'object', additionalProperties: true },
|
|
1763
|
+
},
|
|
1764
|
+
},
|
|
1765
|
+
render: (_args, value) => {
|
|
1766
|
+
const lines = [`Downloaded to ${value.path}.`]
|
|
1767
|
+
if (value.handoff !== undefined) lines.push(`Handed to ${String((value.handoff as Record<string, unknown>).tool)}: ${String((value.handoff as Record<string, unknown>).result ?? 'ok')}`)
|
|
1768
|
+
if (value.remoteError !== undefined) lines.push(`The local file is intact; the remote side did not take it: ${String(value.remoteError)}`)
|
|
1769
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
1770
|
+
},
|
|
1743
1771
|
},
|
|
1744
1772
|
timeoutMs,
|
|
1745
1773
|
isConcurrencySafe: () => false,
|
|
@@ -1749,7 +1777,70 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
1749
1777
|
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1750
1778
|
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1751
1779
|
const result = await browser.download(session, { url: args.url, savePath: args.savePath }, exec.signal)
|
|
1752
|
-
|
|
1780
|
+
// Delivery is an attribute of the download: empty tool = the old behaviour, byte for byte.
|
|
1781
|
+
const plan = deliveryPlan(args.url as string, result.path)
|
|
1782
|
+
if (plan === undefined) return { path: result.path }
|
|
1783
|
+
let remoteValue: JsonValue | undefined
|
|
1784
|
+
try {
|
|
1785
|
+
const tools = (ctx as unknown as { get?: (name: string) => {
|
|
1786
|
+
execute?: (input: unknown) => Promise<unknown>
|
|
1787
|
+
setExecutor?: unknown
|
|
1788
|
+
} | undefined }).get?.('tools')
|
|
1789
|
+
if (tools?.execute === undefined) throw new Error('the tools service is not available on this surface')
|
|
1790
|
+
if (plan.tool === 'dsh_browser_download') throw new Error('the delivery tool must be a different tool from dsh_browser_download')
|
|
1791
|
+
exec.signal.throwIfAborted()
|
|
1792
|
+
const callId = 'handoff-' + globalThis.crypto.randomUUID()
|
|
1793
|
+
// DSH's executor service accepts raw batches. Earlier runtimes accept one parsed call.
|
|
1794
|
+
// Select the API before dispatch so a retry can never upload the same file twice.
|
|
1795
|
+
const batched = typeof tools.setExecutor === 'function'
|
|
1796
|
+
const answer = await tools.execute(batched ? {
|
|
1797
|
+
calls: [{ type: 'tool-call', id: callId, name: plan.tool, arguments: JSON.stringify(plan.args) }],
|
|
1798
|
+
agent: exec.agent,
|
|
1799
|
+
toolSet: (exec as typeof exec & { readonly toolSet?: unknown }).toolSet,
|
|
1800
|
+
signal: exec.signal,
|
|
1801
|
+
} : {
|
|
1802
|
+
callId,
|
|
1803
|
+
rootCallId: exec.rootCallId,
|
|
1804
|
+
parent: exec.token,
|
|
1805
|
+
name: plan.tool,
|
|
1806
|
+
arguments: plan.args,
|
|
1807
|
+
agent: exec.agent,
|
|
1808
|
+
signal: exec.signal,
|
|
1809
|
+
})
|
|
1810
|
+
let outcome = answer
|
|
1811
|
+
let concluded = false
|
|
1812
|
+
if (batched) {
|
|
1813
|
+
const batch = answer as { results?: { callId?: string; result?: unknown }[]; additionalContexts?: unknown[]; concluded?: boolean } | null
|
|
1814
|
+
if (!Array.isArray(batch?.results) || batch.results.length !== 1 || batch.results[0]?.callId !== callId) {
|
|
1815
|
+
throw new Error('the delivery executor returned no matching tool result')
|
|
1816
|
+
}
|
|
1817
|
+
for (const context of batch.additionalContexts ?? []) {
|
|
1818
|
+
exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
|
|
1819
|
+
}
|
|
1820
|
+
concluded = batch.concluded === true
|
|
1821
|
+
outcome = batch.results[0].result
|
|
1822
|
+
}
|
|
1823
|
+
const settled = outcome as { value?: JsonValue; additionalContexts?: unknown[]; concludesTurn?: boolean } | null
|
|
1824
|
+
remoteValue = settled?.value
|
|
1825
|
+
const summary = summariseToolResult(outcome)
|
|
1826
|
+
if (!batched) {
|
|
1827
|
+
for (const context of settled?.additionalContexts ?? []) {
|
|
1828
|
+
exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
|
|
1829
|
+
}
|
|
1830
|
+
concluded = settled?.concludesTurn === true
|
|
1831
|
+
}
|
|
1832
|
+
if (concluded) exec.concludeTurn()
|
|
1833
|
+
return { path: result.path, handoff: { tool: plan.tool, result: summary, value: remoteValue ?? null } }
|
|
1834
|
+
} catch (error) {
|
|
1835
|
+
exec.signal.throwIfAborted()
|
|
1836
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
1837
|
+
if (plan.onFail === 'stop') throw new Error(`dsh_browser_download: saved to ${result.path} locally, but the handoff to "${plan.tool}" failed: ${reason}`)
|
|
1838
|
+
return {
|
|
1839
|
+
path: result.path,
|
|
1840
|
+
remoteError: plan.tool + ': ' + reason,
|
|
1841
|
+
...remoteValue === undefined ? {} : { remoteResult: { tool: plan.tool, value: remoteValue } },
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1753
1844
|
},
|
|
1754
1845
|
}))
|
|
1755
1846
|
|
|
@@ -1897,6 +1988,901 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
1897
1988
|
return { restored }
|
|
1898
1989
|
},
|
|
1899
1990
|
}))
|
|
1991
|
+
|
|
1992
|
+
// ===========================================================================
|
|
1993
|
+
// Observation, assertion and batch work (0.5.7).
|
|
1994
|
+
//
|
|
1995
|
+
// Five capabilities were missing against the other browser plugins in this market: what the
|
|
1996
|
+
// console said, which responses arrived, what happened to a JavaScript dialog (an unanswered
|
|
1997
|
+
// `confirm()` used to hang a whole call), a way to assert a result instead of eyeballing a
|
|
1998
|
+
// screenshot, and a way to run several steps in one call. All of them come from one page-side
|
|
1999
|
+
// probe installed through `execute`, so they work identically on the self-hosted window, a driven
|
|
2000
|
+
// Chrome/Edge and the desktop sidebar — no host change, no bridge protocol version.
|
|
2001
|
+
// ===========================================================================
|
|
2002
|
+
|
|
2003
|
+
/**
|
|
2004
|
+
* What to do with a saved file, from the settings document.
|
|
2005
|
+
*
|
|
2006
|
+
* Read here rather than threaded through the provider on purpose: delivery is a property of how
|
|
2007
|
+
* this deployment saves files, not of which browser carries the page, so every carrier gets it
|
|
2008
|
+
* for free and no seam grows a method for it.
|
|
2009
|
+
*
|
|
2010
|
+
* @param url - the downloaded address, used to pick a per-site override by host.
|
|
2011
|
+
* @param path - the absolute local path just written.
|
|
2012
|
+
* @returns the plan, or undefined when nothing is configured (the old behaviour).
|
|
2013
|
+
*/
|
|
2014
|
+
function deliveryPlan(url: string, path: string): { tool: string; args: Record<string, string>; onFail: 'keep-local' | 'stop' } | undefined {
|
|
2015
|
+
let settings
|
|
2016
|
+
try { settings = settingsStore.get() } catch { return undefined }
|
|
2017
|
+
const delivery = settings.delivery
|
|
2018
|
+
if (delivery === undefined) return undefined
|
|
2019
|
+
let host = ''
|
|
2020
|
+
try { host = new URL(url).hostname.toLowerCase() } catch { host = '' }
|
|
2021
|
+
const override = host === '' ? undefined : (delivery.sites[host] ?? delivery.sites['*'])
|
|
2022
|
+
const tool = override ?? delivery.tool
|
|
2023
|
+
if (typeof tool !== 'string' || tool.trim() === '') return undefined
|
|
2024
|
+
const name = path.split(/[\\/]/).pop() ?? path
|
|
2025
|
+
const size = (() => { try { return String(statSync(path).size) } catch { return '' } })()
|
|
2026
|
+
const args: Record<string, string> = {}
|
|
2027
|
+
for (const [key, value] of Object.entries(delivery.args)) {
|
|
2028
|
+
args[key] = String(value).split('{path}').join(path).split('{name}').join(name).split('{size}').join(size)
|
|
2029
|
+
}
|
|
2030
|
+
if (Object.keys(args).length === 0) args.file_path = path
|
|
2031
|
+
return { tool: tool.trim(), args, onFail: delivery.onFail }
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
/** Check the canonical outcome before describing a completed delivery. */
|
|
2035
|
+
function summariseToolResult(answer: unknown): string {
|
|
2036
|
+
const outcome = answer as { isError?: boolean; value?: unknown; error?: { message?: string }; content?: { text?: string }[] } | null
|
|
2037
|
+
if (outcome === null || typeof outcome !== 'object' || typeof outcome.isError !== 'boolean') {
|
|
2038
|
+
throw new Error('the delivery executor returned an invalid tool result')
|
|
2039
|
+
}
|
|
2040
|
+
if (outcome.isError) {
|
|
2041
|
+
throw new Error(outcome.error?.message || outcome.content?.map(block => block.text ?? '').join(' ') || 'the delivery tool failed')
|
|
2042
|
+
}
|
|
2043
|
+
if (!('value' in outcome)) throw new Error('the delivery executor returned an invalid tool result')
|
|
2044
|
+
const failure = deliveryFailure(outcome.value)
|
|
2045
|
+
if (failure !== undefined) throw new Error(failure)
|
|
2046
|
+
const text = typeof outcome.value === 'string' ? outcome.value : JSON.stringify(outcome.value)
|
|
2047
|
+
return text.length > 200 ? text.slice(0, 200) + '…' : text
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/** Read explicit failure markers in common MCP structured or JSON text responses. */
|
|
2051
|
+
function deliveryFailure(value: unknown): string | undefined {
|
|
2052
|
+
const object = (candidate: unknown): Record<string, unknown> | undefined => {
|
|
2053
|
+
if (typeof candidate === 'string') {
|
|
2054
|
+
try { candidate = JSON.parse(candidate) } catch { return undefined }
|
|
2055
|
+
}
|
|
2056
|
+
return candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
|
|
2057
|
+
? candidate as Record<string, unknown> : undefined
|
|
2058
|
+
}
|
|
2059
|
+
const response = object(value)
|
|
2060
|
+
if (response === undefined) return undefined
|
|
2061
|
+
const blocks = Array.isArray(response.content) ? response.content : []
|
|
2062
|
+
const candidates = [
|
|
2063
|
+
response,
|
|
2064
|
+
object(response.structuredContent),
|
|
2065
|
+
...blocks.map(block => {
|
|
2066
|
+
const content = object(block)
|
|
2067
|
+
return content?.type === 'text' ? object(content.text) : undefined
|
|
2068
|
+
}),
|
|
2069
|
+
]
|
|
2070
|
+
for (const candidate of candidates) {
|
|
2071
|
+
if (candidate === undefined) continue
|
|
2072
|
+
if (candidate.isError !== true && candidate.ok !== false && candidate.success !== false
|
|
2073
|
+
&& candidate.status !== 'error' && candidate.status !== 'failed') continue
|
|
2074
|
+
const error = object(candidate.error)
|
|
2075
|
+
const detail = [candidate.message, candidate.error, error?.message].find(item => typeof item === 'string' && item !== '')
|
|
2076
|
+
return typeof detail === 'string' ? detail : 'the delivery tool reported a failed upload'
|
|
2077
|
+
}
|
|
2078
|
+
return undefined
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
/** Run a script in the page and return its value as text. */
|
|
2082
|
+
async function pageValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, script: string, signal?: AbortSignal): Promise<string> {
|
|
2083
|
+
const result = await browser.execute(session, { script }, signal)
|
|
2084
|
+
if (!result.ok) throw new Error(`page script failed: ${result.exception}`)
|
|
2085
|
+
const raw = result.value
|
|
2086
|
+
return typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/** Fixed operations keep their inputs as data and preserve arbitrary-script permissions. */
|
|
2090
|
+
async function pageOperationValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<string> {
|
|
2091
|
+
const result = typeof browser.pageOperation === 'function'
|
|
2092
|
+
? await browser.pageOperation(session, request, signal)
|
|
2093
|
+
: await browser.execute(session, { script: pageOperationScript(request) }, signal)
|
|
2094
|
+
if (!result.ok) throw new Error('page operation failed: ' + result.exception)
|
|
2095
|
+
return typeof result.value === 'string' ? result.value : JSON.stringify(result.value ?? null)
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
/** Install the fixed probe and report page failures immediately. */
|
|
2099
|
+
async function installProbe(browser: NonNullable<Context['browser']>, session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
|
|
2100
|
+
await pageOperationValue(browser, session, { operation: 'install' }, signal)
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
/** One probe call, parsed. Throws when the probe is absent or the call failed. */
|
|
2104
|
+
async function probe<T = unknown>(
|
|
2105
|
+
browser: NonNullable<Context['browser']>,
|
|
2106
|
+
session: BrowserSessionId,
|
|
2107
|
+
method: BrowserProbeMethod,
|
|
2108
|
+
args: readonly unknown[] = [],
|
|
2109
|
+
signal?: AbortSignal,
|
|
2110
|
+
): Promise<T> {
|
|
2111
|
+
const text = await pageOperationValue(browser, session, { operation: 'probe', method, args }, signal)
|
|
2112
|
+
let parsed: unknown
|
|
2113
|
+
try { parsed = JSON.parse(text) } catch { throw new Error(`page probe returned unreadable JSON: ${text.slice(0, 120)}`) }
|
|
2114
|
+
if (parsed !== null && typeof parsed === 'object' && 'error' in (parsed as Record<string, unknown>)) {
|
|
2115
|
+
throw new Error(`page probe: ${String((parsed as Record<string, unknown>).error)}`)
|
|
2116
|
+
}
|
|
2117
|
+
return parsed as T
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
/**
|
|
2121
|
+
* A probe call that survives a navigation inside a batch.
|
|
2122
|
+
*
|
|
2123
|
+
* Submitting a form replaces the document, and the probe with it, so a later step in the same
|
|
2124
|
+
* batch would fail with `probe-not-installed` — measured on the first real benchmark run. One
|
|
2125
|
+
* reinstall and one retry is enough: a second failure is a real absence, not a stale context.
|
|
2126
|
+
*/
|
|
2127
|
+
async function probeLive<T = unknown>(
|
|
2128
|
+
browser: NonNullable<Context['browser']>,
|
|
2129
|
+
session: BrowserSessionId,
|
|
2130
|
+
method: BrowserProbeMethod,
|
|
2131
|
+
args: readonly unknown[] = [],
|
|
2132
|
+
signal?: AbortSignal,
|
|
2133
|
+
): Promise<T> {
|
|
2134
|
+
try {
|
|
2135
|
+
return await probe<T>(browser, session, method, args, signal)
|
|
2136
|
+
} catch (error) {
|
|
2137
|
+
if (!/probe-not-installed|probe-method-missing/.test(String(error))) throw error
|
|
2138
|
+
await installProbe(browser, session, signal)
|
|
2139
|
+
return await probe<T>(browser, session, method, args, signal)
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
/** Sleep. Long waits are capped by the caller, and the tool timeout still applies. */
|
|
2144
|
+
async function pause(ms: number): Promise<void> {
|
|
2145
|
+
await new Promise<void>(resolve => { setTimeout(resolve, ms) })
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
/** Poll until the callback returns something, or the budget runs out. */
|
|
2149
|
+
async function poll<T>(check: () => Promise<T | undefined>, budgetMs: number): Promise<T | undefined> {
|
|
2150
|
+
const deadline = Date.now() + budgetMs
|
|
2151
|
+
for (;;) {
|
|
2152
|
+
const value = await check()
|
|
2153
|
+
if (value !== undefined) return value
|
|
2154
|
+
if (Date.now() >= deadline) return undefined
|
|
2155
|
+
await pause(200)
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
/**
|
|
2160
|
+
* One flat probe row: what a page can hand back through JSON.
|
|
2161
|
+
*
|
|
2162
|
+
* Concrete rather than `Record<string, unknown>`, because the tool output schema is a JSON value
|
|
2163
|
+
* and the compiler (rightly) refuses to promise that an `unknown` is one.
|
|
2164
|
+
*/
|
|
2165
|
+
type ProbeRow = Record<string, string | number | boolean | null>
|
|
2166
|
+
|
|
2167
|
+
/**
|
|
2168
|
+
* Run one `dsh_browser_check` specification against the page.
|
|
2169
|
+
*
|
|
2170
|
+
* Shared by the `check` tool and by the `{check: …}` step of `dsh_browser_do`, so a batch asserts
|
|
2171
|
+
* exactly what a standalone call asserts.
|
|
2172
|
+
*/
|
|
2173
|
+
async function runChecks(
|
|
2174
|
+
browser: NonNullable<Context['browser']>,
|
|
2175
|
+
session: BrowserSessionId,
|
|
2176
|
+
spec: { readonly selector?: string; readonly text?: string; readonly url?: string; readonly js?: string },
|
|
2177
|
+
signal?: AbortSignal,
|
|
2178
|
+
): Promise<{ pass: boolean; checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> }> {
|
|
2179
|
+
const checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> = []
|
|
2180
|
+
if (spec.selector !== undefined) {
|
|
2181
|
+
const found = await probeLive<{ described?: string } | null>(browser, session, 'find', [{ css: spec.selector }], signal)
|
|
2182
|
+
checks.push({ kind: 'selector', expected: spec.selector, actual: found === null ? 'not found' : String(found.described ?? 'found'), pass: found !== null })
|
|
2183
|
+
}
|
|
2184
|
+
if (spec.text !== undefined) {
|
|
2185
|
+
const present = await pageOperationValue(browser, session, { operation: 'text', text: spec.text }, signal)
|
|
2186
|
+
const ok = present === 'true'
|
|
2187
|
+
checks.push({ kind: 'text', expected: spec.text, actual: ok ? 'present' : 'absent', pass: ok })
|
|
2188
|
+
}
|
|
2189
|
+
if (spec.url !== undefined) {
|
|
2190
|
+
const href = await pageOperationValue(browser, session, { operation: 'url' }, signal).then(text => text.replace(/^"|"$/g, ''))
|
|
2191
|
+
const ok = href.includes(spec.url)
|
|
2192
|
+
checks.push({ kind: 'url', expected: spec.url, actual: href, pass: ok })
|
|
2193
|
+
}
|
|
2194
|
+
if (spec.js !== undefined) {
|
|
2195
|
+
try {
|
|
2196
|
+
const value = await pageValue(browser, session, `(() => { try { return JSON.stringify({ ok: !!(${spec.js}) }) } catch (error) { return JSON.stringify({ ok: false, error: String(error) }) } })()`, signal)
|
|
2197
|
+
const parsed = JSON.parse(value) as { ok?: boolean; error?: string }
|
|
2198
|
+
checks.push({ kind: 'js', expected: spec.js, actual: parsed.ok === true ? 'truthy' : (parsed.error ?? 'falsy'), pass: parsed.ok === true })
|
|
2199
|
+
} catch (error) {
|
|
2200
|
+
checks.push({ kind: 'js', expected: spec.js, actual: String(error), pass: false })
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
return { pass: checks.length > 0 && checks.every(check => check.pass), checks }
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
registerSafely(defineTool({
|
|
2207
|
+
name: 'dsh_browser_console',
|
|
2208
|
+
description: 'Read what the page has logged (console.log/info/warn/error/debug), newest last, capped at 200 lines. Use it when the screen does not explain a failure: a red toast, a form that silently refuses, a page that "just does nothing". Set clear:true first when you only want what happens next. A page that logs objects shows their JSON.',
|
|
2209
|
+
parameters: {
|
|
2210
|
+
limit: { type: 'number', description: 'How many lines, newest last (default 20, max 100).' },
|
|
2211
|
+
filter: { type: 'string', description: 'Only lines containing this text (case-insensitive).' },
|
|
2212
|
+
clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
|
|
2213
|
+
},
|
|
2214
|
+
output: {
|
|
2215
|
+
schema: {
|
|
2216
|
+
type: 'object',
|
|
2217
|
+
additionalProperties: false,
|
|
2218
|
+
properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
|
|
2219
|
+
},
|
|
2220
|
+
render: (_args, value) => {
|
|
2221
|
+
const rows = value.entries as Array<{ level?: string; text?: string }>
|
|
2222
|
+
if (rows.length === 0) return [{ type: 'text', text: 'No console lines yet (nothing logged since the page probe was installed).' }]
|
|
2223
|
+
return [{ type: 'text', text: rows.map(row => `[${String(row.level)}] ${String(row.text)}`).join('\n') }]
|
|
2224
|
+
},
|
|
2225
|
+
},
|
|
2226
|
+
timeoutMs,
|
|
2227
|
+
isConcurrencySafe: () => true,
|
|
2228
|
+
async execute(args, exec) {
|
|
2229
|
+
const browser = ctx.get('browser')
|
|
2230
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2231
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2232
|
+
await installProbe(browser, session, exec.signal)
|
|
2233
|
+
if (args.clear === true) await probe(browser, session, 'clear', ['console'], exec.signal)
|
|
2234
|
+
const entries = await probe<ProbeRow[]>(browser, session, 'read', ['console', args.filter ?? '', args.limit ?? 20], exec.signal)
|
|
2235
|
+
return { entries }
|
|
2236
|
+
},
|
|
2237
|
+
}))
|
|
2238
|
+
|
|
2239
|
+
registerSafely(defineTool({
|
|
2240
|
+
name: 'dsh_browser_network',
|
|
2241
|
+
description: 'List the responses the page has received, newest last: method, status, type and address, for fetch, XHR and resource-timing entries. Use it when a page fills itself from the network and the screen does not say why, or to confirm a submit actually reached the server. onlyFailures keeps status 0 (blocked/aborted) and 4xx/5xx. Resource-timing rows carry no status (the browser never exposed it to the page) and show status 0.',
|
|
2242
|
+
parameters: {
|
|
2243
|
+
limit: { type: 'number', description: 'How many rows, newest last (default 20, max 100).' },
|
|
2244
|
+
filter: { type: 'string', description: 'Only rows whose address contains this text.' },
|
|
2245
|
+
onlyFailures: { type: 'boolean', description: 'Only rows with status 0, or status >= 400.' },
|
|
2246
|
+
clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
|
|
2247
|
+
},
|
|
2248
|
+
output: {
|
|
2249
|
+
schema: {
|
|
2250
|
+
type: 'object',
|
|
2251
|
+
additionalProperties: false,
|
|
2252
|
+
properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
|
|
2253
|
+
},
|
|
2254
|
+
render: (_args, value) => {
|
|
2255
|
+
const rows = value.entries as ProbeRow[]
|
|
2256
|
+
if (rows.length === 0) return [{ type: 'text', text: 'No responses recorded yet.' }]
|
|
2257
|
+
return [{ type: 'text', text: rows.map(row => `${String(row.method)} ${String(row.status)} ${String(row.kind)} ${String(row.ms)}ms ${String(row.url)}`).join('\n') }]
|
|
2258
|
+
},
|
|
2259
|
+
},
|
|
2260
|
+
timeoutMs,
|
|
2261
|
+
isConcurrencySafe: () => true,
|
|
2262
|
+
async execute(args, exec) {
|
|
2263
|
+
const browser = ctx.get('browser')
|
|
2264
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2265
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2266
|
+
await installProbe(browser, session, exec.signal)
|
|
2267
|
+
if (args.clear === true) await probe(browser, session, 'clear', ['network'], exec.signal)
|
|
2268
|
+
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.filter ?? '', args.limit ?? 20], exec.signal)
|
|
2269
|
+
const entries = args.onlyFailures === true
|
|
2270
|
+
? rows.filter(row => Number(row.status) === 0 || Number(row.status) >= 400)
|
|
2271
|
+
: rows
|
|
2272
|
+
return { entries }
|
|
2273
|
+
},
|
|
2274
|
+
}))
|
|
2275
|
+
|
|
2276
|
+
registerSafely(defineTool({
|
|
2277
|
+
name: 'dsh_browser_dialog',
|
|
2278
|
+
description: 'Report JavaScript dialogs (alert/confirm/prompt) the page raised, and choose how they are answered. Dialogs use the native browser UI by default. Setting policy "dismiss" answers alert/prompt with nothing and confirm with false, "accept" answers confirm with true and prompt with its current text. Policy "native" restores the original dialog functions. Reading preserves the current policy; changing it is an action. A dialog raised by the browser itself (beforeunload, HTTP auth) is not covered.',
|
|
2279
|
+
parameters: {
|
|
2280
|
+
policy: { type: 'string', enum: ['native', 'accept', 'dismiss'], description: 'Answer future dialogs this way.' },
|
|
2281
|
+
limit: { type: 'number', description: 'How many recent dialogs to return (default 10).' },
|
|
2282
|
+
},
|
|
2283
|
+
output: {
|
|
2284
|
+
schema: {
|
|
2285
|
+
type: 'object',
|
|
2286
|
+
additionalProperties: false,
|
|
2287
|
+
properties: {
|
|
2288
|
+
policy: { type: 'string', required: true },
|
|
2289
|
+
dialogs: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
2290
|
+
},
|
|
2291
|
+
},
|
|
2292
|
+
render: (_args, value) => {
|
|
2293
|
+
const rows = value.dialogs as ProbeRow[]
|
|
2294
|
+
const head = `Dialog policy: ${String(value.policy)} (${String(value.policy) === 'accept' ? 'confirm→true, prompt→its text' : 'confirm→false, prompt→null'}).`
|
|
2295
|
+
if (rows.length === 0) return [{ type: 'text', text: `${head} No dialogs seen yet.` }]
|
|
2296
|
+
return [{ type: 'text', text: [head, ...rows.map(row => `${String(row.kind)} "${String(row.message)}" → ${String(row.answered)}`)] .join('\n') }]
|
|
2297
|
+
},
|
|
2298
|
+
},
|
|
2299
|
+
timeoutMs,
|
|
2300
|
+
isConcurrencySafe: () => false, // the policy is task-wide state
|
|
2301
|
+
async execute(args, exec) {
|
|
2302
|
+
assertAllowed(state, 'dsh_browser_dialog', taskKey(exec))
|
|
2303
|
+
const browser = ctx.get('browser')
|
|
2304
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2305
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2306
|
+
await installProbe(browser, session, exec.signal)
|
|
2307
|
+
const policy = args.policy === undefined
|
|
2308
|
+
? await probe<string>(browser, session, 'dialogStatus', [], exec.signal)
|
|
2309
|
+
: await probe<string>(browser, session, 'setDialogPolicy', [args.policy], exec.signal)
|
|
2310
|
+
const dialogs = await probe<ProbeRow[]>(browser, session, 'read', ['dialogs', '', args.limit ?? 10], exec.signal)
|
|
2311
|
+
return { policy, dialogs }
|
|
2312
|
+
},
|
|
2313
|
+
}))
|
|
2314
|
+
|
|
2315
|
+
registerSafely(defineTool({
|
|
2316
|
+
name: 'dsh_browser_wait_for_response',
|
|
2317
|
+
description: 'Wait until a response whose address contains `urlContains` has arrived AFTER this call started: optional status (e.g. 200, or 4xx), bounded by timeoutMs. Use it instead of sleeping before a snapshot when a click submits a form or starts a fetch — it returns as soon as the server answered, and says what arrived when it did not. This is the "did the submit reach the server" question that a screenshot cannot answer.',
|
|
2318
|
+
parameters: {
|
|
2319
|
+
urlContains: { type: 'string', required: true, description: 'Substring of the request address.' },
|
|
2320
|
+
status: { type: 'number', description: 'Require this exact status (a non-zero status is required to match).' },
|
|
2321
|
+
timeoutMs: { type: 'number', description: 'How long to wait (default 15000, capped by the tool timeout).' },
|
|
2322
|
+
},
|
|
2323
|
+
output: {
|
|
2324
|
+
schema: {
|
|
2325
|
+
type: 'object',
|
|
2326
|
+
additionalProperties: false,
|
|
2327
|
+
properties: {
|
|
2328
|
+
matched: { type: 'boolean', required: true },
|
|
2329
|
+
reason: { type: 'string', required: true },
|
|
2330
|
+
entry: { type: 'object', additionalProperties: true },
|
|
2331
|
+
},
|
|
2332
|
+
},
|
|
2333
|
+
render: (_args, value) => {
|
|
2334
|
+
const entry = value.entry as Record<string, unknown> | undefined
|
|
2335
|
+
if (!value.matched) return [{ type: 'text', text: `No matching response: ${String(value.reason)}` }]
|
|
2336
|
+
return [{ type: 'text', text: `Matched: ${String(entry?.method)} ${String(entry?.status)} ${String(entry?.url)} (${String(entry?.ms)}ms)` }]
|
|
2337
|
+
},
|
|
2338
|
+
},
|
|
2339
|
+
timeoutMs,
|
|
2340
|
+
isConcurrencySafe: () => true,
|
|
2341
|
+
async execute(args, exec) {
|
|
2342
|
+
const browser = ctx.get('browser')
|
|
2343
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2344
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2345
|
+
await installProbe(browser, session, exec.signal)
|
|
2346
|
+
const cursor = await probe<{ startedAt: number; sequence: number }>(browser, session, 'networkCursor', [], exec.signal)
|
|
2347
|
+
const budget = Math.min(args.timeoutMs ?? 15_000, maxWaitMs)
|
|
2348
|
+
const found = await poll(async () => {
|
|
2349
|
+
const current = await probe<{ startedAt: number; sequence: number }>(browser, session, 'networkCursor', [], exec.signal)
|
|
2350
|
+
if (current.startedAt !== cursor.startedAt) throw new Error('the page changed while waiting for a response; start a new wait on the current page')
|
|
2351
|
+
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.urlContains, 100], exec.signal)
|
|
2352
|
+
const fresh = rows.filter(row => Number(row.sequence) > cursor.sequence && Number(row.status) > 0)
|
|
2353
|
+
const exact = args.status === undefined ? fresh : fresh.filter(row => Number(row.status) === args.status)
|
|
2354
|
+
return exact.length > 0 ? exact[exact.length - 1] : undefined
|
|
2355
|
+
}, budget)
|
|
2356
|
+
if (found === undefined) {
|
|
2357
|
+
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.urlContains, 60], exec.signal)
|
|
2358
|
+
const seen = rows.length === 0 ? 'nothing matched the address' : `${rows.length} older row(s) matched but none arrived after this call started`
|
|
2359
|
+
return { matched: false, reason: `${seen} within ${Math.round(budget / 1000)}s` }
|
|
2360
|
+
}
|
|
2361
|
+
return { matched: true, reason: 'response arrived', entry: found }
|
|
2362
|
+
},
|
|
2363
|
+
}))
|
|
2364
|
+
|
|
2365
|
+
registerSafely(defineTool({
|
|
2366
|
+
name: 'dsh_browser_assert',
|
|
2367
|
+
description: 'Assert facts about the page in one call and get a pass/fail per assertion with the evidence: a CSS selector exists, the body text contains something, the URL contains something, or a JavaScript expression is truthy. Use it to verify a step actually worked — "clicked" and "the form accepted it" are different claims — and before retrying anything that might have already taken effect.',
|
|
2368
|
+
parameters: {
|
|
2369
|
+
selector: { type: 'string', description: 'CSS selector that must match an element.' },
|
|
2370
|
+
text: { type: 'string', description: 'Text that must appear in the page body.' },
|
|
2371
|
+
url: { type: 'string', description: 'Substring the URL must contain.' },
|
|
2372
|
+
js: { type: 'string', description: 'Expression that must be truthy, e.g. document.querySelector("#ok") !== null.' },
|
|
2373
|
+
},
|
|
2374
|
+
output: {
|
|
2375
|
+
schema: {
|
|
2376
|
+
type: 'object',
|
|
2377
|
+
additionalProperties: false,
|
|
2378
|
+
properties: {
|
|
2379
|
+
pass: { type: 'boolean', required: true },
|
|
2380
|
+
checks: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
2381
|
+
},
|
|
2382
|
+
},
|
|
2383
|
+
render: (_args, value) => {
|
|
2384
|
+
const rows = value.checks as ProbeRow[]
|
|
2385
|
+
const lines = rows.map(row => `${row.pass === true ? 'PASS' : 'FAIL'} ${String(row.kind)}: ${String(row.expected)} → ${String(row.actual)}`)
|
|
2386
|
+
return [{ type: 'text', text: `${value.pass === true ? 'All checks passed.' : 'A check failed.'}\n${lines.join('\n')}` }]
|
|
2387
|
+
},
|
|
2388
|
+
},
|
|
2389
|
+
timeoutMs,
|
|
2390
|
+
isConcurrencySafe: () => true,
|
|
2391
|
+
async execute(args, exec) {
|
|
2392
|
+
const browser = ctx.get('browser')
|
|
2393
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2394
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2395
|
+
await installProbe(browser, session, exec.signal)
|
|
2396
|
+
const spec = {
|
|
2397
|
+
...args.selector !== undefined ? { selector: args.selector } : {},
|
|
2398
|
+
...args.text !== undefined ? { text: args.text } : {},
|
|
2399
|
+
...args.url !== undefined ? { url: args.url } : {},
|
|
2400
|
+
...args.js !== undefined ? { js: args.js } : {},
|
|
2401
|
+
}
|
|
2402
|
+
if (Object.keys(spec).length === 0) throw new Error('dsh_browser_assert: give at least one of selector, text, url or js')
|
|
2403
|
+
return await runChecks(browser, session, spec, exec.signal)
|
|
2404
|
+
},
|
|
2405
|
+
}))
|
|
2406
|
+
|
|
2407
|
+
registerSafely(defineTool({
|
|
2408
|
+
name: 'dsh_browser_drag',
|
|
2409
|
+
description: 'Drag from one viewport point to another using trusted browser pointer input. Coordinates are CSS pixels from the top-left of the current viewport. Use for sliders, sortable lists, HTML drag-and-drop and canvas drawing. Check the resulting control value or page state after the gesture.',
|
|
2410
|
+
parameters: {
|
|
2411
|
+
fromX: { type: 'number', required: true, description: 'Start x in viewport CSS pixels.' },
|
|
2412
|
+
fromY: { type: 'number', required: true, description: 'Start y in viewport CSS pixels.' },
|
|
2413
|
+
toX: { type: 'number', required: true, description: 'End x.' },
|
|
2414
|
+
toY: { type: 'number', required: true, description: 'End y.' },
|
|
2415
|
+
steps: { type: 'number', description: 'Intermediate moves (default 12, max 60); more steps make a slider follow the path.' },
|
|
2416
|
+
},
|
|
2417
|
+
output: {
|
|
2418
|
+
schema: {
|
|
2419
|
+
type: 'object',
|
|
2420
|
+
additionalProperties: false,
|
|
2421
|
+
properties: {
|
|
2422
|
+
ok: { type: 'boolean', required: true },
|
|
2423
|
+
reason: { type: 'string', required: true },
|
|
2424
|
+
},
|
|
2425
|
+
},
|
|
2426
|
+
render: (_args, value) => [{ type: 'text', text: value.ok === true ? 'Dragged.' : `Drag failed: ${String(value.reason)}` }],
|
|
2427
|
+
},
|
|
2428
|
+
timeoutMs,
|
|
2429
|
+
isConcurrencySafe: () => false, // a pointer gesture; exclusive within a task
|
|
2430
|
+
async execute(args, exec) {
|
|
2431
|
+
assertAllowed(state, 'dsh_browser_drag', taskKey(exec))
|
|
2432
|
+
const browser = ctx.get('browser')
|
|
2433
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2434
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2435
|
+
const text = await pageOperationValue(browser, session, {
|
|
2436
|
+
operation: 'drag',
|
|
2437
|
+
from: { x: args.fromX, y: args.fromY },
|
|
2438
|
+
to: { x: args.toX, y: args.toY },
|
|
2439
|
+
steps: args.steps ?? 12,
|
|
2440
|
+
}, exec.signal)
|
|
2441
|
+
const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; moved?: number }
|
|
2442
|
+
return { ok: parsed.ok === true, reason: parsed.ok === true ? `moved ${String(parsed.moved)} steps` : String(parsed.reason ?? 'unknown') }
|
|
2443
|
+
},
|
|
2444
|
+
}))
|
|
2445
|
+
|
|
2446
|
+
registerSafely(defineTool({
|
|
2447
|
+
name: 'dsh_browser_doctor',
|
|
2448
|
+
description: 'Report the state of this task\'s browser: page URL, which tools the task restricted away, whether the page probe is installed, and what it has recorded (console lines, responses, dialogs, and how "settled" the page looks). Use it when something behaves oddly and the cause is not visible in the page — before guessing, or before telling the user the browser is broken.',
|
|
2449
|
+
parameters: {},
|
|
2450
|
+
output: {
|
|
2451
|
+
schema: { type: 'object', additionalProperties: false, properties: { report: { type: 'string', required: true } } },
|
|
2452
|
+
render: (_args, value) => [{ type: 'text', text: String(value.report) }],
|
|
2453
|
+
},
|
|
2454
|
+
timeoutMs,
|
|
2455
|
+
isConcurrencySafe: () => true,
|
|
2456
|
+
async execute(_args, exec) {
|
|
2457
|
+
const browser = ctx.get('browser')
|
|
2458
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2459
|
+
const task = taskKey(exec)
|
|
2460
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2461
|
+
await installProbe(browser, session, exec.signal)
|
|
2462
|
+
const url = await pageOperationValue(browser, session, { operation: 'url' }, exec.signal).then(text => text.replace(/^"|"$/g, ''))
|
|
2463
|
+
const settle = await probe<{ pending?: number; quietMs?: number; readyState?: string }>(browser, session, 'settle', [], exec.signal)
|
|
2464
|
+
const consoleRows = await probe<unknown[]>(browser, session, 'read', ['console', '', 100], exec.signal)
|
|
2465
|
+
const networkRows = await probe<unknown[]>(browser, session, 'read', ['network', '', 100], exec.signal)
|
|
2466
|
+
const dialogRows = await probe<ProbeRow[]>(browser, session, 'read', ['dialogs', '', 5], exec.signal)
|
|
2467
|
+
const restricted = state.restrictedByTask.get(task)
|
|
2468
|
+
const lines = [
|
|
2469
|
+
`session ${session}`,
|
|
2470
|
+
`url ${url || '(unknown)'}`,
|
|
2471
|
+
`page ${String(settle?.readyState ?? '?')}, ${String(settle?.pending ?? 0)} request(s) in flight, quiet for ${String(settle?.quietMs ?? 0)}ms`,
|
|
2472
|
+
`probe installed (console ${consoleRows.length}/100, network ${networkRows.length}/100, dialogs ${dialogRows.length}/5)`,
|
|
2473
|
+
restricted === undefined ? 'restricted: no (this task restricted nothing)' : `restricted: ${restricted.length === 0 ? 'everything' : restricted.join(', ')}`,
|
|
2474
|
+
state.configRestrictedTo === undefined ? 'deployment allow-list: none' : `deployment allow-list: ${state.configRestrictedTo.join(', ')}`,
|
|
2475
|
+
]
|
|
2476
|
+
return { report: lines.join('\n') }
|
|
2477
|
+
},
|
|
2478
|
+
}))
|
|
2479
|
+
|
|
2480
|
+
registerSafely(defineTool({
|
|
2481
|
+
name: 'dsh_browser_help',
|
|
2482
|
+
description: 'Look up how to use this browser: a short topic index (locate, wait, batch, dialogs, network, verify, recovery, limits) or one topic\'s text. Use it instead of guessing when a call failed for a reason the error message explains only briefly.',
|
|
2483
|
+
parameters: {
|
|
2484
|
+
topic: { type: 'string', description: 'One topic name; omit for the index.' },
|
|
2485
|
+
},
|
|
2486
|
+
output: {
|
|
2487
|
+
schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
|
|
2488
|
+
render: (_args, value) => [{ type: 'text', text: String(value.text) }],
|
|
2489
|
+
},
|
|
2490
|
+
timeoutMs,
|
|
2491
|
+
isConcurrencySafe: () => true,
|
|
2492
|
+
async execute(args) {
|
|
2493
|
+
const topics: Record<string, string> = {
|
|
2494
|
+
locate: 'Prefer dsh_browser_a11y (roles, names, states) or dsh_browser_snapshot (numbered elements), then click with {target:{by:"text"|css|xpath, value}}. Elements carry a stable CSS selector, so a click re-resolves the element instead of trusting an index that a re-render invalidates.',
|
|
2495
|
+
wait: 'dsh_browser_wait waits for load + an optional URL/selector. dsh_browser_wait_for_response waits for a server answer (that is the "did it submit" wait). dsh_browser_console/network then explain what the page did.',
|
|
2496
|
+
batch: 'dsh_browser_do runs several steps in one call: open/tap/field/type/key/scroll/sleep_ms/wait_text/wait_gone/wait_url/wait_idle/eval/check. It stops at the first step that cannot proceed and reports which one; a tap whose target is covered by a cookie banner dismisses the banner first.',
|
|
2497
|
+
dialogs: 'JavaScript dialogs are answered automatically (default: dismiss). dsh_browser_dialog reports them and can switch to "accept". A dialog from the browser itself (beforeunload, HTTP auth) is not covered — expect a stalled call there and reload.',
|
|
2498
|
+
network: 'dsh_browser_network lists fetch/XHR/resource rows. Status 0 means the page never saw a status (aborted, blocked, or a resource-timing row). Only fetch/XHR rows carry a real status.',
|
|
2499
|
+
verify: 'dsh_browser_assert asserts selector/text/url/js and returns evidence per assertion. Prefer it over reading a screenshot: "clicked" and "the form accepted it" are different claims, and a retry of an unverified submit can double it.',
|
|
2500
|
+
recovery: 'dsh_browser_reset_session closes this task\'s browser session without touching others. dsh_browser_refresh reloads the page. If a carrier was lost, the page context is gone: re-read the page before continuing, and never re-submit something whose result you did not verify.',
|
|
2501
|
+
limits: 'There is no CDP escape hatch and no network interception: the probe sees what the page sees. Downloads go through dsh_browser_download and a directory admission gate. Executing page JavaScript is a settings switch the model cannot lift.',
|
|
2502
|
+
deliver: 'The browser saves a file and returns an absolute path; sending it to Feishu drive, Baidu Netdisk or any MCP-connected storage is a separate tool call with that path. Report where it sits locally AND what the upload tool answered, never just one. If the upload tool is missing or fails, keep the local file and say so — do not retry somewhere else silently.',
|
|
2503
|
+
}
|
|
2504
|
+
if (args.topic === undefined) {
|
|
2505
|
+
return { text: `Topics: ${Object.keys(topics).join(', ')}\nAsk for one with topic=<name>.` }
|
|
2506
|
+
}
|
|
2507
|
+
const text = topics[args.topic]
|
|
2508
|
+
if (text === undefined) throw new Error(`dsh_browser_help: unknown topic "${args.topic}" (${Object.keys(topics).join(', ')})`)
|
|
2509
|
+
return { text }
|
|
2510
|
+
},
|
|
2511
|
+
}))
|
|
2512
|
+
|
|
2513
|
+
registerSafely(defineTool({
|
|
2514
|
+
name: 'dsh_browser_do',
|
|
2515
|
+
description: 'Run several steps in ONE call and report one compact result: "click search, type a query, press Enter, wait for results" is one call instead of five. Steps run in order and stop at the first that cannot proceed. Each step is an object with exactly one key: open {url} | tap {target} | field {target, text} | type {text} | key {key} | scroll {deltaY} | sleep_ms {ms} | wait_text {text} | wait_gone {text} | wait_url {url} | wait_idle {} | eval {script} | check {selector|text|url|js}. A tap whose target is covered by a cookie banner or modal dismisses it first. Waits know when the page has settled and return as soon as the condition holds.',
|
|
2516
|
+
parameters: {
|
|
2517
|
+
steps: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true, description: 'Steps, in order (max 40).' },
|
|
2518
|
+
timeoutMs: { type: 'number', description: 'Budget for the whole batch (default 60000, capped by the tool timeout).' },
|
|
2519
|
+
autoDismiss: { type: 'boolean', description: 'Clear a covering banner before a tap (default true).' },
|
|
2520
|
+
},
|
|
2521
|
+
output: {
|
|
2522
|
+
schema: {
|
|
2523
|
+
type: 'object',
|
|
2524
|
+
additionalProperties: false,
|
|
2525
|
+
properties: {
|
|
2526
|
+
completed: { type: 'number', required: true },
|
|
2527
|
+
total: { type: 'number', required: true },
|
|
2528
|
+
ok: { type: 'boolean', required: true },
|
|
2529
|
+
stoppedAt: { type: 'number' },
|
|
2530
|
+
reason: { type: 'string' },
|
|
2531
|
+
sideEffectMayHaveHappened: { type: 'boolean' },
|
|
2532
|
+
log: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
2533
|
+
},
|
|
2534
|
+
},
|
|
2535
|
+
render: (_args, value) => {
|
|
2536
|
+
const rows = value.log as ProbeRow[]
|
|
2537
|
+
const head = value.ok === true
|
|
2538
|
+
? `${String(value.completed)}/${String(value.total)} steps done.`
|
|
2539
|
+
: `Stopped at step ${String(value.stoppedAt)} (${String(value.completed)}/${String(value.total)} done): ${String(value.reason)}`
|
|
2540
|
+
const warning = value.ok === false && value.sideEffectMayHaveHappened === true
|
|
2541
|
+
? '\nA step that can change the page already ran: the site may have acted on it. Read the site\'s own record before retrying — do not repeat it on the assumption that it failed.'
|
|
2542
|
+
: ''
|
|
2543
|
+
return [{ type: 'text', text: [head + warning, ...rows.map(row => ` ${String(row.index)} ${String(row.kind)}: ${String(row.detail)}`)].join('\n') }]
|
|
2544
|
+
},
|
|
2545
|
+
},
|
|
2546
|
+
timeoutMs,
|
|
2547
|
+
isConcurrencySafe: () => false, // drives the page; exclusive within a task
|
|
2548
|
+
async execute(args, exec) {
|
|
2549
|
+
assertAllowed(state, 'dsh_browser_do', taskKey(exec))
|
|
2550
|
+
const browser = ctx.get('browser')
|
|
2551
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2552
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2553
|
+
const steps = Array.isArray(args.steps) ? args.steps as ProbeRow[] : []
|
|
2554
|
+
if (steps.length === 0) throw new Error('dsh_browser_do: "steps" must be a non-empty array')
|
|
2555
|
+
if (steps.length > 40) throw new Error('dsh_browser_do: at most 40 steps per call — split the work')
|
|
2556
|
+
await installProbe(browser, session, exec.signal)
|
|
2557
|
+
const autoDismiss = args.autoDismiss !== false
|
|
2558
|
+
const budget = Math.min(args.timeoutMs ?? timeoutMs, maxWaitMs)
|
|
2559
|
+
const deadline = Date.now() + budget
|
|
2560
|
+
const log: Array<{ index: number; kind: string; detail: string }> = []
|
|
2561
|
+
// Set once a step that can change server state has run. A failure after that point must not
|
|
2562
|
+
// read like a failure before it: measured on the first real benchmark run, where a batch died
|
|
2563
|
+
// after the form had already been submitted and the message said nothing about it.
|
|
2564
|
+
let dispatched = false
|
|
2565
|
+
const dispatchable = new Set(['tap', 'key', 'eval'])
|
|
2566
|
+
const kinds = ['open', 'tap', 'field', 'type', 'key', 'scroll', 'sleep_ms', 'wait_text', 'wait_gone', 'wait_url', 'wait_idle', 'eval', 'check']
|
|
2567
|
+
|
|
2568
|
+
/** Resolve a target: a string is visible text; an object passes through. */
|
|
2569
|
+
const asTarget = (value: unknown): { by: 'css' | 'text' | 'xpath'; value: string } | undefined => {
|
|
2570
|
+
if (typeof value === 'string' && value !== '') return { by: 'text', value }
|
|
2571
|
+
if (value !== null && typeof value === 'object') {
|
|
2572
|
+
const raw = value as { by?: unknown; value?: unknown }
|
|
2573
|
+
if (typeof raw.value === 'string' && raw.value !== '') {
|
|
2574
|
+
const by = raw.by === 'css' || raw.by === 'xpath' || raw.by === 'text' ? raw.by : 'text'
|
|
2575
|
+
return { by, value: raw.value }
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
return undefined
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
for (let index = 0; index < steps.length; index += 1) {
|
|
2582
|
+
const step = steps[index] ?? {}
|
|
2583
|
+
const keys = Object.keys(step).filter(key => kinds.includes(key))
|
|
2584
|
+
if (keys.length !== 1) {
|
|
2585
|
+
return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `step ${index + 1} must have exactly one of: ${kinds.join(', ')}`, log }
|
|
2586
|
+
}
|
|
2587
|
+
const kind = keys[0] as string
|
|
2588
|
+
const value = step[kind]
|
|
2589
|
+
if (Date.now() > deadline) {
|
|
2590
|
+
return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `budget of ${Math.round(budget / 1000)}s exhausted`, log }
|
|
2591
|
+
}
|
|
2592
|
+
try {
|
|
2593
|
+
let detail = 'ok'
|
|
2594
|
+
if (kind === 'open') {
|
|
2595
|
+
const url = typeof value === 'string' ? value : (value as { url?: unknown })?.url
|
|
2596
|
+
if (typeof url !== 'string') throw new Error('open needs a URL string or {url}')
|
|
2597
|
+
await browser.openUrl(session, { url }, exec.signal)
|
|
2598
|
+
detail = url
|
|
2599
|
+
} else if (kind === 'tap') {
|
|
2600
|
+
const target = asTarget((value as { target?: unknown })?.target ?? value)
|
|
2601
|
+
if (target === undefined) throw new Error('tap needs a target (text, or {by, value})')
|
|
2602
|
+
if (autoDismiss) {
|
|
2603
|
+
const rect = await probeLive<{ x?: number; y?: number; described?: string } | null>(browser, session, 'find', [{ [target.by]: target.value }], exec.signal)
|
|
2604
|
+
if (rect && typeof rect.x === 'number' && typeof rect.y === 'number') {
|
|
2605
|
+
const cover = await probeLive<{ covers?: string | null; dismiss?: { label?: string; x?: number; y?: number } | null }>(browser, session, 'overlayAt', [rect.x, rect.y], exec.signal)
|
|
2606
|
+
if (cover?.dismiss && typeof cover.dismiss.x === 'number' && typeof cover.dismiss.y === 'number') {
|
|
2607
|
+
await browser.click(session, { x: cover.dismiss.x, y: cover.dismiss.y }, exec.signal)
|
|
2608
|
+
detail = `dismissed "${String(cover.dismiss.label)}" first`
|
|
2609
|
+
await pause(150)
|
|
2610
|
+
} else if (cover?.covers !== null && cover?.covers !== undefined && cover.covers !== rect.described) {
|
|
2611
|
+
// Measured on the fixture's human gate: a hidden form left the tap hitting `<html>`,
|
|
2612
|
+
// the step reported "ok", and nothing was submitted. A click that cannot land is a
|
|
2613
|
+
// FAILURE, not a note — a silent no-op is the worst result this tool can return.
|
|
2614
|
+
throw new Error(`the target is not reachable: ${String(cover.covers)} is at that point, not ${String(rect.described)} (hidden, or covered by an overlay that cannot be dismissed)`)
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
await browser.click(session, { target }, exec.signal)
|
|
2619
|
+
} else if (kind === 'field') {
|
|
2620
|
+
const spec = value as { target?: unknown; text?: unknown }
|
|
2621
|
+
const target = asTarget(spec?.target)
|
|
2622
|
+
if (target === undefined || typeof spec?.text !== 'string') throw new Error('field needs {target, text}')
|
|
2623
|
+
await browser.setValue(session, { target, value: spec.text }, exec.signal)
|
|
2624
|
+
detail = `${target.value} ← ${spec.text.slice(0, 40)}`
|
|
2625
|
+
} else if (kind === 'type') {
|
|
2626
|
+
const text = typeof value === 'string' ? value : (value as { text?: unknown })?.text
|
|
2627
|
+
if (typeof text !== 'string') throw new Error('type needs a text string or {text}')
|
|
2628
|
+
await browser.type(session, { text }, exec.signal)
|
|
2629
|
+
detail = text.slice(0, 40)
|
|
2630
|
+
} else if (kind === 'key') {
|
|
2631
|
+
const key = typeof value === 'string' ? value : (value as { key?: unknown })?.key
|
|
2632
|
+
if (typeof key !== 'string') throw new Error('key needs a key name or {key}')
|
|
2633
|
+
await browser.key(session, { key: key as never }, exec.signal)
|
|
2634
|
+
detail = key
|
|
2635
|
+
} else if (kind === 'scroll') {
|
|
2636
|
+
const deltaY = typeof value === 'number' ? value : Number((value as { deltaY?: unknown })?.deltaY ?? Number.NaN)
|
|
2637
|
+
if (!Number.isFinite(deltaY)) throw new Error('scroll needs a number or {deltaY}')
|
|
2638
|
+
await browser.scroll(session, { deltaY }, exec.signal)
|
|
2639
|
+
detail = String(deltaY)
|
|
2640
|
+
} else if (kind === 'sleep_ms') {
|
|
2641
|
+
const requestedMs = typeof value === 'number' ? value : (value as { ms?: unknown })?.ms
|
|
2642
|
+
if (typeof requestedMs !== 'number' || !Number.isFinite(requestedMs) || requestedMs < 0) throw new Error('sleep_ms needs a non-negative number or {ms}')
|
|
2643
|
+
const ms = Math.min(requestedMs, 10_000)
|
|
2644
|
+
await pause(ms)
|
|
2645
|
+
detail = `${ms}ms`
|
|
2646
|
+
} else if (kind === 'wait_text' || kind === 'wait_gone') {
|
|
2647
|
+
const want = typeof value === 'string' ? value : (value as { text?: unknown })?.text
|
|
2648
|
+
if (typeof want !== 'string') throw new Error('wait_text/wait_gone need text or {text}')
|
|
2649
|
+
const found = await poll(async () => {
|
|
2650
|
+
const present = (await pageOperationValue(browser, session, { operation: 'text', text: want }, exec.signal)) === 'true'
|
|
2651
|
+
return (kind === 'wait_text' ? present : !present) ? true : undefined
|
|
2652
|
+
}, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)))
|
|
2653
|
+
if (found === undefined) throw new Error(`timed out waiting for "${want}" to be ${kind === 'wait_text' ? 'present' : 'gone'}`)
|
|
2654
|
+
detail = want
|
|
2655
|
+
} else if (kind === 'wait_url') {
|
|
2656
|
+
const want = typeof value === 'string' ? value : (value as { url?: unknown })?.url
|
|
2657
|
+
if (typeof want !== 'string') throw new Error('wait_url needs a URL fragment or {url}')
|
|
2658
|
+
const budget = Math.max(1_000, Math.min(deadline - Date.now(), 30_000))
|
|
2659
|
+
const hit = await poll(async () => {
|
|
2660
|
+
const href = (await pageOperationValue(browser, session, { operation: 'url' }, exec.signal)).replace(/^"|"$/g, '')
|
|
2661
|
+
return href.includes(want) ? href : undefined
|
|
2662
|
+
}, budget)
|
|
2663
|
+
if (hit === undefined) throw new Error(`timed out waiting for the URL to contain "${want}"`)
|
|
2664
|
+
detail = hit
|
|
2665
|
+
} else if (kind === 'wait_idle') {
|
|
2666
|
+
const idle = await poll(async () => {
|
|
2667
|
+
const settle = await probeLive<{ pending?: number; quietMs?: number; readyState?: string }>(browser, session, 'settle', [], exec.signal)
|
|
2668
|
+
const quiet = Number(settle?.quietMs ?? 0)
|
|
2669
|
+
return Number(settle?.pending ?? 0) === 0 && quiet >= 300 ? settle : undefined
|
|
2670
|
+
}, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)))
|
|
2671
|
+
if (idle === undefined) throw new Error('timed out waiting for the page to go quiet')
|
|
2672
|
+
detail = `quiet for ${String(idle.quietMs)}ms`
|
|
2673
|
+
} else if (kind === 'eval') {
|
|
2674
|
+
const script = typeof value === 'string' ? value : (value as { script?: unknown })?.script
|
|
2675
|
+
if (typeof script !== 'string') throw new Error('eval needs a script string or {script}')
|
|
2676
|
+
const text = await pageValue(browser, session, script, exec.signal)
|
|
2677
|
+
detail = text.slice(0, 80)
|
|
2678
|
+
} else if (kind === 'check') {
|
|
2679
|
+
const result = await runChecks(browser, session, value as { selector?: string; text?: string; url?: string; js?: string }, exec.signal)
|
|
2680
|
+
if (!result.pass) {
|
|
2681
|
+
const failed = result.checks.filter(check => !check.pass).map(check => `${check.kind}: ${check.expected} → ${check.actual}`)
|
|
2682
|
+
throw new Error(`check failed (${failed.join('; ')})`)
|
|
2683
|
+
}
|
|
2684
|
+
detail = `${result.checks.length} check(s) passed`
|
|
2685
|
+
}
|
|
2686
|
+
if (dispatchable.has(kind)) dispatched = true
|
|
2687
|
+
log.push({ index: index + 1, kind, detail })
|
|
2688
|
+
} catch (error) {
|
|
2689
|
+
return {
|
|
2690
|
+
ok: false,
|
|
2691
|
+
completed: index,
|
|
2692
|
+
total: steps.length,
|
|
2693
|
+
stoppedAt: index + 1,
|
|
2694
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
2695
|
+
sideEffectMayHaveHappened: dispatched,
|
|
2696
|
+
log: [...log, { index: index + 1, kind, detail: `failed: ${error instanceof Error ? error.message : String(error)}` }],
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
return { ok: true, completed: steps.length, total: steps.length, log }
|
|
2701
|
+
},
|
|
2702
|
+
}))
|
|
2703
|
+
registerSafely(defineTool({
|
|
2704
|
+
name: 'dsh_browser_upload',
|
|
2705
|
+
description: 'Put a local file into a file input on the page (attachment, avatar, import form). The path must be a file INSIDE the current workspace, and only the bytes of that one file are read. The file is rebuilt in the page as a File and attached through a DataTransfer, so a form that reads input.files and a drop handler both see it; the change event is fired for you. Oversized files are refused rather than truncated.',
|
|
2706
|
+
parameters: {
|
|
2707
|
+
target: { type: 'object', required: true, additionalProperties: true, description: 'The input: {by: "css"|"text"|"xpath", value} — a text target is resolved to the element at that point and then to a nested input[type=file].' },
|
|
2708
|
+
path: { type: 'string', required: true, description: 'Absolute path of a file inside the workspace.' },
|
|
2709
|
+
mime: { type: 'string', description: 'MIME type (default guessed from the extension, else application/octet-stream).' },
|
|
2710
|
+
},
|
|
2711
|
+
output: {
|
|
2712
|
+
schema: {
|
|
2713
|
+
type: 'object',
|
|
2714
|
+
additionalProperties: false,
|
|
2715
|
+
properties: {
|
|
2716
|
+
ok: { type: 'boolean', required: true },
|
|
2717
|
+
name: { type: 'string' },
|
|
2718
|
+
size: { type: 'number' },
|
|
2719
|
+
reason: { type: 'string' },
|
|
2720
|
+
},
|
|
2721
|
+
},
|
|
2722
|
+
render: (_args, value) => [{ type: 'text', text: value.ok === true ? `Attached ${String(value.name)} (${String(value.size)} bytes).` : `Upload failed: ${String(value.reason)}` }],
|
|
2723
|
+
},
|
|
2724
|
+
timeoutMs,
|
|
2725
|
+
isConcurrencySafe: () => false,
|
|
2726
|
+
async execute(args, exec) {
|
|
2727
|
+
assertAllowed(state, 'dsh_browser_upload', taskKey(exec))
|
|
2728
|
+
const browser = ctx.get('browser')
|
|
2729
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2730
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2731
|
+
const target = args.target as { by?: unknown; value?: unknown }
|
|
2732
|
+
const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
|
|
2733
|
+
if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_upload: target.value is required')
|
|
2734
|
+
const { open, realpath, stat } = await import('node:fs/promises')
|
|
2735
|
+
const { resolve, relative, isAbsolute, extname, basename, sep } = await import('node:path')
|
|
2736
|
+
if (!isAbsolute(args.path)) throw new Error('dsh_browser_upload: path must be absolute')
|
|
2737
|
+
const agent = agentOf(exec) as (ExecAgent & { session?: { header?: { cwd?: string } } }) | undefined
|
|
2738
|
+
const directory = (agent?.ctx?.get?.('workingDirectory') ?? ctx.get('workingDirectory')) as {
|
|
2739
|
+
ensure(agent: unknown, signal?: AbortSignal): Promise<string>
|
|
2740
|
+
} | undefined
|
|
2741
|
+
const workspacePath = directory && agent
|
|
2742
|
+
? await directory.ensure(agent, exec.signal)
|
|
2743
|
+
: agent?.session?.header?.cwd ?? process.cwd()
|
|
2744
|
+
if (!isAbsolute(workspacePath)) throw new Error('dsh_browser_upload: the task workspace must be absolute')
|
|
2745
|
+
const workspace = await realpath(workspacePath)
|
|
2746
|
+
const resolved = await realpath(resolve(args.path))
|
|
2747
|
+
const offset = relative(workspace, resolved)
|
|
2748
|
+
if (offset === '..' || offset.startsWith('..' + sep) || isAbsolute(offset)) {
|
|
2749
|
+
throw new Error('dsh_browser_upload: refusing to read a file outside the task workspace')
|
|
2750
|
+
}
|
|
2751
|
+
const expected = await stat(resolved)
|
|
2752
|
+
const LIMIT = 20 * 1024 * 1024
|
|
2753
|
+
if (!expected.isFile()) throw new Error('dsh_browser_upload: path must name a regular file')
|
|
2754
|
+
if (expected.size > LIMIT) throw new Error('dsh_browser_upload: file is over the 20 MB limit')
|
|
2755
|
+
const file = await open(resolved, 'r')
|
|
2756
|
+
let bytes: Buffer
|
|
2757
|
+
try {
|
|
2758
|
+
const opened = await file.stat()
|
|
2759
|
+
if (opened.dev !== expected.dev || opened.ino !== expected.ino
|
|
2760
|
+
|| opened.size !== expected.size || !opened.isFile()
|
|
2761
|
+
|| await realpath(resolve(args.path)) !== resolved) {
|
|
2762
|
+
throw new Error('dsh_browser_upload: file changed while opening; retry')
|
|
2763
|
+
}
|
|
2764
|
+
const chunks: Buffer[] = []
|
|
2765
|
+
let length = 0
|
|
2766
|
+
for await (const chunk of file.createReadStream({ autoClose: false, start: 0, end: LIMIT, signal: exec.signal })) {
|
|
2767
|
+
length += chunk.length
|
|
2768
|
+
if (length > LIMIT) throw new Error('dsh_browser_upload: file grew over the 20 MB limit')
|
|
2769
|
+
chunks.push(chunk as Buffer)
|
|
2770
|
+
}
|
|
2771
|
+
const after = await file.stat()
|
|
2772
|
+
if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || length !== opened.size
|
|
2773
|
+
|| await realpath(resolve(args.path)) !== resolved) {
|
|
2774
|
+
throw new Error('dsh_browser_upload: file changed while reading; retry')
|
|
2775
|
+
}
|
|
2776
|
+
bytes = Buffer.concat(chunks, length)
|
|
2777
|
+
} finally {
|
|
2778
|
+
await file.close()
|
|
2779
|
+
}
|
|
2780
|
+
const guess: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.pdf': 'application/pdf', '.txt': 'text/plain', '.csv': 'text/csv', '.json': 'application/json', '.zip': 'application/zip' }
|
|
2781
|
+
const mime = args.mime ?? guess[extname(resolved).toLowerCase()] ?? 'application/octet-stream'
|
|
2782
|
+
await installProbe(browser, session, exec.signal)
|
|
2783
|
+
const text = await pageOperationValue(browser, session, {
|
|
2784
|
+
operation: 'upload',
|
|
2785
|
+
target: { by, value: target.value },
|
|
2786
|
+
file: { name: basename(resolved), mime, base64: bytes.toString('base64') },
|
|
2787
|
+
}, exec.signal)
|
|
2788
|
+
const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; name?: string; size?: number }
|
|
2789
|
+
return parsed.ok === true
|
|
2790
|
+
? { ok: true, name: String(parsed.name ?? ''), size: Number(parsed.size ?? 0) }
|
|
2791
|
+
: { ok: false, reason: String(parsed.reason ?? 'unknown') }
|
|
2792
|
+
},
|
|
2793
|
+
}))
|
|
2794
|
+
|
|
2795
|
+
registerSafely(defineTool({
|
|
2796
|
+
name: 'dsh_browser_hover',
|
|
2797
|
+
description: 'Scroll an element into view and move the browser pointer to its centre. Supports CSS hover styles and JavaScript mouseover handlers. Use before reading or clicking a hover menu.',
|
|
2798
|
+
parameters: {
|
|
2799
|
+
target: { type: 'object', required: true, additionalProperties: true, description: 'The element: {by: "css"|"text"|"xpath", value}.' },
|
|
2800
|
+
settleMs: { type: 'number', description: 'How long to let the menu appear before returning (default 150).' },
|
|
2801
|
+
},
|
|
2802
|
+
output: {
|
|
2803
|
+
schema: { type: 'object', additionalProperties: false, properties: { hovered: { type: 'boolean', required: true }, at: { type: 'object', additionalProperties: true } } },
|
|
2804
|
+
render: (_args, value) => [{ type: 'text', text: value.hovered === true ? 'Pointer moved over the element.' : 'No element at that target.' }],
|
|
2805
|
+
},
|
|
2806
|
+
timeoutMs,
|
|
2807
|
+
isConcurrencySafe: () => false,
|
|
2808
|
+
async execute(args, exec) {
|
|
2809
|
+
assertAllowed(state, 'dsh_browser_hover', taskKey(exec))
|
|
2810
|
+
const browser = ctx.get('browser')
|
|
2811
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2812
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2813
|
+
const target = args.target as { by?: unknown; value?: unknown }
|
|
2814
|
+
const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
|
|
2815
|
+
if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_hover: target.value is required')
|
|
2816
|
+
await installProbe(browser, session, exec.signal)
|
|
2817
|
+
const where = await probe<{ x?: number; y?: number; described?: string } | null>(browser, session, 'find', [{ [by]: target.value }, true], exec.signal)
|
|
2818
|
+
if (!where || typeof where.x !== 'number' || typeof where.y !== 'number') return { hovered: false, at: {} as ProbeRow }
|
|
2819
|
+
const fired = await probe<boolean>(browser, session, 'hoverAt', [where.x, where.y], exec.signal)
|
|
2820
|
+
await pause(Math.min(args.settleMs ?? 150, 2_000))
|
|
2821
|
+
const at: ProbeRow = { x: where.x, y: where.y, described: String(where.described ?? '') }
|
|
2822
|
+
return { hovered: fired === true, at }
|
|
2823
|
+
},
|
|
2824
|
+
}))
|
|
2825
|
+
|
|
2826
|
+
registerSafely(defineTool({
|
|
2827
|
+
name: 'dsh_browser_find',
|
|
2828
|
+
description: 'Find text on the page (the Ctrl+F equivalent) and get its position, so you can scroll to it or click near it without reading the whole page first. Returns up to 5 hits (all:true for up to 50), each with the surrounding snippet and the viewport point. Text inside shadow roots and iframes is not searched.',
|
|
2829
|
+
parameters: {
|
|
2830
|
+
text: { type: 'string', required: true, description: 'Text to look for (case-insensitive).' },
|
|
2831
|
+
all: { type: 'boolean', description: 'Return up to 50 hits instead of 5.' },
|
|
2832
|
+
},
|
|
2833
|
+
output: {
|
|
2834
|
+
schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true }, hits: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } } },
|
|
2835
|
+
render: (_args, value) => {
|
|
2836
|
+
const hits = value.hits as ProbeRow[]
|
|
2837
|
+
if (hits.length === 0) return [{ type: 'text', text: 'Not found on the page.' }]
|
|
2838
|
+
return [{ type: 'text', text: [`${hits.length} hit(s):`, ...hits.map((hit, index) => ` ${index + 1}. ${String(hit.text)} @ ${String(hit.x)},${String(hit.y)}`)] .join('\n') }]
|
|
2839
|
+
},
|
|
2840
|
+
},
|
|
2841
|
+
timeoutMs,
|
|
2842
|
+
isConcurrencySafe: () => true,
|
|
2843
|
+
async execute(args, exec) {
|
|
2844
|
+
const browser = ctx.get('browser')
|
|
2845
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2846
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2847
|
+
await installProbe(browser, session, exec.signal)
|
|
2848
|
+
const hits = await probe<ProbeRow[]>(browser, session, 'findText', [args.text, args.all === true], exec.signal)
|
|
2849
|
+
return { count: hits.length, hits }
|
|
2850
|
+
},
|
|
2851
|
+
}))
|
|
2852
|
+
|
|
2853
|
+
registerSafely(defineTool({
|
|
2854
|
+
name: 'dsh_browser_state',
|
|
2855
|
+
description: 'One compact answer to "what is on screen": URL, title, load state, requests still in flight and how long the page has been quiet, plus the counts of inputs/buttons/links, scroll position, current selection and the first 400 characters of visible text. Use it before a full snapshot when you only need to know where you are, and after an action to see whether the page moved at all.',
|
|
2856
|
+
parameters: {},
|
|
2857
|
+
output: {
|
|
2858
|
+
schema: {
|
|
2859
|
+
type: 'object',
|
|
2860
|
+
additionalProperties: false,
|
|
2861
|
+
properties: { summary: { type: 'object', additionalProperties: true, required: true } },
|
|
2862
|
+
},
|
|
2863
|
+
render: (_args, value) => {
|
|
2864
|
+
const row = value.summary as ProbeRow
|
|
2865
|
+
return [{ type: 'text', text: [
|
|
2866
|
+
`${String(row.url)}`,
|
|
2867
|
+
`${String(row.title)}`,
|
|
2868
|
+
`${String(row.readyState)}, ${String(row.pending)} in flight, quiet ${String(row.quietMs)}ms`,
|
|
2869
|
+
`${String(row.inputs)} input(s), ${String(row.buttons)} button(s), ${String(row.links)} link(s), scroll ${String(row.scrollY)}`,
|
|
2870
|
+
row.selection ? `selection: ${String(row.selection)}` : 'no selection',
|
|
2871
|
+
String(row.text ?? ''),
|
|
2872
|
+
].join('\n') }]
|
|
2873
|
+
},
|
|
2874
|
+
},
|
|
2875
|
+
timeoutMs,
|
|
2876
|
+
isConcurrencySafe: () => true,
|
|
2877
|
+
async execute(_args, exec) {
|
|
2878
|
+
const browser = ctx.get('browser')
|
|
2879
|
+
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2880
|
+
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2881
|
+
await installProbe(browser, session, exec.signal)
|
|
2882
|
+
const summary = await probe<ProbeRow>(browser, session, 'summary', [], exec.signal)
|
|
2883
|
+
return { summary }
|
|
2884
|
+
},
|
|
2885
|
+
}))
|
|
1900
2886
|
}
|
|
1901
2887
|
|
|
1902
2888
|
/** Test hook: inspect and reset session mappings across every live plugin apply. */
|
|
@@ -1914,4 +2900,3 @@ export const internals = {
|
|
|
1914
2900
|
for (const state of liveStates) state.sessionsByTask.delete(key)
|
|
1915
2901
|
},
|
|
1916
2902
|
}
|
|
1917
|
-
|