dsh-builtin-browser 1.0.1 → 1.0.4
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 +55 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/tool-reference.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- package/dsh-host-patch/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +0 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -44
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -36
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +15 -12
- package/scripts/fix-exports.mjs +6 -16
- package/scripts/install-electron.mjs +55 -5
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +26 -15
- package/skills/dsh-builtin-browser/SKILL.md +27 -2
- package/skills/dsh-builtin-browser/references/batch.md +15 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/runtime.ts +18 -0
- package/src/browser/takeover-target.ts +16 -7
- package/src/browser/types.ts +56 -3
- package/src/browser-electron/authenticated-route.ts +29 -4
- package/src/browser-electron/automatic-maintenance.ts +23 -13
- package/src/browser-electron/bridge-connection.ts +11 -10
- package/src/browser-electron/bridge-install.ts +2 -1
- package/src/browser-electron/bridge-status.ts +61 -22
- package/src/browser-electron/desktop-bridge-host.ts +9 -7
- package/src/browser-electron/desktop-identity.ts +38 -5
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/electron-provision.ts +104 -18
- package/src/browser-electron/entry.ts +1378 -1299
- package/src/browser-electron/extension-browser.ts +11 -4
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +3 -2
- package/src/browser-electron/guest-route.ts +180 -32
- package/src/browser-electron/guest-runtime.ts +61 -10
- package/src/browser-electron/guest-storage.ts +5 -2
- package/src/browser-electron/history-store.ts +3 -6
- package/src/browser-electron/host-main.ts +8 -4
- package/src/browser-electron/host-patch-maintenance.ts +18 -9
- package/src/browser-electron/maintenance-route.ts +2 -1
- package/src/browser-electron/missing-system-browser.ts +11 -10
- package/src/browser-electron/preferred-browser.ts +13 -3
- package/src/browser-electron/preview-route.ts +9 -12
- package/src/browser-electron/process-ownership.ts +9 -3
- package/src/browser-electron/profile-command.ts +2 -1
- package/src/browser-electron/profile-extension.ts +5 -0
- package/src/browser-electron/profile-lease.ts +131 -35
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +158 -4063
- package/src/browser-electron/reference-route.ts +598 -608
- package/src/browser-electron/remote-host.ts +118 -42
- package/src/browser-electron/runtime-status.ts +80 -13
- package/src/browser-electron/settings-store.ts +10 -6
- package/src/browser-electron/sidebar-only-host.ts +4 -2
- package/src/browser-electron/system-browser.ts +537 -184
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/virtual-cursor.ts +24 -14
- package/src/browser-reference/service.ts +38 -7
- package/src/browser-reference/web-sources.ts +4 -1
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +3 -3
- package/src/client/browser/IframeImpl.ts +182 -176
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/web-reference-source.ts +5 -1
- package/src/client/definition.tsx +36 -30
- package/src/client/electron/ElectronWebViewImpl.ts +20 -13
- package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
- package/src/client/electron/NativeChildPresentation.ts +11 -3
- package/src/client/electron/NativeViewPage.ts +19 -5
- package/src/client/index.ts +333 -293
- package/src/client/locales.ts +9 -6
- package/src/client/reference/client/plugin.ts +21 -2
- package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
- package/src/client/reference/client/production/assembly.ts +4 -28
- package/src/client/reference/client/production/availability.ts +0 -2
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/draft-adapter.ts +4 -0
- package/src/client/reference/client/production/http-transport.ts +0 -5
- package/src/client/reference/client/production/production-submission.ts +50 -290
- package/src/client/reference/client/production/protocol.ts +7 -4
- package/src/client/reference/client/production/runtime.ts +41 -86
- package/src/client/reference/client/production/source-marker.ts +49 -13
- package/src/client/reference/client/production/user-text-rule.ts +10 -1
- package/src/client/reference/client/reveal.ts +3 -1
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/settings/index.ts +8 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +163 -52
- package/src/client/startpage/controller.ts +3 -6
- package/src/client/view/BrowserBody.tsx +2 -1
- package/src/client/view/IframePresentation.ts +37 -16
- package/src/client/view/StartPage.tsx +2 -1
- package/src/compat/host-features.ts +92 -0
- package/src/reference-source.ts +1 -1
- package/src/reference-text.ts +23 -1
- package/src/takeover-protocol.ts +11 -2
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +173 -19
- package/src/tool-browser/code-worker.ts +101 -15
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +66 -3534
- package/src/tool-browser/page-probe.ts +229 -28
- package/src/tool-browser/panel-page.ts +3 -1
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +3 -2
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/web-guest.ts +35 -34
- package/dist/client.cjs +0 -43167
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/src/browser-reference/submission-receipts.ts +0 -122
|
@@ -1,146 +1,39 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Model-facing browser tools over `ctx.browser
|
|
3
|
-
*
|
|
4
|
-
* `
|
|
5
|
-
* `dsh_browser_switch_tab`, `dsh_browser_close_tab`, `dsh_browser_reset`).
|
|
2
|
+
* Model-facing browser tools over `ctx.browser`, assembled: config, the prompt guides, safe
|
|
3
|
+
* registration, the `core` surface's loader and the code tool. The tools live in `tools-*.ts`,
|
|
4
|
+
* their shared per-apply state in `state.ts` and the page-probe client in `probe-client.ts`.
|
|
6
5
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* to the seam. Session lifecycle is owned here at the plugin level: each
|
|
10
|
-
* calling task (a DSH session) gets its own browser session — the first
|
|
11
|
-
* `dsh_browser_open` (or any tool when no session exists) opens it, and later
|
|
12
|
-
* tools in the same task reuse it. Concurrent tasks therefore never fight
|
|
13
|
-
* over tabs, history, or navigation state.
|
|
6
|
+
* Session lifecycle is owned at the plugin level: each calling task (a DSH session) gets its own
|
|
7
|
+
* browser session, so concurrent tasks never fight over tabs, history, or navigation state.
|
|
14
8
|
* @module dsh-browser/tool-browser
|
|
15
9
|
*/
|
|
16
10
|
|
|
17
11
|
import type { Context } from '@deepseek-ai/cordis'
|
|
18
|
-
import type { ToolRunContext } from '@deepseek-ai/dsh-tools'
|
|
19
|
-
import type { ImageBlock } from '@deepseek-ai/dsh-llm'
|
|
20
|
-
import { SCREENSHOT_MAX_WIDTH, SCREENSHOT_MAX_HEIGHT, screenshotDimension, screenshotBytes, screenshotVisionEnabled, saveScreenshotImage } from './screenshot-image.ts'
|
|
21
12
|
import { BrowserTakeovers, installTakeovers } from './takeover.ts'
|
|
22
|
-
import { TAKEOVER_TOOL
|
|
23
|
-
import { clearLastOpen, getLastOpen, setLastOpen } from '../browser-electron/open-slot.ts'
|
|
24
|
-
import { readFileSync, statSync } from 'node:fs'
|
|
25
|
-
import { join } from 'node:path'
|
|
13
|
+
import { TAKEOVER_TOOL } from '../takeover-protocol.ts'
|
|
26
14
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
27
|
-
import {
|
|
28
|
-
import { CODE_PROMPT, CODE_TOOL, createCodeTool, type CatalogTool } from './code-tool.ts'
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import type
|
|
33
|
-
import
|
|
34
|
-
import
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
} from './
|
|
42
|
-
|
|
43
|
-
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Register a cleanup that runs once when the process exits.
|
|
47
|
-
*
|
|
48
|
-
* A single hook per process, holding a list of callbacks, rather than one listener per
|
|
49
|
-
* session: sessions come and go, listeners do not, and Node warns when a listener count
|
|
50
|
-
* passes ten.
|
|
51
|
-
*/
|
|
52
|
-
const exitCleanups = new Set<() => void>()
|
|
53
|
-
let exitHookInstalled = false
|
|
54
|
-
function registerExitCleanup(cleanup: () => void): void {
|
|
55
|
-
exitCleanups.add(cleanup)
|
|
56
|
-
if (exitHookInstalled) return
|
|
57
|
-
exitHookInstalled = true
|
|
58
|
-
process.on('exit', () => {
|
|
59
|
-
for (const run of exitCleanups) {
|
|
60
|
-
try { run() } catch { /* exiting; nothing useful to do */ }
|
|
61
|
-
}
|
|
62
|
-
})
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
/** Plugin name used by loader diagnostics. */
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Which surface an open should use.
|
|
70
|
-
*
|
|
71
|
-
* "panel" - place the page in the DSH sidebar and open nothing else (the normal Web behaviour).
|
|
72
|
-
* "builtin"- drive the plugin's own browser; needed when the thing under test IS DSH.
|
|
73
|
-
* @returns the configured surface, defaulting to "panel".
|
|
74
|
-
*/
|
|
75
|
-
function readSurface(): 'panel' | 'builtin' {
|
|
76
|
-
// Try every plausible location and take the first file that actually carries the key. The plugin's
|
|
77
|
-
// own settingsPath() is preferred, but a module instance can hold a stale home while another module in
|
|
78
|
-
// the same process holds the live one — which is exactly why channel read fine and surface did not.
|
|
79
|
-
const declared = (globalThis as unknown as Record<string, unknown>).__dshBrowserSurface
|
|
80
|
-
if (declared === 'panel' || declared === 'builtin') return declared
|
|
81
|
-
const candidates: string[] = []
|
|
82
|
-
try { candidates.push(settingsPath()) } catch { /* no module home */ }
|
|
83
|
-
candidates.push('D:/dsh-home/dsh-builtin-browser-host/settings.json')
|
|
84
|
-
for (const candidate of candidates) {
|
|
85
|
-
if (typeof candidate !== 'string' || candidate === '') continue
|
|
86
|
-
try {
|
|
87
|
-
const parsed = JSON.parse(readFileSync(candidate, 'utf8')) as { browser?: { surface?: unknown } }
|
|
88
|
-
const surface = parsed.browser?.surface
|
|
89
|
-
if (surface === 'builtin' || surface === 'panel') return surface
|
|
90
|
-
} catch { /* next candidate */ }
|
|
91
|
-
}
|
|
92
|
-
return 'panel'
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
|
|
15
|
+
import { BrowserToolError, toBrowserToolError } from './errors.ts'
|
|
16
|
+
import { CODE_PROMPT, CODE_TOOL, createCodeTool, type CatalogTool, type PagePulse } from './code-tool.ts'
|
|
17
|
+
import { pageOperationValue } from './probe-client.ts'
|
|
18
|
+
import { SettingsStore } from '../browser-electron/settings-store.ts'
|
|
19
|
+
import { browserSessionHandle, resolveTabHandle } from '../browser/handles.ts'
|
|
20
|
+
import { readSurface, createState, liveStates, READ_ONLY_TOOLS, taskKey, type ToolScope, maxWaitFor, MAX_FILL_FIELDS, REGISTRATION_ORDER } from './state.ts'
|
|
21
|
+
import { navigationTools } from './tools-navigation.ts'
|
|
22
|
+
import { TOOL_DEFAULT_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
23
|
+
import { observationTools } from './tools-observation.ts'
|
|
24
|
+
import { interactionTools } from './tools-interaction.ts'
|
|
25
|
+
import { debugTools } from './tools-debug.ts'
|
|
26
|
+
import { referenceTools } from './tools-reference.ts'
|
|
27
|
+
import { ptcRuntimeActive, registerTool } from '../compat/host-features.ts'
|
|
28
|
+
|
|
29
|
+
export { READ_ONLY_TOOLS, internals } from './state.ts'
|
|
96
30
|
|
|
97
31
|
// One line at registration: tool handlers are registered once per host start, and a recomposition does
|
|
98
32
|
// not re-register them. Printing the resolved surface here is the only reliable way to tell WHICH build a
|
|
99
33
|
// live host is actually running, instead of inferring it from behaviour.
|
|
100
34
|
try { console.log('[tool-browser] registered, surface=' + readSurface()) } catch { /* logging only */ }
|
|
101
35
|
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Keep the built-in browser for DSH itself.
|
|
105
|
-
*
|
|
106
|
-
* "builtin" exists to debug DSH: a client bundle, the settings panel, the sidebar UI. Using it for an
|
|
107
|
-
* ordinary site opens a window the reader did not ask for — measured as "why did you open the built-in
|
|
108
|
-
* browser again". A non-loopback target therefore degrades to "panel" silently; the caller's intent does
|
|
109
|
-
* not override the rule.
|
|
110
|
-
* @param surface - the requested surface.
|
|
111
|
-
* @param url - the page being opened.
|
|
112
|
-
* @returns the surface that will actually be used.
|
|
113
|
-
*/
|
|
114
|
-
function enforceSurface(surface: 'panel' | 'builtin', _url: string): 'panel' | 'builtin' {
|
|
115
|
-
// The caller decides the surface. An earlier version degraded "builtin" to "panel" for anything but a
|
|
116
|
-
// loopback URL, which also blocked the agent from driving the human's OWN browser — the opposite of what
|
|
117
|
-
// the setting is for. Which window appears is decided by the carrier (bundled Electron vs. the human's
|
|
118
|
-
// Edge), not by the URL. Keeping ordinary tests on the sidebar is a working rule, not a code constraint.
|
|
119
|
-
return surface
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Refuse a request that cannot work BEFORE anything is opened.
|
|
125
|
-
*
|
|
126
|
-
* The sidebar renders pages through a same-origin proxy, so asking it to load this machine answers with a
|
|
127
|
-
* network-level failure that reads like a bug in the page. Reporting that afterwards is useless — the call
|
|
128
|
-
* already happened. The rule is therefore enforced up front: a loopback target on the panel surface is
|
|
129
|
-
* refused, and the message names the surface that does work.
|
|
130
|
-
* @param surface - the surface this call would use.
|
|
131
|
-
* @param url - the page being opened.
|
|
132
|
-
*/
|
|
133
|
-
function assertSurfaceCanHost(surface: 'panel' | 'builtin', url: string): void {
|
|
134
|
-
if (surface !== 'panel') return
|
|
135
|
-
let host: string
|
|
136
|
-
try { host = new URL(url).hostname.toLowerCase() } catch { return }
|
|
137
|
-
const local = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]' || /^127\./u.test(host)
|
|
138
|
-
if (!local) return
|
|
139
|
-
throw new Error('dsh-builtin-browser: the sidebar cannot host this machine (' + host
|
|
140
|
-
+ '). It proxies pages through itself, so loading DSH there is the proxy fetching its own server. '
|
|
141
|
-
+ '调试 DSH 请用 surface: "builtin"(内置浏览器),普通网页才走侧栏。')
|
|
142
|
-
}
|
|
143
|
-
|
|
36
|
+
/** Plugin name used by loader diagnostics. */
|
|
144
37
|
export const name = 'tool-browser'
|
|
145
38
|
/** The tool registry, browser seam, and system-prompt registry this tool layer consumes. */
|
|
146
39
|
export const inject = ['tools', 'browser', 'systemPrompt']
|
|
@@ -162,52 +55,6 @@ export interface Config {
|
|
|
162
55
|
readonly surface?: 'core' | 'code' | 'tools'
|
|
163
56
|
}
|
|
164
57
|
|
|
165
|
-
/** Per-apply (per-context) tool state: sessions, in-flight opens, restriction. */
|
|
166
|
-
interface ToolBrowserState {
|
|
167
|
-
/** Per-task browser sessions, keyed by the calling DSH session id. */
|
|
168
|
-
readonly sessionsByTask: Map<string, BrowserSessionId>
|
|
169
|
-
/** In-flight first-open per task key, so concurrent first calls share one session. */
|
|
170
|
-
readonly pendingOpens: Map<string, Promise<BrowserSessionId>>
|
|
171
|
-
/**
|
|
172
|
-
* Action restriction per task, plus one from the plugin's own configuration.
|
|
173
|
-
*
|
|
174
|
-
* Two different things share this policy. A restriction from `cordis.patch.yml` is an
|
|
175
|
-
* operator decision about the whole plugin, so it applies to everyone and lives in
|
|
176
|
-
* `configRestrictedTo`. One set by `dsh_browser_restrict` is a decision by one task about
|
|
177
|
-
* its own work, so it is keyed by task — a single shared value let one task lock the
|
|
178
|
-
* browser tools of every other task, which is not what any caller asks for. Sessions
|
|
179
|
-
* beside it were already keyed this way; this was not.
|
|
180
|
-
*/
|
|
181
|
-
configRestrictedTo: readonly string[] | undefined
|
|
182
|
-
restrictedByTask: Map<string, readonly string[]>
|
|
183
|
-
/** Active panel opens, including Web iframes that cannot be driven over CDP. */
|
|
184
|
-
panelUrlByTask: Map<string, string>
|
|
185
|
-
pendingPanelOpens: Map<string, Promise<void>>
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function createState(): ToolBrowserState {
|
|
189
|
-
return {
|
|
190
|
-
sessionsByTask: new Map(), pendingOpens: new Map(), configRestrictedTo: undefined,
|
|
191
|
-
restrictedByTask: new Map(), panelUrlByTask: new Map(), pendingPanelOpens: new Map(),
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** Every live state, for the test hook (introspection only, never shared). */
|
|
196
|
-
const liveStates = new Set<ToolBrowserState>()
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Guard one browser tool call against the active restriction. Refuses calls
|
|
200
|
-
* not on the allow-list when a restriction is in effect.
|
|
201
|
-
* @param state - the calling context's tool state.
|
|
202
|
-
* @param toolName - the browser tool about to run.
|
|
203
|
-
*/
|
|
204
|
-
/**
|
|
205
|
-
* Tools that only observe, plus the ones that undo a restriction.
|
|
206
|
-
*
|
|
207
|
-
* Never subject to an allow-list: restricting what the agent may *do* must not also
|
|
208
|
-
* blind it or trap it, and the tool descriptions promise as much. dsh_browser_restrict
|
|
209
|
-
* is in here so a task that restricted everything can still lift it.
|
|
210
|
-
*/
|
|
211
58
|
/** Tool loaded on demand: registers a group of browser tools for the rest of the run. */
|
|
212
59
|
export const LOAD_TOOL = 'dsh_browser_load_tools'
|
|
213
60
|
|
|
@@ -230,321 +77,27 @@ export const CORE_TOOLS: ReadonlySet<string> = new Set([
|
|
|
230
77
|
export const TOOL_GROUPS: Readonly<Record<string, readonly string[]>> = {
|
|
231
78
|
forms: ['dsh_browser_check', 'dsh_browser_clear', 'dsh_browser_set_value', 'dsh_browser_get_value', 'dsh_browser_upload', 'dsh_browser_drag', 'dsh_browser_hover', 'dsh_browser_dialog', 'dsh_browser_click_sequence'],
|
|
232
79
|
navigation: ['dsh_browser_forward', 'dsh_browser_refresh', 'dsh_browser_history', 'dsh_browser_replay', 'dsh_browser_visited', 'dsh_browser_download'],
|
|
233
|
-
debug: ['dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response', 'dsh_browser_assert', 'dsh_browser_doctor'],
|
|
80
|
+
debug: ['dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response', 'dsh_browser_data_sources', 'dsh_browser_fetch_json', 'dsh_browser_assert', 'dsh_browser_doctor'],
|
|
234
81
|
session: ['dsh_browser_session', 'dsh_browser_reset', 'dsh_browser_reset_session', 'dsh_browser_restrict', 'dsh_browser_auth', 'dsh_browser_shortcuts'],
|
|
235
82
|
more: [],
|
|
236
83
|
}
|
|
237
84
|
|
|
238
|
-
/** Guide for the `core` surface. Static, so the prompt prefix caches. */
|
|
239
|
-
const CORE_PROMPT = 'Operate the built-in browser with the dsh_browser_* tools. Each task has its own browser session and window: the human can watch and take over, and other tasks\' pages are not visible to you. The core tools are loaded: dsh_browser_open; dsh_browser_snapshot or dsh_browser_a11y to map a page; click, type, key, scroll, select and fill to act; wait; content, find and scrape to read; screenshot; execute for page JavaScript; the tab tools and back; and reference_capture/reveal/list for citations. Load the other tools by group with dsh_browser_load_tools when a task needs them; loaded tools stay available. To batch, use dsh_browser_do for a fixed list of steps, or dsh_browser_code for a JavaScript program that calls any browser tool as `await tools.dsh_browser_<name>(args)`, loops and branches over the results, overlaps independent reads with Promise.all and prints only what you need. Prefer dsh_browser_code whenever a task takes more than a few actions or spans many pages, and print findings as you go: on a deadline or cancellation everything already printed is still returned. When run_code is available, call the same tools from run_code instead. A blocked page (403, access denied, bot wall) is not the end of the task. Look for another route to the same public information: other pages of the site, its own JSON/API endpoints or sitemap, search-engine results, archived or reader copies, and other reputable sources. Keep each value tied to the source it came from. Report a blocker only once those routes are exhausted, and still deliver everything you did find. On a CAPTCHA, slider or other human verification (dsh_browser_challenge, or a CHALLENGE banner in a result), never retry or solve it: call dsh_browser_request_takeover.'
|
|
240
|
-
|
|
241
|
-
export const READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
|
|
242
|
-
// Tools that only observe.
|
|
243
|
-
'dsh_browser_snapshot', 'dsh_browser_a11y', 'dsh_browser_content', 'dsh_browser_scrape',
|
|
244
|
-
'dsh_browser_screenshot', 'dsh_browser_get_value', 'dsh_browser_wait', 'dsh_browser_challenge',
|
|
245
|
-
'dsh_browser_list_tabs', 'dsh_browser_session', 'dsh_browser_history', 'dsh_browser_visited',
|
|
246
|
-
// Observation added in 0.5.7: console lines, network responses, an assertion, a self-check and the
|
|
247
|
-
// help index. All five only read (the probe's buffers belong to the page, not to the task), so an
|
|
248
|
-
// allow-list must not blind a task that restricted itself.
|
|
249
|
-
'dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response',
|
|
250
|
-
'dsh_browser_assert', 'dsh_browser_doctor', 'dsh_browser_help',
|
|
251
|
-
// Reading the page's own digest and searching its text: observation like the rest.
|
|
252
|
-
'dsh_browser_find', 'dsh_browser_state',
|
|
253
|
-
// References read the page the human already has open and write only this plugin's own store;
|
|
254
|
-
// restricting an agent's actions must not stop it from recording what it was told to read.
|
|
255
|
-
'dsh_browser_reference_capture', 'dsh_browser_reference_reveal', 'dsh_browser_reference_list',
|
|
256
|
-
// dsh_browser_auth reads cookies out of the browser: an observation, and one the
|
|
257
|
-
// credentials switch gates on its own (see credentials.allowRead in the settings).
|
|
258
|
-
// dsh_browser_auth is deliberately NOT here. It reads cookies on "flush" but WRITES them on
|
|
259
|
-
// "restore", to arbitrary domains, which is an action like any other — exempting the tool
|
|
260
|
-
// would let a task that restricted its own actions rewrite the shared browser's logins.
|
|
261
|
-
//
|
|
262
|
-
// Getting out of a bad state, or lifting the restriction itself. Without these a task
|
|
263
|
-
// that restricted everything could neither recover nor be released.
|
|
264
|
-
'dsh_browser_restrict', 'dsh_browser_reset_session', 'dsh_browser_reset',
|
|
265
|
-
])
|
|
266
|
-
function assertAllowed(state: ToolBrowserState, toolName: string, task: string): void {
|
|
267
|
-
// dsh_browser_restrict must stay usable, or a task that restricted everything
|
|
268
|
-
// could never lift it again.
|
|
269
|
-
// An allow-list is a statement about ACTIONS, so it must not take away the ability to
|
|
270
|
-
// look, or to get out of a bad state. The tool description and both READMEs promise
|
|
271
|
-
// that read-only tools are never blocked; before this they were, because only
|
|
272
|
-
// dsh_browser_restrict itself was exempt — a narrow list then locked dsh_browser_history,
|
|
273
|
-
// dsh_browser_reset_session and dsh_browser_auth away with no way back.
|
|
274
|
-
if (READ_ONLY_TOOLS.has(toolName) || toolName === 'dsh_browser_restrict') return
|
|
275
|
-
const config = state.configRestrictedTo
|
|
276
|
-
if (config !== undefined && !config.includes(toolName)) {
|
|
277
|
-
throw new Error(`browser action "${toolName}" is restricted by the plugin configuration (allow-list: ${config.join(', ')})`)
|
|
278
|
-
}
|
|
279
|
-
const allowed = state.restrictedByTask.get(task)
|
|
280
|
-
if (allowed === undefined || allowed.includes(toolName)) return
|
|
281
|
-
throw new Error(`browser action "${toolName}" is restricted (allow-list: ${allowed.join(', ')})`)
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** The agent view a tool execution carries (id + agent-scoped context). */
|
|
285
|
-
interface ExecAgent {
|
|
286
|
-
readonly id?: string
|
|
287
|
-
/** Agent-scoped Cordis context; its effects unwind on agent disposal. */
|
|
288
|
-
readonly ctx?: Context
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/** Extract the agent from a tool-execution context, when one exists. */
|
|
292
|
-
function agentOf(exec: unknown): ExecAgent | undefined {
|
|
293
|
-
return (exec as { agent?: ExecAgent } | undefined)?.agent
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
/**
|
|
297
|
-
* Refuse the bare DSH web root, which answers 401 and looks like a real page.
|
|
298
|
-
*
|
|
299
|
-
* The address comes from `DSH_WEB_URL`, which the harness exports to its children — NOT from a
|
|
300
|
-
* hardcoded port. This machine's GUI has run on 3080 and on 19387, so a number would stop matching
|
|
301
|
-
* exactly when the guard is needed, and the trap is not a port anyway: it is the SHAPE. A loopback
|
|
302
|
-
* address at its root with no token renders as an unauthenticated 401 page, which an agent reads
|
|
303
|
-
* as the site it meant to open.
|
|
304
|
-
* @param rawUrl - the address a caller asked to open.
|
|
305
|
-
*/
|
|
306
|
-
function assertNotBareDshWebUrl(rawUrl: string): void {
|
|
307
|
-
const advertised = process.env.DSH_WEB_URL
|
|
308
|
-
if (typeof advertised !== 'string' || advertised === '') return
|
|
309
|
-
let target: URL
|
|
310
|
-
let dsh: URL
|
|
311
|
-
try {
|
|
312
|
-
target = new URL(rawUrl)
|
|
313
|
-
dsh = new URL(advertised)
|
|
314
|
-
} catch {
|
|
315
|
-
return // not a URL this guard can judge; the provider's own admission is the next gate
|
|
316
|
-
}
|
|
317
|
-
if (target.origin !== dsh.origin) return
|
|
318
|
-
if (target.pathname !== '/') return
|
|
319
|
-
// The authenticated URL printed by `dsh web` carries a token; the bare root does not.
|
|
320
|
-
if (target.searchParams.has('token')) return
|
|
321
|
-
throw new Error(
|
|
322
|
-
'dsh_browser_open: refusing the bare DSH web root (' + dsh.origin + '/) because it carries no '
|
|
323
|
-
+ 'authentication token, so it answers with a 401 page that reads like a real site. Open the '
|
|
324
|
-
+ 'target site instead; to open DSH itself, use the authenticated URL printed by `dsh web`.',
|
|
325
|
-
)
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/**
|
|
329
|
-
* Read a target's `index`, refusing the values that cannot mean anything.
|
|
330
|
-
*
|
|
331
|
-
* The index is looked up in the page (`els[index] ?? null`), so a negative one — `-1`, the
|
|
332
|
-
* common "give me the last one" shorthand — matches nothing. The page script then treated
|
|
333
|
-
* that as "not on the page yet" and polled for its whole 10s budget before reporting
|
|
334
|
-
* "element not found", which reads like a slow page rather than a bad argument. Refusing it
|
|
335
|
-
* here names the real problem immediately.
|
|
336
|
-
* @param target - the caller's target, or undefined when there is none.
|
|
337
|
-
* @returns the index, or undefined to let the page default to 0.
|
|
338
|
-
*/
|
|
339
|
-
function targetIndex(target: { readonly index?: unknown } | undefined): number | undefined {
|
|
340
|
-
const index = target?.index
|
|
341
|
-
if (index === undefined) return undefined
|
|
342
|
-
if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) {
|
|
343
|
-
throw new Error(`target.index must be a non-negative integer (got ${JSON.stringify(index)}); it is a 0-based position among the matches, and negative values such as -1 match nothing — pass the position you want, or narrow the selector`)
|
|
344
|
-
}
|
|
345
|
-
return index
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* The task key for a tool call: the calling DSH session id, or the shared
|
|
350
|
-
* default key when the call carries no agent context (CLI probes, tests).
|
|
351
|
-
* @param exec - the tool-execution context; only its optional agent id is read.
|
|
352
|
-
*/
|
|
353
|
-
function taskKey(exec: { agent?: { id?: string } } | undefined): string {
|
|
354
|
-
return exec?.agent?.id ?? 'default'
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
const effectProperties = {
|
|
358
|
-
verified: { type: 'boolean' as const, description: 'Whether a visible change was observed. Absent when it could not be checked.' },
|
|
359
|
-
note: { type: 'string' as const, description: 'Why the effect is uncertain.' },
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
async function pageFingerprint(browser: NonNullable<Context['browser']>, session: BrowserSessionId): Promise<string | undefined> {
|
|
363
|
-
try {
|
|
364
|
-
const result = await browser.execute(session, {
|
|
365
|
-
script: `(() => {
|
|
366
|
-
const a = document.activeElement
|
|
367
|
-
return JSON.stringify([
|
|
368
|
-
location.href, document.title,
|
|
369
|
-
a ? [a.tagName, a.id || a.getAttribute('name') || a.className || '',
|
|
370
|
-
typeof a.value === 'string' ? a.value.length : null, a.checked, a.selectedIndex,
|
|
371
|
-
a.selectionStart, a.selectionEnd, a.scrollLeft, a.scrollTop] : null,
|
|
372
|
-
window.scrollX, window.scrollY,
|
|
373
|
-
document.body ? document.body.childElementCount : 0,
|
|
374
|
-
document.body ? document.body.innerHTML.length : 0,
|
|
375
|
-
])
|
|
376
|
-
})()`,
|
|
377
|
-
})
|
|
378
|
-
return result.ok && typeof result.value === 'string' ? result.value : undefined
|
|
379
|
-
} catch {
|
|
380
|
-
return undefined
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
async function observedEffect(browser: NonNullable<Context['browser']>, session: BrowserSessionId, before: string | undefined): Promise<{ verified?: boolean; note?: string }> {
|
|
385
|
-
const after = await pageFingerprint(browser, session)
|
|
386
|
-
if (before === undefined || after === undefined) return { note: 'The effect could not be checked.' }
|
|
387
|
-
return before !== after
|
|
388
|
-
? { verified: true }
|
|
389
|
-
: { verified: false, note: 'No visible change observed; the effect is uncertain.' }
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
function effectText(value: { verified?: boolean; note?: string }): string {
|
|
393
|
-
return value.verified === true ? ' Visible change observed.' : ` ${value.note ?? 'The effect could not be checked.'}`
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
function rememberSession(browser: NonNullable<Context['browser']>, state: ToolBrowserState, key: string, agent: ExecAgent | undefined, session: BrowserSessionId | undefined, panelUrl?: string): void {
|
|
397
|
-
const previous = state.sessionsByTask.get(key)
|
|
398
|
-
const previousPanelUrl = state.panelUrlByTask.get(key)
|
|
399
|
-
if (session === undefined) state.sessionsByTask.delete(key)
|
|
400
|
-
else state.sessionsByTask.set(key, session)
|
|
401
|
-
if (panelUrl === undefined) state.panelUrlByTask.delete(key)
|
|
402
|
-
else state.panelUrlByTask.set(key, panelUrl)
|
|
403
|
-
if (previous === session && (previousPanelUrl !== undefined) === (panelUrl !== undefined)) return
|
|
404
|
-
const cleanup = (): void => {
|
|
405
|
-
if (state.sessionsByTask.get(key) !== session || state.panelUrlByTask.has(key) !== (panelUrl !== undefined)) return
|
|
406
|
-
state.sessionsByTask.delete(key)
|
|
407
|
-
state.panelUrlByTask.delete(key)
|
|
408
|
-
if (session !== undefined) void browser.close(session).catch(() => {})
|
|
409
|
-
}
|
|
410
|
-
try {
|
|
411
|
-
if (agent?.ctx !== undefined) agent.ctx.effect(() => cleanup)
|
|
412
|
-
else if (key === 'default' && session !== undefined) registerExitCleanup(() => browser.close(session).catch(() => {}))
|
|
413
|
-
} catch (error) {
|
|
414
|
-
cleanup()
|
|
415
|
-
if (previous !== undefined) state.sessionsByTask.set(key, previous)
|
|
416
|
-
if (previousPanelUrl !== undefined) state.panelUrlByTask.set(key, previousPanelUrl)
|
|
417
|
-
throw error
|
|
418
|
-
}
|
|
419
|
-
if (previous !== undefined && previous !== session) void browser.close(previous).catch(() => {})
|
|
420
|
-
}
|
|
421
|
-
|
|
422
85
|
/**
|
|
423
|
-
*
|
|
424
|
-
*
|
|
425
|
-
*
|
|
426
|
-
* context: it closes automatically when the agent (DSH session) is disposed,
|
|
427
|
-
* so sessions and their windows never leak after a task ends.
|
|
428
|
-
* @param browser - the seam service.
|
|
429
|
-
* @param state - the calling context's tool state.
|
|
430
|
-
* @param key - the task key (see {@link taskKey}).
|
|
431
|
-
* @param agent - the calling agent, when any (its ctx owns the session).
|
|
432
|
-
* @returns the task's session id.
|
|
86
|
+
* Minimal static routing hint for the `core` surface. Detailed tool guidance lives in each tool's
|
|
87
|
+
* description, runtime CHALLENGE banners, and SKILL.md so unrelated conversations do not pay for
|
|
88
|
+
* a long global manual or inherit cross-plugin behavior rules.
|
|
433
89
|
*/
|
|
434
|
-
|
|
435
|
-
await state.pendingPanelOpens.get(key)
|
|
436
|
-
const existing = state.sessionsByTask.get(key)
|
|
437
|
-
if (existing !== undefined) {
|
|
438
|
-
// The human closing a browser window ends that session, so a cached id can
|
|
439
|
-
// be stale: never hand a dead session back to a tool call.
|
|
440
|
-
if (browser.exists(existing)) return existing
|
|
441
|
-
state.sessionsByTask.delete(key)
|
|
442
|
-
}
|
|
443
|
-
const pending = state.pendingOpens.get(key)
|
|
444
|
-
if (pending !== undefined) return pending
|
|
445
|
-
if (state.panelUrlByTask.has(key)) {
|
|
446
|
-
throw new Error('dsh-builtin-browser: the panel surface has no live CDP session for this operation. '
|
|
447
|
-
+ 'Use the CDP-backed DSH desktop sidebar with a connected desktop bridge and call dsh_browser_open again. '
|
|
448
|
-
+ 'The Web iframe panel cannot provide live snapshots, a11y, content, scrape, screenshots, interactions, '
|
|
449
|
-
+ 'uploads, downloads, or reference capture. Reading tools never start a separate browser.')
|
|
450
|
-
}
|
|
451
|
-
// Starting a browser is `dsh_browser_open`'s job and nobody else's. A read tool asking "what is on
|
|
452
|
-
// screen" used to start one — which, with the human's own Edge already running, handed the command over
|
|
453
|
-
// and opened yet another window, reported as "one look, two Edge windows". A reader with nothing open
|
|
454
|
-
// reports that instead of launching anything.
|
|
455
|
-
if (!create) {
|
|
456
|
-
throw new Error('dsh-builtin-browser: nothing is open in this task yet — call dsh_browser_open first. '
|
|
457
|
-
+ 'Reading tools never start a browser.')
|
|
458
|
-
}
|
|
459
|
-
// The task key rides along as the session label so the window title shows
|
|
460
|
-
// which task's page is currently visible to the human.
|
|
461
|
-
const opening = browser.open(key).then(
|
|
462
|
-
session => {
|
|
463
|
-
state.pendingOpens.delete(key)
|
|
464
|
-
rememberSession(browser, state, key, agent, session)
|
|
465
|
-
return session
|
|
466
|
-
},
|
|
467
|
-
error => { state.pendingOpens.delete(key); throw error },
|
|
468
|
-
)
|
|
469
|
-
state.pendingOpens.set(key, opening)
|
|
470
|
-
return opening
|
|
471
|
-
}
|
|
90
|
+
const CORE_PROMPT = 'Use dsh_browser_* tools to drive the built-in browser (per-task isolated sessions). Batch fixed steps with dsh_browser_do, or loops/branching/parallel reads with dsh_browser_code (or run_code under PTC); load extra groups via dsh_browser_load_tools and follow any CHALLENGE banner.'
|
|
472
91
|
|
|
473
|
-
/**
|
|
474
|
-
|
|
475
|
-
if (v === 'true') return true
|
|
476
|
-
if (v === 'false') return false
|
|
477
|
-
// Deliberately NOT coerced to a number. The description says numbers are accepted in
|
|
478
|
-
// string form, and callers pass account numbers, postcodes and zero-padded ids through
|
|
479
|
-
// here: "007" became "7" and "1e3" became "1000", which silently rewrote the value they
|
|
480
|
-
// meant to type. A numeric-looking string is a string; the DOM decides how to store it.
|
|
481
|
-
return v ?? ''
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/**
|
|
485
|
-
* Format a snapshot element list for the model.
|
|
486
|
-
*
|
|
487
|
-
* Coordinates are opt-in. They are only meaningful to a caller that intends to
|
|
488
|
-
* click a pixel position, which means a vision pass; for the far more common case
|
|
489
|
-
* of locating an element by role/label and passing a semantic target, they are the
|
|
490
|
-
* bulkiest and least useful part of every line. Omitting them keeps the listing
|
|
491
|
-
* readable — which is exactly what a model without image input has to work from.
|
|
492
|
-
* @param snapshot - the snapshot payload.
|
|
493
|
-
* @param options - `coords: true` to include each element's viewport position.
|
|
494
|
-
*/
|
|
495
|
-
function formatSnapshot(snapshot: {
|
|
496
|
-
url: string
|
|
497
|
-
title?: string
|
|
498
|
-
elements: readonly { ref: number; kind: string; label: string; x: number; y: number; frame?: boolean; selector?: string }[]
|
|
499
|
-
truncated?: boolean
|
|
500
|
-
challenge?: { blocked: boolean; kind?: string; reason?: string }
|
|
501
|
-
blank?: boolean
|
|
502
|
-
note?: string
|
|
503
|
-
canvas?: boolean
|
|
504
|
-
}, options: { coords?: boolean } = {}): string {
|
|
505
|
-
const showCoords = options.coords === true
|
|
506
|
-
const lines = snapshot.elements.map(el => `[${el.ref}] ${el.kind}: ${el.label}${el.selector !== undefined && el.selector !== '' ? ` {${el.selector}}` : ''}${el.frame === true ? ' (iframe)' : ''}${showCoords ? ` (${el.x},${el.y})` : ''}`)
|
|
507
|
-
const header = `URL: ${snapshot.url}${snapshot.title !== undefined ? `\nTitle: ${snapshot.title}` : ''}`
|
|
508
|
-
// A blank page, a canvas page and a page with nothing interactive are three different facts, and
|
|
509
|
-
// the old wording reported all of them as "no interactive elements found" — which reads as a
|
|
510
|
-
// successful look. Each now says what it is and what to do next.
|
|
511
|
-
const body = snapshot.blank === true
|
|
512
|
-
? `BLANK PAGE: ${snapshot.note ?? 'nothing has been opened in this browser'}. `
|
|
513
|
-
+ 'Do not drive this page — open a URL first (`dsh_browser_open`).'
|
|
514
|
-
: snapshot.canvas === true
|
|
515
|
-
? `CANVAS PAGE: ${snapshot.note ?? 'this page draws its interface on a canvas'}. `
|
|
516
|
-
+ 'A DOM snapshot cannot describe it; use `dsh_browser_screenshot` and coordinate clicks.'
|
|
517
|
-
: lines.length > 0 ? lines.join('\n') : '(no interactive elements found)'
|
|
518
|
-
const tail = snapshot.truncated === true ? '\n(snapshot truncated)' : ''
|
|
519
|
-
const banner = snapshot.challenge?.blocked === true
|
|
520
|
-
? `\n\nCHALLENGE: ${snapshot.challenge.reason ?? 'human-verification'}. Do NOT keep retrying — ask the human to complete it in the shared browser window, then re-snapshot.`
|
|
521
|
-
: ''
|
|
522
|
-
return `${header}\n\n${body}${tail}${banner}`
|
|
523
|
-
}
|
|
92
|
+
/** Minimal static routing hint for the `tools` surface. */
|
|
93
|
+
const TOOLS_PROMPT = 'Use dsh_browser_* tools to drive the built-in browser (per-task isolated sessions). Prefer dsh_browser_a11y or dsh_browser_snapshot to locate targets, dsh_browser_fill for forms, dsh_browser_scrape for lists, dsh_browser_do for multi-step runs, and dsh_browser_assert or dsh_browser_console/network to verify; follow any CHALLENGE banner.'
|
|
524
94
|
|
|
525
95
|
/** Register all browser tools with `ctx.tools`. */
|
|
526
96
|
export function apply(ctx: Context, config: Config = {}): void {
|
|
527
|
-
const timeoutMs = config.timeoutMs ??
|
|
97
|
+
const timeoutMs = config.timeoutMs ?? TOOL_DEFAULT_TIMEOUT_MS
|
|
528
98
|
const surface = config.surface ?? 'core'
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
* finish and report.
|
|
532
|
-
*
|
|
533
|
-
* `dsh_browser_wait` promises a VERDICT — `{ready:false, reason}` — and the enclosing tool
|
|
534
|
-
* call aborts at `timeoutMs`. A caller-supplied budget longer than that aborted the call
|
|
535
|
-
* instead, so the documented verdict never arrived. Clamping to just inside the budget is
|
|
536
|
-
* what keeps the promise: the polling stops, the reason is returned.
|
|
537
|
-
*/
|
|
538
|
-
const maxWaitMs = Math.max(250, timeoutMs - 5_000)
|
|
539
|
-
/**
|
|
540
|
-
* Most fields `dsh_browser_fill` accepts in one batch.
|
|
541
|
-
*
|
|
542
|
-
* The batch runs as ONE page evaluation, so hundreds of fields do not produce hundreds of
|
|
543
|
-
* per-field verdicts — they produce a single evaluate that exceeds the tool budget and
|
|
544
|
-
* throws, which is the opposite of the documented "per-field failures are reported instead
|
|
545
|
-
* of throwing". Real forms are far smaller than this; anything larger should be split.
|
|
546
|
-
*/
|
|
547
|
-
const maxFillFields = 200
|
|
99
|
+
const maxWaitMs = maxWaitFor(timeoutMs)
|
|
100
|
+
const maxFillFields = MAX_FILL_FIELDS
|
|
548
101
|
// Per-context state: sessions, in-flight opens, and the restriction are
|
|
549
102
|
// scoped to THIS plugin apply, so parallel contexts never share sessions
|
|
550
103
|
// or leak restrictions into each other.
|
|
@@ -556,12 +109,6 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
556
109
|
// Re-apply resets the restriction: an omitted allowedActions lifts it.
|
|
557
110
|
state.configRestrictedTo = config.allowedActions !== undefined ? [...config.allowedActions] : undefined
|
|
558
111
|
|
|
559
|
-
ctx.systemPrompt.section({
|
|
560
|
-
name: 'tool:browser-human-takeover',
|
|
561
|
-
order: 152,
|
|
562
|
-
text: 'For CAPTCHAs, sliders, logins, two-factor authentication (2FA), and payments, call dsh_browser_request_takeover with a clear reason and any instructions. Never attempt automatic CAPTCHA or slider solving. Wait for the human, then re-read the fresh page summary and inspect the page before continuing. A skipped or cancelled takeover is not successful completion; do not bypass it or retry protected actions automatically.',
|
|
563
|
-
})
|
|
564
|
-
|
|
565
112
|
ctx.systemPrompt.section({
|
|
566
113
|
name: 'tool:dsh-browser-reference-presentation',
|
|
567
114
|
order: 151,
|
|
@@ -577,7 +124,7 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
577
124
|
? CODE_PROMPT
|
|
578
125
|
: surface === 'core'
|
|
579
126
|
? CORE_PROMPT
|
|
580
|
-
:
|
|
127
|
+
: TOOLS_PROMPT,
|
|
581
128
|
})
|
|
582
129
|
|
|
583
130
|
/**
|
|
@@ -595,29 +142,6 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
595
142
|
// One store for this apply: it caches by mtime, so reading it per download is a stat, not a parse.
|
|
596
143
|
const settingsStore = new SettingsStore()
|
|
597
144
|
|
|
598
|
-
// Built on first use, not at apply time: the provider is registered by another plugin's apply,
|
|
599
|
-
// and a tool registered before the browser exists must still work once it does.
|
|
600
|
-
let referenceService: BrowserReferenceService | undefined
|
|
601
|
-
const references = (): BrowserReferenceService => {
|
|
602
|
-
if (referenceService !== undefined) return referenceService
|
|
603
|
-
const browser = ctx.get('browser')
|
|
604
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
605
|
-
// Keep the SAME image fallback as the floating bar and the HTTP capture
|
|
606
|
-
// (browser-electron/entry.ts): a clipped visible-region read lets an image
|
|
607
|
-
// whose source URL cannot be downloaded still become a real reference.
|
|
608
|
-
referenceService = createReferenceService(browser, {
|
|
609
|
-
visibleCapture: async (sessionId, clip, signal) => {
|
|
610
|
-
const shot = await browser.screenshot(sessionWireId(resolveSessionHandle(sessionId)), { clip, format: 'png' }, signal)
|
|
611
|
-
return { dataUrl: shot.dataUrl, mime: 'image/png' }
|
|
612
|
-
},
|
|
613
|
-
})
|
|
614
|
-
return referenceService
|
|
615
|
-
}
|
|
616
|
-
const referenceCarrier = (): BrowserReferenceCarrier => {
|
|
617
|
-
const channel = settingsStore.get().browser.channel
|
|
618
|
-
return channel === 'sidebar' || channel === 'chrome' || channel === 'edge' ? channel : 'bundled'
|
|
619
|
-
}
|
|
620
|
-
|
|
621
145
|
const catalog = new Map<string, CatalogTool>()
|
|
622
146
|
const loaded = new Set<string>()
|
|
623
147
|
const registerSafely = (definition: ReturnType<typeof defineTool>): void => {
|
|
@@ -635,10 +159,14 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
635
159
|
if (session) tab = resolveTabHandle(browserSessionHandle(owner, session), requested).tab
|
|
636
160
|
}
|
|
637
161
|
if (tab === undefined || takeovers.blocks(owner, tab)) {
|
|
638
|
-
throw new
|
|
162
|
+
throw new BrowserToolError('Browser tab is awaiting human takeover. Agent browser actions are refused until the human confirms completion or skips the request.', 'BROWSER_TAKEOVER_PENDING')
|
|
639
163
|
}
|
|
640
164
|
}
|
|
641
|
-
|
|
165
|
+
try {
|
|
166
|
+
return await execute(args, exec)
|
|
167
|
+
} catch (error) {
|
|
168
|
+
throw toBrowserToolError(error, (exec as { signal?: AbortSignal } | undefined)?.signal)
|
|
169
|
+
}
|
|
642
170
|
} }
|
|
643
171
|
catalog.set(definition.name, definition as unknown as CatalogTool)
|
|
644
172
|
if (surface === 'tools' || definition.name === TAKEOVER_TOOL || (surface === 'core' && CORE_TOOLS.has(definition.name))) {
|
|
@@ -654,3020 +182,40 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
654
182
|
}
|
|
655
183
|
}
|
|
656
184
|
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
outcome: { type: 'string', required: true, enum: ['done', 'skipped', 'cancelled'] },
|
|
666
|
-
page: { type: 'object', required: true, additionalProperties: false, properties: {
|
|
667
|
-
url: { type: 'string', required: true }, title: { type: 'string', required: true },
|
|
668
|
-
snapshotHint: { type: 'string', required: true }, fresh: { type: 'boolean', required: true },
|
|
669
|
-
} },
|
|
670
|
-
} }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
671
|
-
async execute(args, exec) {
|
|
672
|
-
if (!exec.agent?.session) throw new Error('Browser takeover requires an active agent turn.')
|
|
673
|
-
if (!args.reason.trim()) throw new Error('Browser takeover reason must not be empty.')
|
|
674
|
-
if (args.reason.length > 1000 || (args.instructions?.length ?? 0) > 2000) throw new Error('Browser takeover reason or instructions are too long.')
|
|
675
|
-
const owner = taskKey(exec)
|
|
676
|
-
const opening = state.pendingPanelOpens.get(owner)
|
|
677
|
-
if (opening) await opening
|
|
678
|
-
const open = getLastOpen()
|
|
679
|
-
const navigationUrl = open?.owner === owner && Date.now() - open.at < 10000 ? open.url : undefined
|
|
680
|
-
const page = await takeovers.adopt(owner, exec.signal, navigationUrl)
|
|
681
|
-
if (navigationUrl !== undefined && getLastOpen()?.owner === owner) clearLastOpen(open!.at)
|
|
682
|
-
return takeovers.run(page, args.reason.trim(), args.instructions, exec.signal, async (pending): Promise<{ outcome: TakeoverOutcome; page: TakeoverSummary }> => {
|
|
683
|
-
const approval = ctx.get('approval' as never) as unknown as { request(request: {
|
|
684
|
-
agent: ToolRunContext['agent']; toolName: string; reason: string; displayReason: { en: string; zh: string };
|
|
685
|
-
callId: ToolRunContext['callId']; signal: AbortSignal;
|
|
686
|
-
}): Promise<TakeoverDecision> } | undefined
|
|
687
|
-
let decision: TakeoverDecision = 'unavailable'
|
|
688
|
-
try {
|
|
689
|
-
if (approval) decision = await approval.request({ agent: exec.agent, toolName: TAKEOVER_TOOL, callId: exec.callId,
|
|
690
|
-
reason: pending.reason, displayReason: {
|
|
691
|
-
en: `Please take over the browser: ${pending.reason}. When finished, click Allow once or Confirm completion in the sidebar.${pending.instructions ? '\n' + pending.instructions : ''}`,
|
|
692
|
-
zh: `请接管浏览器:${pending.reason}(完成后点「允许一次」或侧栏「确认完成」)${pending.instructions ? '\n' + pending.instructions : ''}`,
|
|
693
|
-
}, signal: pending.controller.signal })
|
|
694
|
-
} finally { pending.controller.abort() }
|
|
695
|
-
const outcome = decision === 'allowed-once' ? 'done' : decision === 'rejected' ? 'skipped' : 'cancelled'
|
|
696
|
-
const unavailable = (error: unknown): TakeoverSummary => ({ url: page.url, title: '', snapshotHint: `Live page summary unavailable: ${String(error).slice(0, 300)}. Re-read the page before continuing.`, fresh: false })
|
|
697
|
-
if (exec.signal.aborted) return { outcome: 'cancelled', page: unavailable('turn stopped') }
|
|
698
|
-
pending.phase = 'summary'
|
|
699
|
-
let fresh: TakeoverSummary
|
|
700
|
-
try {
|
|
701
|
-
if (!page.pageId.startsWith('iframe:')) {
|
|
702
|
-
const browser = ctx.get('browser')!
|
|
703
|
-
const session = await browser.bindPanelPage(`session-${page.owner}`, page.pageId)
|
|
704
|
-
const snapshot = await browser.snapshot(session, AbortSignal.any([exec.signal, AbortSignal.timeout(5000)]))
|
|
705
|
-
fresh = { url: snapshot.url, title: (snapshot.title ?? '').slice(0, 1000), snapshotHint: formatSnapshot(snapshot, {}).slice(0, 1500), fresh: true }
|
|
706
|
-
} else {
|
|
707
|
-
fresh = await new Promise<TakeoverSummary>((resolve, reject) => {
|
|
708
|
-
const finish = (value?: TakeoverSummary, error?: unknown): void => {
|
|
709
|
-
clearTimeout(timer); exec.signal.removeEventListener('abort', abort)
|
|
710
|
-
if (error !== undefined) reject(error); else resolve(value!)
|
|
711
|
-
}
|
|
712
|
-
const abort = (): void => { finish(undefined, exec.signal.reason) }
|
|
713
|
-
const timer = setTimeout(() => { finish(undefined, new Error('sidebar summary timed out')) }, 8000)
|
|
714
|
-
exec.signal.addEventListener('abort', abort, { once: true })
|
|
715
|
-
void pending.summary.then(value => { finish(value) })
|
|
716
|
-
if (exec.signal.aborted) abort()
|
|
717
|
-
})
|
|
718
|
-
}
|
|
719
|
-
} catch (error) { fresh = unavailable(error) }
|
|
720
|
-
return { outcome: exec.signal.aborted ? 'cancelled' : outcome, page: fresh }
|
|
721
|
-
})
|
|
722
|
-
},
|
|
723
|
-
}))
|
|
724
|
-
|
|
725
|
-
// The start page's shared shortcut list, reached through the settings section the
|
|
726
|
-
// sidebar edits. Built lazily for the same reason `references()` is: the settings
|
|
727
|
-
// service is registered by another entry and may not exist yet at apply time.
|
|
728
|
-
const startpageShortcuts = createShortcutStore(() => ctx.get('settings') as unknown as ShortcutSettings | undefined)
|
|
729
|
-
registerSafely(defineTool({
|
|
730
|
-
name: 'dsh_browser_shortcuts',
|
|
731
|
-
description: 'Read or edit the Sidebar Browser start page shortcuts — the shared website entries a human sees on an empty tab. action=list returns them, action=add appends one (title + http(s) url required, http:// or https:// only, at most 48 entries), action=remove drops one by id. The list is shared with the sidebar UI: an entry added here appears on the next empty tab for every conversation, and one a human adds appears here.',
|
|
732
|
-
parameters: {
|
|
733
|
-
action: { type: 'string', required: true, enum: ['list', 'add', 'remove'], description: 'list the shortcuts, add one, or remove one by id.' },
|
|
734
|
-
title: { type: 'string', description: 'Display title (add). At most 80 characters.' },
|
|
735
|
-
url: { type: 'string', description: 'Destination (add): a full http:// or https:// address.' },
|
|
736
|
-
id: { type: 'string', description: 'Shortcut id (remove), as returned by list or add.' },
|
|
737
|
-
},
|
|
738
|
-
output: {
|
|
739
|
-
schema: {
|
|
740
|
-
type: 'object',
|
|
741
|
-
additionalProperties: false,
|
|
742
|
-
properties: {
|
|
743
|
-
shortcuts: {
|
|
744
|
-
type: 'array',
|
|
745
|
-
required: true,
|
|
746
|
-
items: {
|
|
747
|
-
type: 'object',
|
|
748
|
-
additionalProperties: false,
|
|
749
|
-
properties: {
|
|
750
|
-
id: { type: 'string', required: true },
|
|
751
|
-
title: { type: 'string', required: true },
|
|
752
|
-
url: { type: 'string', required: true },
|
|
753
|
-
iconKey: { type: 'string' },
|
|
754
|
-
},
|
|
755
|
-
},
|
|
756
|
-
},
|
|
757
|
-
changed: { type: 'string', description: 'What the call changed: added <id>, removed <id>, or empty for list.' },
|
|
758
|
-
},
|
|
759
|
-
},
|
|
760
|
-
render: (_args, value) => {
|
|
761
|
-
const rows = value.shortcuts as Array<{ id: string; title: string; url: string }>
|
|
762
|
-
const changed = typeof value.changed === 'string' && value.changed !== '' ? `${value.changed}\n` : ''
|
|
763
|
-
const body = rows.length === 0
|
|
764
|
-
? '(the start page has no shortcuts)'
|
|
765
|
-
: rows.map(row => `- ${row.title} -> ${row.url} [${row.id}]`).join('\n')
|
|
766
|
-
return [{ type: 'text', text: `${changed}${rows.length} shortcut(s):\n${body}` }]
|
|
767
|
-
},
|
|
768
|
-
},
|
|
769
|
-
timeoutMs,
|
|
770
|
-
isConcurrencySafe: () => false,
|
|
771
|
-
async execute(args, exec) {
|
|
772
|
-
assertAllowed(state, 'dsh_browser_shortcuts', taskKey(exec))
|
|
773
|
-
try {
|
|
774
|
-
if (args.action === 'list') {
|
|
775
|
-
const reading = startpageShortcuts.list()
|
|
776
|
-
return { shortcuts: reading.shortcuts.map(row => ({ ...row })), changed: '' }
|
|
777
|
-
}
|
|
778
|
-
if (args.action === 'add') {
|
|
779
|
-
const result = await startpageShortcuts.add({ title: args.title, url: args.url })
|
|
780
|
-
return { shortcuts: result.shortcuts.map(row => ({ ...row })), changed: `added ${result.shortcut.id}` }
|
|
781
|
-
}
|
|
782
|
-
if (typeof args.id !== 'string' || args.id === '') throw new Error('remove needs the shortcut id')
|
|
783
|
-
const result = await startpageShortcuts.remove(args.id)
|
|
784
|
-
return {
|
|
785
|
-
shortcuts: result.shortcuts.map(row => ({ ...row })),
|
|
786
|
-
changed: result.removed ? `removed ${args.id}` : `${args.id} was not in the list`,
|
|
787
|
-
}
|
|
788
|
-
} catch (error) {
|
|
789
|
-
// The store reports refusals as typed errors; a tool must not answer with a stack.
|
|
790
|
-
throw new Error(`start page shortcuts: ${error instanceof Error ? error.message : String(error)}`)
|
|
791
|
-
}
|
|
792
|
-
},
|
|
793
|
-
}))
|
|
794
|
-
|
|
795
|
-
registerSafely(defineTool({
|
|
796
|
-
name: 'dsh_browser_open',
|
|
797
|
-
description: 'Open a URL on the selected controllable surface (default: panel). Success returns a live snapshot and supports subsequent browser tools on that same page. A Web iframe or unavailable desktop bridge is refused; no manual-only navigation is queued. Reading tools never start another browser. newTab is optional on CDP surfaces. Never treat the bare DSH host (e.g. http://127.0.0.1:3080/) as the target — it needs the authenticated URL printed by `dsh web`, and the bare root is refused.',
|
|
798
|
-
parameters: {
|
|
799
|
-
url: { type: 'string', required: true, description: 'The URL to open (HTTP/HTTPS).' },
|
|
800
|
-
newTab: { type: 'boolean', description: 'Open in a new tab instead of the active one.' },
|
|
801
|
-
// Explicit per-call surface. "panel" (default) places the page in the DSH sidebar and opens no
|
|
802
|
-
// window; "builtin" drives the plugin's own browser, which is what debugging DSH itself needs.
|
|
803
|
-
surface: { type: 'string', enum: ['panel', 'builtin'], description: 'panel (default): the DSH sidebar only; builtin: the plugin browser, for debugging DSH itself.' },
|
|
804
|
-
},
|
|
805
|
-
output: {
|
|
806
|
-
schema: {
|
|
807
|
-
type: 'object',
|
|
808
|
-
additionalProperties: false,
|
|
809
|
-
properties: {
|
|
810
|
-
url: { type: 'string', required: true },
|
|
811
|
-
title: { type: 'string' },
|
|
812
|
-
carrier: { type: 'string' },
|
|
813
|
-
truncated: { type: 'boolean' },
|
|
814
|
-
elements: {
|
|
815
|
-
type: 'array',
|
|
816
|
-
required: true,
|
|
817
|
-
// Same shared item schema as dsh_browser_open's, so the two cannot drift apart.
|
|
818
|
-
items: ELEMENT_ITEM_SCHEMA,
|
|
819
|
-
},
|
|
820
|
-
challenge: {
|
|
821
|
-
type: 'object',
|
|
822
|
-
additionalProperties: false,
|
|
823
|
-
properties: {
|
|
824
|
-
blocked: { type: 'boolean', required: true },
|
|
825
|
-
kind: { type: 'string' },
|
|
826
|
-
reason: { type: 'string' },
|
|
827
|
-
},
|
|
828
|
-
},
|
|
829
|
-
},
|
|
830
|
-
},
|
|
831
|
-
// dsh_browser_open is an overview of what just loaded, not a locator: it has no
|
|
832
|
-
// `coords` parameter, so coordinates stay off here (dsh_browser_snapshot owns
|
|
833
|
-
// that switch for callers that actually target pixels).
|
|
834
|
-
render: (_args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
|
|
835
|
-
},
|
|
836
|
-
timeoutMs,
|
|
837
|
-
isConcurrencySafe: () => false, // opens tabs / navigates; exclusive within a task
|
|
838
|
-
async execute(args, exec) {
|
|
839
|
-
assertAllowed(state, 'dsh_browser_open', taskKey(exec))
|
|
840
|
-
assertNotBareDshWebUrl(args.url)
|
|
841
|
-
// ONE surface per open. On the Web shell the reader's sidebar is the browsing surface; opening the
|
|
842
|
-
// plugin's own browser as well produced two live views of the same page (reported as "you opened the
|
|
843
|
-
// built-in browser AND the sidebar at once"). `browser.surface` decides: "panel" (default on Web)
|
|
844
|
-
// places the page in the sidebar and opens no window; "builtin" is the debugging surface.
|
|
845
|
-
const surfaceHint = (args as { surface?: 'panel' | 'builtin' }).surface
|
|
846
|
-
const surface = enforceSurface(surfaceHint ?? readSurface(), args.url)
|
|
847
|
-
const browser = ctx.get('browser')
|
|
848
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
849
|
-
const key = taskKey(exec)
|
|
850
|
-
if (surface === 'panel') {
|
|
851
|
-
const preceding = state.pendingPanelOpens.get(key)
|
|
852
|
-
let previous: BrowserSessionId | undefined
|
|
853
|
-
let session: BrowserSessionId | undefined
|
|
854
|
-
const opening = (async () => {
|
|
855
|
-
await preceding
|
|
856
|
-
await state.pendingOpens.get(key)
|
|
857
|
-
previous = state.sessionsByTask.get(key)
|
|
858
|
-
const target = new URL(args.url)
|
|
859
|
-
if (target.protocol !== 'http:' && target.protocol !== 'https:') throw new Error('dsh_browser_open: panel requires an HTTP/HTTPS URL')
|
|
860
|
-
exec.signal?.throwIfAborted()
|
|
861
|
-
session = state.panelUrlByTask.has(key) && previous !== undefined && browser.exists(previous)
|
|
862
|
-
? previous : await browser.openPanel?.(key)
|
|
863
|
-
if (session === undefined) {
|
|
864
|
-
assertSurfaceCanHost(surface, args.url)
|
|
865
|
-
exec.signal?.throwIfAborted()
|
|
866
|
-
setLastOpen(args.url, Date.now(), key)
|
|
867
|
-
rememberSession(browser, state, key, agentOf(exec), undefined, args.url)
|
|
868
|
-
return { url: args.url, carrier: 'panel-iframe-navigation-requested', title: '', elements: [], truncated: false }
|
|
869
|
-
}
|
|
870
|
-
await browser.openUrl(session, { url: args.url, ...args.newTab === true ? { newTab: true } : {} }, exec.signal)
|
|
871
|
-
const snapshot = await browser.snapshot(session, exec.signal)
|
|
872
|
-
exec.signal?.throwIfAborted()
|
|
873
|
-
rememberSession(browser, state, key, agentOf(exec), session, args.url)
|
|
874
|
-
return {
|
|
875
|
-
url: snapshot.url,
|
|
876
|
-
...snapshot.title !== undefined ? { title: snapshot.title } : {},
|
|
877
|
-
elements: snapshot.elements.map(el => projectElement(el)),
|
|
878
|
-
truncated: snapshot.truncated,
|
|
879
|
-
...snapshot.challenge !== undefined ? { challenge: snapshot.challenge } : {},
|
|
880
|
-
}
|
|
881
|
-
})()
|
|
882
|
-
const pending = opening.then(() => {})
|
|
883
|
-
state.pendingPanelOpens.set(key, pending)
|
|
884
|
-
void pending.catch(() => {})
|
|
885
|
-
try { return await opening } catch (error) {
|
|
886
|
-
if (session !== undefined && session !== previous) await browser.close(session).catch(() => {})
|
|
887
|
-
throw error
|
|
888
|
-
} finally {
|
|
889
|
-
if (state.pendingPanelOpens.get(key) === pending) state.pendingPanelOpens.delete(key)
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
await state.pendingPanelOpens.get(key)
|
|
893
|
-
await state.pendingOpens.get(key)
|
|
894
|
-
if (state.panelUrlByTask.has(key)) {
|
|
895
|
-
const previous = state.sessionsByTask.get(key)
|
|
896
|
-
state.sessionsByTask.delete(key)
|
|
897
|
-
state.panelUrlByTask.delete(key)
|
|
898
|
-
if (previous !== undefined) await browser.close(previous)
|
|
899
|
-
}
|
|
900
|
-
const session = await ensureSession(browser, state, key, agentOf(exec), true)
|
|
901
|
-
try {
|
|
902
|
-
await browser.openUrl(session, {
|
|
903
|
-
url: args.url,
|
|
904
|
-
...args.newTab === true ? { newTab: true } : {},
|
|
905
|
-
}, exec.signal)
|
|
906
|
-
} catch (error) {
|
|
907
|
-
// The human's browser is already running on its own profile: the launch hands the request over and
|
|
908
|
-
// exits with code 0. A new window opened inside THEIR browser with their logins — what "use my
|
|
909
|
-
// Edge" means — it is simply not driveable, because their instance has no debugging port.
|
|
910
|
-
const message = error instanceof Error ? error.message : String(error)
|
|
911
|
-
if (!/exited immediately after launch \(exit code 0\)/u.test(message)) throw error
|
|
912
|
-
return { url: args.url, carrier: 'launched-user-profile', title: '', elements: [], truncated: false }
|
|
913
|
-
}
|
|
914
|
-
// Hand the page to the Web sidebar as well. The desktop shell is told through the bridge; the Web
|
|
915
|
-
// shell has no such channel, so the client polls this slot and places the tab itself. Written in the
|
|
916
|
-
// TOOL (not a provider) on purpose: every open passes through here whatever serves it.
|
|
917
|
-
try { setLastOpen(args.url, Date.now()) } catch { /* best effort */ }
|
|
918
|
-
let snapshot: Awaited<ReturnType<typeof browser.snapshot>>
|
|
919
|
-
try {
|
|
920
|
-
snapshot = await browser.snapshot(session, exec.signal)
|
|
921
|
-
} catch (error) {
|
|
922
|
-
// The human's browser is ALREADY running on its own profile, so a launch hands the request over
|
|
923
|
-
// and the launcher exits with code 0. That is not a failure: a new window opened inside THEIR
|
|
924
|
-
// browser, with their logins, which is exactly what "use my Edge" means. It is only undriveable,
|
|
925
|
-
// because their instance has no debugging port. Report the page, not an error.
|
|
926
|
-
const message = error instanceof Error ? error.message : String(error)
|
|
927
|
-
if (!/exited immediately after launch \(exit code 0\)/u.test(message)) throw error
|
|
928
|
-
return {
|
|
929
|
-
url: args.url,
|
|
930
|
-
carrier: 'launched-user-profile',
|
|
931
|
-
title: '',
|
|
932
|
-
elements: [],
|
|
933
|
-
truncated: false,
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
return {
|
|
937
|
-
url: snapshot.url,
|
|
938
|
-
carrier: String((globalThis as unknown as Record<string, unknown>).__dshBrowserCarrier ?? 'bundled'),
|
|
939
|
-
...snapshot.title !== undefined ? { title: snapshot.title } : {},
|
|
940
|
-
elements: snapshot.elements.map(el => projectElement(el)),
|
|
941
|
-
truncated: snapshot.truncated,
|
|
942
|
-
...snapshot.challenge !== undefined ? { challenge: snapshot.challenge } : {},
|
|
943
|
-
}
|
|
944
|
-
},
|
|
945
|
-
}))
|
|
946
|
-
|
|
947
|
-
registerSafely(defineTool({
|
|
948
|
-
name: 'dsh_browser_snapshot',
|
|
949
|
-
description: 'Return an AI-friendly snapshot of the current shared-browser page: numbered interactive elements (inputs, buttons, links) the model can cite. This is the primary way to understand a page, and it needs no image input — every listed element can afterwards be addressed by a semantic target (dsh_browser_click, dsh_browser_type, dsh_browser_check, …) rather than by coordinates.',
|
|
950
|
-
parameters: {
|
|
951
|
-
coords: { type: 'boolean', description: 'Also print each element\'s viewport coordinates. Off by default; only useful when a vision pass is going to click a pixel position.' },
|
|
952
|
-
},
|
|
953
|
-
output: {
|
|
954
|
-
schema: {
|
|
955
|
-
type: 'object',
|
|
956
|
-
additionalProperties: false,
|
|
957
|
-
properties: {
|
|
958
|
-
url: { type: 'string', required: true },
|
|
959
|
-
title: { type: 'string' },
|
|
960
|
-
truncated: { type: 'boolean' },
|
|
961
|
-
elements: {
|
|
962
|
-
type: 'array',
|
|
963
|
-
required: true,
|
|
964
|
-
items: {
|
|
965
|
-
type: 'object',
|
|
966
|
-
additionalProperties: false,
|
|
967
|
-
properties: {
|
|
968
|
-
ref: { type: 'number', required: true },
|
|
969
|
-
kind: { type: 'string', required: true },
|
|
970
|
-
label: { type: 'string', required: true },
|
|
971
|
-
x: { type: 'number', required: true },
|
|
972
|
-
y: { type: 'number', required: true },
|
|
973
|
-
frame: { type: 'boolean' },
|
|
974
|
-
// The page-side script computes this for every element and the tool layer
|
|
975
|
-
// passes it through. Without it in the schema, a declared
|
|
976
|
-
// additionalProperties: false rejects the whole result at run time — which is
|
|
977
|
-
// how this was found, on the very first real call, after a static review had
|
|
978
|
-
// called the change verified.
|
|
979
|
-
selector: { type: 'string' },
|
|
980
|
-
},
|
|
981
|
-
},
|
|
982
|
-
},
|
|
983
|
-
challenge: {
|
|
984
|
-
type: 'object',
|
|
985
|
-
additionalProperties: false,
|
|
986
|
-
properties: {
|
|
987
|
-
blocked: { type: 'boolean', required: true },
|
|
988
|
-
kind: { type: 'string' },
|
|
989
|
-
reason: { type: 'string' },
|
|
990
|
-
},
|
|
991
|
-
},
|
|
992
|
-
},
|
|
993
|
-
},
|
|
994
|
-
render: (args, value) => [{ type: 'text', text: formatSnapshot(value, { coords: args.coords === true }) }],
|
|
995
|
-
},
|
|
996
|
-
timeoutMs,
|
|
997
|
-
isConcurrencySafe: () => true,
|
|
998
|
-
async execute(_args, exec) {
|
|
999
|
-
const browser = ctx.get('browser')
|
|
1000
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1001
|
-
const key = taskKey(exec)
|
|
1002
|
-
const session = await ensureSession(browser, state, key, agentOf(exec))
|
|
1003
|
-
const snapshot = await browser.snapshot(session, exec.signal)
|
|
1004
|
-
return {
|
|
1005
|
-
url: snapshot.url,
|
|
1006
|
-
...snapshot.title !== undefined ? { title: snapshot.title } : {},
|
|
1007
|
-
elements: snapshot.elements.map(el => projectElement(el)),
|
|
1008
|
-
truncated: snapshot.truncated,
|
|
1009
|
-
...snapshot.challenge !== undefined ? { challenge: snapshot.challenge } : {},
|
|
1010
|
-
}
|
|
1011
|
-
},
|
|
1012
|
-
}))
|
|
1013
|
-
|
|
1014
|
-
registerSafely(defineTool({
|
|
1015
|
-
name: 'dsh_browser_a11y',
|
|
1016
|
-
description: 'Read the accessibility tree: every interactive node with its role (button/link/textbox/checkbox/…), accessible name, value, and states (enabled/checked/expanded/…); coordinates only with coords: true. Prefer this over dsh_browser_snapshot to understand structure and find the right element — roles and names say WHAT each node is, and the name is what dsh_browser_click matches when targeting by text. Penetrates same-origin iframes and shadow roots.',
|
|
1017
|
-
parameters: {
|
|
1018
|
-
includeHidden: { type: 'boolean', description: 'Include hidden elements (default false).' },
|
|
1019
|
-
maxNodes: { type: 'number', description: 'Maximum nodes (default 150, range 10-5000).' },
|
|
1020
|
-
coords: { type: 'boolean', description: 'Include each element\'s viewport coordinates. Off by default: a semantic target needs no coordinates, and they are pure noise unless a vision pass is going to click a pixel position.' },
|
|
1021
|
-
},
|
|
1022
|
-
output: {
|
|
1023
|
-
schema: {
|
|
1024
|
-
type: 'object',
|
|
1025
|
-
additionalProperties: false,
|
|
1026
|
-
properties: {
|
|
1027
|
-
url: { type: 'string', required: true },
|
|
1028
|
-
title: { type: 'string' },
|
|
1029
|
-
count: { type: 'number', required: true },
|
|
1030
|
-
truncated: { type: 'boolean' },
|
|
1031
|
-
nodes: {
|
|
1032
|
-
type: 'array',
|
|
1033
|
-
required: true,
|
|
1034
|
-
// Same shared table as the node projection.
|
|
1035
|
-
items: NODE_ITEM_SCHEMA,
|
|
1036
|
-
},
|
|
1037
|
-
},
|
|
1038
|
-
},
|
|
1039
|
-
render: (args, value) => {
|
|
1040
|
-
const nodes = value.nodes as Array<{ ref: number; role: string; name: string; value?: string | null; states: string[]; depth: number; tag: string; x: number; y: number; frame?: boolean; selector?: string }>
|
|
1041
|
-
// Built for reading, not for imaging: containment is shown as indentation
|
|
1042
|
-
// (the depth was already collected and simply thrown away), an empty state
|
|
1043
|
-
// list adds nothing, and coordinates appear only when asked for — a model
|
|
1044
|
-
// working from the DOM never needs them, and they are the bulkiest part of
|
|
1045
|
-
// every line.
|
|
1046
|
-
const showCoords = args.coords === true
|
|
1047
|
-
const lines = nodes.map(n => {
|
|
1048
|
-
const valuePart = n.value !== undefined && n.value !== null ? ` value="${String(n.value).slice(0, 60)}"` : ''
|
|
1049
|
-
// One space per level, not two: indentation was 19.7% of a measured 38,953-character
|
|
1050
|
-
// result, and DOM depth is not a11y depth — deep wrapper divs push it to the cap.
|
|
1051
|
-
const indent = ' '.repeat(Math.max(0, Math.min(8, Number(n.depth) || 0)))
|
|
1052
|
-
const coordsPart = showCoords ? ` (${n.x},${n.y})` : ''
|
|
1053
|
-
// Only states that are not the default. `states=[enabled]` was printed on 405 of 500
|
|
1054
|
-
// nodes whose state WAS the default — 22% of the output for no information. Absence
|
|
1055
|
-
// now means "enabled", which the description states.
|
|
1056
|
-
const notableStates = Array.isArray(n.states) ? n.states.filter((state: string) => state !== 'enabled') : []
|
|
1057
|
-
const statePart = notableStates.length > 0 ? ` states=[${notableStates.join(',')}]` : ''
|
|
1058
|
-
// The provider computes this for a node with an id or a name; printing it is what
|
|
1059
|
-
// makes the node something the caller can point at instead of guessing at its text.
|
|
1060
|
-
const selectorPart = typeof n.selector === 'string' && n.selector !== '' ? ` {${n.selector}}` : ''
|
|
1061
|
-
return `${indent}[${n.ref}] ${n.role} "${n.name}"${valuePart}${coordsPart}${statePart}${selectorPart}${n.frame === true ? ' (iframe)' : ''}`
|
|
1062
|
-
})
|
|
1063
|
-
const header = `URL: ${value.url}${value.title !== undefined ? `\nTitle: ${value.title}` : ''}`
|
|
1064
|
-
// The "coords: true" hint used to be appended to EVERY a11y result. It already lives in
|
|
1065
|
-
// the parameter description, so repeating it in each model turn was pure token cost.
|
|
1066
|
-
return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}` }]
|
|
1067
|
-
},
|
|
1068
|
-
},
|
|
1069
|
-
timeoutMs,
|
|
1070
|
-
isConcurrencySafe: () => true,
|
|
1071
|
-
async execute(args, exec) {
|
|
1072
|
-
const browser = ctx.get('browser')
|
|
1073
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1074
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1075
|
-
const result = await browser.a11y(session, {
|
|
1076
|
-
...args.includeHidden === true ? { includeHidden: true } : {},
|
|
1077
|
-
...args.maxNodes !== undefined ? { maxNodes: args.maxNodes } : {},
|
|
1078
|
-
}, exec.signal)
|
|
1079
|
-
return {
|
|
1080
|
-
url: result.url,
|
|
1081
|
-
...result.title !== undefined ? { title: result.title } : {},
|
|
1082
|
-
count: result.count,
|
|
1083
|
-
truncated: result.truncated,
|
|
1084
|
-
// The projection drops `value: null` (the schema declares a string, and the contract is
|
|
1085
|
-
// that an absent value means "not applicable"), so the run-time shape and the inferred
|
|
1086
|
-
// type differ by exactly that. The field table is what keeps the schema and the
|
|
1087
|
-
// projection in agreement; this assertion is the type-level echo of that.
|
|
1088
|
-
// The projection and the schema are now generated from one field table, so the shape
|
|
1089
|
-
// they agree on is guaranteed at run time. TypeScript cannot see that agreement — it
|
|
1090
|
-
// infers the output type from the schema object and compares it against the provider's
|
|
1091
|
-
// interface, which describes the provider's internal shape rather than the contract
|
|
1092
|
-
// (`value` nullable internally, absent on the wire; `selector` required by the
|
|
1093
|
-
// interface, optional in the inferred schema). The assertion bridges that last gap; the
|
|
1094
|
-
// test that walks every registered tool is what checks the agreement for real.
|
|
1095
|
-
nodes: result.nodes.map(n => projectNode(n)) as never,
|
|
1096
|
-
}
|
|
1097
|
-
},
|
|
1098
|
-
}))
|
|
1099
|
-
|
|
1100
|
-
registerSafely(defineTool({
|
|
1101
|
-
name: 'dsh_browser_challenge',
|
|
1102
|
-
description: 'Check whether a human-verification challenge (CAPTCHA / bot detection: Cloudflare "Just a moment", reCAPTCHA, hCaptcha, Turnstile) is blocking the current page. When blocked, do NOT keep retrying automated steps — ask the human to complete the verification in the shared browser window, then re-check with dsh_browser_snapshot.',
|
|
1103
|
-
parameters: {},
|
|
1104
|
-
output: {
|
|
1105
|
-
schema: {
|
|
1106
|
-
type: 'object',
|
|
1107
|
-
additionalProperties: false,
|
|
1108
|
-
properties: {
|
|
1109
|
-
blocked: { type: 'boolean', required: true },
|
|
1110
|
-
kind: { type: 'string' },
|
|
1111
|
-
reason: { type: 'string' },
|
|
1112
|
-
hint: { type: 'string' },
|
|
1113
|
-
},
|
|
1114
|
-
},
|
|
1115
|
-
render: (_args, value) => [{
|
|
1116
|
-
type: 'text',
|
|
1117
|
-
text: value.blocked
|
|
1118
|
-
? `Challenge detected: ${value.reason ?? value.kind ?? 'human-verification'}. ${value.hint ?? ''}`
|
|
1119
|
-
: 'No human-verification challenge detected.',
|
|
1120
|
-
}],
|
|
1121
|
-
},
|
|
1122
|
-
timeoutMs,
|
|
1123
|
-
isConcurrencySafe: () => true,
|
|
1124
|
-
async execute(_args, exec) {
|
|
1125
|
-
const browser = ctx.get('browser')
|
|
1126
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1127
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1128
|
-
const challenge = await browser.detectChallenge(session, exec.signal)
|
|
1129
|
-
return {
|
|
1130
|
-
blocked: challenge.blocked,
|
|
1131
|
-
...challenge.kind !== undefined ? { kind: challenge.kind } : {},
|
|
1132
|
-
...challenge.reason !== undefined ? { reason: challenge.reason } : {},
|
|
1133
|
-
hint: challenge.blocked
|
|
1134
|
-
? 'Ask the human to complete the verification in the shared browser window (the page is visible to them), then re-check with dsh_browser_snapshot.'
|
|
1135
|
-
: '',
|
|
1136
|
-
}
|
|
1137
|
-
},
|
|
1138
|
-
}))
|
|
1139
|
-
|
|
1140
|
-
registerSafely(defineTool({
|
|
1141
|
-
name: 'dsh_browser_wait',
|
|
1142
|
-
description: 'Wait until the shared-browser page is ready: load complete, and optionally the expected URL and/or a CSS selector present (top document or same-origin iframes). Use after dsh_browser_open on slow sites instead of snapshotting a white page — wait for the URL you navigated to first. Returns ready=true/false with a short reason; a miss is not an error.',
|
|
1143
|
-
parameters: {
|
|
1144
|
-
timeoutMs: { type: 'number', description: 'Maximum wait in ms (default 30000).' },
|
|
1145
|
-
url: { type: 'string', description: 'Expected page URL (exact or prefix), e.g. the URL you opened.' },
|
|
1146
|
-
selector: { type: 'string', description: 'CSS selector that must exist.' },
|
|
1147
|
-
},
|
|
1148
|
-
output: {
|
|
1149
|
-
schema: {
|
|
1150
|
-
type: 'object',
|
|
1151
|
-
additionalProperties: false,
|
|
1152
|
-
properties: {
|
|
1153
|
-
ready: { type: 'boolean', required: true },
|
|
1154
|
-
reason: { type: 'string', required: true },
|
|
1155
|
-
},
|
|
1156
|
-
},
|
|
1157
|
-
render: (_args, value) => [{ type: 'text', text: value.ready ? 'Page ready.' : `Wait timed out: ${value.reason}` }],
|
|
1158
|
-
},
|
|
1159
|
-
timeoutMs,
|
|
1160
|
-
isConcurrencySafe: () => true,
|
|
1161
|
-
async execute(args, exec) {
|
|
1162
|
-
const browser = ctx.get('browser')
|
|
1163
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1164
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1165
|
-
const result = await browser.waitFor(session, {
|
|
1166
|
-
// Capped so an over-budget argument returns the documented verdict (see maxWaitMs)
|
|
1167
|
-
// rather than aborting the whole tool call.
|
|
1168
|
-
...args.timeoutMs !== undefined ? { timeoutMs: Math.min(args.timeoutMs, maxWaitMs) } : {},
|
|
1169
|
-
...args.url !== undefined ? { url: args.url } : {},
|
|
1170
|
-
...args.selector !== undefined ? { selector: args.selector } : {},
|
|
1171
|
-
}, exec.signal)
|
|
1172
|
-
return { ready: result.ready, reason: result.reason }
|
|
1173
|
-
},
|
|
1174
|
-
}))
|
|
1175
|
-
|
|
1176
|
-
registerSafely(defineTool({
|
|
1177
|
-
name: 'dsh_browser_execute',
|
|
1178
|
-
description: 'Execute JavaScript in the shared-browser page context. This is the primary way to interact with page elements: focus, fill inputs (use the native value setter for framework-controlled inputs, then dispatch an input event), click buttons (element.click() or a constructed MouseEvent). Returns the evaluation result by value, or the exception text.',
|
|
1179
|
-
parameters: {
|
|
1180
|
-
script: { type: 'string', required: true, description: 'The JavaScript expression to evaluate in the page context.' },
|
|
1181
|
-
args: { type: 'array', items: { type: 'string' }, description: 'Optional arguments injected into the script scope as arguments[0..n].' },
|
|
1182
|
-
},
|
|
1183
|
-
output: {
|
|
1184
|
-
schema: {
|
|
1185
|
-
type: 'object',
|
|
1186
|
-
additionalProperties: false,
|
|
1187
|
-
properties: {
|
|
1188
|
-
ok: { type: 'boolean', required: true },
|
|
1189
|
-
value: { type: 'string' },
|
|
1190
|
-
exception: { type: 'string' },
|
|
1191
|
-
},
|
|
1192
|
-
},
|
|
1193
|
-
// A return value is whatever the page produced, and `document.body.outerHTML` measured
|
|
1194
|
-
// 157,350 characters — ~39-52k tokens from one call. Bounded, with the cut stated so the
|
|
1195
|
-
// caller knows to narrow the expression rather than the value being silently short.
|
|
1196
|
-
render: (_args, value) => {
|
|
1197
|
-
if (!value.ok) return [{ type: 'text', text: `Exception: ${value.exception}` }]
|
|
1198
|
-
const rendered = String(value.value ?? '')
|
|
1199
|
-
const cap = 50_000
|
|
1200
|
-
const text = rendered.length > cap
|
|
1201
|
-
? `Result: ${rendered.slice(0, cap)}\n(result truncated at ${cap} of ${rendered.length} characters — return a smaller value, or write it with dsh_browser_execute + a variable)`
|
|
1202
|
-
: `Result: ${rendered}`
|
|
1203
|
-
return [{ type: 'text', text }]
|
|
1204
|
-
},
|
|
1205
|
-
},
|
|
1206
|
-
timeoutMs,
|
|
1207
|
-
isConcurrencySafe: () => false, // page JS can be stateful
|
|
1208
|
-
async execute(args, exec) {
|
|
1209
|
-
assertAllowed(state, 'dsh_browser_execute', taskKey(exec))
|
|
1210
|
-
const browser = ctx.get('browser')
|
|
1211
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1212
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1213
|
-
const result = await browser.execute(session, {
|
|
1214
|
-
script: args.script,
|
|
1215
|
-
args: args.args ?? [],
|
|
1216
|
-
}, exec.signal)
|
|
1217
|
-
if (result.ok) {
|
|
1218
|
-
const raw = result.value
|
|
1219
|
-
const value = typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
|
|
1220
|
-
return { ok: true, value }
|
|
1221
|
-
}
|
|
1222
|
-
return { ok: false, exception: result.exception }
|
|
1223
|
-
},
|
|
1224
|
-
}))
|
|
1225
|
-
|
|
1226
|
-
registerSafely(defineTool({
|
|
1227
|
-
name: 'dsh_browser_content',
|
|
1228
|
-
description: 'Fetch the current shared-browser page content in a chosen format: html (raw DOM), markdown (structured reading), txt (plain text), or json. Optionally scope to a CSS selector and cap the length. Use this to read page content, not to interact.',
|
|
1229
|
-
parameters: {
|
|
1230
|
-
format: { type: 'string', required: true, enum: ['html', 'markdown', 'txt', 'json'], description: 'Output format.' },
|
|
1231
|
-
selector: { type: 'string', description: 'CSS selector limiting the fetch to one region (e.g. #main).' },
|
|
1232
|
-
maxChars: { type: 'number', description: 'Maximum characters of returned content.' },
|
|
1233
|
-
timeoutMs: { type: 'number', description: 'Evaluation timeout in ms (default 30000).' },
|
|
1234
|
-
},
|
|
1235
|
-
output: {
|
|
1236
|
-
schema: {
|
|
1237
|
-
type: 'object',
|
|
1238
|
-
additionalProperties: false,
|
|
1239
|
-
properties: {
|
|
1240
|
-
content: { type: 'string', required: true },
|
|
1241
|
-
truncated: { type: 'boolean', required: true },
|
|
1242
|
-
},
|
|
1243
|
-
},
|
|
1244
|
-
render: (_args, value) => [{ type: 'text', text: value.content + (value.truncated ? `\n(content truncated — narrow it with selector= or raise maxChars)` : '') }],
|
|
1245
|
-
},
|
|
1246
|
-
timeoutMs,
|
|
1247
|
-
isConcurrencySafe: () => true,
|
|
1248
|
-
async execute(args, exec) {
|
|
1249
|
-
const browser = ctx.get('browser')
|
|
1250
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1251
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1252
|
-
const result = await browser.content(session, {
|
|
1253
|
-
format: args.format,
|
|
1254
|
-
...args.selector !== undefined ? { selector: args.selector } : {},
|
|
1255
|
-
...args.maxChars !== undefined ? { maxChars: args.maxChars } : {},
|
|
1256
|
-
...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
|
|
1257
|
-
}, exec.signal)
|
|
1258
|
-
return { content: result.content, truncated: result.truncated }
|
|
1259
|
-
},
|
|
1260
|
-
}))
|
|
1261
|
-
|
|
1262
|
-
registerSafely(defineTool({
|
|
1263
|
-
name: 'dsh_browser_scrape',
|
|
1264
|
-
description: 'Extract structured data from a page: give the container CSS selector (item) and a field map (name -> selector, optionally selector@attr to take an attribute; a@href yields the absolute URL). Returns one object per item. Static CSS queries only — no arbitrary code runs — so it is safe on any page. Use for list pages (search results, cards, tables) instead of hand-writing dsh_browser_execute.',
|
|
1265
|
-
parameters: {
|
|
1266
|
-
item: { type: 'string', required: true, description: 'CSS selector of each result container (e.g. "div.card").' },
|
|
1267
|
-
fields: {
|
|
1268
|
-
type: 'object',
|
|
1269
|
-
required: true,
|
|
1270
|
-
additionalProperties: true,
|
|
1271
|
-
description: 'Field map: name -> selector[@attr] (e.g. {"title": "h3", "url": "a@href"}).',
|
|
1272
|
-
},
|
|
1273
|
-
timeoutMs: { type: 'number', description: 'Wait budget for the item selector in ms (default 5000).' },
|
|
1274
|
-
},
|
|
1275
|
-
output: {
|
|
1276
|
-
schema: {
|
|
1277
|
-
type: 'object',
|
|
1278
|
-
additionalProperties: false,
|
|
1279
|
-
properties: {
|
|
1280
|
-
count: { type: 'number', required: true },
|
|
1281
|
-
items: {
|
|
1282
|
-
type: 'array',
|
|
1283
|
-
required: true,
|
|
1284
|
-
items: { type: 'object', additionalProperties: true },
|
|
1285
|
-
},
|
|
1286
|
-
},
|
|
1287
|
-
},
|
|
1288
|
-
render: (_args, value) => [{
|
|
1289
|
-
type: 'text',
|
|
1290
|
-
// Compact, unlike the pretty-printed form this used to emit: two-space indentation
|
|
1291
|
-
// carries no information a model can use and cost 13.7% of a measured 39,559-character
|
|
1292
|
-
// result. The count leads so the caller can tell a short list from a capped one.
|
|
1293
|
-
text: `${value.count} item(s):\n${JSON.stringify(value.items)}`,
|
|
1294
|
-
}],
|
|
1295
|
-
},
|
|
1296
|
-
timeoutMs,
|
|
1297
|
-
isConcurrencySafe: () => true,
|
|
1298
|
-
async execute(args, exec) {
|
|
1299
|
-
assertAllowed(state, 'dsh_browser_scrape', taskKey(exec))
|
|
1300
|
-
const browser = ctx.get('browser')
|
|
1301
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1302
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1303
|
-
const fields = (args.fields ?? {}) as Record<string, string>
|
|
1304
|
-
const result = await browser.scrape(session, {
|
|
1305
|
-
item: args.item,
|
|
1306
|
-
fields: Object.entries(fields).map(([name, selector]) => ({ name, selector })),
|
|
1307
|
-
...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
|
|
1308
|
-
}, exec.signal)
|
|
1309
|
-
return { count: result.count, items: result.items.map(it => ({ ...it })) as never }
|
|
1310
|
-
},
|
|
1311
|
-
}))
|
|
1312
|
-
|
|
1313
|
-
registerSafely(defineTool({
|
|
1314
|
-
name: 'dsh_browser_click',
|
|
1315
|
-
description: 'Click in the shared browser. Prefer target {by: css|text|xpath, value, index?}: the element is located from the DOM, scrolled into view, and clicked at its centre — no image input needed, and the only form that works without vision. Alternatively x/y viewport coordinates, meaningful only after a vision model located the element on a dsh_browser_screenshot; refused under the non-visual strategy. Provide exactly one of target or x/y.',
|
|
1316
|
-
parameters: {
|
|
1317
|
-
target: {
|
|
1318
|
-
type: 'object',
|
|
1319
|
-
additionalProperties: false,
|
|
1320
|
-
properties: {
|
|
1321
|
-
by: { type: 'string', enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css). text matches an element\'s own visible text, exact first then contains.' },
|
|
1322
|
-
value: { type: 'string', required: true, description: 'The CSS selector, visible text, or XPath expression.' },
|
|
1323
|
-
index: { type: 'number', description: '0-based index of the match (default 0).' },
|
|
1324
|
-
},
|
|
1325
|
-
description: 'Locate the element semantically and click it (css/text/xpath).',
|
|
1326
|
-
},
|
|
1327
|
-
x: { type: 'number', description: 'Viewport x coordinate (CSS px), taken from a dsh_browser_screenshot read by a vision model. Prefer a semantic target — it works without image input.' },
|
|
1328
|
-
y: { type: 'number', description: 'Viewport y coordinate (CSS px), taken from the same screenshot as x.' },
|
|
1329
|
-
},
|
|
1330
|
-
output: {
|
|
1331
|
-
schema: { type: 'object', additionalProperties: false, properties: { clicked: { type: 'boolean', required: true }, ...effectProperties } },
|
|
1332
|
-
render: (_args, value) => [{ type: 'text', text: value.clicked ? 'Clicked.' + effectText(value) : 'Click failed.' }],
|
|
1333
|
-
},
|
|
1334
|
-
timeoutMs,
|
|
1335
|
-
isConcurrencySafe: () => false,
|
|
1336
|
-
async execute(args, exec) {
|
|
1337
|
-
assertAllowed(state, 'dsh_browser_click', taskKey(exec))
|
|
1338
|
-
const browser = ctx.get('browser')
|
|
1339
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1340
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1341
|
-
const target = args.target as { by?: string; value?: string; index?: number } | undefined
|
|
1342
|
-
// A target whose value is empty is a caller mistake, not a request to fall back.
|
|
1343
|
-
// Degrading silently sent typed text to whatever held focus — possibly a password
|
|
1344
|
-
// field — or dropped the semantic target in favour of coordinates.
|
|
1345
|
-
if (target !== undefined && typeof target.value === 'string' && target.value === '') {
|
|
1346
|
-
throw new Error('target.value is empty; pass a css selector, visible text or XPath, or omit target entirely to use x/y')
|
|
1347
|
-
}
|
|
1348
|
-
const index = targetIndex(target)
|
|
1349
|
-
const before = await pageFingerprint(browser, session)
|
|
1350
|
-
if (target !== undefined && typeof target.value === 'string' && target.value !== '') {
|
|
1351
|
-
await browser.click(session, {
|
|
1352
|
-
target: {
|
|
1353
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1354
|
-
value: target.value,
|
|
1355
|
-
...index !== undefined ? { index } : {},
|
|
1356
|
-
},
|
|
1357
|
-
}, exec.signal)
|
|
1358
|
-
} else {
|
|
1359
|
-
if (typeof args.x !== 'number' || typeof args.y !== 'number') {
|
|
1360
|
-
throw new Error('dsh_browser_click: provide a target (css/text/xpath) or x/y coordinates')
|
|
1361
|
-
}
|
|
1362
|
-
await browser.click(session, { x: args.x, y: args.y }, exec.signal)
|
|
1363
|
-
}
|
|
1364
|
-
return { clicked: true, ...await observedEffect(browser, session, before) }
|
|
1365
|
-
},
|
|
1366
|
-
}))
|
|
1367
|
-
|
|
1368
|
-
registerSafely(defineTool({
|
|
1369
|
-
name: 'dsh_browser_click_sequence',
|
|
1370
|
-
description: 'Click many points in order, in one call. Use this instead of repeated dsh_browser_click when a page needs a run of coordinate clicks — a canvas board, a map, a drawing surface. Each point is clicked with the same real input sequence the single click uses; between points the call waits intervalMs (default 40 ms), which is what stops a page from reading two presses as a double click. Stops at the first point that fails and says where, so a run that half-landed is reported rather than looking complete.',
|
|
1371
|
-
parameters: {
|
|
1372
|
-
points: {
|
|
1373
|
-
type: 'array',
|
|
1374
|
-
required: true,
|
|
1375
|
-
description: 'Points to click, in order, in viewport CSS pixels — the same space dsh_browser_screenshot reports.',
|
|
1376
|
-
items: {
|
|
1377
|
-
type: 'object',
|
|
1378
|
-
additionalProperties: false,
|
|
1379
|
-
properties: {
|
|
1380
|
-
x: { type: 'number', required: true, description: 'Viewport x in CSS px.' },
|
|
1381
|
-
y: { type: 'number', required: true, description: 'Viewport y in CSS px.' },
|
|
1382
|
-
},
|
|
1383
|
-
},
|
|
1384
|
-
},
|
|
1385
|
-
intervalMs: { type: 'number', description: 'Milliseconds between points (default 40).' },
|
|
1386
|
-
},
|
|
1387
|
-
output: {
|
|
1388
|
-
schema: {
|
|
1389
|
-
type: 'object',
|
|
1390
|
-
additionalProperties: false,
|
|
1391
|
-
properties: {
|
|
1392
|
-
clicked: { type: 'number', required: true, description: 'How many points landed.' },
|
|
1393
|
-
...effectProperties,
|
|
1394
|
-
failedAt: { type: 'number', description: 'Index of the point that failed, when one did.' },
|
|
1395
|
-
error: { type: 'string', description: 'Why that point failed.' },
|
|
1396
|
-
},
|
|
1397
|
-
},
|
|
1398
|
-
render: (_args, value) => [{
|
|
1399
|
-
type: 'text',
|
|
1400
|
-
text: value.failedAt === undefined
|
|
1401
|
-
? `Clicked ${String(value.clicked)} point(s).` + effectText(value)
|
|
1402
|
-
: `Clicked ${String(value.clicked)} point(s), then stopped at index ${String(value.failedAt)}: ${String(value.error ?? 'unknown')}`,
|
|
1403
|
-
}],
|
|
1404
|
-
},
|
|
1405
|
-
timeoutMs,
|
|
1406
|
-
isConcurrencySafe: () => false,
|
|
1407
|
-
async execute(args, exec) {
|
|
1408
|
-
assertAllowed(state, 'dsh_browser_click_sequence', taskKey(exec))
|
|
1409
|
-
const browser = ctx.get('browser')
|
|
1410
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1411
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1412
|
-
const points = Array.isArray(args.points) ? args.points : []
|
|
1413
|
-
const intervalMs = typeof args.intervalMs === 'number' ? args.intervalMs : undefined
|
|
1414
|
-
const before = await pageFingerprint(browser, session)
|
|
1415
|
-
const result = await browser.clickSequence(session, { points, ...intervalMs === undefined ? {} : { intervalMs } })
|
|
1416
|
-
return { ...result, ...await observedEffect(browser, session, before) }
|
|
1417
|
-
},
|
|
1418
|
-
}))
|
|
1419
|
-
|
|
1420
|
-
registerSafely(defineTool({
|
|
1421
|
-
name: 'dsh_browser_type',
|
|
1422
|
-
description: 'Type text into the focused element of the shared browser, or into a located element (pass target {by: css|text|xpath, value, index?} to focus it first). Text is inserted at the focus via CDP Input.insertText. For setting whole field values (and React-controlled inputs) prefer dsh_browser_set_value; use dsh_browser_key for Enter/Tab/arrows.',
|
|
1423
|
-
parameters: {
|
|
1424
|
-
text: { type: 'string', required: true, description: 'The text to insert.' },
|
|
1425
|
-
target: {
|
|
1426
|
-
type: 'object',
|
|
1427
|
-
additionalProperties: false,
|
|
1428
|
-
properties: {
|
|
1429
|
-
by: { type: 'string', enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css).' },
|
|
1430
|
-
value: { type: 'string', required: true, description: 'The CSS selector, visible text, or XPath expression.' },
|
|
1431
|
-
index: { type: 'number', description: '0-based index of the match (default 0).' },
|
|
1432
|
-
},
|
|
1433
|
-
description: 'Focus this element first, then type (css/text/xpath).',
|
|
1434
|
-
},
|
|
1435
|
-
},
|
|
1436
|
-
output: {
|
|
1437
|
-
schema: { type: 'object', additionalProperties: false, properties: { typed: { type: 'boolean', required: true }, ...effectProperties } },
|
|
1438
|
-
render: (_args, value) => [{ type: 'text', text: value.typed ? `Typed ${String(_args.text).length} chars.` + effectText(value) : 'Type failed.' }],
|
|
1439
|
-
},
|
|
1440
|
-
timeoutMs,
|
|
1441
|
-
isConcurrencySafe: () => false,
|
|
1442
|
-
async execute(args, exec) {
|
|
1443
|
-
assertAllowed(state, 'dsh_browser_type', taskKey(exec))
|
|
1444
|
-
const browser = ctx.get('browser')
|
|
1445
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1446
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1447
|
-
const target = args.target as { by?: string; value?: string; index?: number } | undefined
|
|
1448
|
-
// A target whose value is empty is a caller mistake, not a request to fall back.
|
|
1449
|
-
// Degrading silently sent typed text to whatever held focus — possibly a password
|
|
1450
|
-
// field — or dropped the semantic target in favour of coordinates.
|
|
1451
|
-
if (target !== undefined && typeof target.value === 'string' && target.value === '') {
|
|
1452
|
-
throw new Error('target.value is empty; pass a css selector, visible text or XPath, or omit target entirely to use x/y')
|
|
1453
|
-
}
|
|
1454
|
-
const index = targetIndex(target)
|
|
1455
|
-
const before = await pageFingerprint(browser, session)
|
|
1456
|
-
if (target !== undefined && typeof target.value === 'string' && target.value !== '') {
|
|
1457
|
-
await browser.type(session, {
|
|
1458
|
-
text: args.text,
|
|
1459
|
-
target: {
|
|
1460
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1461
|
-
value: target.value,
|
|
1462
|
-
...index !== undefined ? { index } : {},
|
|
1463
|
-
},
|
|
1464
|
-
}, exec.signal)
|
|
1465
|
-
} else {
|
|
1466
|
-
await browser.type(session, { text: args.text }, exec.signal)
|
|
1467
|
-
}
|
|
1468
|
-
return { typed: true, ...await observedEffect(browser, session, before) }
|
|
1469
|
-
},
|
|
1470
|
-
}))
|
|
1471
|
-
|
|
1472
|
-
registerSafely(defineTool({
|
|
1473
|
-
name: 'dsh_browser_scroll',
|
|
1474
|
-
description: 'Scroll the shared-browser page: by pixel deltas (deltaX/deltaY), to a CSS selector\'s element, or to the top/bottom. Use to reveal below-the-fold content before snapshotting or clicking.',
|
|
1475
|
-
parameters: {
|
|
1476
|
-
deltaX: { type: 'number', description: 'Horizontal scroll delta in CSS pixels.' },
|
|
1477
|
-
deltaY: { type: 'number', description: 'Vertical scroll delta in CSS pixels.' },
|
|
1478
|
-
selector: { type: 'string', description: 'Scroll the element matching this CSS selector into view.' },
|
|
1479
|
-
toTop: { type: 'boolean', description: 'Scroll to the top of the page.' },
|
|
1480
|
-
toBottom: { type: 'boolean', description: 'Scroll to the bottom of the page.' },
|
|
1481
|
-
},
|
|
1482
|
-
output: {
|
|
1483
|
-
schema: { type: 'object', additionalProperties: false, properties: { scrolled: { type: 'boolean', required: true }, ...effectProperties } },
|
|
1484
|
-
render: (_args, value) => [{ type: 'text', text: value.scrolled ? 'Scrolled.' + effectText(value) : 'Scroll failed.' }],
|
|
1485
|
-
},
|
|
1486
|
-
timeoutMs,
|
|
1487
|
-
isConcurrencySafe: () => false, // mutates page scroll state; exclusive within a task
|
|
1488
|
-
async execute(args, exec) {
|
|
1489
|
-
assertAllowed(state, 'dsh_browser_scroll', taskKey(exec))
|
|
1490
|
-
const browser = ctx.get('browser')
|
|
1491
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1492
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1493
|
-
const before = await pageFingerprint(browser, session)
|
|
1494
|
-
await browser.scroll(session, {
|
|
1495
|
-
...args.deltaX !== undefined ? { deltaX: args.deltaX } : {},
|
|
1496
|
-
...args.deltaY !== undefined ? { deltaY: args.deltaY } : {},
|
|
1497
|
-
...args.selector !== undefined ? { selector: args.selector } : {},
|
|
1498
|
-
...args.toTop === true ? { toTop: true } : {},
|
|
1499
|
-
...args.toBottom === true ? { toBottom: true } : {},
|
|
1500
|
-
}, exec.signal)
|
|
1501
|
-
return { scrolled: true, ...await observedEffect(browser, session, before) }
|
|
1502
|
-
},
|
|
1503
|
-
}))
|
|
1504
|
-
|
|
1505
|
-
registerSafely(defineTool({
|
|
1506
|
-
name: 'dsh_browser_back',
|
|
1507
|
-
description: 'Go back one step in the shared-browser page history. A no-op when there is no previous entry.',
|
|
1508
|
-
parameters: {},
|
|
1509
|
-
output: {
|
|
1510
|
-
schema: { type: 'object', additionalProperties: false, properties: { back: { type: 'boolean', required: true } } },
|
|
1511
|
-
render: (_args, value) => [{ type: 'text', text: value.back ? 'Went back.' : 'Failed.' }],
|
|
1512
|
-
},
|
|
1513
|
-
timeoutMs,
|
|
1514
|
-
isConcurrencySafe: () => false, // mutates page state; exclusive within a task
|
|
1515
|
-
async execute(_args, exec) {
|
|
1516
|
-
assertAllowed(state, 'dsh_browser_back', taskKey(exec))
|
|
1517
|
-
const browser = ctx.get('browser')
|
|
1518
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1519
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1520
|
-
await browser.back(session, exec.signal)
|
|
1521
|
-
return { back: true }
|
|
1522
|
-
},
|
|
1523
|
-
}))
|
|
1524
|
-
|
|
1525
|
-
registerSafely(defineTool({
|
|
1526
|
-
name: 'dsh_browser_forward',
|
|
1527
|
-
description: 'Go forward one step in the shared-browser page history. A no-op when there is no next entry.',
|
|
1528
|
-
parameters: {},
|
|
1529
|
-
output: {
|
|
1530
|
-
schema: { type: 'object', additionalProperties: false, properties: { forward: { type: 'boolean', required: true } } },
|
|
1531
|
-
render: (_args, value) => [{ type: 'text', text: value.forward ? 'Went forward.' : 'Failed.' }],
|
|
1532
|
-
},
|
|
1533
|
-
timeoutMs,
|
|
1534
|
-
isConcurrencySafe: () => false, // mutates page state; exclusive within a task
|
|
1535
|
-
async execute(_args, exec) {
|
|
1536
|
-
assertAllowed(state, 'dsh_browser_forward', taskKey(exec))
|
|
1537
|
-
const browser = ctx.get('browser')
|
|
1538
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1539
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1540
|
-
await browser.forward(session, exec.signal)
|
|
1541
|
-
return { forward: true }
|
|
1542
|
-
},
|
|
1543
|
-
}))
|
|
1544
|
-
|
|
1545
|
-
registerSafely(defineTool({
|
|
1546
|
-
name: 'dsh_browser_refresh',
|
|
1547
|
-
description: 'Reload the current page in the shared browser (like a browser\'s refresh button). Use after a page got stuck, to apply script changes, or to re-fetch a page.',
|
|
1548
|
-
parameters: {},
|
|
1549
|
-
output: {
|
|
1550
|
-
schema: { type: 'object', additionalProperties: false, properties: { refreshed: { type: 'boolean', required: true } } },
|
|
1551
|
-
render: (_args, value) => [{ type: 'text', text: value.refreshed ? 'Page reloaded.' : 'Failed.' }],
|
|
1552
|
-
},
|
|
1553
|
-
timeoutMs,
|
|
1554
|
-
isConcurrencySafe: () => false, // reloads the page; exclusive within a task
|
|
1555
|
-
async execute(_args, exec) {
|
|
1556
|
-
assertAllowed(state, 'dsh_browser_refresh', taskKey(exec))
|
|
1557
|
-
const browser = ctx.get('browser')
|
|
1558
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1559
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1560
|
-
await browser.reload(session, exec.signal)
|
|
1561
|
-
return { refreshed: true }
|
|
1562
|
-
},
|
|
1563
|
-
}))
|
|
1564
|
-
|
|
1565
|
-
registerSafely(defineTool({
|
|
1566
|
-
name: 'dsh_browser_key',
|
|
1567
|
-
description: 'Press one named key in the shared-browser page (Enter, Tab, Escape, Backspace, Delete, ArrowUp/Down/Left/Right, Home, End, PageUp, PageDown, Space). Use after focusing an input to submit a chat box (Enter), move focus (Tab), or navigate a list (arrows).',
|
|
1568
|
-
parameters: {
|
|
1569
|
-
key: { type: 'string', required: true, enum: ['Enter', 'Tab', 'Escape', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Space'], description: 'The key to press.' },
|
|
1570
|
-
},
|
|
1571
|
-
output: {
|
|
1572
|
-
schema: { type: 'object', additionalProperties: false, properties: { pressed: { type: 'boolean', required: true }, ...effectProperties } },
|
|
1573
|
-
render: (_args, value) => [{ type: 'text', text: value.pressed ? `Pressed ${String(_args.key)}.` + effectText(value) : 'Key press failed.' }],
|
|
1574
|
-
},
|
|
1575
|
-
timeoutMs,
|
|
1576
|
-
isConcurrencySafe: () => false, // mutates page state; exclusive within a task
|
|
1577
|
-
async execute(args, exec) {
|
|
1578
|
-
assertAllowed(state, 'dsh_browser_key', taskKey(exec))
|
|
1579
|
-
const browser = ctx.get('browser')
|
|
1580
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1581
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1582
|
-
const before = await pageFingerprint(browser, session)
|
|
1583
|
-
await browser.key(session, { key: args.key }, exec.signal)
|
|
1584
|
-
return { pressed: true, ...await observedEffect(browser, session, before) }
|
|
1585
|
-
},
|
|
1586
|
-
}))
|
|
1587
|
-
|
|
1588
|
-
registerSafely(defineTool({
|
|
1589
|
-
name: 'dsh_browser_fill',
|
|
1590
|
-
description: 'Fill a form in one batch: each field takes a CSS selector or name/label/placeholder text plus its value (boolean for checkbox/radio; option value or visible text for selects and radio groups). The native setter plus input/change events fire, so React/Vue controlled inputs update. Optionally submit the form. Prefer this over hand-written dsh_browser_execute; per-field failures are reported instead of throwing.',
|
|
1591
|
-
parameters: {
|
|
1592
|
-
fields: {
|
|
1593
|
-
type: 'array',
|
|
1594
|
-
required: true,
|
|
1595
|
-
items: {
|
|
1596
|
-
type: 'object',
|
|
1597
|
-
additionalProperties: true,
|
|
1598
|
-
properties: {
|
|
1599
|
-
selector: { type: 'string', description: 'CSS selector; when present, candidates are scoped to it.' },
|
|
1600
|
-
name: { type: 'string', description: 'Match by the field\'s name attribute.' },
|
|
1601
|
-
label: { type: 'string', description: 'Match by associated <label> text or aria-label.' },
|
|
1602
|
-
placeholder: { type: 'string', description: 'Match by placeholder text.' },
|
|
1603
|
-
kind: { type: 'string', enum: ['text', 'textarea', 'checkbox', 'radio', 'select'], description: 'Field kind; defaults to text.' },
|
|
1604
|
-
value: { type: 'string', required: true, description: 'Value to set (string form; booleans/numbers accepted as strings). Required: omitting it would be read as "set empty", which unchecks a checkbox and clears a text field while still reporting success.' },
|
|
1605
|
-
},
|
|
1606
|
-
},
|
|
1607
|
-
},
|
|
1608
|
-
submit: { type: 'boolean', description: 'Submit the containing form after filling (default false).' },
|
|
1609
|
-
},
|
|
1610
|
-
output: {
|
|
1611
|
-
schema: {
|
|
1612
|
-
type: 'object',
|
|
1613
|
-
additionalProperties: false,
|
|
1614
|
-
properties: {
|
|
1615
|
-
fields: {
|
|
1616
|
-
type: 'array',
|
|
1617
|
-
required: true,
|
|
1618
|
-
items: {
|
|
1619
|
-
type: 'object',
|
|
1620
|
-
additionalProperties: false,
|
|
1621
|
-
properties: {
|
|
1622
|
-
ok: { type: 'boolean', required: true },
|
|
1623
|
-
target: { type: 'string', required: true },
|
|
1624
|
-
method: { type: 'string' },
|
|
1625
|
-
error: { type: 'string' },
|
|
1626
|
-
},
|
|
1627
|
-
},
|
|
1628
|
-
},
|
|
1629
|
-
submitted: { type: 'boolean', required: true },
|
|
1630
|
-
},
|
|
1631
|
-
},
|
|
1632
|
-
render: (_args, value) => [{
|
|
1633
|
-
type: 'text',
|
|
1634
|
-
text: (() => {
|
|
1635
|
-
const fields = value.fields as { ok: boolean; target: string; method?: string; error?: string }[]
|
|
1636
|
-
const failed = fields.filter(f => !f.ok)
|
|
1637
|
-
const lines = fields.map(f => `${f.ok ? 'OK' : 'FAIL'} ${f.target}${f.ok ? ` (${f.method ?? 'input'})` : `: ${f.error ?? 'unknown error'}`}`)
|
|
1638
|
-
const head = failed.length === 0
|
|
1639
|
-
? `Filled ${fields.length}/${fields.length} fields${value.submitted ? ' and submitted the form' : ''}.`
|
|
1640
|
-
: `Filled ${fields.length - failed.length}/${fields.length} fields; ${failed.length} failed:`
|
|
1641
|
-
return head + '\n' + lines.join('\n')
|
|
1642
|
-
})(),
|
|
1643
|
-
}],
|
|
1644
|
-
},
|
|
1645
|
-
timeoutMs,
|
|
1646
|
-
isConcurrencySafe: () => false,
|
|
1647
|
-
async execute(args, exec) {
|
|
1648
|
-
assertAllowed(state, 'dsh_browser_fill', taskKey(exec))
|
|
1649
|
-
const browser = ctx.get('browser')
|
|
1650
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1651
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1652
|
-
const requested = args.fields ?? []
|
|
1653
|
-
if (requested.length > maxFillFields) {
|
|
1654
|
-
throw new Error(`dsh_browser_fill: ${requested.length} fields in one call exceeds the ${maxFillFields}-field limit; split it into several calls so each one can report per-field results instead of timing out as a batch`)
|
|
1655
|
-
}
|
|
1656
|
-
const fields = requested.map((f: { selector?: string; name?: string; label?: string; placeholder?: string; kind?: string; value?: string }) => {
|
|
1657
|
-
// A missing value is a caller mistake, not a request to clear the field. Turning
|
|
1658
|
-
// it into '' silently unchecks a checkbox or empties a text input while the tool
|
|
1659
|
-
// still reports success, so it fails loudly. The schema marks value required, but
|
|
1660
|
-
// a call can still arrive without it.
|
|
1661
|
-
if (f.value === undefined) {
|
|
1662
|
-
const matcher = f.selector ?? f.name ?? f.label ?? f.placeholder ?? '(no matcher)'
|
|
1663
|
-
throw new Error(`dsh_browser_fill: field "${matcher}" has no "value"; pass one (use "false" to uncheck, or "" to clear deliberately)`)
|
|
1664
|
-
}
|
|
1665
|
-
return {
|
|
1666
|
-
...f.selector !== undefined ? { selector: f.selector } : {},
|
|
1667
|
-
...f.name !== undefined ? { name: f.name } : {},
|
|
1668
|
-
...f.label !== undefined ? { label: f.label } : {},
|
|
1669
|
-
...f.placeholder !== undefined ? { placeholder: f.placeholder } : {},
|
|
1670
|
-
...f.kind !== undefined ? { kind: f.kind as 'text' | 'textarea' | 'checkbox' | 'radio' | 'select' } : {},
|
|
1671
|
-
value: parseFillValue(f.value),
|
|
1672
|
-
}
|
|
1673
|
-
})
|
|
1674
|
-
const result = await browser.fillForm(session, {
|
|
1675
|
-
fields,
|
|
1676
|
-
...args.submit === true ? { submit: true } : {},
|
|
1677
|
-
}, exec.signal)
|
|
1678
|
-
return {
|
|
1679
|
-
fields: result.fields.map(f => ({ ok: f.ok, target: f.target, ...f.method !== undefined ? { method: f.method } : {}, ...f.error !== undefined ? { error: f.error } : {} })),
|
|
1680
|
-
submitted: result.submitted,
|
|
1681
|
-
}
|
|
1682
|
-
},
|
|
1683
|
-
}))
|
|
1684
|
-
|
|
1685
|
-
// ---------------------------------------------------------------------------
|
|
1686
|
-
// Single-control form primitives, all target-based (css/text/xpath).
|
|
1687
|
-
// ---------------------------------------------------------------------------
|
|
1688
|
-
const targetParam = {
|
|
1689
|
-
type: 'object' as const,
|
|
1690
|
-
required: true as const,
|
|
1691
|
-
additionalProperties: false as const,
|
|
1692
|
-
properties: {
|
|
1693
|
-
by: { type: 'string' as const, enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css). text matches an element\'s own visible text, exact first then contains.' },
|
|
1694
|
-
value: { type: 'string' as const, required: true as const, description: 'The CSS selector, visible text, or XPath expression.' },
|
|
1695
|
-
index: { type: 'number' as const, description: '0-based index of the match (default 0).' },
|
|
1696
|
-
},
|
|
1697
|
-
description: 'Locate the element (css/text/xpath).',
|
|
1698
|
-
}
|
|
1699
|
-
|
|
1700
|
-
registerSafely(defineTool({
|
|
1701
|
-
name: 'dsh_browser_set_value',
|
|
1702
|
-
description: 'Set the value of ONE input/textarea/select/contenteditable, located by css/text/xpath. Uses the native setter plus input/change events, so React/Vue controlled inputs update correctly. For selects pass the option value or visible text. For a whole form at once prefer dsh_browser_fill.',
|
|
1703
|
-
parameters: {
|
|
1704
|
-
target: targetParam,
|
|
1705
|
-
value: { type: 'string', required: true, description: 'The value to set (string form; numbers/booleans accepted).' },
|
|
1706
|
-
},
|
|
1707
|
-
output: {
|
|
1708
|
-
schema: {
|
|
1709
|
-
type: 'object',
|
|
1710
|
-
additionalProperties: false,
|
|
1711
|
-
properties: {
|
|
1712
|
-
method: { type: 'string', required: true, description: 'How the value was applied: input/textarea/select/contenteditable.' },
|
|
1713
|
-
value: { type: 'string', required: true },
|
|
1714
|
-
},
|
|
1715
|
-
},
|
|
1716
|
-
render: (_args, value) => [{ type: 'text', text: `Set via ${value.method}.` }],
|
|
1717
|
-
},
|
|
1718
|
-
timeoutMs,
|
|
1719
|
-
isConcurrencySafe: () => false, // mutates a field; exclusive within a task
|
|
1720
|
-
async execute(args, exec) {
|
|
1721
|
-
assertAllowed(state, 'dsh_browser_set_value', taskKey(exec))
|
|
1722
|
-
const browser = ctx.get('browser')
|
|
1723
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1724
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1725
|
-
const target = args.target as { by?: string; value: string; index?: number }
|
|
1726
|
-
const result = await browser.setValue(session, {
|
|
1727
|
-
target: {
|
|
1728
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1729
|
-
value: target.value,
|
|
1730
|
-
...target.index !== undefined ? { index: target.index } : {},
|
|
1731
|
-
},
|
|
1732
|
-
value: parseFillValue(args.value),
|
|
1733
|
-
}, exec.signal)
|
|
1734
|
-
return { method: result.method, value: result.value }
|
|
1735
|
-
},
|
|
1736
|
-
}))
|
|
1737
|
-
|
|
1738
|
-
registerSafely(defineTool({
|
|
1739
|
-
name: 'dsh_browser_check',
|
|
1740
|
-
description: 'Check (or uncheck, with checked=false) a checkbox or radio button, located by css/text/xpath.',
|
|
1741
|
-
parameters: {
|
|
1742
|
-
target: targetParam,
|
|
1743
|
-
checked: { type: 'boolean', description: 'Desired state (default true = check).' },
|
|
1744
|
-
},
|
|
1745
|
-
output: {
|
|
1746
|
-
schema: { type: 'object', additionalProperties: false, properties: { checked: { type: 'boolean', required: true } } },
|
|
1747
|
-
render: (_args, value) => [{ type: 'text', text: value.checked ? 'Checked.' : 'Unchecked.' }],
|
|
1748
|
-
},
|
|
1749
|
-
timeoutMs,
|
|
1750
|
-
isConcurrencySafe: () => false, // mutates a field; exclusive within a task
|
|
1751
|
-
async execute(args, exec) {
|
|
1752
|
-
assertAllowed(state, 'dsh_browser_check', taskKey(exec))
|
|
1753
|
-
const browser = ctx.get('browser')
|
|
1754
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1755
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1756
|
-
const target = args.target as { by?: string; value: string; index?: number }
|
|
1757
|
-
const result = await browser.check(session, {
|
|
1758
|
-
target: {
|
|
1759
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1760
|
-
value: target.value,
|
|
1761
|
-
...target.index !== undefined ? { index: target.index } : {},
|
|
1762
|
-
},
|
|
1763
|
-
...args.checked !== undefined ? { checked: args.checked } : {},
|
|
1764
|
-
}, exec.signal)
|
|
1765
|
-
return { checked: result.checked }
|
|
1766
|
-
},
|
|
1767
|
-
}))
|
|
1768
|
-
|
|
1769
|
-
registerSafely(defineTool({
|
|
1770
|
-
name: 'dsh_browser_select',
|
|
1771
|
-
description: 'Select one option of a <select>, located by css/text/xpath — by option value, visible text, or 0-based index (provide exactly one).',
|
|
1772
|
-
parameters: {
|
|
1773
|
-
target: targetParam,
|
|
1774
|
-
optionValue: { type: 'string', description: 'Match the option by its value attribute.' },
|
|
1775
|
-
optionText: { type: 'string', description: 'Match the option by its visible text.' },
|
|
1776
|
-
optionIndex: { type: 'number', description: 'Match the option by its 0-based index.' },
|
|
1777
|
-
},
|
|
1778
|
-
output: {
|
|
1779
|
-
schema: {
|
|
1780
|
-
type: 'object',
|
|
1781
|
-
additionalProperties: false,
|
|
1782
|
-
properties: {
|
|
1783
|
-
value: { type: 'string', required: true },
|
|
1784
|
-
text: { type: 'string', required: true },
|
|
1785
|
-
},
|
|
1786
|
-
},
|
|
1787
|
-
render: (_args, value) => [{ type: 'text', text: `Selected "${value.text}".` }],
|
|
1788
|
-
},
|
|
1789
|
-
timeoutMs,
|
|
1790
|
-
isConcurrencySafe: () => false, // mutates a field; exclusive within a task
|
|
1791
|
-
async execute(args, exec) {
|
|
1792
|
-
assertAllowed(state, 'dsh_browser_select', taskKey(exec))
|
|
1793
|
-
const browser = ctx.get('browser')
|
|
1794
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1795
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1796
|
-
const target = args.target as { by?: string; value: string; index?: number }
|
|
1797
|
-
const result = await browser.selectOption(session, {
|
|
1798
|
-
target: {
|
|
1799
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1800
|
-
value: target.value,
|
|
1801
|
-
...target.index !== undefined ? { index: target.index } : {},
|
|
1802
|
-
},
|
|
1803
|
-
...args.optionValue !== undefined ? { optionValue: args.optionValue } : {},
|
|
1804
|
-
...args.optionText !== undefined ? { optionText: args.optionText } : {},
|
|
1805
|
-
...args.optionIndex !== undefined ? { optionIndex: args.optionIndex } : {},
|
|
1806
|
-
}, exec.signal)
|
|
1807
|
-
return { value: result.value, text: result.text }
|
|
1808
|
-
},
|
|
1809
|
-
}))
|
|
1810
|
-
|
|
1811
|
-
registerSafely(defineTool({
|
|
1812
|
-
name: 'dsh_browser_clear',
|
|
1813
|
-
description: 'Clear an input/textarea/contenteditable, or uncheck a checkbox/radio, located by css/text/xpath.',
|
|
1814
|
-
parameters: {
|
|
1815
|
-
target: targetParam,
|
|
1816
|
-
},
|
|
1817
|
-
output: {
|
|
1818
|
-
schema: { type: 'object', additionalProperties: false, properties: { cleared: { type: 'boolean', required: true } } },
|
|
1819
|
-
render: (_args, value) => [{ type: 'text', text: value.cleared ? 'Cleared.' : 'Failed.' }],
|
|
1820
|
-
},
|
|
1821
|
-
timeoutMs,
|
|
1822
|
-
isConcurrencySafe: () => false, // mutates a field; exclusive within a task
|
|
1823
|
-
async execute(args, exec) {
|
|
1824
|
-
assertAllowed(state, 'dsh_browser_clear', taskKey(exec))
|
|
1825
|
-
const browser = ctx.get('browser')
|
|
1826
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1827
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1828
|
-
const target = args.target as { by?: string; value: string; index?: number }
|
|
1829
|
-
await browser.clearField(session, {
|
|
1830
|
-
target: {
|
|
1831
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1832
|
-
value: target.value,
|
|
1833
|
-
...target.index !== undefined ? { index: target.index } : {},
|
|
1834
|
-
},
|
|
1835
|
-
}, exec.signal)
|
|
1836
|
-
return { cleared: true }
|
|
1837
|
-
},
|
|
1838
|
-
}))
|
|
1839
|
-
|
|
1840
|
-
registerSafely(defineTool({
|
|
1841
|
-
name: 'dsh_browser_get_value',
|
|
1842
|
-
description: 'Read the current value of one input/textarea/select/contenteditable, located by css/text/xpath. Use to VERIFY that a fill worked (e.g. before submitting).',
|
|
1843
|
-
parameters: {
|
|
1844
|
-
target: targetParam,
|
|
1845
|
-
},
|
|
1846
|
-
output: {
|
|
1847
|
-
schema: {
|
|
1848
|
-
type: 'object',
|
|
1849
|
-
additionalProperties: false,
|
|
1850
|
-
properties: {
|
|
1851
|
-
value: { type: 'string' },
|
|
1852
|
-
checked: { type: 'boolean', description: 'For checkbox/radio.' },
|
|
1853
|
-
selectedText: { type: 'string', description: 'For <select>.', },
|
|
1854
|
-
},
|
|
1855
|
-
},
|
|
1856
|
-
render: (_args, value) => [{ type: 'text', text: (() => {
|
|
1857
|
-
if (value.checked !== undefined) return `checked=${value.checked}`
|
|
1858
|
-
if (value.selectedText !== undefined) return `selected: ${value.selectedText}`
|
|
1859
|
-
return `value: ${value.value ?? '(none)'}`
|
|
1860
|
-
})() }],
|
|
1861
|
-
},
|
|
1862
|
-
timeoutMs,
|
|
1863
|
-
isConcurrencySafe: () => true,
|
|
1864
|
-
async execute(args, exec) {
|
|
1865
|
-
assertAllowed(state, 'dsh_browser_get_value', taskKey(exec))
|
|
1866
|
-
const browser = ctx.get('browser')
|
|
1867
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1868
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1869
|
-
const target = args.target as { by?: string; value: string; index?: number }
|
|
1870
|
-
const result = await browser.getValue(session, {
|
|
1871
|
-
target: {
|
|
1872
|
-
by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
|
|
1873
|
-
value: target.value,
|
|
1874
|
-
...target.index !== undefined ? { index: target.index } : {},
|
|
1875
|
-
},
|
|
1876
|
-
}, exec.signal)
|
|
1877
|
-
return {
|
|
1878
|
-
...result.value !== null ? { value: result.value } : {},
|
|
1879
|
-
...result.checked !== undefined ? { checked: result.checked } : {},
|
|
1880
|
-
...result.selectedText !== undefined ? { selectedText: result.selectedText } : {},
|
|
1881
|
-
}
|
|
1882
|
-
},
|
|
1883
|
-
}))
|
|
1884
|
-
|
|
1885
|
-
registerSafely(defineTool({
|
|
1886
|
-
name: 'dsh_browser_screenshot',
|
|
1887
|
-
description: 'Screenshot the Desktop browser (PNG default, JPEG where supported). Vision-capable active models receive the image directly; non-vision or unknown models receive text metadata only. Images are downscaled to at most 1280x960 and limited to 4 MiB; retry with smaller dimensions if encoding exceeds the limit. Supports fullPage and savePath. Web iframe screenshots are unavailable. Never solve CAPTCHAs automatically; request human takeover instead.',
|
|
1888
|
-
parameters: {
|
|
1889
|
-
fullPage: { type: 'boolean', description: 'Capture the full scrollable page instead of the viewport (default false).' },
|
|
1890
|
-
savePath: { type: 'string', description: 'Absolute file path to also save the image to. Must resolve inside the configured downloadDir (default: the system Downloads folder, localized names such as ~/下载 included); an existing file is never overwritten.' },
|
|
1891
|
-
format: { type: 'string', enum: ['png', 'jpeg'], description: 'Image format (default png; jpeg needs the self-hosted browser or an installed Chrome/Edge; the desktop sidebar returns PNG because the Electron CDP JPEG encoder hangs).' },
|
|
1892
|
-
quality: { type: 'number', description: 'JPEG quality 1-100 (default 80); ignored for PNG.' },
|
|
1893
|
-
maxWidth: { type: 'number', description: 'Downscale to fit within this width (aspect preserved).' },
|
|
1894
|
-
maxHeight: { type: 'number', description: 'Downscale to fit within this height (aspect preserved).' },
|
|
1895
|
-
},
|
|
1896
|
-
output: {
|
|
1897
|
-
schema: {
|
|
1898
|
-
type: 'object',
|
|
1899
|
-
additionalProperties: false,
|
|
1900
|
-
properties: {
|
|
1901
|
-
bytes: { type: 'number', required: true, description: 'Encoded screenshot byte count.' },
|
|
1902
|
-
attachment: {
|
|
1903
|
-
type: 'object', additionalProperties: false,
|
|
1904
|
-
properties: {
|
|
1905
|
-
attachmentId: { type: 'string', required: true },
|
|
1906
|
-
mediaType: { type: 'string', required: true },
|
|
1907
|
-
bytes: { type: 'number', required: true },
|
|
1908
|
-
width: { type: 'number', required: true },
|
|
1909
|
-
height: { type: 'number', required: true },
|
|
1910
|
-
},
|
|
1911
|
-
},
|
|
1912
|
-
width: { type: 'number', description: 'Pixel width of the returned image, when the capture was measured (present with maxWidth/maxHeight).' },
|
|
1913
|
-
height: { type: 'number', description: 'Pixel height of the returned image, when the capture was measured.' },
|
|
1914
|
-
path: { type: 'string', description: 'The file path the screenshot was saved to, when savePath was given.' },
|
|
1915
|
-
},
|
|
1916
|
-
},
|
|
1917
|
-
render: (_args, value) => [
|
|
1918
|
-
{ type: 'text', text: `Screenshot captured (${Math.round(value.bytes / 1024)} KiB${value.width !== undefined && value.height !== undefined ? `, ${value.width}x${value.height}` : ''})${value.path !== undefined ? ` saved to ${value.path}` : ''}.` },
|
|
1919
|
-
...value.attachment === undefined ? [] : [{ type: 'image' as const, attachment: value.attachment as ImageBlock['attachment'] }],
|
|
1920
|
-
],
|
|
1921
|
-
},
|
|
1922
|
-
timeoutMs,
|
|
1923
|
-
isConcurrencySafe: () => true,
|
|
1924
|
-
async execute(args, exec) {
|
|
1925
|
-
const browser = ctx.get('browser')
|
|
1926
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1927
|
-
const key = taskKey(exec)
|
|
1928
|
-
await state.pendingPanelOpens.get(key)
|
|
1929
|
-
const existing = state.sessionsByTask.get(key)
|
|
1930
|
-
if (state.panelUrlByTask.has(key) && (existing === undefined || !browser.exists(existing))) {
|
|
1931
|
-
throw new Error('Web 侧栏暂不支持截图:iframe 无法被网页静默截图 (panel surface unavailable). Use the CDP-backed DSH desktop sidebar with a connected desktop bridge for screenshots.')
|
|
1932
|
-
}
|
|
1933
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1934
|
-
const vision = await screenshotVisionEnabled(ctx, exec, exec.signal)
|
|
1935
|
-
const maxWidth = screenshotDimension(args.maxWidth, SCREENSHOT_MAX_WIDTH)
|
|
1936
|
-
const maxHeight = screenshotDimension(args.maxHeight, SCREENSHOT_MAX_HEIGHT)
|
|
1937
|
-
const shot = await browser.screenshot(session, {
|
|
1938
|
-
...args.fullPage === true ? { fullPage: true } : {},
|
|
1939
|
-
...args.savePath !== undefined ? { savePath: args.savePath } : {},
|
|
1940
|
-
...args.format !== undefined ? { format: args.format } : {},
|
|
1941
|
-
...args.quality !== undefined ? { quality: args.quality } : {},
|
|
1942
|
-
maxWidth,
|
|
1943
|
-
maxHeight,
|
|
1944
|
-
}, exec.signal)
|
|
1945
|
-
exec.signal?.throwIfAborted()
|
|
1946
|
-
const image = screenshotBytes(shot.dataUrl)
|
|
1947
|
-
const attachment = vision ? await saveScreenshotImage(ctx, image, maxWidth, maxHeight) : undefined
|
|
1948
|
-
exec.signal?.throwIfAborted()
|
|
1949
|
-
return {
|
|
1950
|
-
bytes: image.data.length,
|
|
1951
|
-
...attachment === undefined ? {} : { attachment },
|
|
1952
|
-
...shot.path !== undefined ? { path: shot.path } : {},
|
|
1953
|
-
...shot.width !== undefined ? { width: shot.width } : {},
|
|
1954
|
-
...shot.height !== undefined ? { height: shot.height } : {},
|
|
1955
|
-
}
|
|
1956
|
-
},
|
|
1957
|
-
}))
|
|
1958
|
-
|
|
1959
|
-
if (config.tabTools !== false) {
|
|
1960
|
-
registerSafely(defineTool({
|
|
1961
|
-
name: 'dsh_browser_list_tabs',
|
|
1962
|
-
description: 'List the shared-browser session\'s tabs with their URLs and which is active.',
|
|
1963
|
-
parameters: {},
|
|
1964
|
-
output: {
|
|
1965
|
-
schema: {
|
|
1966
|
-
type: 'object',
|
|
1967
|
-
additionalProperties: false,
|
|
1968
|
-
properties: {
|
|
1969
|
-
tabs: {
|
|
1970
|
-
type: 'array',
|
|
1971
|
-
required: true,
|
|
1972
|
-
items: {
|
|
1973
|
-
type: 'object',
|
|
1974
|
-
additionalProperties: false,
|
|
1975
|
-
properties: {
|
|
1976
|
-
id: { type: 'string', required: true },
|
|
1977
|
-
url: { type: 'string', required: true },
|
|
1978
|
-
active: { type: 'boolean', required: true },
|
|
1979
|
-
},
|
|
1980
|
-
},
|
|
1981
|
-
},
|
|
1982
|
-
},
|
|
1983
|
-
},
|
|
1984
|
-
render: (_args, value) => [{
|
|
1985
|
-
type: 'text',
|
|
1986
|
-
text: (value.tabs as { id: string; url: string; active: boolean }[])
|
|
1987
|
-
.map(t => `${t.active ? '*' : ' '} ${t.id} ${t.url}`).join('\n'),
|
|
1988
|
-
}],
|
|
1989
|
-
},
|
|
1990
|
-
timeoutMs,
|
|
1991
|
-
isConcurrencySafe: () => true,
|
|
1992
|
-
async execute(_args, exec) {
|
|
1993
|
-
const browser = ctx.get('browser')
|
|
1994
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
1995
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
1996
|
-
const tabs = await browser.listTabs(session)
|
|
1997
|
-
return { tabs: scopedTabs(browserSessionHandle(taskKey(exec), session), tabs).map(t => ({ id: t.id, url: t.url, active: t.active })) }
|
|
1998
|
-
},
|
|
1999
|
-
}))
|
|
2000
|
-
|
|
2001
|
-
registerSafely(defineTool({
|
|
2002
|
-
name: 'dsh_browser_switch_tab',
|
|
2003
|
-
description: 'Switch the shared browser to a tab by id (from dsh_browser_list_tabs).',
|
|
2004
|
-
parameters: {
|
|
2005
|
-
tabId: { type: 'string', required: true, description: 'The tab id to switch to.' },
|
|
2006
|
-
},
|
|
2007
|
-
output: {
|
|
2008
|
-
schema: { type: 'object', additionalProperties: false, properties: { switched: { type: 'boolean', required: true } } },
|
|
2009
|
-
render: (_args, value) => [{ type: 'text', text: value.switched ? 'Switched.' : 'Tab not found.' }],
|
|
2010
|
-
},
|
|
2011
|
-
timeoutMs,
|
|
2012
|
-
isConcurrencySafe: () => false, // mutates the active tab; exclusive within a task
|
|
2013
|
-
async execute(args, exec) {
|
|
2014
|
-
assertAllowed(state, 'dsh_browser_switch_tab', taskKey(exec))
|
|
2015
|
-
const browser = ctx.get('browser')
|
|
2016
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2017
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2018
|
-
const handle = resolveTabHandle(browserSessionHandle(taskKey(exec), session), args.tabId)
|
|
2019
|
-
await browser.switchTab(session, tabWireId(handle))
|
|
2020
|
-
return { switched: true }
|
|
2021
|
-
},
|
|
2022
|
-
}))
|
|
2023
|
-
|
|
2024
|
-
registerSafely(defineTool({
|
|
2025
|
-
name: 'dsh_browser_close_tab',
|
|
2026
|
-
description: 'Close a tab in the shared browser by id. Closing the active tab activates the next.',
|
|
2027
|
-
parameters: {
|
|
2028
|
-
tabId: { type: 'string', required: true, description: 'The tab id to close.' },
|
|
2029
|
-
},
|
|
2030
|
-
output: {
|
|
2031
|
-
schema: { type: 'object', additionalProperties: false, properties: { closed: { type: 'boolean', required: true } } },
|
|
2032
|
-
render: (_args, value) => [{ type: 'text', text: value.closed ? 'Closed.' : 'Tab not found.' }],
|
|
2033
|
-
},
|
|
2034
|
-
timeoutMs,
|
|
2035
|
-
isConcurrencySafe: () => false, // mutates the tab list; exclusive within a task
|
|
2036
|
-
async execute(args, exec) {
|
|
2037
|
-
assertAllowed(state, 'dsh_browser_close_tab', taskKey(exec))
|
|
2038
|
-
const browser = ctx.get('browser')
|
|
2039
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2040
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2041
|
-
const handle = resolveTabHandle(browserSessionHandle(taskKey(exec), session), args.tabId)
|
|
2042
|
-
await browser.closeTab(session, tabWireId(handle))
|
|
2043
|
-
return { closed: true }
|
|
2044
|
-
},
|
|
2045
|
-
}))
|
|
2046
|
-
|
|
2047
|
-
registerSafely(defineTool({
|
|
2048
|
-
name: 'dsh_browser_reset',
|
|
2049
|
-
description: 'Close every tab in the shared browser and start fresh with one blank tab.',
|
|
2050
|
-
parameters: {},
|
|
2051
|
-
output: {
|
|
2052
|
-
schema: { type: 'object', additionalProperties: false, properties: { reset: { type: 'boolean', required: true } } },
|
|
2053
|
-
render: (_args, value) => [{ type: 'text', text: value.reset ? 'Browser reset.' : 'Failed.' }],
|
|
2054
|
-
},
|
|
2055
|
-
timeoutMs,
|
|
2056
|
-
isConcurrencySafe: () => false, // closes every tab; exclusive within a task
|
|
2057
|
-
async execute(_args, exec) {
|
|
2058
|
-
assertAllowed(state, 'dsh_browser_reset', taskKey(exec))
|
|
2059
|
-
const browser = ctx.get('browser')
|
|
2060
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2061
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2062
|
-
await browser.reset(session)
|
|
2063
|
-
return { reset: true }
|
|
2064
|
-
},
|
|
2065
|
-
}))
|
|
2066
|
-
}
|
|
2067
|
-
|
|
2068
|
-
registerSafely(defineTool({
|
|
2069
|
-
name: 'dsh_browser_history',
|
|
2070
|
-
description: 'List the shared browser session\'s recorded operation history (navigate/execute/click/type), newest last, with per-step success/error. Use to understand what the agent did and to pick a step to replay.',
|
|
2071
|
-
parameters: {
|
|
2072
|
-
verbose: { type: 'boolean', description: "Include each operation's parameters (default false). They are what you just sent, so they are omitted unless asked for." },
|
|
2073
|
-
},
|
|
2074
|
-
output: {
|
|
2075
|
-
schema: {
|
|
2076
|
-
type: 'object',
|
|
2077
|
-
additionalProperties: false,
|
|
2078
|
-
properties: {
|
|
2079
|
-
entries: {
|
|
2080
|
-
type: 'array',
|
|
2081
|
-
required: true,
|
|
2082
|
-
items: {
|
|
2083
|
-
type: 'object',
|
|
2084
|
-
additionalProperties: false,
|
|
2085
|
-
properties: {
|
|
2086
|
-
seq: { type: 'number', required: true },
|
|
2087
|
-
action: { type: 'string', required: true },
|
|
2088
|
-
ok: { type: 'boolean', required: true },
|
|
2089
|
-
params: { type: 'object', additionalProperties: true, required: true },
|
|
2090
|
-
result: { type: 'string' },
|
|
2091
|
-
error: { type: 'string' },
|
|
2092
|
-
},
|
|
2093
|
-
},
|
|
2094
|
-
},
|
|
2095
|
-
},
|
|
2096
|
-
},
|
|
2097
|
-
render: (args, value) => {
|
|
2098
|
-
const entries = value.entries as Array<{ seq: number; action: string; ok: boolean; params: Record<string, unknown>; result?: string; error?: string }>
|
|
2099
|
-
if (entries.length === 0) return [{ type: 'text', text: '(no recorded operations yet)' }]
|
|
2100
|
-
// The parameters are what the caller itself just sent, so echoing them back is cost
|
|
2101
|
-
// without information — measured at 18,162 characters for 200 operations, of which the
|
|
2102
|
-
// per-entry params dominated. Only the tail is shown by default: the recent steps are
|
|
2103
|
-
// what a caller reasons about, and the count leads so the tail is not mistaken for all.
|
|
2104
|
-
const recent = entries.slice(-20)
|
|
2105
|
-
const omitted = entries.length - recent.length
|
|
2106
|
-
const lines = recent.map(e => `#${e.seq} ${e.action} ${e.ok ? 'ok' : 'FAIL'}${e.result !== undefined ? ` -> ${e.result}` : ''}${e.error !== undefined ? ` !! ${e.error}` : ''}${args.verbose === true ? ` ${JSON.stringify(e.params)}` : ''}`)
|
|
2107
|
-
const header = omitted > 0
|
|
2108
|
-
? `${entries.length} operations recorded; showing the last ${recent.length} (${args.verbose === true ? '' : ' (pass verbose: true for parameters)'}):`
|
|
2109
|
-
: `${entries.length} operation(s):`
|
|
2110
|
-
return [{ type: 'text', text: `${header}\n${lines.join('\n')}` }]
|
|
2111
|
-
},
|
|
2112
|
-
},
|
|
2113
|
-
timeoutMs,
|
|
2114
|
-
isConcurrencySafe: () => true,
|
|
2115
|
-
async execute(_args, exec) {
|
|
2116
|
-
const browser = ctx.get('browser')
|
|
2117
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2118
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2119
|
-
const entries = await browser.history(session)
|
|
2120
|
-
const rendered = entries.map(e => {
|
|
2121
|
-
const params = JSON.parse(JSON.stringify(e.params)) as Record<string, unknown>
|
|
2122
|
-
// Typed text / set values (possibly passwords) are kept verbatim in
|
|
2123
|
-
// the provider's history so replay can re-issue them, but must not be
|
|
2124
|
-
// echoed back to the model: mask them in the tool output, preserving
|
|
2125
|
-
// the length.
|
|
2126
|
-
if (e.action === 'type' && typeof params.text === 'string') {
|
|
2127
|
-
params.text = '*'.repeat(Math.min(params.text.length, 64)) + ` (${params.text.length} chars)`
|
|
2128
|
-
}
|
|
2129
|
-
if (e.action === 'setValue' && typeof params.value === 'string') {
|
|
2130
|
-
params.value = '*'.repeat(Math.min(params.value.length, 64)) + ` (${params.value.length} chars)`
|
|
2131
|
-
}
|
|
2132
|
-
// Replay of type/setValue carries the same sensitive fields.
|
|
2133
|
-
if (e.action === 'replay' && params.of === 'type' && typeof params.text === 'string') {
|
|
2134
|
-
params.text = '*'.repeat(Math.min(params.text.length, 64)) + ` (${params.text.length} chars)`
|
|
2135
|
-
}
|
|
2136
|
-
// Execute scripts may embed form tokens / credentials; mask script,
|
|
2137
|
-
// args, and result for both direct execute and replay-of-execute.
|
|
2138
|
-
const isExecute = e.action === 'execute' || (e.action === 'replay' && params.of === 'execute')
|
|
2139
|
-
if (isExecute) {
|
|
2140
|
-
if (typeof params.script === 'string') {
|
|
2141
|
-
params.script = `/* ${params.script.length} chars redacted */`
|
|
2142
|
-
}
|
|
2143
|
-
if (Array.isArray(params.args)) {
|
|
2144
|
-
params.args = params.args.map(() => '***')
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
const row: { seq: number; action: string; ok: boolean; params: unknown; result?: string; error?: string } = {
|
|
2148
|
-
seq: e.seq,
|
|
2149
|
-
action: e.action,
|
|
2150
|
-
ok: e.ok,
|
|
2151
|
-
params,
|
|
2152
|
-
}
|
|
2153
|
-
if (isExecute && typeof e.result === 'string') {
|
|
2154
|
-
row.result = `[${e.result.length} chars redacted]`
|
|
2155
|
-
} else if (e.result !== undefined) {
|
|
2156
|
-
row.result = e.result
|
|
2157
|
-
}
|
|
2158
|
-
if (e.error !== undefined) row.error = e.error
|
|
2159
|
-
return row
|
|
2160
|
-
})
|
|
2161
|
-
return { entries: rendered as never }
|
|
2162
|
-
},
|
|
2163
|
-
}))
|
|
2164
|
-
|
|
2165
|
-
registerSafely(defineTool({
|
|
2166
|
-
name: 'dsh_browser_visited',
|
|
2167
|
-
description: 'List pages the shared browser has visited, newest first, from the PERSISTENT browsing history: it survives closing the browser and restarting DSH, so it is how you (or the human) find a page again afterwards. Reopen one by passing its url to dsh_browser_open. Not to be confused with dsh_browser_history, which is only the current session\'s operation log (navigate/click/type) and disappears with the session.',
|
|
2168
|
-
parameters: {
|
|
2169
|
-
limit: { type: 'number', description: 'Maximum entries to return (default 30, capped at 200).' },
|
|
2170
|
-
domain: { type: 'string', description: 'Only visits whose hostname contains this text (case-insensitive).' },
|
|
2171
|
-
query: { type: 'string', description: 'Only visits whose URL or title contains this text (case-insensitive).' },
|
|
2172
|
-
session: { type: 'string', description: 'Only visits recorded by this task/session label — use it to separate your own pages from another session\'s or the human\'s.' },
|
|
2173
|
-
},
|
|
2174
|
-
output: {
|
|
2175
|
-
schema: {
|
|
2176
|
-
type: 'object',
|
|
2177
|
-
additionalProperties: false,
|
|
2178
|
-
properties: {
|
|
2179
|
-
count: { type: 'number', required: true },
|
|
2180
|
-
entries: {
|
|
2181
|
-
type: 'array',
|
|
2182
|
-
required: true,
|
|
2183
|
-
items: {
|
|
2184
|
-
type: 'object',
|
|
2185
|
-
additionalProperties: false,
|
|
2186
|
-
properties: {
|
|
2187
|
-
at: { type: 'number', required: true },
|
|
2188
|
-
url: { type: 'string', required: true },
|
|
2189
|
-
title: { type: 'string' },
|
|
2190
|
-
session: { type: 'string' },
|
|
2191
|
-
},
|
|
2192
|
-
},
|
|
2193
|
-
},
|
|
2194
|
-
},
|
|
2195
|
-
},
|
|
2196
|
-
render: (_args, value) => {
|
|
2197
|
-
const entries = value.entries as Array<{ at: number; url: string; title?: string; session?: string }>
|
|
2198
|
-
let lastSession: string | undefined
|
|
2199
|
-
if (entries.length === 0) {
|
|
2200
|
-
return [{ type: 'text', text: '(no recorded visits — nothing has been browsed yet, or history recording is turned off in settings)' }]
|
|
2201
|
-
}
|
|
2202
|
-
return [{
|
|
2203
|
-
type: 'text',
|
|
2204
|
-
text: entries.map(entry => {
|
|
2205
|
-
const when = new Date(entry.at).toISOString().replace('T', ' ').slice(0, 16)
|
|
2206
|
-
const title = entry.title !== undefined ? `${entry.title} — ` : ''
|
|
2207
|
-
const tag = entry.session !== undefined && entry.session !== lastSession
|
|
2208
|
-
? ` [session ${entry.session.slice(0, 8)}]`
|
|
2209
|
-
: ''
|
|
2210
|
-
lastSession = entry.session
|
|
2211
|
-
return `${when} ${title}${entry.url}${tag}`
|
|
2212
|
-
}).join('\n'),
|
|
2213
|
-
}]
|
|
2214
|
-
},
|
|
2215
|
-
},
|
|
2216
|
-
timeoutMs,
|
|
2217
|
-
isConcurrencySafe: () => true,
|
|
2218
|
-
async execute(args, _exec) {
|
|
2219
|
-
const browser = ctx.get('browser')
|
|
2220
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2221
|
-
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? args.limit : 30
|
|
2222
|
-
const limit = Math.max(1, Math.min(200, Math.floor(rawLimit)))
|
|
2223
|
-
const domain = typeof args.domain === 'string' && args.domain.trim() !== '' ? args.domain.trim() : undefined
|
|
2224
|
-
const query = typeof args.query === 'string' && args.query.trim() !== '' ? args.query.trim() : undefined
|
|
2225
|
-
const session = typeof args.session === 'string' && args.session.trim() !== '' ? args.session.trim() : undefined
|
|
2226
|
-
const entries = browser.visited({
|
|
2227
|
-
limit,
|
|
2228
|
-
...domain !== undefined ? { domain } : {},
|
|
2229
|
-
...query !== undefined ? { query } : {},
|
|
2230
|
-
...session !== undefined ? { session } : {},
|
|
2231
|
-
})
|
|
2232
|
-
return {
|
|
2233
|
-
count: entries.length,
|
|
2234
|
-
entries: entries.map(entry => ({
|
|
2235
|
-
at: entry.at,
|
|
2236
|
-
url: entry.url,
|
|
2237
|
-
...entry.title !== undefined ? { title: entry.title } : {},
|
|
2238
|
-
...entry.session !== undefined ? { session: entry.session } : {},
|
|
2239
|
-
})),
|
|
2240
|
-
}
|
|
2241
|
-
},
|
|
2242
|
-
}))
|
|
2243
|
-
|
|
2244
|
-
registerSafely(defineTool({
|
|
2245
|
-
name: 'dsh_browser_replay',
|
|
2246
|
-
description: 'Replay one recorded browser operation by its history sequence number (from dsh_browser_history). Navigate/click/type are re-issued against the current page; execute re-runs its script. The replayed step is appended to history as a new entry.',
|
|
2247
|
-
parameters: {
|
|
2248
|
-
seq: { type: 'number', required: true, description: 'The history entry sequence number to replay.' },
|
|
2249
|
-
},
|
|
2250
|
-
output: {
|
|
2251
|
-
schema: { type: 'object', additionalProperties: false, properties: { replayed: { type: 'boolean', required: true } } },
|
|
2252
|
-
render: (_args, value) => [{ type: 'text', text: value.replayed ? 'Replayed.' : 'Replay failed.' }],
|
|
2253
|
-
},
|
|
2254
|
-
timeoutMs,
|
|
2255
|
-
isConcurrencySafe: () => false,
|
|
2256
|
-
async execute(args, exec) {
|
|
2257
|
-
assertAllowed(state, 'dsh_browser_replay', taskKey(exec))
|
|
2258
|
-
const browser = ctx.get('browser')
|
|
2259
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2260
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2261
|
-
await browser.replay(session, args.seq)
|
|
2262
|
-
return { replayed: true }
|
|
2263
|
-
},
|
|
2264
|
-
}))
|
|
2265
|
-
|
|
2266
|
-
registerSafely(defineTool({
|
|
2267
|
-
name: 'dsh_browser_download',
|
|
2268
|
-
description: 'Download a URL to a local file, keeping the browser session\'s cookies and login state. Use for fetching files behind authentication or from the current page context. Available on the self-hosted browser; the desktop shell delegates downloads to the real browser UI.',
|
|
2269
|
-
parameters: {
|
|
2270
|
-
url: { type: 'string', required: true, description: 'The URL to download.' },
|
|
2271
|
-
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.' },
|
|
2272
|
-
},
|
|
2273
|
-
output: {
|
|
2274
|
-
schema: {
|
|
2275
|
-
type: 'object',
|
|
2276
|
-
additionalProperties: false,
|
|
2277
|
-
properties: {
|
|
2278
|
-
path: { type: 'string', required: true },
|
|
2279
|
-
handoff: { type: 'object', additionalProperties: true },
|
|
2280
|
-
remoteError: { type: 'string' },
|
|
2281
|
-
remoteResult: { type: 'object', additionalProperties: true },
|
|
2282
|
-
},
|
|
2283
|
-
},
|
|
2284
|
-
render: (_args, value) => {
|
|
2285
|
-
const lines = [`Downloaded to ${value.path}.`]
|
|
2286
|
-
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')}`)
|
|
2287
|
-
if (value.remoteError !== undefined) lines.push(`The local file is intact; the remote side did not take it: ${String(value.remoteError)}`)
|
|
2288
|
-
return [{ type: 'text', text: lines.join('\n') }]
|
|
2289
|
-
},
|
|
2290
|
-
},
|
|
2291
|
-
timeoutMs,
|
|
2292
|
-
isConcurrencySafe: () => false,
|
|
2293
|
-
async execute(args, exec) {
|
|
2294
|
-
assertAllowed(state, 'dsh_browser_download', taskKey(exec))
|
|
2295
|
-
const browser = ctx.get('browser')
|
|
2296
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2297
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2298
|
-
const result = await browser.download(session, { url: args.url, savePath: args.savePath }, exec.signal)
|
|
2299
|
-
// Delivery is an attribute of the download: empty tool = the old behaviour, byte for byte.
|
|
2300
|
-
const plan = deliveryPlan(args.url as string, result.path)
|
|
2301
|
-
if (plan === undefined) return { path: result.path }
|
|
2302
|
-
let remoteValue: JsonValue | undefined
|
|
2303
|
-
try {
|
|
2304
|
-
const tools = (ctx as unknown as { get?: (name: string) => {
|
|
2305
|
-
execute?: (input: unknown) => Promise<unknown>
|
|
2306
|
-
setExecutor?: unknown
|
|
2307
|
-
} | undefined }).get?.('tools')
|
|
2308
|
-
if (tools?.execute === undefined) throw new Error('the tools service is not available on this surface')
|
|
2309
|
-
if (plan.tool === 'dsh_browser_download') throw new Error('the delivery tool must be a different tool from dsh_browser_download')
|
|
2310
|
-
exec.signal.throwIfAborted()
|
|
2311
|
-
const callId = 'handoff-' + globalThis.crypto.randomUUID()
|
|
2312
|
-
// DSH's executor service accepts raw batches. Earlier runtimes accept one parsed call.
|
|
2313
|
-
// Select the API before dispatch so a retry can never upload the same file twice.
|
|
2314
|
-
const batched = typeof tools.setExecutor === 'function'
|
|
2315
|
-
const answer = await tools.execute(batched ? {
|
|
2316
|
-
calls: [{ type: 'tool-call', id: callId, name: plan.tool, arguments: JSON.stringify(plan.args) }],
|
|
2317
|
-
agent: exec.agent,
|
|
2318
|
-
toolSet: (exec as typeof exec & { readonly toolSet?: unknown }).toolSet,
|
|
2319
|
-
signal: exec.signal,
|
|
2320
|
-
} : {
|
|
2321
|
-
callId,
|
|
2322
|
-
rootCallId: exec.rootCallId,
|
|
2323
|
-
parent: exec.token,
|
|
2324
|
-
name: plan.tool,
|
|
2325
|
-
arguments: plan.args,
|
|
2326
|
-
agent: exec.agent,
|
|
2327
|
-
signal: exec.signal,
|
|
2328
|
-
})
|
|
2329
|
-
let outcome = answer
|
|
2330
|
-
let concluded = false
|
|
2331
|
-
if (batched) {
|
|
2332
|
-
const batch = answer as { results?: { callId?: string; result?: unknown }[]; additionalContexts?: unknown[]; concluded?: boolean } | null
|
|
2333
|
-
if (!Array.isArray(batch?.results) || batch.results.length !== 1 || batch.results[0]?.callId !== callId) {
|
|
2334
|
-
throw new Error('the delivery executor returned no matching tool result')
|
|
2335
|
-
}
|
|
2336
|
-
for (const context of batch.additionalContexts ?? []) {
|
|
2337
|
-
exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
|
|
2338
|
-
}
|
|
2339
|
-
concluded = batch.concluded === true
|
|
2340
|
-
outcome = batch.results[0].result
|
|
2341
|
-
}
|
|
2342
|
-
const settled = outcome as { value?: JsonValue; additionalContexts?: unknown[]; concludesTurn?: boolean } | null
|
|
2343
|
-
remoteValue = settled?.value
|
|
2344
|
-
const summary = summariseToolResult(outcome)
|
|
2345
|
-
if (!batched) {
|
|
2346
|
-
for (const context of settled?.additionalContexts ?? []) {
|
|
2347
|
-
exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
|
|
2348
|
-
}
|
|
2349
|
-
concluded = settled?.concludesTurn === true
|
|
2350
|
-
}
|
|
2351
|
-
if (concluded) exec.concludeTurn()
|
|
2352
|
-
return { path: result.path, handoff: { tool: plan.tool, result: summary, value: remoteValue ?? null } }
|
|
2353
|
-
} catch (error) {
|
|
2354
|
-
exec.signal.throwIfAborted()
|
|
2355
|
-
const reason = error instanceof Error ? error.message : String(error)
|
|
2356
|
-
if (plan.onFail === 'stop') throw new Error(`dsh_browser_download: saved to ${result.path} locally, but the handoff to "${plan.tool}" failed: ${reason}`)
|
|
2357
|
-
return {
|
|
2358
|
-
path: result.path,
|
|
2359
|
-
remoteError: plan.tool + ': ' + reason,
|
|
2360
|
-
...remoteValue === undefined ? {} : { remoteResult: { tool: plan.tool, value: remoteValue } },
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
},
|
|
2364
|
-
}))
|
|
2365
|
-
|
|
2366
|
-
registerSafely(defineTool({
|
|
2367
|
-
name: 'dsh_browser_session',
|
|
2368
|
-
description: 'Show THIS task\'s browser session: its id and open tabs. Each task (DSH session) has its own browser session, so this reflects what your task drives. The window is shared with the human and other tasks, but tab sets and history are isolated per task.',
|
|
2369
|
-
parameters: {},
|
|
2370
|
-
output: {
|
|
2371
|
-
schema: {
|
|
2372
|
-
type: 'object',
|
|
2373
|
-
additionalProperties: false,
|
|
2374
|
-
properties: {
|
|
2375
|
-
session: { type: 'string', required: true },
|
|
2376
|
-
tabs: {
|
|
2377
|
-
type: 'array',
|
|
2378
|
-
required: true,
|
|
2379
|
-
items: {
|
|
2380
|
-
type: 'object',
|
|
2381
|
-
additionalProperties: false,
|
|
2382
|
-
properties: {
|
|
2383
|
-
id: { type: 'string', required: true },
|
|
2384
|
-
url: { type: 'string', required: true },
|
|
2385
|
-
active: { type: 'boolean', required: true },
|
|
2386
|
-
},
|
|
2387
|
-
},
|
|
2388
|
-
},
|
|
2389
|
-
},
|
|
2390
|
-
},
|
|
2391
|
-
render: (_args, value) => [{
|
|
2392
|
-
type: 'text',
|
|
2393
|
-
text: `Session ${value.session}\n${(value.tabs as { id: string; url: string; active: boolean }[]).map(t => `${t.active ? '*' : ' '} ${t.id} ${t.url}`).join('\n')}`,
|
|
2394
|
-
}],
|
|
2395
|
-
},
|
|
2396
|
-
timeoutMs,
|
|
2397
|
-
isConcurrencySafe: () => true,
|
|
2398
|
-
async execute(_args, exec) {
|
|
2399
|
-
const browser = ctx.get('browser')
|
|
2400
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2401
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2402
|
-
const tabs = await browser.listTabs(session)
|
|
2403
|
-
const scope = browserSessionHandle(taskKey(exec), session)
|
|
2404
|
-
return { session: sessionWireId(scope), tabs: scopedTabs(scope, tabs).map(t => ({ id: t.id, url: t.url, active: t.active })) }
|
|
2405
|
-
},
|
|
2406
|
-
}))
|
|
2407
|
-
|
|
2408
|
-
registerSafely(defineTool({
|
|
2409
|
-
name: 'dsh_browser_reset_session',
|
|
2410
|
-
description: 'Reset THIS task\'s browser session: close it entirely so the next dsh_browser_* call starts a fresh session with one blank tab. Other tasks\' sessions are untouched. Use when a session is in a bad state or you want a clean slate.',
|
|
2411
|
-
parameters: {},
|
|
2412
|
-
output: {
|
|
2413
|
-
schema: { type: 'object', additionalProperties: false, properties: { reset: { type: 'boolean', required: true } } },
|
|
2414
|
-
render: (_args, value) => [{ type: 'text', text: value.reset ? 'This task\'s browser session was closed; the next call starts fresh.' : 'Failed.' }],
|
|
2415
|
-
},
|
|
2416
|
-
timeoutMs,
|
|
2417
|
-
isConcurrencySafe: () => false, // closes the whole session; exclusive within a task
|
|
2418
|
-
async execute(_args, exec) {
|
|
2419
|
-
assertAllowed(state, 'dsh_browser_reset_session', taskKey(exec))
|
|
2420
|
-
const browser = ctx.get('browser')
|
|
2421
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2422
|
-
const key = taskKey(exec)
|
|
2423
|
-
await state.pendingPanelOpens.get(key)
|
|
2424
|
-
state.panelUrlByTask.delete(key)
|
|
2425
|
-
const session = state.sessionsByTask.get(key)
|
|
2426
|
-
if (session !== undefined) {
|
|
2427
|
-
try {
|
|
2428
|
-
await browser.close(session)
|
|
2429
|
-
} finally {
|
|
2430
|
-
// Always forget the mapping so the next call opens a fresh session,
|
|
2431
|
-
// even if the provider close threw (the session is half-closed).
|
|
2432
|
-
state.sessionsByTask.delete(key)
|
|
2433
|
-
}
|
|
2434
|
-
}
|
|
2435
|
-
return { reset: true }
|
|
2436
|
-
},
|
|
2437
|
-
}))
|
|
2438
|
-
|
|
2439
|
-
registerSafely(defineTool({
|
|
2440
|
-
name: 'dsh_browser_restrict',
|
|
2441
|
-
description: 'Allow only the listed browser tools; any other dsh_browser_* call is refused. Empty list or omitted lifts it. Never blocked whatever the list says — the observing tools (snapshot/a11y/content/scrape/screenshot/get_value/wait/challenge/list_tabs/session/history/visited) and restrict/reset/reset_session — so a restriction can always be read around and undone. A SOFT guardrail against stray clicks, NOT a security boundary: you can lift it with an empty list.',
|
|
2442
|
-
parameters: {
|
|
2443
|
-
allowed: {
|
|
2444
|
-
type: 'array',
|
|
2445
|
-
items: { type: 'string' },
|
|
2446
|
-
description: 'Allow-list of browser tool names; empty clears the restriction.',
|
|
2447
|
-
},
|
|
2448
|
-
},
|
|
2449
|
-
output: {
|
|
2450
|
-
schema: { type: 'object', additionalProperties: false, properties: { restrictedTo: { type: 'array', required: true, items: { type: 'string' } } } },
|
|
2451
|
-
render: (_args, value) => [{ type: 'text', text: (value.restrictedTo as string[]).length > 0 ? `Restricted to: ${(value.restrictedTo as string[]).join(', ')}` : 'Restriction lifted.' }],
|
|
2452
|
-
},
|
|
2453
|
-
timeoutMs,
|
|
2454
|
-
isConcurrencySafe: () => false,
|
|
2455
|
-
async execute(args, exec) {
|
|
2456
|
-
// Always allowed so the guard can be lifted.
|
|
2457
|
-
const allowed = args.allowed ?? []
|
|
2458
|
-
const unknown = allowed.filter((t: string) => !t.startsWith('dsh_browser_'))
|
|
2459
|
-
if (unknown.length > 0) {
|
|
2460
|
-
throw new Error(`dsh_browser_restrict: unknown tool name(s) ${unknown.map(t => `"${t}"`).join(', ')} (must start with "dsh_browser_")`)
|
|
2461
|
-
}
|
|
2462
|
-
// Empty list (or omitted) lifts this task's restriction; a non-empty list is its
|
|
2463
|
-
// new allow-list. Per task, not per plugin: this state object is shared by every
|
|
2464
|
-
// agent, so one value here used to lock every other task's browser tools.
|
|
2465
|
-
//
|
|
2466
|
-
if (allowed.length === 0) state.restrictedByTask.delete(taskKey(exec))
|
|
2467
|
-
else state.restrictedByTask.set(taskKey(exec), [...allowed])
|
|
2468
|
-
const current = state.restrictedByTask.get(taskKey(exec))
|
|
2469
|
-
return { restrictedTo: current === undefined ? [] : [...current] }
|
|
2470
|
-
},
|
|
2471
|
-
}))
|
|
2472
|
-
|
|
2473
|
-
registerSafely(defineTool({
|
|
2474
|
-
name: 'dsh_browser_auth',
|
|
2475
|
-
description: 'Export or restore the session\'s cookies (login state): "flush" returns a JSON cookie list, "restore" takes that list back (e.g. after the host restarted). Works on all carriers. Refused when the credential switch is off. Exported cookies are LIVE CREDENTIALS: never echo them into the conversation or logs; keep the list in a private file.',
|
|
2476
|
-
parameters: {
|
|
2477
|
-
action: { type: 'string', required: true, enum: ['flush', 'restore'], description: 'flush = export cookies; restore = import cookies.' },
|
|
2478
|
-
cookies: { type: 'array', items: { type: 'object', additionalProperties: true }, description: 'Cookie list to restore (required when action=restore).' },
|
|
2479
|
-
},
|
|
2480
|
-
output: {
|
|
2481
|
-
schema: {
|
|
2482
|
-
type: 'object',
|
|
2483
|
-
additionalProperties: false,
|
|
2484
|
-
properties: {
|
|
2485
|
-
cookies: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
2486
|
-
restored: { type: 'number' },
|
|
2487
|
-
},
|
|
2488
|
-
},
|
|
2489
|
-
render: (_args, value) => [{ type: 'text', text: value.cookies !== undefined ? `Exported ${(value.cookies as unknown[]).length} cookies — LIVE CREDENTIALS; store privately and never echo them.` : `Restored ${value.restored} cookies.` }],
|
|
2490
|
-
},
|
|
2491
|
-
timeoutMs,
|
|
2492
|
-
isConcurrencySafe: () => false,
|
|
2493
|
-
async execute(args, exec) {
|
|
2494
|
-
assertAllowed(state, 'dsh_browser_auth', taskKey(exec))
|
|
2495
|
-
const browser = ctx.get('browser')
|
|
2496
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2497
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2498
|
-
if (args.action === 'flush') {
|
|
2499
|
-
const cookies = await browser.flushAuth(session)
|
|
2500
|
-
return { cookies: cookies.map(c => ({ ...c })) as never }
|
|
2501
|
-
}
|
|
2502
|
-
// The description says cookies are required for restore; without this check an
|
|
2503
|
-
// empty call returned {restored: 0} and rendered 'Restored 0 cookies.', which
|
|
2504
|
-
// reads as success and would leave the caller believing the login was restored.
|
|
2505
|
-
if (!Array.isArray(args.cookies) || args.cookies.length === 0) {
|
|
2506
|
-
throw new Error('dsh_browser_auth: action "restore" needs a non-empty "cookies" array (get one from action "flush" on the same profile)')
|
|
2507
|
-
}
|
|
2508
|
-
const list = args.cookies as unknown[]
|
|
2509
|
-
const restored = await browser.restoreAuth(session, list as never)
|
|
2510
|
-
return { restored }
|
|
2511
|
-
},
|
|
2512
|
-
}))
|
|
2513
|
-
|
|
2514
|
-
// ===========================================================================
|
|
2515
|
-
// Observation, assertion and batch work (0.5.7).
|
|
2516
|
-
//
|
|
2517
|
-
// Five capabilities were missing against the other browser plugins in this market: what the
|
|
2518
|
-
// console said, which responses arrived, what happened to a JavaScript dialog (an unanswered
|
|
2519
|
-
// `confirm()` used to hang a whole call), a way to assert a result instead of eyeballing a
|
|
2520
|
-
// screenshot, and a way to run several steps in one call. All of them come from one page-side
|
|
2521
|
-
// probe installed through `execute`, so they work identically on the self-hosted window, a driven
|
|
2522
|
-
// Chrome/Edge and the desktop sidebar — no host change, no bridge protocol version.
|
|
2523
|
-
// ===========================================================================
|
|
2524
|
-
|
|
2525
|
-
/**
|
|
2526
|
-
* What to do with a saved file, from the settings document.
|
|
2527
|
-
*
|
|
2528
|
-
* Read here rather than threaded through the provider on purpose: delivery is a property of how
|
|
2529
|
-
* this deployment saves files, not of which browser carries the page, so every carrier gets it
|
|
2530
|
-
* for free and no seam grows a method for it.
|
|
2531
|
-
*
|
|
2532
|
-
* @param url - the downloaded address, used to pick a per-site override by host.
|
|
2533
|
-
* @param path - the absolute local path just written.
|
|
2534
|
-
* @returns the plan, or undefined when nothing is configured (the old behaviour).
|
|
2535
|
-
*/
|
|
2536
|
-
function deliveryPlan(url: string, path: string): { tool: string; args: Record<string, string>; onFail: 'keep-local' | 'stop' } | undefined {
|
|
2537
|
-
let settings
|
|
2538
|
-
try { settings = settingsStore.get() } catch { return undefined }
|
|
2539
|
-
const delivery = settings.delivery
|
|
2540
|
-
if (delivery === undefined) return undefined
|
|
2541
|
-
let host = ''
|
|
2542
|
-
try { host = new URL(url).hostname.toLowerCase() } catch { host = '' }
|
|
2543
|
-
const override = host === '' ? undefined : (delivery.sites[host] ?? delivery.sites['*'])
|
|
2544
|
-
const tool = override ?? delivery.tool
|
|
2545
|
-
if (typeof tool !== 'string' || tool.trim() === '') return undefined
|
|
2546
|
-
const name = path.split(/[\\/]/).pop() ?? path
|
|
2547
|
-
const size = (() => { try { return String(statSync(path).size) } catch { return '' } })()
|
|
2548
|
-
const args: Record<string, string> = {}
|
|
2549
|
-
for (const [key, value] of Object.entries(delivery.args)) {
|
|
2550
|
-
args[key] = String(value).split('{path}').join(path).split('{name}').join(name).split('{size}').join(size)
|
|
2551
|
-
}
|
|
2552
|
-
if (Object.keys(args).length === 0) args.file_path = path
|
|
2553
|
-
return { tool: tool.trim(), args, onFail: delivery.onFail }
|
|
2554
|
-
}
|
|
2555
|
-
|
|
2556
|
-
/** Check the canonical outcome before describing a completed delivery. */
|
|
2557
|
-
function summariseToolResult(answer: unknown): string {
|
|
2558
|
-
const outcome = answer as { isError?: boolean; value?: unknown; error?: { message?: string }; content?: { text?: string }[] } | null
|
|
2559
|
-
if (outcome === null || typeof outcome !== 'object' || typeof outcome.isError !== 'boolean') {
|
|
2560
|
-
throw new Error('the delivery executor returned an invalid tool result')
|
|
2561
|
-
}
|
|
2562
|
-
if (outcome.isError) {
|
|
2563
|
-
throw new Error(outcome.error?.message || outcome.content?.map(block => block.text ?? '').join(' ') || 'the delivery tool failed')
|
|
2564
|
-
}
|
|
2565
|
-
if (!('value' in outcome)) throw new Error('the delivery executor returned an invalid tool result')
|
|
2566
|
-
const failure = deliveryFailure(outcome.value)
|
|
2567
|
-
if (failure !== undefined) throw new Error(failure)
|
|
2568
|
-
const text = typeof outcome.value === 'string' ? outcome.value : JSON.stringify(outcome.value)
|
|
2569
|
-
return text.length > 200 ? text.slice(0, 200) + '…' : text
|
|
2570
|
-
}
|
|
2571
|
-
|
|
2572
|
-
/** Read explicit failure markers in common MCP structured or JSON text responses. */
|
|
2573
|
-
function deliveryFailure(value: unknown): string | undefined {
|
|
2574
|
-
const object = (candidate: unknown): Record<string, unknown> | undefined => {
|
|
2575
|
-
if (typeof candidate === 'string') {
|
|
2576
|
-
try { candidate = JSON.parse(candidate) } catch { return undefined }
|
|
2577
|
-
}
|
|
2578
|
-
return candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
|
|
2579
|
-
? candidate as Record<string, unknown> : undefined
|
|
2580
|
-
}
|
|
2581
|
-
const response = object(value)
|
|
2582
|
-
if (response === undefined) return undefined
|
|
2583
|
-
const blocks = Array.isArray(response.content) ? response.content : []
|
|
2584
|
-
const candidates = [
|
|
2585
|
-
response,
|
|
2586
|
-
object(response.structuredContent),
|
|
2587
|
-
...blocks.map(block => {
|
|
2588
|
-
const content = object(block)
|
|
2589
|
-
return content?.type === 'text' ? object(content.text) : undefined
|
|
2590
|
-
}),
|
|
2591
|
-
]
|
|
2592
|
-
for (const candidate of candidates) {
|
|
2593
|
-
if (candidate === undefined) continue
|
|
2594
|
-
if (candidate.isError !== true && candidate.ok !== false && candidate.success !== false
|
|
2595
|
-
&& candidate.status !== 'error' && candidate.status !== 'failed') continue
|
|
2596
|
-
const error = object(candidate.error)
|
|
2597
|
-
const detail = [candidate.message, candidate.error, error?.message].find(item => typeof item === 'string' && item !== '')
|
|
2598
|
-
return typeof detail === 'string' ? detail : 'the delivery tool reported a failed upload'
|
|
2599
|
-
}
|
|
2600
|
-
return undefined
|
|
2601
|
-
}
|
|
2602
|
-
|
|
2603
|
-
/** Run a script in the page and return its value as text. */
|
|
2604
|
-
async function pageValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, script: string, signal?: AbortSignal): Promise<string> {
|
|
2605
|
-
const result = await browser.execute(session, { script }, signal)
|
|
2606
|
-
if (!result.ok) throw new Error(`page script failed: ${result.exception}`)
|
|
2607
|
-
const raw = result.value
|
|
2608
|
-
return typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
|
|
2609
|
-
}
|
|
2610
|
-
|
|
2611
|
-
/** Fixed operations keep their inputs as data and preserve arbitrary-script permissions. */
|
|
2612
|
-
async function pageOperationValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<string> {
|
|
2613
|
-
const result = typeof browser.pageOperation === 'function'
|
|
2614
|
-
? await browser.pageOperation(session, request, signal)
|
|
2615
|
-
: await browser.execute(session, { script: pageOperationScript(request) }, signal)
|
|
2616
|
-
if (!result.ok) throw new Error('page operation failed: ' + result.exception)
|
|
2617
|
-
return typeof result.value === 'string' ? result.value : JSON.stringify(result.value ?? null)
|
|
185
|
+
const scope: ToolScope = { ctx, config, state, takeovers, settingsStore, timeoutMs, maxWaitMs, maxFillFields, surface }
|
|
186
|
+
const definitions = new Map([
|
|
187
|
+
...debugTools(scope), ...navigationTools(scope), ...observationTools(scope),
|
|
188
|
+
...interactionTools(scope), ...referenceTools(scope),
|
|
189
|
+
].map(definition => [definition.name, definition] as const))
|
|
190
|
+
for (const toolName of REGISTRATION_ORDER) {
|
|
191
|
+
const definition = definitions.get(toolName)
|
|
192
|
+
if (definition !== undefined) registerSafely(definition)
|
|
2618
193
|
}
|
|
2619
194
|
|
|
2620
|
-
|
|
2621
|
-
async function installProbe(browser: NonNullable<Context['browser']>, session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
|
|
2622
|
-
await pageOperationValue(browser, session, { operation: 'install' }, signal)
|
|
2623
|
-
}
|
|
2624
|
-
|
|
2625
|
-
/** One probe call, parsed. Throws when the probe is absent or the call failed. */
|
|
2626
|
-
async function probe<T = unknown>(
|
|
2627
|
-
browser: NonNullable<Context['browser']>,
|
|
2628
|
-
session: BrowserSessionId,
|
|
2629
|
-
method: BrowserProbeMethod,
|
|
2630
|
-
args: readonly unknown[] = [],
|
|
2631
|
-
signal?: AbortSignal,
|
|
2632
|
-
): Promise<T> {
|
|
2633
|
-
const text = await pageOperationValue(browser, session, { operation: 'probe', method, args }, signal)
|
|
2634
|
-
let parsed: unknown
|
|
2635
|
-
try { parsed = JSON.parse(text) } catch { throw new Error(`page probe returned unreadable JSON: ${text.slice(0, 120)}`) }
|
|
2636
|
-
if (parsed !== null && typeof parsed === 'object' && 'error' in (parsed as Record<string, unknown>)) {
|
|
2637
|
-
throw new Error(`page probe: ${String((parsed as Record<string, unknown>).error)}`)
|
|
2638
|
-
}
|
|
2639
|
-
return parsed as T
|
|
2640
|
-
}
|
|
2641
|
-
|
|
2642
|
-
/**
|
|
2643
|
-
* A probe call that survives a navigation inside a batch.
|
|
2644
|
-
*
|
|
2645
|
-
* Submitting a form replaces the document, and the probe with it, so a later step in the same
|
|
2646
|
-
* batch would fail with `probe-not-installed` — measured on the first real benchmark run. One
|
|
2647
|
-
* reinstall and one retry is enough: a second failure is a real absence, not a stale context.
|
|
2648
|
-
*/
|
|
2649
|
-
async function probeLive<T = unknown>(
|
|
2650
|
-
browser: NonNullable<Context['browser']>,
|
|
2651
|
-
session: BrowserSessionId,
|
|
2652
|
-
method: BrowserProbeMethod,
|
|
2653
|
-
args: readonly unknown[] = [],
|
|
2654
|
-
signal?: AbortSignal,
|
|
2655
|
-
): Promise<T> {
|
|
195
|
+
if (surface !== 'tools') {
|
|
2656
196
|
try {
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
}
|
|
2663
|
-
}
|
|
2664
|
-
|
|
2665
|
-
/** Sleep. Long waits are capped by the caller, and the tool timeout still applies. */
|
|
2666
|
-
async function pause(ms: number): Promise<void> {
|
|
2667
|
-
await new Promise<void>(resolve => { setTimeout(resolve, ms) })
|
|
2668
|
-
}
|
|
2669
|
-
|
|
2670
|
-
/** Poll until the callback returns something, or the budget runs out. */
|
|
2671
|
-
async function poll<T>(check: () => Promise<T | undefined>, budgetMs: number): Promise<T | undefined> {
|
|
2672
|
-
const deadline = Date.now() + budgetMs
|
|
2673
|
-
for (;;) {
|
|
2674
|
-
const value = await check()
|
|
2675
|
-
if (value !== undefined) return value
|
|
2676
|
-
if (Date.now() >= deadline) return undefined
|
|
2677
|
-
await pause(200)
|
|
2678
|
-
}
|
|
2679
|
-
}
|
|
2680
|
-
|
|
2681
|
-
/**
|
|
2682
|
-
* One flat probe row: what a page can hand back through JSON.
|
|
2683
|
-
*
|
|
2684
|
-
* Concrete rather than `Record<string, unknown>`, because the tool output schema is a JSON value
|
|
2685
|
-
* and the compiler (rightly) refuses to promise that an `unknown` is one.
|
|
2686
|
-
*/
|
|
2687
|
-
type ProbeRow = Record<string, string | number | boolean | null>
|
|
2688
|
-
|
|
2689
|
-
/**
|
|
2690
|
-
* Run one `dsh_browser_check` specification against the page.
|
|
2691
|
-
*
|
|
2692
|
-
* Shared by the `check` tool and by the `{check: …}` step of `dsh_browser_do`, so a batch asserts
|
|
2693
|
-
* exactly what a standalone call asserts.
|
|
2694
|
-
*/
|
|
2695
|
-
async function runChecks(
|
|
2696
|
-
browser: NonNullable<Context['browser']>,
|
|
2697
|
-
session: BrowserSessionId,
|
|
2698
|
-
spec: { readonly selector?: string; readonly text?: string; readonly url?: string; readonly js?: string },
|
|
2699
|
-
signal?: AbortSignal,
|
|
2700
|
-
): Promise<{ pass: boolean; checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> }> {
|
|
2701
|
-
const checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> = []
|
|
2702
|
-
if (spec.selector !== undefined) {
|
|
2703
|
-
const found = await probeLive<{ described?: string } | null>(browser, session, 'find', [{ css: spec.selector }], signal)
|
|
2704
|
-
checks.push({ kind: 'selector', expected: spec.selector, actual: found === null ? 'not found' : String(found.described ?? 'found'), pass: found !== null })
|
|
2705
|
-
}
|
|
2706
|
-
if (spec.text !== undefined) {
|
|
2707
|
-
const present = await pageOperationValue(browser, session, { operation: 'text', text: spec.text }, signal)
|
|
2708
|
-
const ok = present === 'true'
|
|
2709
|
-
checks.push({ kind: 'text', expected: spec.text, actual: ok ? 'present' : 'absent', pass: ok })
|
|
2710
|
-
}
|
|
2711
|
-
if (spec.url !== undefined) {
|
|
2712
|
-
const href = await pageOperationValue(browser, session, { operation: 'url' }, signal).then(text => text.replace(/^"|"$/g, ''))
|
|
2713
|
-
const ok = href.includes(spec.url)
|
|
2714
|
-
checks.push({ kind: 'url', expected: spec.url, actual: href, pass: ok })
|
|
2715
|
-
}
|
|
2716
|
-
if (spec.js !== undefined) {
|
|
2717
|
-
try {
|
|
2718
|
-
const value = await pageValue(browser, session, `(() => { try { return JSON.stringify({ ok: !!(${spec.js}) }) } catch (error) { return JSON.stringify({ ok: false, error: String(error) }) } })()`, signal)
|
|
2719
|
-
const parsed = JSON.parse(value) as { ok?: boolean; error?: string }
|
|
2720
|
-
checks.push({ kind: 'js', expected: spec.js, actual: parsed.ok === true ? 'truthy' : (parsed.error ?? 'falsy'), pass: parsed.ok === true })
|
|
2721
|
-
} catch (error) {
|
|
2722
|
-
checks.push({ kind: 'js', expected: spec.js, actual: String(error), pass: false })
|
|
2723
|
-
}
|
|
2724
|
-
}
|
|
2725
|
-
return { pass: checks.length > 0 && checks.every(check => check.pass), checks }
|
|
2726
|
-
}
|
|
2727
|
-
|
|
2728
|
-
registerSafely(defineTool({
|
|
2729
|
-
name: 'dsh_browser_console',
|
|
2730
|
-
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.',
|
|
2731
|
-
parameters: {
|
|
2732
|
-
limit: { type: 'number', description: 'How many lines, newest last (default 20, max 100).' },
|
|
2733
|
-
filter: { type: 'string', description: 'Only lines containing this text (case-insensitive).' },
|
|
2734
|
-
clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
|
|
2735
|
-
},
|
|
2736
|
-
output: {
|
|
2737
|
-
schema: {
|
|
2738
|
-
type: 'object',
|
|
2739
|
-
additionalProperties: false,
|
|
2740
|
-
properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
|
|
2741
|
-
},
|
|
2742
|
-
render: (_args, value) => {
|
|
2743
|
-
const rows = value.entries as Array<{ level?: string; text?: string }>
|
|
2744
|
-
if (rows.length === 0) return [{ type: 'text', text: 'No console lines yet (nothing logged since the page probe was installed).' }]
|
|
2745
|
-
return [{ type: 'text', text: rows.map(row => `[${String(row.level)}] ${String(row.text)}`).join('\n') }]
|
|
2746
|
-
},
|
|
2747
|
-
},
|
|
2748
|
-
timeoutMs,
|
|
2749
|
-
isConcurrencySafe: () => true,
|
|
2750
|
-
async execute(args, exec) {
|
|
2751
|
-
const browser = ctx.get('browser')
|
|
2752
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2753
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2754
|
-
await installProbe(browser, session, exec.signal)
|
|
2755
|
-
if (args.clear === true) await probe(browser, session, 'clear', ['console'], exec.signal)
|
|
2756
|
-
const entries = await probe<ProbeRow[]>(browser, session, 'read', ['console', args.filter ?? '', args.limit ?? 20], exec.signal)
|
|
2757
|
-
return { entries }
|
|
2758
|
-
},
|
|
2759
|
-
}))
|
|
2760
|
-
|
|
2761
|
-
registerSafely(defineTool({
|
|
2762
|
-
name: 'dsh_browser_network',
|
|
2763
|
-
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.',
|
|
2764
|
-
parameters: {
|
|
2765
|
-
limit: { type: 'number', description: 'How many rows, newest last (default 20, max 100).' },
|
|
2766
|
-
filter: { type: 'string', description: 'Only rows whose address contains this text.' },
|
|
2767
|
-
onlyFailures: { type: 'boolean', description: 'Only rows with status 0, or status >= 400.' },
|
|
2768
|
-
clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
|
|
2769
|
-
},
|
|
2770
|
-
output: {
|
|
2771
|
-
schema: {
|
|
2772
|
-
type: 'object',
|
|
2773
|
-
additionalProperties: false,
|
|
2774
|
-
properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
|
|
2775
|
-
},
|
|
2776
|
-
render: (_args, value) => {
|
|
2777
|
-
const rows = value.entries as ProbeRow[]
|
|
2778
|
-
if (rows.length === 0) return [{ type: 'text', text: 'No responses recorded yet.' }]
|
|
2779
|
-
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') }]
|
|
2780
|
-
},
|
|
2781
|
-
},
|
|
2782
|
-
timeoutMs,
|
|
2783
|
-
isConcurrencySafe: () => true,
|
|
2784
|
-
async execute(args, exec) {
|
|
2785
|
-
const browser = ctx.get('browser')
|
|
2786
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2787
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2788
|
-
await installProbe(browser, session, exec.signal)
|
|
2789
|
-
if (args.clear === true) await probe(browser, session, 'clear', ['network'], exec.signal)
|
|
2790
|
-
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.filter ?? '', args.limit ?? 20], exec.signal)
|
|
2791
|
-
const entries = args.onlyFailures === true
|
|
2792
|
-
? rows.filter(row => Number(row.status) === 0 || Number(row.status) >= 400)
|
|
2793
|
-
: rows
|
|
2794
|
-
return { entries }
|
|
2795
|
-
},
|
|
2796
|
-
}))
|
|
2797
|
-
|
|
2798
|
-
registerSafely(defineTool({
|
|
2799
|
-
name: 'dsh_browser_dialog',
|
|
2800
|
-
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.',
|
|
2801
|
-
parameters: {
|
|
2802
|
-
policy: { type: 'string', enum: ['native', 'accept', 'dismiss'], description: 'Answer future dialogs this way.' },
|
|
2803
|
-
limit: { type: 'number', description: 'How many recent dialogs to return (default 10).' },
|
|
2804
|
-
},
|
|
2805
|
-
output: {
|
|
2806
|
-
schema: {
|
|
2807
|
-
type: 'object',
|
|
2808
|
-
additionalProperties: false,
|
|
2809
|
-
properties: {
|
|
2810
|
-
policy: { type: 'string', required: true },
|
|
2811
|
-
dialogs: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
2812
|
-
},
|
|
2813
|
-
},
|
|
2814
|
-
render: (_args, value) => {
|
|
2815
|
-
const rows = value.dialogs as ProbeRow[]
|
|
2816
|
-
const head = `Dialog policy: ${String(value.policy)} (${String(value.policy) === 'accept' ? 'confirm→true, prompt→its text' : 'confirm→false, prompt→null'}).`
|
|
2817
|
-
if (rows.length === 0) return [{ type: 'text', text: `${head} No dialogs seen yet.` }]
|
|
2818
|
-
return [{ type: 'text', text: [head, ...rows.map(row => `${String(row.kind)} "${String(row.message)}" → ${String(row.answered)}`)] .join('\n') }]
|
|
2819
|
-
},
|
|
2820
|
-
},
|
|
2821
|
-
timeoutMs,
|
|
2822
|
-
isConcurrencySafe: () => false, // the policy is task-wide state
|
|
2823
|
-
async execute(args, exec) {
|
|
2824
|
-
assertAllowed(state, 'dsh_browser_dialog', taskKey(exec))
|
|
2825
|
-
const browser = ctx.get('browser')
|
|
2826
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2827
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2828
|
-
await installProbe(browser, session, exec.signal)
|
|
2829
|
-
const policy = args.policy === undefined
|
|
2830
|
-
? await probe<string>(browser, session, 'dialogStatus', [], exec.signal)
|
|
2831
|
-
: await probe<string>(browser, session, 'setDialogPolicy', [args.policy], exec.signal)
|
|
2832
|
-
const dialogs = await probe<ProbeRow[]>(browser, session, 'read', ['dialogs', '', args.limit ?? 10], exec.signal)
|
|
2833
|
-
return { policy, dialogs }
|
|
2834
|
-
},
|
|
2835
|
-
}))
|
|
2836
|
-
|
|
2837
|
-
registerSafely(defineTool({
|
|
2838
|
-
name: 'dsh_browser_wait_for_response',
|
|
2839
|
-
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.',
|
|
2840
|
-
parameters: {
|
|
2841
|
-
urlContains: { type: 'string', required: true, description: 'Substring of the request address.' },
|
|
2842
|
-
status: { type: 'number', description: 'Require this exact status (a non-zero status is required to match).' },
|
|
2843
|
-
timeoutMs: { type: 'number', description: 'How long to wait (default 15000, capped by the tool timeout).' },
|
|
2844
|
-
},
|
|
2845
|
-
output: {
|
|
2846
|
-
schema: {
|
|
2847
|
-
type: 'object',
|
|
2848
|
-
additionalProperties: false,
|
|
2849
|
-
properties: {
|
|
2850
|
-
matched: { type: 'boolean', required: true },
|
|
2851
|
-
reason: { type: 'string', required: true },
|
|
2852
|
-
entry: { type: 'object', additionalProperties: true },
|
|
2853
|
-
},
|
|
2854
|
-
},
|
|
2855
|
-
render: (_args, value) => {
|
|
2856
|
-
const entry = value.entry as Record<string, unknown> | undefined
|
|
2857
|
-
if (!value.matched) return [{ type: 'text', text: `No matching response: ${String(value.reason)}` }]
|
|
2858
|
-
return [{ type: 'text', text: `Matched: ${String(entry?.method)} ${String(entry?.status)} ${String(entry?.url)} (${String(entry?.ms)}ms)` }]
|
|
2859
|
-
},
|
|
2860
|
-
},
|
|
2861
|
-
timeoutMs,
|
|
2862
|
-
isConcurrencySafe: () => true,
|
|
2863
|
-
async execute(args, exec) {
|
|
2864
|
-
const browser = ctx.get('browser')
|
|
2865
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2866
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2867
|
-
await installProbe(browser, session, exec.signal)
|
|
2868
|
-
const cursor = await probe<{ startedAt: number; sequence: number }>(browser, session, 'networkCursor', [], exec.signal)
|
|
2869
|
-
// Batched code holds back the triggering action until the cursor is captured.
|
|
2870
|
-
;(exec as { armed?: () => void }).armed?.()
|
|
2871
|
-
const budget = Math.min(args.timeoutMs ?? 15_000, maxWaitMs)
|
|
2872
|
-
const found = await poll(async () => {
|
|
2873
|
-
const current = await probe<{ startedAt: number; sequence: number }>(browser, session, 'networkCursor', [], exec.signal)
|
|
2874
|
-
if (current.startedAt !== cursor.startedAt) throw new Error('the page changed while waiting for a response; start a new wait on the current page')
|
|
2875
|
-
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.urlContains, 100], exec.signal)
|
|
2876
|
-
const fresh = rows.filter(row => Number(row.sequence) > cursor.sequence && Number(row.status) > 0)
|
|
2877
|
-
const exact = args.status === undefined ? fresh : fresh.filter(row => Number(row.status) === args.status)
|
|
2878
|
-
return exact.length > 0 ? exact[exact.length - 1] : undefined
|
|
2879
|
-
}, budget)
|
|
2880
|
-
if (found === undefined) {
|
|
2881
|
-
const rows = await probe<ProbeRow[]>(browser, session, 'read', ['network', args.urlContains, 60], exec.signal)
|
|
2882
|
-
const seen = rows.length === 0 ? 'nothing matched the address' : `${rows.length} older row(s) matched but none arrived after this call started`
|
|
2883
|
-
return { matched: false, reason: `${seen} within ${Math.round(budget / 1000)}s` }
|
|
2884
|
-
}
|
|
2885
|
-
return { matched: true, reason: 'response arrived', entry: found }
|
|
2886
|
-
},
|
|
2887
|
-
}))
|
|
2888
|
-
|
|
2889
|
-
registerSafely(defineTool({
|
|
2890
|
-
name: 'dsh_browser_assert',
|
|
2891
|
-
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.',
|
|
2892
|
-
parameters: {
|
|
2893
|
-
selector: { type: 'string', description: 'CSS selector that must match an element.' },
|
|
2894
|
-
text: { type: 'string', description: 'Text that must appear in the page body.' },
|
|
2895
|
-
url: { type: 'string', description: 'Substring the URL must contain.' },
|
|
2896
|
-
js: { type: 'string', description: 'Expression that must be truthy, e.g. document.querySelector("#ok") !== null.' },
|
|
2897
|
-
},
|
|
2898
|
-
output: {
|
|
2899
|
-
schema: {
|
|
2900
|
-
type: 'object',
|
|
2901
|
-
additionalProperties: false,
|
|
2902
|
-
properties: {
|
|
2903
|
-
pass: { type: 'boolean', required: true },
|
|
2904
|
-
checks: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
2905
|
-
},
|
|
2906
|
-
},
|
|
2907
|
-
render: (_args, value) => {
|
|
2908
|
-
const rows = value.checks as ProbeRow[]
|
|
2909
|
-
const lines = rows.map(row => `${row.pass === true ? 'PASS' : 'FAIL'} ${String(row.kind)}: ${String(row.expected)} → ${String(row.actual)}`)
|
|
2910
|
-
return [{ type: 'text', text: `${value.pass === true ? 'All checks passed.' : 'A check failed.'}\n${lines.join('\n')}` }]
|
|
2911
|
-
},
|
|
2912
|
-
},
|
|
2913
|
-
timeoutMs,
|
|
2914
|
-
isConcurrencySafe: () => true,
|
|
2915
|
-
async execute(args, exec) {
|
|
2916
|
-
const browser = ctx.get('browser')
|
|
2917
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2918
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2919
|
-
await installProbe(browser, session, exec.signal)
|
|
2920
|
-
const spec = {
|
|
2921
|
-
...args.selector !== undefined ? { selector: args.selector } : {},
|
|
2922
|
-
...args.text !== undefined ? { text: args.text } : {},
|
|
2923
|
-
...args.url !== undefined ? { url: args.url } : {},
|
|
2924
|
-
...args.js !== undefined ? { js: args.js } : {},
|
|
2925
|
-
}
|
|
2926
|
-
if (Object.keys(spec).length === 0) throw new Error('dsh_browser_assert: give at least one of selector, text, url or js')
|
|
2927
|
-
return await runChecks(browser, session, spec, exec.signal)
|
|
2928
|
-
},
|
|
2929
|
-
}))
|
|
2930
|
-
|
|
2931
|
-
registerSafely(defineTool({
|
|
2932
|
-
name: 'dsh_browser_drag',
|
|
2933
|
-
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.',
|
|
2934
|
-
parameters: {
|
|
2935
|
-
fromX: { type: 'number', required: true, description: 'Start x in viewport CSS pixels.' },
|
|
2936
|
-
fromY: { type: 'number', required: true, description: 'Start y in viewport CSS pixels.' },
|
|
2937
|
-
toX: { type: 'number', required: true, description: 'End x.' },
|
|
2938
|
-
toY: { type: 'number', required: true, description: 'End y.' },
|
|
2939
|
-
steps: { type: 'number', description: 'Intermediate moves (default 12, max 60); more steps make a slider follow the path.' },
|
|
2940
|
-
},
|
|
2941
|
-
output: {
|
|
2942
|
-
schema: {
|
|
2943
|
-
type: 'object',
|
|
2944
|
-
additionalProperties: false,
|
|
2945
|
-
properties: {
|
|
2946
|
-
ok: { type: 'boolean', required: true },
|
|
2947
|
-
reason: { type: 'string', required: true },
|
|
2948
|
-
},
|
|
2949
|
-
},
|
|
2950
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === true ? 'Dragged.' : `Drag failed: ${String(value.reason)}` }],
|
|
2951
|
-
},
|
|
2952
|
-
timeoutMs,
|
|
2953
|
-
isConcurrencySafe: () => false, // a pointer gesture; exclusive within a task
|
|
2954
|
-
async execute(args, exec) {
|
|
2955
|
-
assertAllowed(state, 'dsh_browser_drag', taskKey(exec))
|
|
2956
|
-
const browser = ctx.get('browser')
|
|
2957
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2958
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2959
|
-
const text = await pageOperationValue(browser, session, {
|
|
2960
|
-
operation: 'drag',
|
|
2961
|
-
from: { x: args.fromX, y: args.fromY },
|
|
2962
|
-
to: { x: args.toX, y: args.toY },
|
|
2963
|
-
steps: args.steps ?? 12,
|
|
2964
|
-
}, exec.signal)
|
|
2965
|
-
const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; moved?: number }
|
|
2966
|
-
return { ok: parsed.ok === true, reason: parsed.ok === true ? `moved ${String(parsed.moved)} steps` : String(parsed.reason ?? 'unknown') }
|
|
2967
|
-
},
|
|
2968
|
-
}))
|
|
2969
|
-
|
|
2970
|
-
registerSafely(defineTool({
|
|
2971
|
-
name: 'dsh_browser_doctor',
|
|
2972
|
-
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.',
|
|
2973
|
-
parameters: {},
|
|
2974
|
-
output: {
|
|
2975
|
-
schema: { type: 'object', additionalProperties: false, properties: { report: { type: 'string', required: true } } },
|
|
2976
|
-
render: (_args, value) => [{ type: 'text', text: String(value.report) }],
|
|
2977
|
-
},
|
|
2978
|
-
timeoutMs,
|
|
2979
|
-
isConcurrencySafe: () => true,
|
|
2980
|
-
async execute(_args, exec) {
|
|
2981
|
-
const browser = ctx.get('browser')
|
|
2982
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
2983
|
-
const task = taskKey(exec)
|
|
2984
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
2985
|
-
await installProbe(browser, session, exec.signal)
|
|
2986
|
-
const url = await pageOperationValue(browser, session, { operation: 'url' }, exec.signal).then(text => text.replace(/^"|"$/g, ''))
|
|
2987
|
-
const settle = await probe<{ pending?: number; quietMs?: number; readyState?: string }>(browser, session, 'settle', [], exec.signal)
|
|
2988
|
-
const consoleRows = await probe<unknown[]>(browser, session, 'read', ['console', '', 100], exec.signal)
|
|
2989
|
-
const networkRows = await probe<unknown[]>(browser, session, 'read', ['network', '', 100], exec.signal)
|
|
2990
|
-
const dialogRows = await probe<ProbeRow[]>(browser, session, 'read', ['dialogs', '', 5], exec.signal)
|
|
2991
|
-
const restricted = state.restrictedByTask.get(task)
|
|
2992
|
-
const lines = [
|
|
2993
|
-
`session ${session}`,
|
|
2994
|
-
`url ${url || '(unknown)'}`,
|
|
2995
|
-
`page ${String(settle?.readyState ?? '?')}, ${String(settle?.pending ?? 0)} request(s) in flight, quiet for ${String(settle?.quietMs ?? 0)}ms`,
|
|
2996
|
-
`probe installed (console ${consoleRows.length}/100, network ${networkRows.length}/100, dialogs ${dialogRows.length}/5)`,
|
|
2997
|
-
restricted === undefined ? 'restricted: no (this task restricted nothing)' : `restricted: ${restricted.length === 0 ? 'everything' : restricted.join(', ')}`,
|
|
2998
|
-
state.configRestrictedTo === undefined ? 'deployment allow-list: none' : `deployment allow-list: ${state.configRestrictedTo.join(', ')}`,
|
|
2999
|
-
]
|
|
3000
|
-
return { report: lines.join('\n') }
|
|
3001
|
-
},
|
|
3002
|
-
}))
|
|
3003
|
-
|
|
3004
|
-
registerSafely(defineTool({
|
|
3005
|
-
name: 'dsh_browser_help',
|
|
3006
|
-
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.',
|
|
3007
|
-
parameters: {
|
|
3008
|
-
topic: { type: 'string', description: 'One topic name; omit for the index.' },
|
|
3009
|
-
},
|
|
3010
|
-
output: {
|
|
3011
|
-
schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
|
|
3012
|
-
render: (_args, value) => [{ type: 'text', text: String(value.text) }],
|
|
3013
|
-
},
|
|
3014
|
-
timeoutMs,
|
|
3015
|
-
isConcurrencySafe: () => true,
|
|
3016
|
-
async execute(args) {
|
|
3017
|
-
const topics: Record<string, string> = {
|
|
3018
|
-
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.',
|
|
3019
|
-
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.',
|
|
3020
|
-
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.',
|
|
3021
|
-
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.',
|
|
3022
|
-
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.',
|
|
3023
|
-
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.',
|
|
3024
|
-
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.',
|
|
3025
|
-
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.',
|
|
3026
|
-
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.',
|
|
3027
|
-
}
|
|
3028
|
-
if (args.topic === undefined) {
|
|
3029
|
-
return { text: `Topics: ${Object.keys(topics).join(', ')}\nAsk for one with topic=<name>.` }
|
|
3030
|
-
}
|
|
3031
|
-
const text = topics[args.topic]
|
|
3032
|
-
if (text === undefined) throw new Error(`dsh_browser_help: unknown topic "${args.topic}" (${Object.keys(topics).join(', ')})`)
|
|
3033
|
-
return { text }
|
|
3034
|
-
},
|
|
3035
|
-
}))
|
|
3036
|
-
|
|
3037
|
-
registerSafely(defineTool({
|
|
3038
|
-
name: 'dsh_browser_do',
|
|
3039
|
-
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.',
|
|
3040
|
-
parameters: {
|
|
3041
|
-
steps: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true, description: 'Steps, in order (max 40).' },
|
|
3042
|
-
timeoutMs: { type: 'number', description: 'Budget for the whole batch (default 60000, capped by the tool timeout).' },
|
|
3043
|
-
autoDismiss: { type: 'boolean', description: 'Clear a covering banner before a tap (default true).' },
|
|
3044
|
-
},
|
|
3045
|
-
output: {
|
|
3046
|
-
schema: {
|
|
3047
|
-
type: 'object',
|
|
3048
|
-
additionalProperties: false,
|
|
3049
|
-
properties: {
|
|
3050
|
-
completed: { type: 'number', required: true },
|
|
3051
|
-
total: { type: 'number', required: true },
|
|
3052
|
-
ok: { type: 'boolean', required: true },
|
|
3053
|
-
stoppedAt: { type: 'number' },
|
|
3054
|
-
reason: { type: 'string' },
|
|
3055
|
-
sideEffectMayHaveHappened: { type: 'boolean' },
|
|
3056
|
-
log: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
|
|
3057
|
-
},
|
|
3058
|
-
},
|
|
3059
|
-
render: (_args, value) => {
|
|
3060
|
-
const rows = value.log as ProbeRow[]
|
|
3061
|
-
const head = value.ok === true
|
|
3062
|
-
? `${String(value.completed)}/${String(value.total)} steps done.`
|
|
3063
|
-
: `Stopped at step ${String(value.stoppedAt)} (${String(value.completed)}/${String(value.total)} done): ${String(value.reason)}`
|
|
3064
|
-
const warning = value.ok === false && value.sideEffectMayHaveHappened === true
|
|
3065
|
-
? '\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.'
|
|
3066
|
-
: ''
|
|
3067
|
-
return [{ type: 'text', text: [head + warning, ...rows.map(row => ` ${String(row.index)} ${String(row.kind)}: ${String(row.detail)}`)].join('\n') }]
|
|
3068
|
-
},
|
|
3069
|
-
},
|
|
3070
|
-
timeoutMs,
|
|
3071
|
-
isConcurrencySafe: () => false, // drives the page; exclusive within a task
|
|
3072
|
-
async execute(args, exec) {
|
|
3073
|
-
assertAllowed(state, 'dsh_browser_do', taskKey(exec))
|
|
3074
|
-
const browser = ctx.get('browser')
|
|
3075
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3076
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
3077
|
-
const steps = Array.isArray(args.steps) ? args.steps as ProbeRow[] : []
|
|
3078
|
-
if (steps.length === 0) throw new Error('dsh_browser_do: "steps" must be a non-empty array')
|
|
3079
|
-
if (steps.length > 40) throw new Error('dsh_browser_do: at most 40 steps per call — split the work')
|
|
3080
|
-
await installProbe(browser, session, exec.signal)
|
|
3081
|
-
const autoDismiss = args.autoDismiss !== false
|
|
3082
|
-
const budget = Math.min(args.timeoutMs ?? timeoutMs, maxWaitMs)
|
|
3083
|
-
const deadline = Date.now() + budget
|
|
3084
|
-
const log: Array<{ index: number; kind: string; detail: string }> = []
|
|
3085
|
-
// Set once a step that can change server state has run. A failure after that point must not
|
|
3086
|
-
// read like a failure before it: measured on the first real benchmark run, where a batch died
|
|
3087
|
-
// after the form had already been submitted and the message said nothing about it.
|
|
3088
|
-
let dispatched = false
|
|
3089
|
-
const dispatchable = new Set(['tap', 'key', 'eval'])
|
|
3090
|
-
const kinds = ['open', 'tap', 'field', 'type', 'key', 'scroll', 'sleep_ms', 'wait_text', 'wait_gone', 'wait_url', 'wait_idle', 'eval', 'check']
|
|
3091
|
-
|
|
3092
|
-
/** Resolve a target: a string is visible text; an object passes through. */
|
|
3093
|
-
const asTarget = (value: unknown): { by: 'css' | 'text' | 'xpath'; value: string } | undefined => {
|
|
3094
|
-
if (typeof value === 'string' && value !== '') return { by: 'text', value }
|
|
3095
|
-
if (value !== null && typeof value === 'object') {
|
|
3096
|
-
const raw = value as { by?: unknown; value?: unknown }
|
|
3097
|
-
if (typeof raw.value === 'string' && raw.value !== '') {
|
|
3098
|
-
const by = raw.by === 'css' || raw.by === 'xpath' || raw.by === 'text' ? raw.by : 'text'
|
|
3099
|
-
return { by, value: raw.value }
|
|
3100
|
-
}
|
|
3101
|
-
}
|
|
3102
|
-
return undefined
|
|
3103
|
-
}
|
|
3104
|
-
|
|
3105
|
-
for (let index = 0; index < steps.length; index += 1) {
|
|
3106
|
-
const step = steps[index] ?? {}
|
|
3107
|
-
const keys = Object.keys(step).filter(key => kinds.includes(key))
|
|
3108
|
-
if (keys.length !== 1) {
|
|
3109
|
-
return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `step ${index + 1} must have exactly one of: ${kinds.join(', ')}`, log }
|
|
3110
|
-
}
|
|
3111
|
-
const kind = keys[0] as string
|
|
3112
|
-
const value = step[kind]
|
|
3113
|
-
if (Date.now() > deadline) {
|
|
3114
|
-
return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `budget of ${Math.round(budget / 1000)}s exhausted`, log }
|
|
3115
|
-
}
|
|
197
|
+
// Reads the page the action left behind without starting a session or installing the probe.
|
|
198
|
+
const pulse = async (exec: never): Promise<PagePulse | undefined> => {
|
|
199
|
+
const browser = ctx.get('browser')
|
|
200
|
+
const session = state.sessionsByTask.get(taskKey(exec))
|
|
201
|
+
if (browser === undefined || session === undefined) return undefined
|
|
3116
202
|
try {
|
|
3117
|
-
|
|
3118
|
-
if (
|
|
3119
|
-
const url = typeof value === 'string' ? value : (value as { url?: unknown })?.url
|
|
3120
|
-
if (typeof url !== 'string') throw new Error('open needs a URL string or {url}')
|
|
3121
|
-
await browser.openUrl(session, { url }, exec.signal)
|
|
3122
|
-
detail = url
|
|
3123
|
-
} else if (kind === 'tap') {
|
|
3124
|
-
const target = asTarget((value as { target?: unknown })?.target ?? value)
|
|
3125
|
-
if (target === undefined) throw new Error('tap needs a target (text, or {by, value})')
|
|
3126
|
-
if (autoDismiss) {
|
|
3127
|
-
const rect = await probeLive<{ x?: number; y?: number; described?: string } | null>(browser, session, 'find', [{ [target.by]: target.value }], exec.signal)
|
|
3128
|
-
if (rect && typeof rect.x === 'number' && typeof rect.y === 'number') {
|
|
3129
|
-
const cover = await probeLive<{ covers?: string | null; dismiss?: { label?: string; x?: number; y?: number } | null }>(browser, session, 'overlayAt', [rect.x, rect.y], exec.signal)
|
|
3130
|
-
if (cover?.dismiss && typeof cover.dismiss.x === 'number' && typeof cover.dismiss.y === 'number') {
|
|
3131
|
-
await browser.click(session, { x: cover.dismiss.x, y: cover.dismiss.y }, exec.signal)
|
|
3132
|
-
detail = `dismissed "${String(cover.dismiss.label)}" first`
|
|
3133
|
-
await pause(150)
|
|
3134
|
-
} else if (cover?.covers !== null && cover?.covers !== undefined && cover.covers !== rect.described) {
|
|
3135
|
-
// Measured on the fixture's human gate: a hidden form left the tap hitting `<html>`,
|
|
3136
|
-
// the step reported "ok", and nothing was submitted. A click that cannot land is a
|
|
3137
|
-
// FAILURE, not a note — a silent no-op is the worst result this tool can return.
|
|
3138
|
-
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)`)
|
|
3139
|
-
}
|
|
3140
|
-
}
|
|
3141
|
-
}
|
|
3142
|
-
await browser.click(session, { target }, exec.signal)
|
|
3143
|
-
} else if (kind === 'field') {
|
|
3144
|
-
const spec = value as { target?: unknown; text?: unknown }
|
|
3145
|
-
const target = asTarget(spec?.target)
|
|
3146
|
-
if (target === undefined || typeof spec?.text !== 'string') throw new Error('field needs {target, text}')
|
|
3147
|
-
await browser.setValue(session, { target, value: spec.text }, exec.signal)
|
|
3148
|
-
detail = `${target.value} ← ${spec.text.slice(0, 40)}`
|
|
3149
|
-
} else if (kind === 'type') {
|
|
3150
|
-
const text = typeof value === 'string' ? value : (value as { text?: unknown })?.text
|
|
3151
|
-
if (typeof text !== 'string') throw new Error('type needs a text string or {text}')
|
|
3152
|
-
await browser.type(session, { text }, exec.signal)
|
|
3153
|
-
detail = text.slice(0, 40)
|
|
3154
|
-
} else if (kind === 'key') {
|
|
3155
|
-
const key = typeof value === 'string' ? value : (value as { key?: unknown })?.key
|
|
3156
|
-
if (typeof key !== 'string') throw new Error('key needs a key name or {key}')
|
|
3157
|
-
await browser.key(session, { key: key as never }, exec.signal)
|
|
3158
|
-
detail = key
|
|
3159
|
-
} else if (kind === 'scroll') {
|
|
3160
|
-
const deltaY = typeof value === 'number' ? value : Number((value as { deltaY?: unknown })?.deltaY ?? Number.NaN)
|
|
3161
|
-
if (!Number.isFinite(deltaY)) throw new Error('scroll needs a number or {deltaY}')
|
|
3162
|
-
await browser.scroll(session, { deltaY }, exec.signal)
|
|
3163
|
-
detail = String(deltaY)
|
|
3164
|
-
} else if (kind === 'sleep_ms') {
|
|
3165
|
-
const requestedMs = typeof value === 'number' ? value : (value as { ms?: unknown })?.ms
|
|
3166
|
-
if (typeof requestedMs !== 'number' || !Number.isFinite(requestedMs) || requestedMs < 0) throw new Error('sleep_ms needs a non-negative number or {ms}')
|
|
3167
|
-
const ms = Math.min(requestedMs, 10_000)
|
|
3168
|
-
await pause(ms)
|
|
3169
|
-
detail = `${ms}ms`
|
|
3170
|
-
} else if (kind === 'wait_text' || kind === 'wait_gone') {
|
|
3171
|
-
const want = typeof value === 'string' ? value : (value as { text?: unknown })?.text
|
|
3172
|
-
if (typeof want !== 'string') throw new Error('wait_text/wait_gone need text or {text}')
|
|
3173
|
-
const found = await poll(async () => {
|
|
3174
|
-
const present = (await pageOperationValue(browser, session, { operation: 'text', text: want }, exec.signal)) === 'true'
|
|
3175
|
-
return (kind === 'wait_text' ? present : !present) ? true : undefined
|
|
3176
|
-
}, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)))
|
|
3177
|
-
if (found === undefined) throw new Error(`timed out waiting for "${want}" to be ${kind === 'wait_text' ? 'present' : 'gone'}`)
|
|
3178
|
-
detail = want
|
|
3179
|
-
} else if (kind === 'wait_url') {
|
|
3180
|
-
const want = typeof value === 'string' ? value : (value as { url?: unknown })?.url
|
|
3181
|
-
if (typeof want !== 'string') throw new Error('wait_url needs a URL fragment or {url}')
|
|
3182
|
-
const budget = Math.max(1_000, Math.min(deadline - Date.now(), 30_000))
|
|
3183
|
-
const hit = await poll(async () => {
|
|
3184
|
-
const href = (await pageOperationValue(browser, session, { operation: 'url' }, exec.signal)).replace(/^"|"$/g, '')
|
|
3185
|
-
return href.includes(want) ? href : undefined
|
|
3186
|
-
}, budget)
|
|
3187
|
-
if (hit === undefined) throw new Error(`timed out waiting for the URL to contain "${want}"`)
|
|
3188
|
-
detail = hit
|
|
3189
|
-
} else if (kind === 'wait_idle') {
|
|
3190
|
-
const idle = await poll(async () => {
|
|
3191
|
-
const settle = await probeLive<{ pending?: number; quietMs?: number; readyState?: string }>(browser, session, 'settle', [], exec.signal)
|
|
3192
|
-
const quiet = Number(settle?.quietMs ?? 0)
|
|
3193
|
-
return Number(settle?.pending ?? 0) === 0 && quiet >= 300 ? settle : undefined
|
|
3194
|
-
}, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)))
|
|
3195
|
-
if (idle === undefined) throw new Error('timed out waiting for the page to go quiet')
|
|
3196
|
-
detail = `quiet for ${String(idle.quietMs)}ms`
|
|
3197
|
-
} else if (kind === 'eval') {
|
|
3198
|
-
const script = typeof value === 'string' ? value : (value as { script?: unknown })?.script
|
|
3199
|
-
if (typeof script !== 'string') throw new Error('eval needs a script string or {script}')
|
|
3200
|
-
const text = await pageValue(browser, session, script, exec.signal)
|
|
3201
|
-
detail = text.slice(0, 80)
|
|
3202
|
-
} else if (kind === 'check') {
|
|
3203
|
-
const result = await runChecks(browser, session, value as { selector?: string; text?: string; url?: string; js?: string }, exec.signal)
|
|
3204
|
-
if (!result.pass) {
|
|
3205
|
-
const failed = result.checks.filter(check => !check.pass).map(check => `${check.kind}: ${check.expected} → ${check.actual}`)
|
|
3206
|
-
throw new Error(`check failed (${failed.join('; ')})`)
|
|
3207
|
-
}
|
|
3208
|
-
detail = `${result.checks.length} check(s) passed`
|
|
3209
|
-
}
|
|
3210
|
-
if (dispatchable.has(kind)) dispatched = true
|
|
3211
|
-
log.push({ index: index + 1, kind, detail })
|
|
3212
|
-
} catch (error) {
|
|
203
|
+
const raw = JSON.parse(await pageOperationValue(browser, session, { operation: 'pulse' }, (exec as { signal?: AbortSignal }).signal)) as Partial<PagePulse> | null
|
|
204
|
+
if (typeof raw?.title !== 'string') return undefined
|
|
3213
205
|
return {
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
reason: error instanceof Error ? error.message : String(error),
|
|
3219
|
-
sideEffectMayHaveHappened: dispatched,
|
|
3220
|
-
log: [...log, { index: index + 1, kind, detail: `failed: ${error instanceof Error ? error.message : String(error)}` }],
|
|
206
|
+
title: raw.title,
|
|
207
|
+
alerts: Array.isArray(raw.alerts) ? raw.alerts.filter(text => typeof text === 'string') : [],
|
|
208
|
+
dialogs: Array.isArray(raw.dialogs) ? raw.dialogs.filter(row => typeof row?.at === 'number' && typeof row.kind === 'string') : [],
|
|
209
|
+
probe: Number(raw.probe) || 0,
|
|
3221
210
|
}
|
|
211
|
+
} catch {
|
|
212
|
+
return undefined
|
|
3222
213
|
}
|
|
3223
214
|
}
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
name: 'dsh_browser_upload',
|
|
3229
|
-
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.',
|
|
3230
|
-
parameters: {
|
|
3231
|
-
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].' },
|
|
3232
|
-
path: { type: 'string', required: true, description: 'Absolute path of a file inside the workspace.' },
|
|
3233
|
-
mime: { type: 'string', description: 'MIME type (default guessed from the extension, else application/octet-stream).' },
|
|
3234
|
-
},
|
|
3235
|
-
output: {
|
|
3236
|
-
schema: {
|
|
3237
|
-
type: 'object',
|
|
3238
|
-
additionalProperties: false,
|
|
3239
|
-
properties: {
|
|
3240
|
-
ok: { type: 'boolean', required: true },
|
|
3241
|
-
name: { type: 'string' },
|
|
3242
|
-
size: { type: 'number' },
|
|
3243
|
-
reason: { type: 'string' },
|
|
3244
|
-
},
|
|
3245
|
-
},
|
|
3246
|
-
render: (_args, value) => [{ type: 'text', text: value.ok === true ? `Attached ${String(value.name)} (${String(value.size)} bytes).` : `Upload failed: ${String(value.reason)}` }],
|
|
3247
|
-
},
|
|
3248
|
-
timeoutMs,
|
|
3249
|
-
isConcurrencySafe: () => false,
|
|
3250
|
-
async execute(args, exec) {
|
|
3251
|
-
assertAllowed(state, 'dsh_browser_upload', taskKey(exec))
|
|
3252
|
-
const browser = ctx.get('browser')
|
|
3253
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3254
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
3255
|
-
const target = args.target as { by?: unknown; value?: unknown }
|
|
3256
|
-
const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
|
|
3257
|
-
if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_upload: target.value is required')
|
|
3258
|
-
const { open, realpath, stat } = await import('node:fs/promises')
|
|
3259
|
-
const { resolve, relative, isAbsolute, extname, basename, sep } = await import('node:path')
|
|
3260
|
-
if (!isAbsolute(args.path)) throw new Error('dsh_browser_upload: path must be absolute')
|
|
3261
|
-
const agent = agentOf(exec) as (ExecAgent & { session?: { header?: { cwd?: string } } }) | undefined
|
|
3262
|
-
const directory = (agent?.ctx?.get?.('workingDirectory') ?? ctx.get('workingDirectory')) as {
|
|
3263
|
-
ensure(agent: unknown, signal?: AbortSignal): Promise<string>
|
|
3264
|
-
} | undefined
|
|
3265
|
-
const workspacePath = directory && agent
|
|
3266
|
-
? await directory.ensure(agent, exec.signal)
|
|
3267
|
-
: agent?.session?.header?.cwd ?? process.cwd()
|
|
3268
|
-
if (!isAbsolute(workspacePath)) throw new Error('dsh_browser_upload: the task workspace must be absolute')
|
|
3269
|
-
const workspace = await realpath(workspacePath)
|
|
3270
|
-
const resolved = await realpath(resolve(args.path))
|
|
3271
|
-
const offset = relative(workspace, resolved)
|
|
3272
|
-
if (offset === '..' || offset.startsWith('..' + sep) || isAbsolute(offset)) {
|
|
3273
|
-
throw new Error('dsh_browser_upload: refusing to read a file outside the task workspace')
|
|
3274
|
-
}
|
|
3275
|
-
const expected = await stat(resolved)
|
|
3276
|
-
const LIMIT = 20 * 1024 * 1024
|
|
3277
|
-
if (!expected.isFile()) throw new Error('dsh_browser_upload: path must name a regular file')
|
|
3278
|
-
if (expected.size > LIMIT) throw new Error('dsh_browser_upload: file is over the 20 MB limit')
|
|
3279
|
-
const file = await open(resolved, 'r')
|
|
3280
|
-
let bytes: Buffer
|
|
3281
|
-
try {
|
|
3282
|
-
const opened = await file.stat()
|
|
3283
|
-
if (opened.dev !== expected.dev || opened.ino !== expected.ino
|
|
3284
|
-
|| opened.size !== expected.size || !opened.isFile()
|
|
3285
|
-
|| await realpath(resolve(args.path)) !== resolved) {
|
|
3286
|
-
throw new Error('dsh_browser_upload: file changed while opening; retry')
|
|
3287
|
-
}
|
|
3288
|
-
const chunks: Buffer[] = []
|
|
3289
|
-
let length = 0
|
|
3290
|
-
for await (const chunk of file.createReadStream({ autoClose: false, start: 0, end: LIMIT, signal: exec.signal })) {
|
|
3291
|
-
length += chunk.length
|
|
3292
|
-
if (length > LIMIT) throw new Error('dsh_browser_upload: file grew over the 20 MB limit')
|
|
3293
|
-
chunks.push(chunk as Buffer)
|
|
3294
|
-
}
|
|
3295
|
-
const after = await file.stat()
|
|
3296
|
-
if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || length !== opened.size
|
|
3297
|
-
|| await realpath(resolve(args.path)) !== resolved) {
|
|
3298
|
-
throw new Error('dsh_browser_upload: file changed while reading; retry')
|
|
3299
|
-
}
|
|
3300
|
-
bytes = Buffer.concat(chunks, length)
|
|
3301
|
-
} finally {
|
|
3302
|
-
await file.close()
|
|
3303
|
-
}
|
|
3304
|
-
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' }
|
|
3305
|
-
const mime = args.mime ?? guess[extname(resolved).toLowerCase()] ?? 'application/octet-stream'
|
|
3306
|
-
await installProbe(browser, session, exec.signal)
|
|
3307
|
-
const text = await pageOperationValue(browser, session, {
|
|
3308
|
-
operation: 'upload',
|
|
3309
|
-
target: { by, value: target.value },
|
|
3310
|
-
file: { name: basename(resolved), mime, base64: bytes.toString('base64') },
|
|
3311
|
-
}, exec.signal)
|
|
3312
|
-
const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; name?: string; size?: number }
|
|
3313
|
-
return parsed.ok === true
|
|
3314
|
-
? { ok: true, name: String(parsed.name ?? ''), size: Number(parsed.size ?? 0) }
|
|
3315
|
-
: { ok: false, reason: String(parsed.reason ?? 'unknown') }
|
|
3316
|
-
},
|
|
3317
|
-
}))
|
|
3318
|
-
|
|
3319
|
-
registerSafely(defineTool({
|
|
3320
|
-
name: 'dsh_browser_hover',
|
|
3321
|
-
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.',
|
|
3322
|
-
parameters: {
|
|
3323
|
-
target: { type: 'object', required: true, additionalProperties: true, description: 'The element: {by: "css"|"text"|"xpath", value}.' },
|
|
3324
|
-
settleMs: { type: 'number', description: 'How long to let the menu appear before returning (default 150).' },
|
|
3325
|
-
},
|
|
3326
|
-
output: {
|
|
3327
|
-
schema: { type: 'object', additionalProperties: false, properties: { hovered: { type: 'boolean', required: true }, at: { type: 'object', additionalProperties: true } } },
|
|
3328
|
-
render: (_args, value) => [{ type: 'text', text: value.hovered === true ? 'Pointer moved over the element.' : 'No element at that target.' }],
|
|
3329
|
-
},
|
|
3330
|
-
timeoutMs,
|
|
3331
|
-
isConcurrencySafe: () => false,
|
|
3332
|
-
async execute(args, exec) {
|
|
3333
|
-
assertAllowed(state, 'dsh_browser_hover', taskKey(exec))
|
|
3334
|
-
const browser = ctx.get('browser')
|
|
3335
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3336
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
3337
|
-
const target = args.target as { by?: unknown; value?: unknown }
|
|
3338
|
-
const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
|
|
3339
|
-
if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_hover: target.value is required')
|
|
3340
|
-
await installProbe(browser, session, exec.signal)
|
|
3341
|
-
const where = await probe<{ x?: number; y?: number; described?: string } | null>(browser, session, 'find', [{ [by]: target.value }, true], exec.signal)
|
|
3342
|
-
if (!where || typeof where.x !== 'number' || typeof where.y !== 'number') return { hovered: false, at: {} as ProbeRow }
|
|
3343
|
-
const fired = await probe<boolean>(browser, session, 'hoverAt', [where.x, where.y], exec.signal)
|
|
3344
|
-
await pause(Math.min(args.settleMs ?? 150, 2_000))
|
|
3345
|
-
const at: ProbeRow = { x: where.x, y: where.y, described: String(where.described ?? '') }
|
|
3346
|
-
return { hovered: fired === true, at }
|
|
3347
|
-
},
|
|
3348
|
-
}))
|
|
3349
|
-
|
|
3350
|
-
registerSafely(defineTool({
|
|
3351
|
-
name: 'dsh_browser_find',
|
|
3352
|
-
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.',
|
|
3353
|
-
parameters: {
|
|
3354
|
-
text: { type: 'string', required: true, description: 'Text to look for (case-insensitive).' },
|
|
3355
|
-
all: { type: 'boolean', description: 'Return up to 50 hits instead of 5.' },
|
|
3356
|
-
},
|
|
3357
|
-
output: {
|
|
3358
|
-
schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true }, hits: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } } },
|
|
3359
|
-
render: (_args, value) => {
|
|
3360
|
-
const hits = value.hits as ProbeRow[]
|
|
3361
|
-
if (hits.length === 0) return [{ type: 'text', text: 'Not found on the page.' }]
|
|
3362
|
-
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') }]
|
|
3363
|
-
},
|
|
3364
|
-
},
|
|
3365
|
-
timeoutMs,
|
|
3366
|
-
isConcurrencySafe: () => true,
|
|
3367
|
-
async execute(args, exec) {
|
|
3368
|
-
const browser = ctx.get('browser')
|
|
3369
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3370
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
3371
|
-
await installProbe(browser, session, exec.signal)
|
|
3372
|
-
const hits = await probe<ProbeRow[]>(browser, session, 'findText', [args.text, args.all === true], exec.signal)
|
|
3373
|
-
return { count: hits.length, hits }
|
|
3374
|
-
},
|
|
3375
|
-
}))
|
|
3376
|
-
|
|
3377
|
-
registerSafely(defineTool({
|
|
3378
|
-
name: 'dsh_browser_state',
|
|
3379
|
-
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.',
|
|
3380
|
-
parameters: {},
|
|
3381
|
-
output: {
|
|
3382
|
-
schema: {
|
|
3383
|
-
type: 'object',
|
|
3384
|
-
additionalProperties: false,
|
|
3385
|
-
properties: { summary: { type: 'object', additionalProperties: true, required: true } },
|
|
3386
|
-
},
|
|
3387
|
-
render: (_args, value) => {
|
|
3388
|
-
const row = value.summary as ProbeRow
|
|
3389
|
-
return [{ type: 'text', text: [
|
|
3390
|
-
`${String(row.url)}`,
|
|
3391
|
-
`${String(row.title)}`,
|
|
3392
|
-
`${String(row.readyState)}, ${String(row.pending)} in flight, quiet ${String(row.quietMs)}ms`,
|
|
3393
|
-
`${String(row.inputs)} input(s), ${String(row.buttons)} button(s), ${String(row.links)} link(s), scroll ${String(row.scrollY)}`,
|
|
3394
|
-
row.selection ? `selection: ${String(row.selection)}` : 'no selection',
|
|
3395
|
-
String(row.text ?? ''),
|
|
3396
|
-
].join('\n') }]
|
|
3397
|
-
},
|
|
3398
|
-
},
|
|
3399
|
-
timeoutMs,
|
|
3400
|
-
isConcurrencySafe: () => true,
|
|
3401
|
-
async execute(_args, exec) {
|
|
3402
|
-
const browser = ctx.get('browser')
|
|
3403
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3404
|
-
const key = taskKey(exec)
|
|
3405
|
-
const session = await ensureSession(browser, state, key, agentOf(exec))
|
|
3406
|
-
await installProbe(browser, session, exec.signal)
|
|
3407
|
-
const summary = await probe<ProbeRow>(browser, session, 'summary', [], exec.signal)
|
|
3408
|
-
return { summary }
|
|
3409
|
-
},
|
|
3410
|
-
}))
|
|
3411
|
-
|
|
3412
|
-
registerSafely(defineTool({
|
|
3413
|
-
name: 'dsh_browser_reference_capture',
|
|
3414
|
-
description: 'Capture what the human has selected in the shared-browser page as a durable reference, so it can be quoted and found again later. The reference keeps the selected text with enough surrounding context to relocate it, any images selected with their real bytes, and any table as a structural snapshot. Tool-only captures are stored for later dsh_browser_reference_reveal or export and do not create a chat capsule; do not emit dsh-browser-ref: URIs, reference markers, or synthetic source links in the reply. Re-capturing the same region creates a NEW reference, because a stored reference is an immutable snapshot.',
|
|
3415
|
-
parameters: {
|
|
3416
|
-
allowPartial: { type: 'boolean', description: 'Commit the fragments that succeeded when another fragment failed (default false: a group with a broken image or oversized table is refused as a whole).' },
|
|
3417
|
-
tableSelector: { type: 'string', description: 'Capture this table whole (CSS selector) even when the selection does not touch it.' },
|
|
3418
|
-
excerptText: { type: 'string', description: 'With no live selection, register the first occurrence of this exact page text as an agent excerpt. Two occurrences make it ambiguous and are refused.' },
|
|
3419
|
-
},
|
|
3420
|
-
output: {
|
|
3421
|
-
schema: {
|
|
3422
|
-
type: 'object',
|
|
3423
|
-
additionalProperties: false,
|
|
3424
|
-
properties: {
|
|
3425
|
-
ok: { type: 'boolean', required: true },
|
|
3426
|
-
referenceId: { type: 'string' },
|
|
3427
|
-
pageUrl: { type: 'string' },
|
|
3428
|
-
title: { type: 'string' },
|
|
3429
|
-
parts: {
|
|
3430
|
-
type: 'array',
|
|
3431
|
-
required: true,
|
|
3432
|
-
items: {
|
|
3433
|
-
type: 'object',
|
|
3434
|
-
additionalProperties: false,
|
|
3435
|
-
properties: {
|
|
3436
|
-
partId: { type: 'string', required: true },
|
|
3437
|
-
type: { type: 'string', required: true },
|
|
3438
|
-
preview: { type: 'string', required: true },
|
|
3439
|
-
},
|
|
3440
|
-
},
|
|
3441
|
-
},
|
|
3442
|
-
failures: {
|
|
3443
|
-
type: 'array',
|
|
3444
|
-
required: true,
|
|
3445
|
-
items: {
|
|
3446
|
-
type: 'object',
|
|
3447
|
-
additionalProperties: false,
|
|
3448
|
-
properties: {
|
|
3449
|
-
kind: { type: 'string', required: true },
|
|
3450
|
-
reason: { type: 'string', required: true },
|
|
3451
|
-
},
|
|
3452
|
-
},
|
|
3453
|
-
},
|
|
3454
|
-
},
|
|
3455
|
-
},
|
|
3456
|
-
render: (_args, value) => {
|
|
3457
|
-
if (value.ok !== true) {
|
|
3458
|
-
const reasons = value.failures.map(failure => `${failure.kind}: ${failure.reason}`).join('; ')
|
|
3459
|
-
return [{ type: 'text', text: `Nothing was captured. ${reasons}` }]
|
|
3460
|
-
}
|
|
3461
|
-
const lines = [
|
|
3462
|
-
`Reference ${value.referenceId} captured from ${value.title !== undefined && value.title !== '' ? value.title : value.pageUrl}.`,
|
|
3463
|
-
'Stored in the reference library for dsh_browser_reference_reveal or export (tool-only captures do not create a chat capsule). Do not emit dsh-browser-ref: URIs or reference markers in the reply.',
|
|
3464
|
-
...value.parts.map(part => ` ${part.partId} (${part.type}): ${part.preview}`),
|
|
3465
|
-
]
|
|
3466
|
-
if (value.failures.length > 0) lines.push(`(${value.failures.length} fragment(s) failed and were left out: ${value.failures.map(failure => failure.reason).join('; ')})`)
|
|
3467
|
-
return [{ type: 'text', text: lines.join('\n') }]
|
|
3468
|
-
},
|
|
3469
|
-
},
|
|
3470
|
-
timeoutMs,
|
|
3471
|
-
isConcurrencySafe: () => false,
|
|
3472
|
-
async execute(args, exec) {
|
|
3473
|
-
const browser = ctx.get('browser')
|
|
3474
|
-
if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
|
|
3475
|
-
const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
|
|
3476
|
-
const outcome = await references().capture({
|
|
3477
|
-
// The DSH session owns the reference; the provider session holds the page. They are
|
|
3478
|
-
// different ids, and reveal needs the second one even after the first is long gone.
|
|
3479
|
-
sessionId: taskKey(exec),
|
|
3480
|
-
browserSessionId: session,
|
|
3481
|
-
origin: args.excerptText !== undefined ? 'agent-excerpt' : 'user-selection',
|
|
3482
|
-
entry: 'agent-tool',
|
|
3483
|
-
carrier: state.panelUrlByTask.has(taskKey(exec)) ? 'sidebar' : referenceCarrier(),
|
|
3484
|
-
...args.allowPartial !== undefined ? { allowPartial: args.allowPartial } : {},
|
|
3485
|
-
...args.tableSelector !== undefined ? { tableSelector: args.tableSelector } : {},
|
|
3486
|
-
...args.excerptText !== undefined ? { excerptText: args.excerptText } : {},
|
|
3487
|
-
}, exec.signal)
|
|
3488
|
-
const failures = outcome.failures.map(failure => ({ kind: failure.kind, reason: failure.reason }))
|
|
3489
|
-
if (outcome.reference === undefined) return { ok: false, parts: [], failures }
|
|
3490
|
-
const summary = summarizeReference(outcome.reference)
|
|
3491
|
-
return {
|
|
3492
|
-
ok: true,
|
|
3493
|
-
referenceId: summary.referenceId,
|
|
3494
|
-
pageUrl: summary.pageUrl,
|
|
3495
|
-
title: summary.title,
|
|
3496
|
-
// The summary's arrays are readonly; the schema declares a mutable array,
|
|
3497
|
-
// so the parts are projected into plain objects rather than cast away.
|
|
3498
|
-
parts: summary.parts.map(part => ({ partId: part.partId, type: part.type, preview: part.preview })),
|
|
3499
|
-
failures,
|
|
3500
|
-
}
|
|
3501
|
-
},
|
|
3502
|
-
}))
|
|
3503
|
-
|
|
3504
|
-
registerSafely(defineTool({
|
|
3505
|
-
name: 'dsh_browser_reference_reveal',
|
|
3506
|
-
description: 'Return to a stored browser reference: select the browser session that captured it, verify the page is still the same one, then scroll to and highlight the part. Without partId the reference\'s first part is located; pass a partId to locate one specific fragment. A result status of page-mismatch means the session is showing another page (open the stored pageUrl first); ambiguous means several candidates matched equally and the exact one cannot be chosen; session-unavailable means the browser that captured it is gone.',
|
|
3507
|
-
parameters: {
|
|
3508
|
-
referenceId: { type: 'string', required: true, description: 'The reference id, with or without the dsh-browser-ref: prefix.' },
|
|
3509
|
-
partId: { type: 'string', description: 'Locate this fragment instead of the whole reference\'s first part.' },
|
|
3510
|
-
},
|
|
3511
|
-
output: {
|
|
3512
|
-
schema: {
|
|
3513
|
-
type: 'object',
|
|
3514
|
-
additionalProperties: false,
|
|
3515
|
-
properties: {
|
|
3516
|
-
status: { type: 'string', required: true },
|
|
3517
|
-
pageUrl: { type: 'string', required: true },
|
|
3518
|
-
currentUrl: { type: 'string' },
|
|
3519
|
-
note: { type: 'string' },
|
|
3520
|
-
parts: {
|
|
3521
|
-
type: 'array',
|
|
3522
|
-
required: true,
|
|
3523
|
-
items: {
|
|
3524
|
-
type: 'object',
|
|
3525
|
-
additionalProperties: false,
|
|
3526
|
-
properties: {
|
|
3527
|
-
partId: { type: 'string', required: true },
|
|
3528
|
-
type: { type: 'string', required: true },
|
|
3529
|
-
status: { type: 'string', required: true },
|
|
3530
|
-
matches: { type: 'number' },
|
|
3531
|
-
collapsed: { type: 'boolean' },
|
|
3532
|
-
note: { type: 'string' },
|
|
3533
|
-
},
|
|
3534
|
-
},
|
|
3535
|
-
},
|
|
3536
|
-
},
|
|
3537
|
-
},
|
|
3538
|
-
render: (_args, value) => {
|
|
3539
|
-
const head = value.status === 'revealed'
|
|
3540
|
-
? 'Located the reference in the page.'
|
|
3541
|
-
: `Could not locate the reference: ${value.status}${value.note !== undefined ? ` — ${value.note}` : ''}`
|
|
3542
|
-
const lines = [head, ...value.parts.map(part => ` ${part.partId} (${part.type}): ${part.status}${part.matches !== undefined ? `, ${part.matches} match(es)` : ''}${part.collapsed === true ? ', whitespace-collapsed' : ''}${part.note !== undefined ? ` — ${part.note}` : ''}`)]
|
|
3543
|
-
return [{ type: 'text', text: lines.join('\n') }]
|
|
3544
|
-
},
|
|
3545
|
-
},
|
|
3546
|
-
timeoutMs,
|
|
3547
|
-
isConcurrencySafe: () => false,
|
|
3548
|
-
async execute(args, exec) {
|
|
3549
|
-
// The documented citation form is `dsh-browser-ref:<referenceId>/<partId?>`; accept it
|
|
3550
|
-
// whole so a model can paste what it wrote instead of splitting the id by hand.
|
|
3551
|
-
let referenceId = args.referenceId.startsWith('dsh-browser-ref:') ? args.referenceId.slice('dsh-browser-ref:'.length) : args.referenceId
|
|
3552
|
-
let partId = args.partId
|
|
3553
|
-
const slash = referenceId.indexOf('/')
|
|
3554
|
-
if (slash !== -1) {
|
|
3555
|
-
if (partId === undefined) partId = referenceId.slice(slash + 1)
|
|
3556
|
-
referenceId = referenceId.slice(0, slash)
|
|
3557
|
-
}
|
|
3558
|
-
const outcome = await references().reveal(referenceId, {
|
|
3559
|
-
ownerSessionId: taskKey(exec),
|
|
3560
|
-
...partId !== undefined && partId !== '' ? { partId } : {},
|
|
3561
|
-
}, exec.signal)
|
|
3562
|
-
return {
|
|
3563
|
-
status: outcome.status,
|
|
3564
|
-
pageUrl: outcome.pageUrl,
|
|
3565
|
-
...outcome.currentUrl !== undefined ? { currentUrl: outcome.currentUrl } : {},
|
|
3566
|
-
...outcome.note !== undefined ? { note: outcome.note } : {},
|
|
3567
|
-
parts: outcome.parts.map(part => ({
|
|
3568
|
-
partId: part.partId,
|
|
3569
|
-
type: part.type,
|
|
3570
|
-
status: part.status,
|
|
3571
|
-
...part.matches !== undefined ? { matches: part.matches } : {},
|
|
3572
|
-
...part.collapsed !== undefined ? { collapsed: part.collapsed } : {},
|
|
3573
|
-
...part.note !== undefined ? { note: part.note } : {},
|
|
3574
|
-
})),
|
|
3575
|
-
}
|
|
3576
|
-
},
|
|
3577
|
-
}))
|
|
3578
|
-
|
|
3579
|
-
registerSafely(defineTool({
|
|
3580
|
-
name: 'dsh_browser_reference_list',
|
|
3581
|
-
description: 'List the browser references stored for this task, newest first: id, page, capture time, and one preview line per fragment. Use it to identify a reference from earlier in the conversation. Source navigation is provided by reference capsules; do not repeat reference URIs, source URLs, markers, or source/citation links in the reply.',
|
|
3582
|
-
parameters: {
|
|
3583
|
-
limit: { type: 'number', description: 'Most references to return (default 20, maximum 100).' },
|
|
3584
|
-
},
|
|
3585
|
-
output: {
|
|
3586
|
-
schema: {
|
|
3587
|
-
type: 'object',
|
|
3588
|
-
additionalProperties: false,
|
|
3589
|
-
properties: {
|
|
3590
|
-
references: {
|
|
3591
|
-
type: 'array',
|
|
3592
|
-
required: true,
|
|
3593
|
-
items: {
|
|
3594
|
-
type: 'object',
|
|
3595
|
-
additionalProperties: false,
|
|
3596
|
-
properties: {
|
|
3597
|
-
referenceId: { type: 'string', required: true },
|
|
3598
|
-
title: { type: 'string', required: true },
|
|
3599
|
-
pageUrl: { type: 'string', required: true },
|
|
3600
|
-
capturedAt: { type: 'string', required: true },
|
|
3601
|
-
carrier: { type: 'string', required: true },
|
|
3602
|
-
origin: { type: 'string', required: true },
|
|
3603
|
-
entry: { type: 'string', required: true },
|
|
3604
|
-
partCount: { type: 'number', required: true },
|
|
3605
|
-
parts: {
|
|
3606
|
-
type: 'array',
|
|
3607
|
-
required: true,
|
|
3608
|
-
items: {
|
|
3609
|
-
type: 'object',
|
|
3610
|
-
additionalProperties: false,
|
|
3611
|
-
properties: {
|
|
3612
|
-
partId: { type: 'string', required: true },
|
|
3613
|
-
type: { type: 'string', required: true },
|
|
3614
|
-
preview: { type: 'string', required: true },
|
|
3615
|
-
},
|
|
3616
|
-
},
|
|
3617
|
-
},
|
|
3618
|
-
},
|
|
3619
|
-
},
|
|
3620
|
-
},
|
|
3621
|
-
},
|
|
3622
|
-
},
|
|
3623
|
-
render: (_args, value) => {
|
|
3624
|
-
if (value.references.length === 0) return [{ type: 'text', text: 'No browser references are stored for this task.' }]
|
|
3625
|
-
return [{
|
|
3626
|
-
type: 'text',
|
|
3627
|
-
text: value.references.map(reference => [
|
|
3628
|
-
`Reference ${reference.referenceId} — ${reference.title !== '' ? reference.title : reference.pageUrl} (${reference.capturedAt}); source navigation is in its capsule, not a reply link.`,
|
|
3629
|
-
...reference.parts.map(part => ` ${part.partId} (${part.type}): ${part.preview}`),
|
|
3630
|
-
].join('\n')).join('\n\n'),
|
|
3631
|
-
}]
|
|
3632
|
-
},
|
|
3633
|
-
},
|
|
3634
|
-
timeoutMs,
|
|
3635
|
-
isConcurrencySafe: () => true,
|
|
3636
|
-
async execute(args, exec) {
|
|
3637
|
-
const key = taskKey(exec)
|
|
3638
|
-
const limit = Math.min(Math.max(Math.trunc(args.limit ?? 20), 1), 100)
|
|
3639
|
-
// Always scoped: with no agent the key is `default`, and an unfiltered read
|
|
3640
|
-
// would hand this task every conversation's references.
|
|
3641
|
-
const stored = references().list({ sessionId: key, limit })
|
|
3642
|
-
return {
|
|
3643
|
-
references: stored.slice().reverse().map(reference => {
|
|
3644
|
-
const summary = summarizeReference(reference)
|
|
3645
|
-
return {
|
|
3646
|
-
referenceId: summary.referenceId,
|
|
3647
|
-
title: summary.title,
|
|
3648
|
-
pageUrl: summary.pageUrl,
|
|
3649
|
-
capturedAt: summary.capturedAt,
|
|
3650
|
-
carrier: summary.carrier,
|
|
3651
|
-
origin: summary.origin,
|
|
3652
|
-
entry: summary.entry,
|
|
3653
|
-
partCount: summary.partCount,
|
|
3654
|
-
parts: summary.parts.map(part => ({ partId: part.partId, type: part.type, preview: part.preview })),
|
|
3655
|
-
}
|
|
3656
|
-
}),
|
|
3657
|
-
}
|
|
3658
|
-
},
|
|
3659
|
-
}))
|
|
3660
|
-
|
|
3661
|
-
// Under DSH's PTC executor run_code already batches every tool, so the code tool steps aside.
|
|
3662
|
-
const ptcMode = (): boolean => {
|
|
3663
|
-
try { return (ctx as { get?: (name: string) => unknown }).get?.('ptcRuntime') !== undefined } catch { return false }
|
|
3664
|
-
}
|
|
3665
|
-
if (surface !== 'tools') {
|
|
3666
|
-
try {
|
|
3667
|
-
const code = createCodeTool(catalog)
|
|
3668
|
-
// Registration options (`when`) arrived with DSH 0.2.2; older registries ignore them.
|
|
3669
|
-
// On the code surface it is the only browser tool, so it stays even under PTC.
|
|
3670
|
-
;(ctx.tools.register as (tool: unknown, options?: { when: () => boolean }) => unknown)(code.tool, surface === 'core' ? { when: () => !ptcMode() } : undefined)
|
|
215
|
+
const code = createCodeTool(catalog, pulse)
|
|
216
|
+
// On the code surface it is the only browser tool, so it stays even under PTC; on `core`,
|
|
217
|
+
// DSH's PTC run_code already batches every tool, so the code tool steps aside.
|
|
218
|
+
registerTool(ctx.tools, code.tool, surface === 'core' ? (context?: { readonly agent?: unknown }) => !ptcRuntimeActive(ctx, context) : undefined)
|
|
3671
219
|
ctx.effect(() => code.dispose)
|
|
3672
220
|
} catch (error) {
|
|
3673
221
|
ctx.logger?.warn?.(`dsh-builtin-browser: could not register ${CODE_TOOL} (${String(error)}).`)
|
|
@@ -3696,7 +244,7 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
3696
244
|
async execute(args) {
|
|
3697
245
|
const groups = Array.isArray(args.groups) ? args.groups.map(String) : []
|
|
3698
246
|
const unknown = groups.filter(group => !(group in TOOL_GROUPS))
|
|
3699
|
-
if (groups.length === 0 || unknown.length > 0) throw new
|
|
247
|
+
if (groups.length === 0 || unknown.length > 0) throw new BrowserToolError(`unknown tool group(s): ${unknown.join(', ') || '(none given)'}; groups are ${Object.keys(TOOL_GROUPS).join(', ')}`, 'BROWSER_UNKNOWN_TOOL_GROUP')
|
|
3700
248
|
const names = [...new Set(groups.flatMap(members))]
|
|
3701
249
|
const fresh: string[] = []
|
|
3702
250
|
for (const name of names) {
|
|
@@ -3715,19 +263,3 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
3715
263
|
}
|
|
3716
264
|
}
|
|
3717
265
|
}
|
|
3718
|
-
|
|
3719
|
-
/** Test hook: inspect and reset session mappings across every live plugin apply. */
|
|
3720
|
-
export const internals = {
|
|
3721
|
-
/** A copy of every live apply's per-task session map (task key -> provider session id). */
|
|
3722
|
-
get sessions(): ReadonlyMap<string, BrowserSessionId> {
|
|
3723
|
-
const merged = new Map<string, BrowserSessionId>()
|
|
3724
|
-
for (const state of liveStates) {
|
|
3725
|
-
for (const [key, session] of state.sessionsByTask) merged.set(key, session)
|
|
3726
|
-
}
|
|
3727
|
-
return merged
|
|
3728
|
-
},
|
|
3729
|
-
/** Drop one task's mapping (across live applies) without closing the provider session. */
|
|
3730
|
-
clearSession(key = 'default'): void {
|
|
3731
|
-
for (const state of liveStates) state.sessionsByTask.delete(key)
|
|
3732
|
-
},
|
|
3733
|
-
}
|