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,11 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
// 反复出现过的两个事故:
|
|
4
|
-
// 1. dev 出口指向 `dist/client.cjs` → vite 把 CJS 当 ESM 导入,浏览器里 `window.__ModuleLoader__`
|
|
5
|
-
// 还是 undefined,整页红屏 `Cannot read properties of undefined (reading 'load')`。
|
|
6
|
-
// 2. 包里留着 `dist/client.mjs` → 它是薄壳(`export { apply } from "./client/index.ts"`),
|
|
7
|
-
// 被加载时 vite 报 `Failed to resolve import "./client/index.ts"` 并遮住整页。
|
|
8
|
-
// 这两条都属于「动作之前的拦截」:构建期直接失败,而不是等运行时红屏。
|
|
1
|
+
// 出口守卫:在构建结束时断言两套出口与 DSH 0.2.3 客户端产物信封形态,避免「dev 指向打包产物」
|
|
2
|
+
// 或「旧自注入 <style> 逻辑回流」等问题再次复发。
|
|
9
3
|
import { existsSync, readFileSync } from 'node:fs'
|
|
10
4
|
|
|
11
5
|
const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8').replace(/^\uFEFF/, ''))
|
|
@@ -20,10 +14,10 @@ const publishClient = manifest.publishConfig?.exports?.['./client']
|
|
|
20
14
|
|
|
21
15
|
if (typeof devClient !== 'string' || !devClient.endsWith('src/client/index.ts')) {
|
|
22
16
|
problems.push(`exports['./client'] 必须指向源码(当前 ${JSON.stringify(devClient)}):dev 由宿主打包链处理客户端半,`
|
|
23
|
-
+ '
|
|
17
|
+
+ '指向打包产物会让浏览器在 `window.__ModuleLoader__` 就绪前加载 CJS 工厂并抛 `Cannot read properties of undefined (reading \'load\')`')
|
|
24
18
|
}
|
|
25
|
-
if (publishClient !== './
|
|
26
|
-
problems.push(`publishConfig.exports['./client'] 必须是 ./
|
|
19
|
+
if (publishClient !== './lib/client.js') {
|
|
20
|
+
problems.push(`publishConfig.exports['./client'] 必须是 ./lib/client.js(当前 ${JSON.stringify(publishClient)})`)
|
|
27
21
|
}
|
|
28
22
|
if (typeof manifest.exports?.['.'] !== 'string' || !manifest.exports['.'].endsWith('src/index.ts')) {
|
|
29
23
|
problems.push('exports[\'.\'] 必须指向源码 src/index.ts(dev 形态)')
|
|
@@ -32,16 +26,33 @@ if (manifest.publishConfig?.exports?.['.'] !== './lib/index.js') {
|
|
|
32
26
|
problems.push("publishConfig.exports['.'] 必须是 ./lib/index.js(tsc 产物;打包产物会残留 .ts 说明符)")
|
|
33
27
|
}
|
|
34
28
|
|
|
29
|
+
const clientBundleUrl = new URL('../lib/client.js', import.meta.url)
|
|
30
|
+
if (!existsSync(clientBundleUrl)) {
|
|
31
|
+
problems.push('lib/client.js 缺失:构建未产出 DSH 0.2.3 客户端工厂')
|
|
32
|
+
} else {
|
|
33
|
+
const clientCode = readFileSync(clientBundleUrl, 'utf8')
|
|
34
|
+
const expectedBanner = `window.__ModuleLoader__.load({ id: ${JSON.stringify(manifest.name)}, factory: (require) => {`
|
|
35
|
+
if (!clientCode.startsWith(expectedBanner)) {
|
|
36
|
+
problems.push(`lib/client.js 必须以 ${expectedBanner} 开头`)
|
|
37
|
+
}
|
|
38
|
+
if (!clientCode.includes('meta: () => ({ stylesheets:')) {
|
|
39
|
+
problems.push('lib/client.js 必须通过 meta: () => ({ stylesheets: ... }) 向宿主移交样式表')
|
|
40
|
+
}
|
|
41
|
+
if (clientCode.includes('data-plugin-css')) {
|
|
42
|
+
problems.push('lib/client.js 不得残留旧版运行期 <style data-plugin-css> 自注入逻辑')
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
const distDir = new URL('../dist/', import.meta.url)
|
|
36
|
-
for (const forbidden of ['client.mjs', 'client.mjs.map']) {
|
|
47
|
+
for (const forbidden of ['client.cjs', 'client.mjs', 'client.mjs.map']) {
|
|
37
48
|
if (existsSync(new URL(forbidden, distDir))) {
|
|
38
|
-
problems.push(`dist/${forbidden}
|
|
49
|
+
problems.push(`dist/${forbidden} 必须不存在:客户端产物已统一切至 lib/client.js`)
|
|
39
50
|
}
|
|
40
51
|
}
|
|
41
52
|
|
|
42
53
|
if (problems.length > 0) {
|
|
43
|
-
console.error('[exports-guard]
|
|
54
|
+
console.error('[exports-guard] 出口或客户端产物形态不合格:')
|
|
44
55
|
for (const problem of problems) console.error(` - ${problem}`)
|
|
45
56
|
process.exit(1)
|
|
46
57
|
}
|
|
47
|
-
console.log('[exports-guard] 通过:dev→src / publish→lib+
|
|
58
|
+
console.log('[exports-guard] 通过:dev→src / publish→lib + lib/client.js(0.2.3 信封与 meta().stylesheets)')
|
|
@@ -43,12 +43,36 @@ The next cell can keep using `rows`.
|
|
|
43
43
|
- Input: `click(target)`, `type(target, text, {submit})`, `fill_input(target, text)`, `select(target, optionText)`,
|
|
44
44
|
`fill(fields, {submit})`, `click_at_xy(x, y)`, `type_text(text)`, `press_key(key)`, `scroll(dy)` or `scroll(x, y, dy)`,
|
|
45
45
|
`upload_file(selector, path)`. A `target` is visible text, a CSS selector, `{text|css|xpath, index}` or `{x, y}`.
|
|
46
|
-
- Waiting: `wait_for_element(selector)`, `
|
|
46
|
+
- Waiting: `wait_for_element(selector)`, `wait_for_text(text)`, `wait_for_gone(text)`,
|
|
47
|
+
`wait_until(jsExpression, { timeoutMs, intervalMs })` (returns the truthy value; a timeout quotes
|
|
48
|
+
the last result), `wait_for_response(urlContains, trigger, { status, timeoutMs })`,
|
|
49
|
+
`wait_for_network_idle()`. Each returns as soon as its condition holds and throws when it never
|
|
50
|
+
does; `sleep(ms)` only as a last resort (capped at 60 s; a cell that keeps sleeping gets a hint).
|
|
51
|
+
- Data: `inspect_data_sources()` reports embedded state (`__NEXT_DATA__`, `__INITIAL_STATE__`,
|
|
52
|
+
JSON and ld+json scripts) with sizes, keys and array paths, the JSON APIs the page called,
|
|
53
|
+
data-like resources (including requests made before the probe) and declared endpoints.
|
|
54
|
+
`fetch_json(url, { method, headers, body })` fetches from the page with its same-origin cookies
|
|
55
|
+
and returns parsed JSON; a non-2xx status throws with the status and the start of the body.
|
|
47
56
|
- References: `refs.capture({excerptText})`, `refs.list()`, `refs.reveal({referenceId})`.
|
|
48
57
|
- Everything else: `call(name, args)` (download, console, network, wait_for_response, dialog, hover,
|
|
49
58
|
drag, set_value, check, scrape, a11y, assert, do, reset_session, ...). `await help()` lists the
|
|
50
59
|
actions and `await help(name)` describes one.
|
|
51
60
|
|
|
61
|
+
## Data before DOM
|
|
62
|
+
|
|
63
|
+
Before scraping a list, a directory, paginated or lazy-loaded data, call `inspect_data_sources()`.
|
|
64
|
+
When the page already holds the rows as JSON or calls an API for them, read that source instead
|
|
65
|
+
of the DOM, and check the count you collected against the total the site states:
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
const sources = await inspect_data_sources()
|
|
69
|
+
print(JSON.stringify(sources.embedded.map(s => [s.name, s.arrays])), JSON.stringify(sources.apis))
|
|
70
|
+
// The page called /api/stores?page=1: fetch every page at once with its cookies.
|
|
71
|
+
const pages = await Promise.all([1, 2, 3, 4].map(n => fetch_json(`/api/stores?page=${n}`)))
|
|
72
|
+
const stores = pages.flatMap(p => p.items)
|
|
73
|
+
print(stores.length, JSON.stringify(stores.slice(0, 3)))
|
|
74
|
+
```
|
|
75
|
+
|
|
52
76
|
## Batch, do not drip
|
|
53
77
|
|
|
54
78
|
Every call is a full model turn. Put a run of steps in one cell, and use loops for lists and
|
|
@@ -59,7 +83,8 @@ in the same cell. Return only what you need: a few fields from `js()` beat a who
|
|
|
59
83
|
|
|
60
84
|
"Clicked" and "the form accepted it" are different claims: check the URL, a confirmation message,
|
|
61
85
|
or a server response before moving on. Arm `wait_for_response` before the triggering action
|
|
62
|
-
inside a code cell; see [batch examples](references/batch.md).
|
|
86
|
+
inside a code cell; see [batch examples](references/batch.md). Each action's printed result ends with a `→` line: the URL or tab change, the page title after
|
|
87
|
+
a change, new alert messages and dialogs answered. If a cell timed out or was
|
|
63
88
|
cancelled, inspect the current page before repeating anything that changes server state.
|
|
64
89
|
If access is denied, report what you verified. For a research task, you can use a different,
|
|
65
90
|
publicly available source without bypassing the original site's access restrictions.
|
|
@@ -48,6 +48,21 @@ await tools.dsh_browser_click({ target: { by: 'css', value: 'button[type=submit]
|
|
|
48
48
|
print(await response)
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
+
The REPL helper does the same in one call: `wait_for_response(urlContains, trigger, opts)`
|
|
52
|
+
starts watching before it calls `trigger()` and returns the matching response row:
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
const saved = await wait_for_response('/api/profile', () => click('Save'), { status: 200 })
|
|
56
|
+
await wait_for_text('Profile saved')
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
When the condition is page state rather than text or a response, poll an expression instead of
|
|
60
|
+
sleeping; the timeout error quotes the last value it saw:
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
const count = await wait_until(`document.querySelectorAll('.result').length >= 20 && document.querySelectorAll('.result').length`, { timeoutMs: 8000 })
|
|
64
|
+
```
|
|
65
|
+
|
|
51
66
|
Adapt the URL and selector to the current page. The scheduler arms the response
|
|
52
67
|
wait before it lets the action run. Issue unrelated reads in parallel, not competing
|
|
53
68
|
mutations. A timeout or cancellation does not undo actions that already ran.
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anti-bot block handling: one classifier for challenge and block pages, the recovery each kind
|
|
3
|
+
* calls for, and the public routes to the same information when a site refuses automation.
|
|
4
|
+
*
|
|
5
|
+
* The signatures are data, so the page-context detector (generated by {@link challengeDetectSource})
|
|
6
|
+
* and the Web proxy's server-side probe ({@link classifyBlock} on raw HTML) cannot drift apart.
|
|
7
|
+
* Nothing here solves a CAPTCHA or evades a block: interactive checks go to the human, network
|
|
8
|
+
* (IP) blocks are reported as an environment limit, and the rest get one paced retry and then
|
|
9
|
+
* other public sources.
|
|
10
|
+
* @module dsh-browser/browser/anti-bot
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { BrowserChallenge } from './types.ts'
|
|
14
|
+
|
|
15
|
+
/** What the agent should do about a blocked page. */
|
|
16
|
+
export type BlockRecovery =
|
|
17
|
+
/** A human verification (CAPTCHA, slider, press-and-hold): hand the tab to the human. */
|
|
18
|
+
| 'takeover'
|
|
19
|
+
/** A self-clearing JavaScript interstitial: wait for it in the same tab, then re-check. */
|
|
20
|
+
| 'wait'
|
|
21
|
+
/** A refusal that a fresh session and slower pacing may get past once; then fall back. */
|
|
22
|
+
| 'retry'
|
|
23
|
+
/** The network itself is refused (datacenter/VPN IP): an environment limit, use other sources. */
|
|
24
|
+
| 'environment'
|
|
25
|
+
|
|
26
|
+
/** Facts about a loaded page, as the classifier sees them. */
|
|
27
|
+
export interface BlockEvidence {
|
|
28
|
+
/** HTTP status of the main document, when known. */
|
|
29
|
+
readonly status?: number
|
|
30
|
+
readonly title?: string
|
|
31
|
+
/** Visible text (or raw HTML on the server side). */
|
|
32
|
+
readonly text?: string
|
|
33
|
+
/** Space-separated `src` of the page's iframes. */
|
|
34
|
+
readonly frames?: string
|
|
35
|
+
/** Visible challenge widgets found in the DOM, by kind (page context only). */
|
|
36
|
+
readonly widgets?: readonly string[]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Signature {
|
|
40
|
+
readonly kind: string
|
|
41
|
+
readonly recovery: BlockRecovery
|
|
42
|
+
readonly reason: string
|
|
43
|
+
/** Matched against the lower-cased title + text. */
|
|
44
|
+
readonly text?: string
|
|
45
|
+
/** Matched against the lower-cased iframe sources. */
|
|
46
|
+
readonly frames?: string
|
|
47
|
+
/** A visible widget of this kind (page context). */
|
|
48
|
+
readonly widget?: string
|
|
49
|
+
/** Only counts on an error status (>= 400), so a page that merely mentions the words is not a block. */
|
|
50
|
+
readonly errorOnly?: boolean
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Ordered: the first match wins, so interactive checks come before the interstitials that host
|
|
55
|
+
* them and network blocks come before generic refusals.
|
|
56
|
+
*/
|
|
57
|
+
const SIGNATURES: readonly Signature[] = [
|
|
58
|
+
{ kind: 'hcaptcha', recovery: 'takeover', reason: 'hCaptcha verification', widget: 'hcaptcha', frames: 'hcaptcha\\.com/captcha' },
|
|
59
|
+
{ kind: 'recaptcha', recovery: 'takeover', reason: 'Google reCAPTCHA verification', widget: 'recaptcha', frames: 'recaptcha/(?:api2|enterprise)/bframe' },
|
|
60
|
+
{ kind: 'turnstile', recovery: 'takeover', reason: 'Cloudflare Turnstile verification', widget: 'turnstile', frames: 'challenges\\.cloudflare\\.com/cdn-cgi/challenge-platform/.*turnstile' },
|
|
61
|
+
{ kind: 'perimeterx', recovery: 'takeover', reason: 'PerimeterX "Press & Hold" verification', text: 'press (?:&|and) hold|px-captcha', widget: 'perimeterx' },
|
|
62
|
+
{ kind: 'datadome', recovery: 'takeover', reason: 'DataDome verification', frames: 'captcha-delivery\\.com|geo\\.captcha-delivery' },
|
|
63
|
+
{ kind: 'slider', recovery: 'takeover', reason: 'Slider / puzzle verification', text: '\u6ed1\u52a8.{0,8}(?:\u9a8c\u8bc1|\u6ed1\u5757|\u62fc\u56fe)|\u62d6\u52a8.{0,12}(?:\u6ed1\u5757|\u62fc\u56fe)|slide to verify|drag the slider|geetest', widget: 'slider' },
|
|
64
|
+
{ kind: 'google-sorry', recovery: 'environment', reason: 'Google "unusual traffic from your computer network" block', text: 'unusual traffic from your computer network|our systems have detected unusual traffic' },
|
|
65
|
+
{ kind: 'ip-block', recovery: 'environment', reason: 'The site refuses this network (IP / hosting provider block)', text: 'your ip(?: address)? (?:has been|is|was) (?:blocked|banned|blacklisted)|requests from your (?:ip|network) |datacenter|data center ip|hosting provider|vpn or proxy', errorOnly: true },
|
|
66
|
+
{ kind: 'cloudflare', recovery: 'wait', reason: 'Cloudflare "Just a moment" interstitial', widget: 'cloudflare', text: 'just a moment\\.\\.\\.|checking your browser|checking if the site connection is secure|cf-browser-verification|cf_chl_|cf-chl-' },
|
|
67
|
+
{ kind: 'baidu-verify', recovery: 'takeover', reason: 'Baidu security verification (\u767e\u5ea6\u5b89\u5168\u9a8c\u8bc1)', text: 'wappass\\.baidu\\.com|\u767e\u5ea6\u5b89\u5168\u9a8c\u8bc1' },
|
|
68
|
+
{ kind: 'human-check', recovery: 'takeover', reason: 'Human-verification challenge', text: 'verify you are (?:a )?human|verify you are not a robot|are you a robot|\u4eba\u673a\u9a8c\u8bc1|\u5b89\u5168\u9a8c\u8bc1|\u8bf7\u5b8c\u6210\u9a8c\u8bc1' },
|
|
69
|
+
{ kind: 'rate-limit', recovery: 'retry', reason: 'Rate limited (HTTP 429)', text: '', errorOnly: true },
|
|
70
|
+
{ kind: 'access-denied', recovery: 'retry', reason: 'Access denied by the site\'s bot protection', text: 'access denied|attention required|request blocked|you have been blocked|forbidden|not authorized to access|bot detected|automated (?:access|requests|queries)|enable javascript and cookies|pardon our interruption|\u8bbf\u95ee\u88ab\u62d2\u7edd|\u8bbf\u95ee\u53d7\u9650', errorOnly: true },
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
/** Signatures as JSON-safe data for the page-context detector. */
|
|
74
|
+
const SIGNATURE_DATA = SIGNATURES.map(s => ({ ...s }))
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Classify a page. The same function runs in the page (through {@link challengeDetectSource}) and
|
|
78
|
+
* in Node, so it must stay self-contained: no imports, no closures over module state.
|
|
79
|
+
* @param evidence - what the page shows.
|
|
80
|
+
* @param signatures - the signature table.
|
|
81
|
+
* @returns the challenge verdict.
|
|
82
|
+
*/
|
|
83
|
+
function classify(evidence: BlockEvidence, signatures: readonly Signature[]): BrowserChallenge {
|
|
84
|
+
const status = typeof evidence.status === 'number' ? evidence.status : 0
|
|
85
|
+
const text = ((evidence.title ?? '') + '\n' + (evidence.text ?? '')).toLowerCase()
|
|
86
|
+
const frames = (evidence.frames ?? '').toLowerCase()
|
|
87
|
+
const widgets = evidence.widgets ?? []
|
|
88
|
+
for (const s of signatures) {
|
|
89
|
+
if (s.errorOnly === true && status < 400) continue
|
|
90
|
+
if (s.kind === 'rate-limit') {
|
|
91
|
+
if (status === 429) return { blocked: true, kind: s.kind, reason: s.reason, recovery: s.recovery, ...status > 0 ? { status } : {} }
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
const hit = (s.widget !== undefined && widgets.includes(s.widget))
|
|
95
|
+
|| (s.frames !== undefined && new RegExp(s.frames, 'i').test(frames))
|
|
96
|
+
|| (s.text !== undefined && s.text !== '' && new RegExp(s.text, 'i').test(text))
|
|
97
|
+
if (hit) return { blocked: true, kind: s.kind, reason: s.reason, recovery: s.recovery, ...status > 0 ? { status } : {} }
|
|
98
|
+
}
|
|
99
|
+
// An error page with almost nothing on it, served to a browser, is a refusal in all but name.
|
|
100
|
+
if ((status === 403 || status === 503) && text.replace(/\s+/g, ' ').trim().length < 400) {
|
|
101
|
+
return { blocked: true, kind: 'access-denied', reason: `HTTP ${status} with an empty page (likely a bot block)`, recovery: 'retry', status }
|
|
102
|
+
}
|
|
103
|
+
return { blocked: false }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Classify a page from what it shows.
|
|
108
|
+
* @param evidence - status, title, text, iframe sources and visible widgets.
|
|
109
|
+
* @returns `{ blocked: false }` or the kind, reason and recovery.
|
|
110
|
+
*/
|
|
111
|
+
export function classifyBlock(evidence: BlockEvidence): BrowserChallenge {
|
|
112
|
+
return classify(evidence, SIGNATURES)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The page-context detector: collects the evidence (main-document status, visible text including
|
|
117
|
+
* open shadow roots and same-origin frames, iframe sources, and challenge widgets that are actually
|
|
118
|
+
* visible, so an invisible reCAPTCHA v3 badge on a login page is not a block) and classifies it.
|
|
119
|
+
* @returns a JavaScript expression evaluating to a {@link BrowserChallenge}.
|
|
120
|
+
*/
|
|
121
|
+
export function challengeDetectSource(): string {
|
|
122
|
+
return `(() => {
|
|
123
|
+
try {
|
|
124
|
+
const visible = el => { if (!el) return false; const r = el.getBoundingClientRect(); if (r.width < 30 || r.height < 30) return false; const cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none' && Number(cs.opacity) > 0.05 }
|
|
125
|
+
let extra = ''
|
|
126
|
+
const frames = []
|
|
127
|
+
const widgets = new Set()
|
|
128
|
+
const seen = new Set()
|
|
129
|
+
const scan = doc => {
|
|
130
|
+
if (seen.has(doc)) return
|
|
131
|
+
seen.add(doc)
|
|
132
|
+
for (const el of doc.querySelectorAll('*')) {
|
|
133
|
+
if (el.shadowRoot) { extra += '\\n' + (el.shadowRoot.textContent || '').slice(0, 2000); scan(el.shadowRoot) }
|
|
134
|
+
if (el.tagName === 'IFRAME') {
|
|
135
|
+
const src = el.src || ''
|
|
136
|
+
frames.push(src)
|
|
137
|
+
if (visible(el)) {
|
|
138
|
+
if (/hcaptcha\\.com/i.test(src)) widgets.add('hcaptcha')
|
|
139
|
+
if (/recaptcha\\/(?:api2|enterprise)\\/(?:anchor|bframe)/i.test(src)) widgets.add('recaptcha')
|
|
140
|
+
if (/challenges\\.cloudflare\\.com/i.test(src)) widgets.add('turnstile')
|
|
141
|
+
}
|
|
142
|
+
try { const d = el.contentDocument; if (d) { extra += '\\n' + ((d.body && d.body.innerText) || '').slice(0, 2000); scan(d) } } catch { /* cross-origin */ }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
scan(document)
|
|
147
|
+
for (const [selector, kind] of [['.h-captcha', 'hcaptcha'], ['.g-recaptcha', 'recaptcha'], ['.cf-turnstile', 'turnstile'], ['#px-captcha', 'perimeterx'], ['.geetest_panel, .geetest_slider, .nc_wrapper, .captcha-slider, #slider-captcha', 'slider']]) {
|
|
148
|
+
for (const el of document.querySelectorAll(selector)) if (visible(el)) widgets.add(kind)
|
|
149
|
+
}
|
|
150
|
+
if (document.querySelector('#challenge-running, #challenge-stage, #cf-chl-container, #cf-challenge-running')) widgets.add('cloudflare')
|
|
151
|
+
const nav = performance.getEntriesByType && performance.getEntriesByType('navigation')[0]
|
|
152
|
+
const status = nav && typeof nav.responseStatus === 'number' ? nav.responseStatus : 0
|
|
153
|
+
const evidence = { status, title: document.title || '', text: ((document.body && document.body.innerText) || '').slice(0, 4000) + extra.slice(0, 4000), frames: frames.join(' '), widgets: [...widgets] }
|
|
154
|
+
return (${classify.toString()})(evidence, ${JSON.stringify(SIGNATURE_DATA)})
|
|
155
|
+
} catch { return { blocked: false } }
|
|
156
|
+
})()`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* How long to pause before the one retry a refused page gets, so the retry reads as a person
|
|
161
|
+
* coming back rather than a script hammering. `DSH_BROWSER_BLOCK_RETRY_MS` tunes it (tests use 0).
|
|
162
|
+
* @returns the pause in milliseconds.
|
|
163
|
+
*/
|
|
164
|
+
export function blockRetryDelayMs(): number {
|
|
165
|
+
const raw = Number(process.env.DSH_BROWSER_BLOCK_RETRY_MS)
|
|
166
|
+
return Number.isFinite(raw) && raw >= 0 ? Math.min(raw, 60_000) : 2500
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** One alternative public route to the information a blocked page holds. */
|
|
170
|
+
export interface FallbackRoute {
|
|
171
|
+
readonly kind: 'api' | 'search' | 'archive'
|
|
172
|
+
readonly url: string
|
|
173
|
+
readonly note: string
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const enc = encodeURIComponent
|
|
177
|
+
|
|
178
|
+
function safeDecode(text: string): string {
|
|
179
|
+
try { return decodeURIComponent(text) } catch { return text }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Public, documented endpoints of well-known sites that serve the same content without a browser.
|
|
184
|
+
* @param url - the blocked page.
|
|
185
|
+
* @returns the site's own API routes, most specific first.
|
|
186
|
+
*/
|
|
187
|
+
function siteApis(url: URL): FallbackRoute[] {
|
|
188
|
+
const host = url.hostname.replace(/^(?:www|m|old|new)\./u, '')
|
|
189
|
+
const parts = url.pathname.split('/').filter(Boolean)
|
|
190
|
+
const out: FallbackRoute[] = []
|
|
191
|
+
if (host === 'reddit.com') {
|
|
192
|
+
out.push({ kind: 'api', url: `https://www.reddit.com${url.pathname.replace(/\/$/u, '')}.json${url.search}`, note: 'Reddit JSON view of the same listing or thread' })
|
|
193
|
+
} else if (host === 'github.com' && parts.length >= 2) {
|
|
194
|
+
const [owner, repo, section, ...rest] = parts
|
|
195
|
+
const base = `https://api.github.com/repos/${owner}/${repo}`
|
|
196
|
+
const tail = section === 'issues' || section === 'pull' ? `/${section === 'pull' ? 'pulls' : 'issues'}${rest[0] !== undefined ? `/${rest[0]}` : ''}` : section === 'releases' ? '/releases' : ''
|
|
197
|
+
out.push({ kind: 'api', url: base + tail, note: 'GitHub REST API' })
|
|
198
|
+
} else if (/(?:^|\.)wikipedia\.org$/u.test(host) && parts[0] === 'wiki' && parts[1] !== undefined) {
|
|
199
|
+
out.push({ kind: 'api', url: `https://${url.hostname}/api/rest_v1/page/html/${parts.slice(1).join('/')}`, note: 'Wikipedia REST API (page HTML)' })
|
|
200
|
+
} else if (host === 'news.ycombinator.com' && url.searchParams.get('id') !== null) {
|
|
201
|
+
out.push({ kind: 'api', url: `https://hacker-news.firebaseio.com/v0/item/${enc(url.searchParams.get('id')!)}.json`, note: 'Hacker News Firebase API' })
|
|
202
|
+
} else if (host === 'stackoverflow.com' && parts[0] === 'questions' && parts[1] !== undefined) {
|
|
203
|
+
out.push({ kind: 'api', url: `https://api.stackexchange.com/2.3/questions/${parts[1]}?site=stackoverflow&filter=withbody`, note: 'Stack Exchange API' })
|
|
204
|
+
} else if (host === 'npmjs.com' && parts[0] === 'package' && parts[1] !== undefined) {
|
|
205
|
+
out.push({ kind: 'api', url: `https://registry.npmjs.org/${parts.slice(1).join('/')}`, note: 'npm registry metadata' })
|
|
206
|
+
} else if (host === 'pypi.org' && parts[0] === 'project' && parts[1] !== undefined) {
|
|
207
|
+
out.push({ kind: 'api', url: `https://pypi.org/pypi/${parts[1]}/json`, note: 'PyPI JSON API' })
|
|
208
|
+
} else if ((host === 'youtube.com' && url.searchParams.get('v') !== null) || host === 'youtu.be') {
|
|
209
|
+
out.push({ kind: 'api', url: `https://www.youtube.com/oembed?format=json&url=${enc(url.href)}`, note: 'YouTube oEmbed (title, channel)' })
|
|
210
|
+
}
|
|
211
|
+
return out
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Other public routes to a blocked page's information, in the order worth trying: the site's own
|
|
216
|
+
* API, search-engine results (snippets and other copies), then web archives.
|
|
217
|
+
* @param target - the blocked page's URL.
|
|
218
|
+
* @returns the routes; empty for a non-HTTP URL.
|
|
219
|
+
*/
|
|
220
|
+
export function fallbackRoutes(target: string): FallbackRoute[] {
|
|
221
|
+
let url: URL
|
|
222
|
+
try { url = new URL(target) } catch { return [] }
|
|
223
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return []
|
|
224
|
+
// Third parties get the page's address only: a query, fragment or userinfo can carry a session
|
|
225
|
+
// token or a signature, and these routes are fetched from other services.
|
|
226
|
+
const page = `${url.protocol}//${url.host}${url.pathname}`
|
|
227
|
+
const bare = page.replace(/^https?:\/\//u, '')
|
|
228
|
+
const terms = `${url.hostname} ${safeDecode(url.pathname).replace(/[/_-]+/gu, ' ').trim()}`.trim()
|
|
229
|
+
return [
|
|
230
|
+
...siteApis(url),
|
|
231
|
+
{ kind: 'search', url: `https://www.bing.com/search?q=${enc(terms)}`, note: 'Bing results: snippets and other copies of the page' },
|
|
232
|
+
{ kind: 'search', url: `https://duckduckgo.com/html/?q=${enc(terms)}`, note: 'DuckDuckGo HTML results' },
|
|
233
|
+
{ kind: 'archive', url: `https://web.archive.org/web/2/${page}`, note: 'Wayback Machine: latest archived copy' },
|
|
234
|
+
{ kind: 'archive', url: `https://archive.ph/newest/${bare}`, note: 'archive.today: latest snapshot' },
|
|
235
|
+
]
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* What the agent is told to do for a verdict: one line, static per kind so it stays cache friendly.
|
|
240
|
+
* @param challenge - the verdict.
|
|
241
|
+
* @returns the instruction, or '' when the page is not blocked.
|
|
242
|
+
*/
|
|
243
|
+
export function recoveryAdvice(challenge: BrowserChallenge): string {
|
|
244
|
+
if (challenge.blocked !== true) return ''
|
|
245
|
+
switch (challenge.recovery) {
|
|
246
|
+
case 'takeover': return 'Human verification: never solve it or retry it yourself. Call dsh_browser_request_takeover so the human completes it in the browser, then re-read the page. If takeover is skipped or unavailable, use the fallback routes.'
|
|
247
|
+
case 'wait': return 'A self-clearing interstitial: dsh_browser_wait (a few seconds) and re-check; if it turns into a human check, request takeover; if it persists, use the fallback routes.'
|
|
248
|
+
case 'environment': return 'The site refuses this network (an environment limit, not something to work around): do not retry. Use the fallback routes and report the block.'
|
|
249
|
+
default: return 'The site refused automated access. One paced retry in a fresh session was already made when it says so; do not hammer the site. Use the fallback routes for the same public information.'
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-side DOM traversal shared by every page script that looks elements up.
|
|
3
|
+
*
|
|
4
|
+
* Browser Use reads into same-origin iframes and open shadow roots; a lookup that only asks
|
|
5
|
+
* `document` misses what the snapshot just listed. Inject {@link DEEP_DOM_SOURCE} at the top of a
|
|
6
|
+
* page script, then use `__dshRoots()`, `__dshQuery(selector)` and `__dshQueryAll(selector)`.
|
|
7
|
+
* Cross-origin frames and closed shadow roots stay opaque, as the browser requires.
|
|
8
|
+
* @module dsh-browser/browser/deep-dom
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const DEEP_DOM_SOURCE = `
|
|
12
|
+
const __dshRoots = (start) => {
|
|
13
|
+
const roots = []
|
|
14
|
+
const seen = new Set()
|
|
15
|
+
const visit = (root) => {
|
|
16
|
+
if (!root || seen.has(root)) return
|
|
17
|
+
seen.add(root)
|
|
18
|
+
roots.push(root)
|
|
19
|
+
for (const el of root.querySelectorAll('*')) {
|
|
20
|
+
if (el.shadowRoot) visit(el.shadowRoot)
|
|
21
|
+
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
|
|
22
|
+
try { const d = el.contentDocument; if (d) visit(d) } catch (error) { /* cross-origin */ }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
visit(start || document)
|
|
27
|
+
return roots
|
|
28
|
+
}
|
|
29
|
+
const __dshQuery = (selector) => {
|
|
30
|
+
const top = document.querySelector(selector)
|
|
31
|
+
if (top) return top
|
|
32
|
+
for (const root of __dshRoots()) { const found = root.querySelector(selector); if (found) return found }
|
|
33
|
+
return null
|
|
34
|
+
}
|
|
35
|
+
const __dshQueryAll = (selector) => {
|
|
36
|
+
const all = Array.from(document.querySelectorAll(selector))
|
|
37
|
+
for (const root of __dshRoots().slice(1)) all.push(...root.querySelectorAll(selector))
|
|
38
|
+
return all
|
|
39
|
+
}
|
|
40
|
+
`
|
package/src/browser/runtime.ts
CHANGED
|
@@ -154,6 +154,24 @@ export class BrowserRuntime extends Service {
|
|
|
154
154
|
constructor(ctx: Context, config: BrowserRuntimeConfig = {}) {
|
|
155
155
|
super(ctx, 'browser')
|
|
156
156
|
this.providerId = config.browserProvider
|
|
157
|
+
// Optionally claim the DSH >= 0.2.3 exclusive `ctx.browserUse` registry when present
|
|
158
|
+
// so co-installed browser-use plugins cannot silently collide.
|
|
159
|
+
const surface = ctx as unknown as {
|
|
160
|
+
inject?: (deps: readonly string[], callback: (scope: {
|
|
161
|
+
readonly browserUse: { register(name: string): () => void }
|
|
162
|
+
effect(callback: () => (() => void) | void, label?: string): void
|
|
163
|
+
}) => void) => void
|
|
164
|
+
}
|
|
165
|
+
if (typeof surface.inject === 'function') {
|
|
166
|
+
try {
|
|
167
|
+
surface.inject(['browserUse'], (scope) => {
|
|
168
|
+
if (typeof scope.browserUse?.register !== 'function') return
|
|
169
|
+
scope.effect(() => scope.browserUse.register('dsh-builtin-browser'), 'dsh-builtin-browser: browserUse registration')
|
|
170
|
+
})
|
|
171
|
+
} catch {
|
|
172
|
+
// Optional host service: ignore when unavailable in minimal or legacy contexts.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
157
175
|
}
|
|
158
176
|
|
|
159
177
|
/**
|
|
@@ -8,29 +8,38 @@ export interface CarrierTakeoverTarget {
|
|
|
8
8
|
readonly tabId: string
|
|
9
9
|
readonly pageId: string
|
|
10
10
|
readonly url: string
|
|
11
|
+
/** `until` aborts when the takeover ends. */
|
|
12
|
+
readonly reveal?: (until?: AbortSignal) => Promise<boolean>
|
|
11
13
|
readonly connected: () => boolean
|
|
14
|
+
/** When this target belongs to the owner but cannot be handed to a human (e.g. headless), explain why instead of falling back. */
|
|
15
|
+
readonly unavailableReason?: () => string | undefined
|
|
12
16
|
}
|
|
13
17
|
|
|
14
|
-
const sources = new WeakMap<object, (owner: string) => readonly CarrierTakeoverTarget[]>()
|
|
18
|
+
const sources = new WeakMap<object, { readonly list: (owner: string) => readonly CarrierTakeoverTarget[]; readonly exclusive: boolean }>()
|
|
15
19
|
|
|
16
20
|
function browserIdentity(browser: object): object {
|
|
17
21
|
return Service.prototype.isPrototypeOf(browser) ? (browser as Record<symbol, object | undefined>)[symbols.original] ?? browser : browser
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
export function hasCarrierTakeover(browser: object | undefined): boolean {
|
|
21
|
-
return browser !== undefined && sources.
|
|
25
|
+
return browser !== undefined && sources.get(browserIdentity(browser))?.exclusive === true
|
|
22
26
|
}
|
|
23
27
|
|
|
24
|
-
|
|
25
|
-
|
|
28
|
+
/** `exclusive: false` lets a carrier with no tab for the owner fall back to the sidebar. */
|
|
29
|
+
export function registerCarrierTakeover(browser: object, list: (owner: string) => readonly CarrierTakeoverTarget[], { exclusive = true } = {}): () => void {
|
|
30
|
+
const key = browserIdentity(browser), source = { list, exclusive }
|
|
26
31
|
sources.set(key, source)
|
|
27
32
|
return () => { if (sources.get(key) === source) sources.delete(key) }
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
export function carrierTakeoverTarget(browser: object | undefined, owner: string, pageId?: string): CarrierTakeoverTarget | undefined {
|
|
31
36
|
if (!browser) return undefined
|
|
32
|
-
const
|
|
33
|
-
&&
|
|
37
|
+
const owned = sources.get(browserIdentity(browser))?.list(referenceOwnerKey(owner)).filter(target => referenceOwnerKey(target.owner) === referenceOwnerKey(owner)
|
|
38
|
+
&& (pageId === undefined || target.pageId === pageId)) ?? []
|
|
39
|
+
const candidates = owned.filter(target => target.connected())
|
|
34
40
|
if (candidates.length > 1) throw new Error('Select one browser session in this conversation before requesting takeover.')
|
|
35
|
-
return candidates[0]
|
|
41
|
+
if (candidates[0] !== undefined) return candidates[0]
|
|
42
|
+
const blocked = owned.map(target => target.unavailableReason?.()).find(reason => typeof reason === 'string' && reason !== '')
|
|
43
|
+
if (blocked !== undefined) throw new Error(blocked)
|
|
44
|
+
return undefined
|
|
36
45
|
}
|
package/src/browser/types.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* @module dsh-browser/browser/types
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { HarnessError } from '@deepseek-ai/dsh-
|
|
10
|
+
import { HarnessError } from '@deepseek-ai/dsh-error'
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Stable identity of one browser session, resolved by the Host through a
|
|
@@ -379,12 +379,14 @@ export type BrowserPageOperationRequest =
|
|
|
379
379
|
| { readonly operation: 'probe'; readonly method: BrowserProbeMethod; readonly args?: readonly unknown[] }
|
|
380
380
|
| { readonly operation: 'text'; readonly text: string }
|
|
381
381
|
| { readonly operation: 'url' }
|
|
382
|
+
| { readonly operation: 'pulse' }
|
|
383
|
+
| { readonly operation: 'fetch'; readonly url: string; readonly init: { readonly method?: string; readonly headers?: Readonly<Record<string, string>>; readonly body?: string } }
|
|
382
384
|
| { readonly operation: 'drag'; readonly from: { x: number; y: number }; readonly to: { x: number; y: number }; readonly steps: number }
|
|
383
385
|
| { readonly operation: 'upload'; readonly target: { by: 'css' | 'text' | 'xpath'; value: string }; readonly file: { name: string; mime: string; base64: string } }
|
|
384
386
|
|
|
385
387
|
/** Provider-owned probe operations; JavaScript properties such as constructor are excluded. */
|
|
386
388
|
export type BrowserProbeMethod = 'read' | 'clear' | 'settle' | 'find' | 'overlayAt' | 'summary'
|
|
387
|
-
| 'findText' | 'hoverAt' | 'setDialogPolicy' | 'dialogStatus' | 'networkCursor'
|
|
389
|
+
| 'findText' | 'hoverAt' | 'setDialogPolicy' | 'dialogStatus' | 'networkCursor' | 'dataSources'
|
|
388
390
|
|
|
389
391
|
/**
|
|
390
392
|
* Result of an execute. Mirrors CDP `Runtime.evaluate` semantics: either a
|
|
@@ -529,10 +531,14 @@ export interface BrowserA11yResult {
|
|
|
529
531
|
export interface BrowserChallenge {
|
|
530
532
|
/** Whether a challenge currently blocks the page. */
|
|
531
533
|
readonly blocked: boolean
|
|
532
|
-
/** Machine-readable kind
|
|
534
|
+
/** Machine-readable kind, e.g. cloudflare | hcaptcha | recaptcha | turnstile | slider | access-denied | ip-block. */
|
|
533
535
|
readonly kind?: string
|
|
534
536
|
/** Short human-readable description, e.g. 'Cloudflare "Just a moment" interstitial'. */
|
|
535
537
|
readonly reason?: string
|
|
538
|
+
/** What to do about it: takeover (human verification), wait, retry, or environment (network refused). */
|
|
539
|
+
readonly recovery?: 'takeover' | 'wait' | 'retry' | 'environment'
|
|
540
|
+
/** HTTP status of the main document, when known. */
|
|
541
|
+
readonly status?: number
|
|
536
542
|
}
|
|
537
543
|
|
|
538
544
|
/**
|
|
@@ -815,3 +821,50 @@ export interface BrowserHistoryEntry {
|
|
|
815
821
|
* own (e.g. `BROWSER_CDP_ATTACH_FAILED`).
|
|
816
822
|
*/
|
|
817
823
|
export class BrowserError extends HarnessError {}
|
|
824
|
+
|
|
825
|
+
/** What a browser carrier can do for a tool call; tools ask for one capability instead of naming carriers. */
|
|
826
|
+
export interface CarrierCapabilities {
|
|
827
|
+
/** A live Chrome DevTools Protocol session drives the page. */
|
|
828
|
+
readonly cdp: boolean
|
|
829
|
+
readonly liveSnapshot: boolean
|
|
830
|
+
readonly interaction: boolean
|
|
831
|
+
readonly screenshot: boolean
|
|
832
|
+
readonly nativeTabs: boolean
|
|
833
|
+
readonly backgroundRender: boolean
|
|
834
|
+
readonly takeover: boolean
|
|
835
|
+
readonly referenceCapture: boolean
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
export type CarrierCapability = keyof CarrierCapabilities
|
|
839
|
+
|
|
840
|
+
/** A CDP-backed page: the plugin browser, an attached system browser or the desktop sidebar. */
|
|
841
|
+
export const CDP_CARRIER_CAPABILITIES: CarrierCapabilities = Object.freeze({
|
|
842
|
+
cdp: true, liveSnapshot: true, interaction: true, screenshot: true,
|
|
843
|
+
nativeTabs: true, backgroundRender: true, takeover: true, referenceCapture: true,
|
|
844
|
+
})
|
|
845
|
+
|
|
846
|
+
/** The Web sidebar's iframe: it can be navigated, nothing else. */
|
|
847
|
+
export const WEB_PANEL_CAPABILITIES: CarrierCapabilities = Object.freeze({
|
|
848
|
+
cdp: false, liveSnapshot: false, interaction: false, screenshot: false,
|
|
849
|
+
nativeTabs: false, backgroundRender: false, takeover: false, referenceCapture: false,
|
|
850
|
+
})
|
|
851
|
+
|
|
852
|
+
/** A tool needed a capability the current carrier lacks. */
|
|
853
|
+
export class CarrierCapabilityError extends BrowserError {
|
|
854
|
+
readonly capability: CarrierCapability
|
|
855
|
+
constructor(capability: CarrierCapability, message: string) {
|
|
856
|
+
super(message, 'BROWSER_CARRIER_CAPABILITY_UNAVAILABLE')
|
|
857
|
+
this.name = 'CarrierCapabilityError'
|
|
858
|
+
this.capability = capability
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Refuse an operation the carrier cannot perform.
|
|
864
|
+
* @param capabilities - the current carrier's capabilities.
|
|
865
|
+
* @param required - the one capability the operation needs.
|
|
866
|
+
* @param guidance - the refusal the model sees: what is missing and which carrier to switch to.
|
|
867
|
+
*/
|
|
868
|
+
export function assertCapability(capabilities: CarrierCapabilities, required: CarrierCapability, guidance: string): void {
|
|
869
|
+
if (!capabilities[required]) throw new CarrierCapabilityError(required, guidance)
|
|
870
|
+
}
|