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.
Files changed (222) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -0,0 +1,664 @@
1
+ import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserContentRequest, BrowserContentResult, BrowserScrapeRequest, BrowserScrapeResult, BrowserSessionId, BrowserSnapshotResult, BrowserWaitRequest, BrowserWaitResult } from '../browser/types.ts'
3
+ import { BrowserError } from '../browser/types.ts'
4
+ import { DEEP_DOM_SOURCE } from '../browser/deep-dom.ts'
5
+ import { challengeDetectSource } from '../browser/anti-bot.ts'
6
+ import { PROVIDER_TIMEOUTS, TARGET_SCRIPT_GRACE_MS, delay, pagePollSlice, withTimeout, handleSendEvaluate } from './provider-core.ts'
7
+ import { ProviderNavigation } from './provider-navigation.ts'
8
+
9
+ /** Page-context block / human-verification detection; the classifier lives in `browser/anti-bot.ts`. */
10
+ const CHALLENGE_DETECT_EXPRESSION = challengeDetectSource()
11
+
12
+ /** Cap on content returned by a snapshot fetch to keep the wire bounded. */
13
+ const SNAPSHOT_LABEL_MAX = 120
14
+
15
+ export abstract class ProviderObservation extends ProviderNavigation {
16
+ /**
17
+ * Poll until the active tab's page is ready (and optional URL/selector
18
+ * match), or the budget runs out. Returns a verdict instead of throwing on
19
+ * timeout — the caller (model) decides what a miss means. Polling evaluates
20
+ * in the CURRENT document, so after a navigation the old document may
21
+ * briefly answer; pass the expected `url` to disambiguate.
22
+ */
23
+ async waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult> {
24
+ const tab = this.activeTab(this.session(session))
25
+ signal?.throwIfAborted()
26
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
27
+ const deadline = Date.now() + timeoutMs
28
+ const url = request.url ?? ''
29
+ const selector = request.selector ?? ''
30
+ const checkLoaded = request.loaded !== false
31
+ const expression = `(() => {${DEEP_DOM_SOURCE}
32
+ const wantUrl = ${JSON.stringify(url)}
33
+ const wantSelector = ${JSON.stringify(selector)}
34
+ const inDoc = (_doc, sel) => { try { return __dshQuery(sel) !== null } catch { return false } }
35
+ const href = location.href
36
+ // Exact match wins; otherwise prefix-match within the SAME origin only,
37
+ // so wantUrl "https://a.com" never matches a cross-origin page whose
38
+ // host merely starts with the same characters ("https://a.com.evil.com").
39
+ let urlOk = wantUrl === '' || href === wantUrl
40
+ if (!urlOk && wantUrl !== '') {
41
+ try {
42
+ const want = new URL(wantUrl)
43
+ const got = new URL(href)
44
+ urlOk = want.origin === got.origin && href.startsWith(wantUrl)
45
+ } catch { urlOk = false }
46
+ }
47
+ const loadedOk = document.readyState === 'complete' || document.readyState === 'interactive'
48
+ const foundOk = wantSelector === '' || inDoc(document, wantSelector)
49
+ return { urlOk, loadedOk, foundOk }
50
+ })()`
51
+ for (;;) {
52
+ const result = await withTimeout(
53
+ handleSendEvaluate(tab.handle, expression),
54
+ Math.min(PROVIDER_TIMEOUTS.interaction, Math.max(250, deadline - Date.now())),
55
+ signal,
56
+ 'browser: wait poll timed out',
57
+ timedOut => { this.interrupt(tab.handle, timedOut) },
58
+ )
59
+ if (!result.ok) {
60
+ throw new BrowserError(`browser: wait failed: ${result.exception}`, 'BROWSER_WAIT_FAILED')
61
+ }
62
+ const state = result.value as { urlOk: boolean; loadedOk: boolean; foundOk: boolean }
63
+ const urlOk = url === '' || state.urlOk === true
64
+ const loadedOk = !checkLoaded || state.loadedOk === true
65
+ const foundOk = selector === '' || state.foundOk === true
66
+ if (urlOk && loadedOk && foundOk) {
67
+ return { ready: true, reason: 'condition met' }
68
+ }
69
+ if (Date.now() >= deadline) {
70
+ const misses: string[] = []
71
+ if (!urlOk) misses.push(`url not yet "${url}"`)
72
+ if (!loadedOk) misses.push('page not loaded')
73
+ if (!foundOk) misses.push(`selector "${selector}" not found`)
74
+ return { ready: false, reason: misses.join('; ') }
75
+ }
76
+ // Sleep between polls, abortable by the caller.
77
+ // Sleep between polls; delay() removes its abort listener on both paths, which the
78
+ // hand-rolled version here did not — a 30s wait leaked about 150 of them.
79
+ await delay(200, signal)
80
+ }
81
+ }
82
+
83
+ /** Produce an AI-friendly snapshot of the active tab. */
84
+ async snapshot(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserSnapshotResult> {
85
+ const s = this.session(session)
86
+ const tab = this.activeTab(s)
87
+ signal?.throwIfAborted()
88
+ // A tab that has never navigated is a blank, uncommitted view. The collector cannot answer in
89
+ // it — there is no document to commit — so the call would sit out its whole budget before
90
+ // saying anything. Answering the empty page immediately is both faster and more truthful.
91
+ //
92
+ // `about:blank` needs the same answer for a different reason: it HAS a document, so the collector
93
+ // runs, finds nothing, and returns zero elements — indistinguishable from a real page with nothing
94
+ // interactive. A caller then acts on it and receives success values, which is how a carrier swap
95
+ // that started a fresh window looked like working tools operating on the wrong page (issue #37).
96
+ const blankUrl = tab.url === '' || tab.url === 'about:blank'
97
+ if (blankUrl) {
98
+ return {
99
+ url: tab.url,
100
+ elements: [],
101
+ truncated: false,
102
+ blank: true,
103
+ note: tab.url === ''
104
+ ? 'no page has been opened in this browser yet'
105
+ : 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
106
+ }
107
+ }
108
+ const script = `(() => {
109
+ const cap = ${String(this.snapshotMaxElements)}
110
+ const url = location.href
111
+ const title = document.title || undefined
112
+ // Collect interactive elements from the top document AND from shadow
113
+ // roots and same-origin iframes (cross-origin iframes stay opaque — the
114
+ // browser forbids reading them, and so does this snapshot). Elements
115
+ // inside iframes carry a frame flag so the model knows DOM selectors
116
+ // are frame-scoped; coordinates below are always top-document.
117
+ const SELECTOR = 'input, textarea, select, button, a[href], [role="button"], [role="searchbox"], [contenteditable="true"]'
118
+ const els = []
119
+ const seen = new Set()
120
+ const collect = (doc, inFrame) => {
121
+ if (seen.has(doc)) return
122
+ seen.add(doc)
123
+ const hosts = []
124
+ for (const el of doc.querySelectorAll('*')) {
125
+ if (el.matches(SELECTOR)) els.push({ el, inFrame })
126
+ if (el.shadowRoot) hosts.push({ doc: el.shadowRoot, inFrame })
127
+ if (el.tagName === 'IFRAME') {
128
+ try { const d = el.contentDocument; if (d) hosts.push({ doc: d, inFrame: true }) } catch { /* cross-origin */ }
129
+ }
130
+ }
131
+ for (const h of hosts) collect(h.doc, h.inFrame)
132
+ }
133
+ collect(document, false)
134
+ // Absolute viewport coordinates in the TOP document: iframe content is
135
+ // offset by each ancestor iframe's rect, so coordinate clicks land on
136
+ // the right element no matter which frame it lives in.
137
+ const absRect = (el, doc) => {
138
+ const r = el.getBoundingClientRect()
139
+ let x = r.x, y = r.y
140
+ let d = doc
141
+ while (d && d.defaultView && d.defaultView.frameElement) {
142
+ const fr = d.defaultView.frameElement.getBoundingClientRect()
143
+ x += fr.x; y += fr.y
144
+ d = d.defaultView.frameElement.ownerDocument
145
+ }
146
+ return { x, y, w: r.width, h: r.height }
147
+ }
148
+ const out = []
149
+ for (const { el, inFrame } of els) {
150
+ if (out.length >= cap) break
151
+ const r = el.getBoundingClientRect()
152
+ // Cheap layout check first; only force style recalc when it passes.
153
+ if (r.width < 4 || r.height < 4) continue
154
+ const cs = getComputedStyle(el)
155
+ if (cs.visibility === 'hidden' || cs.display === 'none') continue
156
+ const kind = el.tagName === 'INPUT' ? (el.type === 'checkbox' ? 'checkbox' : (el.type === 'submit' || el.type === 'button' ? 'button' : 'input'))
157
+ : el.tagName === 'TEXTAREA' ? 'textarea'
158
+ : el.tagName === 'SELECT' ? 'select'
159
+ : el.tagName === 'BUTTON' ? 'button'
160
+ : el.tagName === 'A' ? 'link' : 'other'
161
+ // An anchor wrapping only an image has no text: 4399.com's 1608 game links are all
162
+ // <a href><img alt="名字"></a>, so every label came out empty and the whole page read as
163
+ // "no interactive elements" while it was full of them.
164
+ const imageAlt = el.tagName === 'A' || el.tagName === 'BUTTON'
165
+ ? (el.querySelector('img[alt]')?.getAttribute('alt') ?? '')
166
+ : ''
167
+ const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || imageAlt
168
+ || el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
169
+ if (!label && kind !== 'link') continue
170
+ const a = absRect(el, el.ownerDocument)
171
+ out.push({
172
+ ref: out.length + 1,
173
+ kind,
174
+ label,
175
+ selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
176
+ x: Math.round(a.x + a.w / 2),
177
+ y: Math.round(a.y + a.h / 2),
178
+ ...inFrame ? { frame: true } : {},
179
+ })
180
+ }
181
+ const challenge = ${CHALLENGE_DETECT_EXPRESSION}
182
+ // The page's own URL is the authority on whether there is a document. The tracked tab.url is
183
+ // a bookkeeping copy that can lag behind a navigation the browser performed itself, and a
184
+ // stale copy made this check miss on a real about:blank tab.
185
+ const blankPage = out.length === 0 && (url === '' || url === 'about:blank')
186
+ // Independent of the element list: a page can mix DOM controls with a canvas that holds the
187
+ // part the caller actually needs. Measured on sudoku.com — 60 links were collected and the
188
+ // board, drawn on a canvas, was invisible in the same result.
189
+ //
190
+ // The thresholds keep a decorative canvas from claiming a page: at least 80x80 per canvas and
191
+ // 10% of the viewport in total. Anything smaller is reported by nothing, which is right.
192
+ let canvas
193
+ if (blankPage !== true) {
194
+ let area = 0
195
+ let count = 0
196
+ for (const c of document.querySelectorAll('canvas')) {
197
+ const r = c.getBoundingClientRect()
198
+ if (r.width < 80 || r.height < 80) continue
199
+ count += 1
200
+ area += r.width * r.height
201
+ }
202
+ const view = window.innerWidth * window.innerHeight
203
+ if (count > 0 && view > 0 && area / view >= 0.1) canvas = true
204
+ }
205
+ return {
206
+ url,
207
+ title,
208
+ elements: out,
209
+ truncated: out.length >= cap,
210
+ challenge,
211
+ ...blankPage === true
212
+ ? {
213
+ blank: true,
214
+ note: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
215
+ }
216
+ : {},
217
+ ...canvas === true
218
+ ? {
219
+ canvas: true,
220
+ note: out.length === 0
221
+ ? 'this page draws its interface on a canvas, so there is no DOM content for a snapshot. '
222
+ + 'Use dsh_browser_screenshot to see it, and coordinates with dsh_browser_click to act on it.'
223
+ : 'part of this page is drawn on a canvas, which no element list can describe. The elements '
224
+ + 'below are real; anything inside the canvas is only visible in dsh_browser_screenshot.',
225
+ }
226
+ : {},
227
+ }
228
+ })()`
229
+ // Same hang guard as execute: a renderer that has not committed after
230
+ // navigate would otherwise block snapshot forever.
231
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
232
+ let result: { ok: true; value: unknown } | { ok: false; exception: string }
233
+ try {
234
+ result = await withTimeout(
235
+ handleSendEvaluate(tab.handle, script),
236
+ timeoutMs,
237
+ signal,
238
+ `browser: snapshot timed out after ${timeoutMs}ms`,
239
+ timedOut => { this.interrupt(tab.handle, timedOut) },
240
+ ) as { ok: true; value: unknown } | { ok: false; exception: string }
241
+ } catch (error) {
242
+ if (error instanceof Error && error.name === 'TimeoutError') {
243
+ this.quarantine(tab.handle)
244
+ throw new BrowserError(
245
+ 'browser: snapshot timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
246
+ 'BROWSER_SNAPSHOT_TIMEOUT',
247
+ { cause: error },
248
+ )
249
+ }
250
+ throw error
251
+ }
252
+ if (!result.ok) throw new BrowserError(`browser: snapshot evaluation failed: ${result.exception}`, 'BROWSER_SNAPSHOT_FAILED')
253
+ const value = result.value as BrowserSnapshotResult
254
+ return value
255
+ }
256
+
257
+ /**
258
+ * Read the active tab's accessibility tree: semantic roles/names/states for
259
+ * every interactive node (Chrome's `computedRole`/`computedName` when
260
+ * available, tag/attribute inference otherwise). Pierces same-origin
261
+ * iframes and shadow roots like the snapshot; cross-origin frames stay
262
+ * opaque. Coordinates are top-document viewport-relative, so a node can
263
+ * also be driven by click/type.
264
+ */
265
+ async a11y(session: BrowserSessionId, request: BrowserA11yRequest, signal?: AbortSignal): Promise<BrowserA11yResult> {
266
+ const s = this.session(session)
267
+ const tab = this.activeTab(s)
268
+ signal?.throwIfAborted()
269
+ // Same short-circuit as `snapshot`: a tab that never navigated has no committed document, so
270
+ // the tree cannot be read and the call would spend its whole budget discovering that.
271
+ if (tab.url === '') return { url: '', title: undefined, count: 0, nodes: [], truncated: false }
272
+ const includeHidden = request.includeHidden === true
273
+ // 150 rather than 500. The cap fills on any real page, and 500 nodes measured 38,953
274
+ // characters — 10k-13k tokens for a single call. A caller that needs more asks for it.
275
+ const maxNodes = Math.max(10, Math.min(5000, Math.floor(request.maxNodes ?? 150)))
276
+ const script = `(() => {
277
+ const includeHidden = ${String(includeHidden)}
278
+ const maxNodes = ${String(maxNodes)}
279
+ const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK', 'TITLE'])
280
+ const ACTIONABLE = new Set(['button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'listbox', 'slider', 'spinbutton', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'switch', 'option', 'summary', 'treeitem', 'scrollbar'])
281
+ const CONTENT_NAMED = new Set(['button', 'link', 'heading', 'summary', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'treeitem', 'option', 'listitem', 'switch', 'checkbox', 'radio', 'searchbox', 'textbox'])
282
+ const out = []
283
+ const seen = new Set()
284
+ const ownText = (el) => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
285
+ const visible = (el) => {
286
+ const r = el.getBoundingClientRect()
287
+ const cs = getComputedStyle(el)
288
+ return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
289
+ }
290
+ const roleOf = (el) => {
291
+ const computed = el.computedRole
292
+ if (typeof computed === 'string' && computed && computed !== 'none' && computed !== 'generic') return computed
293
+ const tag = el.tagName.toLowerCase()
294
+ if (el instanceof HTMLAnchorElement) return el.hasAttribute('href') ? 'link' : 'generic'
295
+ if (tag === 'button') return 'button'
296
+ if (tag === 'textarea') return 'textbox'
297
+ if (tag === 'select') return el.hasAttribute('multiple') ? 'listbox' : 'combobox'
298
+ if (tag === 'img') return el.getAttribute('alt') === '' ? 'presentation' : 'img'
299
+ if (/^h[1-6]$/.test(tag)) return 'heading'
300
+ if (tag === 'ul' || tag === 'ol') return 'list'
301
+ if (tag === 'li') return 'listitem'
302
+ if (tag === 'nav') return 'navigation'
303
+ if (tag === 'main') return 'main'
304
+ if (tag === 'form') return 'form'
305
+ if (tag === 'table') return 'table'
306
+ if (tag === 'tr') return 'row'
307
+ if (tag === 'td') return 'cell'
308
+ if (tag === 'th') return 'columnheader'
309
+ if (tag === 'dialog') return 'dialog'
310
+ if (tag === 'summary') return 'button'
311
+ if (tag === 'input') {
312
+ const t = el.type
313
+ if (t === 'checkbox') return 'checkbox'
314
+ if (t === 'radio') return 'radio'
315
+ if (t === 'range') return 'slider'
316
+ if (t === 'number') return 'spinbutton'
317
+ if (t === 'button' || t === 'submit' || t === 'reset' || t === 'image') return 'button'
318
+ if (t === 'hidden') return 'none'
319
+ if (t === 'search') return 'searchbox'
320
+ return 'textbox'
321
+ }
322
+ return 'generic'
323
+ }
324
+ const nameOf = (el, role) => {
325
+ const computed = el.computedName
326
+ if (typeof computed === 'string' && computed && computed.trim() !== '') return computed.trim()
327
+ const aria = el.getAttribute('aria-label')
328
+ if (aria) return aria
329
+ const labelledby = el.getAttribute('aria-labelledby')
330
+ if (labelledby) {
331
+ const ref = document.getElementById(labelledby.split(/\\s+/)[0])
332
+ if (ref) {
333
+ const t = (ref.textContent || '').trim()
334
+ if (t) return t
335
+ }
336
+ }
337
+ if (el.hasAttribute('alt')) return el.getAttribute('alt')
338
+ if (el.hasAttribute('title')) return el.getAttribute('title')
339
+ if (el.placeholder) return el.placeholder
340
+ if (CONTENT_NAMED.has(role)) {
341
+ const t = ownText(el)
342
+ if (t) return t
343
+ }
344
+ if (el.id) {
345
+ const lbl = document.querySelector('label[for=' + JSON.stringify(el.id) + ']')
346
+ if (lbl) {
347
+ const t = (lbl.textContent || '').trim()
348
+ if (t) return t
349
+ }
350
+ }
351
+ return ''
352
+ }
353
+ const valueOf = (el) => {
354
+ if (el instanceof HTMLInputElement) return el.type === 'checkbox' || el.type === 'radio' ? null : el.value
355
+ if (el instanceof HTMLTextAreaElement) return el.value
356
+ if (el instanceof HTMLSelectElement) {
357
+ const o = el.options[el.selectedIndex]
358
+ return o ? (o.textContent || '').trim() : null
359
+ }
360
+ if (el.isContentEditable) return (el.textContent || '').trim()
361
+ return null
362
+ }
363
+ const statesOf = (el) => {
364
+ const st = []
365
+ if (!el.disabled) st.push('enabled'); else st.push('disabled')
366
+ if (el.checked) st.push('checked'); else if (el.getAttribute('aria-checked') === 'false') st.push('unchecked')
367
+ const expanded = el.getAttribute('aria-expanded')
368
+ if (expanded === 'true') st.push('expanded')
369
+ if (expanded === 'false') st.push('collapsed')
370
+ if (el.required) st.push('required')
371
+ if (el.readOnly) st.push('readonly')
372
+ if (el.selected) st.push('selected')
373
+ const pressed = el.getAttribute('aria-pressed')
374
+ if (pressed === 'true') st.push('pressed')
375
+ return st
376
+ }
377
+ const depthOf = (el) => {
378
+ let d = 0
379
+ let p = el.parentElement
380
+ while (p) { d++; p = p.parentElement }
381
+ return d
382
+ }
383
+ const absRect = (el, doc) => {
384
+ const r = el.getBoundingClientRect()
385
+ let x = r.x, y = r.y
386
+ let d = doc
387
+ while (d && d.defaultView && d.defaultView.frameElement) {
388
+ const fr = d.defaultView.frameElement.getBoundingClientRect()
389
+ x += fr.x; y += fr.y
390
+ d = d.defaultView.frameElement.ownerDocument
391
+ }
392
+ return { x, y, w: r.width, h: r.height }
393
+ }
394
+ const walk = (doc, inFrame, baseDepth) => {
395
+ if (seen.has(doc)) return
396
+ seen.add(doc)
397
+ for (const el of doc.querySelectorAll('*')) {
398
+ if (out.length >= maxNodes) return
399
+ if (SKIP.has(el.tagName)) continue
400
+ if (el.shadowRoot) walk(el.shadowRoot, inFrame, baseDepth + 1)
401
+ if (el.tagName === 'IFRAME') {
402
+ try { const d = el.contentDocument; if (d) walk(d, true, baseDepth + 1) } catch { /* cross-origin */ }
403
+ }
404
+ const role = roleOf(el)
405
+ if (role === 'none' || role === 'presentation' || role === 'generic') continue
406
+ if (!includeHidden && !visible(el)) continue
407
+ const name = nameOf(el, role)
408
+ if (!name && !ACTIONABLE.has(role)) continue
409
+ const a = absRect(el, el.ownerDocument)
410
+ out.push({
411
+ ref: out.length + 1,
412
+ role,
413
+ name: name.slice(0, 120),
414
+ value: valueOf(el),
415
+ states: statesOf(el),
416
+ depth: baseDepth + depthOf(el),
417
+ // Same derivation as the snapshot collector: an id or a name is what makes a node
418
+ // something the caller can point at without guessing at its text. The tool-layer
419
+ // schema declared this field before this line existed, so the schema was promising
420
+ // a value the tool never sent.
421
+ selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
422
+ tag: el.tagName.toLowerCase(),
423
+ x: Math.round(a.x + a.w / 2),
424
+ y: Math.round(a.y + a.h / 2),
425
+ ...inFrame ? { frame: true } : {},
426
+ })
427
+ }
428
+ }
429
+ walk(document, false, 0)
430
+ return { url: location.href, title: document.title || undefined, count: out.length, nodes: out, truncated: out.length >= maxNodes }
431
+ })()`
432
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
433
+ let result: { ok: true; value: unknown } | { ok: false; exception: string }
434
+ try {
435
+ result = await withTimeout(
436
+ handleSendEvaluate(tab.handle, script),
437
+ timeoutMs,
438
+ signal,
439
+ `browser: a11y timed out after ${timeoutMs}ms`,
440
+ timedOut => { this.interrupt(tab.handle, timedOut) },
441
+ ) as { ok: true; value: unknown } | { ok: false; exception: string }
442
+ } catch (error) {
443
+ if (error instanceof Error && error.name === 'TimeoutError') {
444
+ this.quarantine(tab.handle)
445
+ throw new BrowserError(
446
+ 'browser: a11y timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
447
+ 'BROWSER_A11Y_TIMEOUT',
448
+ { cause: error },
449
+ )
450
+ }
451
+ throw error
452
+ }
453
+ if (!result.ok) throw new BrowserError(`browser: a11y evaluation failed: ${result.exception}`, 'BROWSER_A11Y_FAILED')
454
+ const value = result.value as BrowserA11yResult
455
+ this.record(s, 'a11y', { includeHidden, maxNodes }, true, { result: `${value.count} nodes` })
456
+ return value
457
+ }
458
+
459
+ /** Check whether a human-verification challenge is blocking the active tab. */
460
+ async detectChallenge(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserChallenge> {
461
+ const s = this.session(session)
462
+ const tab = this.activeTab(s)
463
+ signal?.throwIfAborted()
464
+ const timeoutMs = PROVIDER_TIMEOUTS.action
465
+ const result = await withTimeout(
466
+ handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION),
467
+ timeoutMs,
468
+ signal,
469
+ `browser: challenge detection timed out after ${timeoutMs}ms`,
470
+ timedOut => { this.interrupt(tab.handle, timedOut) },
471
+ )
472
+ if (!result.ok) {
473
+ throw new BrowserError(`browser: challenge detection failed: ${result.exception}`, 'BROWSER_CHALLENGE_DETECT_FAILED')
474
+ }
475
+ const value = result.value as BrowserChallenge
476
+ return {
477
+ blocked: value.blocked === true,
478
+ kind: value.kind,
479
+ reason: value.reason,
480
+ ...value.recovery !== undefined ? { recovery: value.recovery } : {},
481
+ ...typeof value.status === 'number' ? { status: value.status } : {},
482
+ }
483
+ }
484
+
485
+ /** Fetch page content in a requested format. */
486
+ async content(session: BrowserSessionId, request: BrowserContentRequest, signal?: AbortSignal): Promise<BrowserContentResult> {
487
+ const tab = this.activeTab(this.session(session))
488
+ signal?.throwIfAborted()
489
+ const selector = request.selector ?? ''
490
+ const format = request.format
491
+ // Per-format caps. A full HTML document is enormous, but the same limit applied to
492
+ // plain text is no limit at all (a whole page of text measured 25,882 characters).
493
+ // This bounds the common case instead of letting one call spend 25k-33k tokens.
494
+ //
495
+ // The plugin config overrides the lot when it is set — see `contentMaxChars`. The caller's
496
+ // own `maxChars` still outranks both: an explicit per-call bound is the most specific
497
+ // statement of intent there is.
498
+ const maxChars = request.maxChars
499
+ ?? this.contentMaxChars
500
+ ?? (format === 'html' || format === 'json' ? 50_000 : 20_000)
501
+ const script = `(() => {${DEEP_DOM_SOURCE}
502
+ const root = ${selector === '' ? 'document.body' : `__dshQuery(${JSON.stringify(selector)})`}
503
+ if (!root) return { ok: false, reason: 'selector not found' }
504
+ const fmt = ${JSON.stringify(format)}
505
+ // Both walkers pierce shadow roots and same-origin iframes (cross-origin
506
+ // iframes stay opaque — the browser forbids reading them).
507
+ let content = ''
508
+ if (fmt === 'txt') {
509
+ // Prefer the browser's own rendered text.
510
+ //
511
+ // Walking text nodes and joining them is not equivalent: pages that wrap
512
+ // every character in its own element — one-character spans for a
513
+ // per-character animation, which is common — produce one text node per
514
+ // letter, and joining those with spaces turns every word into a column of
515
+ // letters. The rendered text reassembles them the way a reader sees them,
516
+ // and it also honours visibility, so hidden text does not leak out.
517
+ // (No backticks in this comment: it lives inside a template literal.)
518
+ const rendered = typeof root.innerText === 'string' ? root.innerText : ''
519
+ if (rendered.trim() !== '') {
520
+ content = rendered
521
+ } else {
522
+ // Fallback for nodes without layout (a detached root, or a fragment):
523
+ // collect text directly, still piercing shadow roots and same-origin
524
+ // iframes, and join without inventing separators beyond what the markup
525
+ // already implies.
526
+ const parts = []
527
+ const textWalk = (node) => {
528
+ if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
529
+ if (node.nodeType !== Node.ELEMENT_NODE) return
530
+ const tag = node.tagName.toLowerCase()
531
+ if (tag === 'script' || tag === 'style' || tag === 'noscript') return
532
+ if (tag === 'iframe') {
533
+ try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) textWalk(c) } catch { /* cross-origin */ }
534
+ return
535
+ }
536
+ if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) textWalk(c)
537
+ for (const child of node.childNodes) textWalk(child)
538
+ }
539
+ textWalk(root)
540
+ content = parts.join(' ')
541
+ }
542
+ }
543
+ else if (fmt === 'html') content = root.outerHTML || ''
544
+ // A DOM element has no own enumerable properties — everything lives on the prototype
545
+ // chain — so JSON.stringify(root) is always "{}". That is not a structured view of
546
+ // the page, it is an empty object the caller will read as "no data here" and then
547
+ // retry with other selectors. Serialise the markup instead, which is what a caller
548
+ // asking for JSON of an element can actually use.
549
+ else if (fmt === 'json') content = JSON.stringify({ html: root.outerHTML, tag: root.tagName.toLowerCase() })
550
+ else {
551
+ // markdown: headings, paragraphs, links, lists (best-effort)
552
+ const parts = []
553
+ const walk = (node) => {
554
+ if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
555
+ if (node.nodeType !== Node.ELEMENT_NODE) return
556
+ const tag = node.tagName.toLowerCase()
557
+ if (tag === 'script' || tag === 'style' || tag === 'noscript') return
558
+ if (tag === 'iframe') {
559
+ try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) walk(c) } catch { /* cross-origin */ }
560
+ return
561
+ }
562
+ if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) walk(c)
563
+ if (tag === 'h1' || tag === 'h2' || tag === 'h3' || tag === 'h4') parts.push('\\n' + '#'.repeat(Number(tag[1])) + ' ' + (node.textContent || '').trim() + '\\n')
564
+ else if (tag === 'a') { const t = (node.textContent || '').trim(); if (t) parts.push('[' + t + '](' + (node.href || '') + ')') }
565
+ else if (tag === 'li') parts.push(' - ' + (node.textContent || '').trim())
566
+ else if (tag === 'p' || tag === 'div' || tag === 'section' || tag === 'article') { const t = (node.textContent || '').trim(); if (t) parts.push(t + '\\n') }
567
+ else { for (const child of node.childNodes) walk(child) }
568
+ }
569
+ walk(root)
570
+ // Join without a separator: each part already carries its own trailing
571
+ // newline, so a space join would smear headings/links into run-on text.
572
+ content = parts.join('')
573
+ }
574
+ const truncated = content.length > ${String(maxChars)}
575
+ return { ok: true, content: content.slice(0, ${String(maxChars)}), truncated }
576
+ })()`
577
+ // Honor a per-call timeout: content evaluation can hang on a heavy page,
578
+ // so a caller-supplied budget bounds it. Unlike a bare signal entry check,
579
+ // withTimeout also interrupts a call already in flight.
580
+ const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
581
+ const result = await withTimeout(
582
+ handleSendEvaluate(tab.handle, script),
583
+ timeoutMs,
584
+ signal,
585
+ `browser: content timed out after ${timeoutMs}ms`,
586
+ timedOut => { this.interrupt(tab.handle, timedOut) },
587
+ )
588
+ if (!result.ok) throw new BrowserError(`browser: content evaluation failed: ${result.exception}`, 'BROWSER_CONTENT_FAILED')
589
+ const value = result.value as { ok: boolean; reason?: string; content?: string; truncated?: boolean }
590
+ if (!value.ok) throw new BrowserError(`browser: content fetch failed: ${value.reason ?? 'unknown'}`, 'BROWSER_CONTENT_FAILED')
591
+ return { content: value.content ?? '', truncated: value.truncated ?? false }
592
+ }
593
+
594
+ /**
595
+ * Extract structured data from repeated DOM items (static CSS, CSP-safe —
596
+ * no arbitrary code runs). Waits for the item selector, then maps each item
597
+ * through the field selectors; `selector@attr` reads an attribute instead
598
+ * of text (`a@href` yields an absolute URL).
599
+ */
600
+ async scrape(session: BrowserSessionId, request: BrowserScrapeRequest, signal?: AbortSignal): Promise<BrowserScrapeResult> {
601
+ const s = this.session(session)
602
+ const tab = this.activeTab(s)
603
+ signal?.throwIfAborted()
604
+ const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
605
+ const script = (sliceMs: number, last: boolean): string => `(async () => {${DEEP_DOM_SOURCE}
606
+ const itemSel = ${JSON.stringify(request.item)}
607
+ const fields = ${JSON.stringify(request.fields)}
608
+ const sliceMs = ${String(sliceMs)}
609
+ const last = ${String(last)}
610
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
611
+ const parseField = f => {
612
+ const m = /^(.*)@([A-Za-z][A-Za-z0-9_-]*)$/.exec(f.selector.trim())
613
+ if (m) return { base: m[1].trim(), attr: m[2] }
614
+ return { base: f.selector, attr: null }
615
+ }
616
+ const deadline = Date.now() + sliceMs
617
+ let items = []
618
+ for (;;) {
619
+ // Immediate, like match() above: an unparseable selector can never match.
620
+ try { items = __dshQueryAll(itemSel) }
621
+ catch (error) { return { ok: false, error: 'invalid CSS selector ' + JSON.stringify(itemSel) + ' (' + String((error && error.message) || error) + ')' } }
622
+ if (items.length > 0) break
623
+ if (Date.now() >= deadline) return last ? { ok: false, error: 'no elements matched: ' + itemSel } : { pending: true }
624
+ await sleep(100)
625
+ }
626
+ const out = []
627
+ for (const it of items) {
628
+ const row = {}
629
+ for (const f of fields) {
630
+ const { base, attr } = parseField(f)
631
+ let el = null
632
+ try { el = base === '' ? it : it.querySelector(base) } catch { el = null }
633
+ if (!el) { row[f.name] = null; continue }
634
+ if (attr !== null) {
635
+ const v = el.getAttribute(attr)
636
+ row[f.name] = attr === 'href' && el.tagName === 'A' && v ? new URL(v, el.baseURI).href : v
637
+ continue
638
+ }
639
+ row[f.name] = (el.textContent || '').trim()
640
+ }
641
+ out.push(row)
642
+ }
643
+ return { ok: true, count: out.length, items: out }
644
+ })()`
645
+ const deadline = Date.now() + timeoutMs
646
+ let value: { ok?: boolean; pending?: boolean; error?: string; count?: number; items?: Record<string, string | null>[] }
647
+ do {
648
+ const { sliceMs, last } = pagePollSlice(deadline)
649
+ const result = await withTimeout(
650
+ handleSendEvaluate(tab.handle, script(sliceMs, last)),
651
+ Math.max(sliceMs, deadline - Date.now()) + TARGET_SCRIPT_GRACE_MS,
652
+ signal,
653
+ `browser: scrape timed out after ${timeoutMs}ms`,
654
+ timedOut => { this.interrupt(tab.handle, timedOut) },
655
+ )
656
+ if (!result.ok) throw new BrowserError(`browser: scrape evaluation failed: ${result.exception}`, 'BROWSER_SCRAPE_FAILED')
657
+ value = result.value as typeof value
658
+ } while (value?.pending === true)
659
+ if (value.ok !== true) throw new BrowserError(`browser: scrape failed: ${value.error ?? 'unknown'}`, 'BROWSER_SCRAPE_FAILED')
660
+ const items = value.items ?? []
661
+ this.record(s, 'scrape', { item: request.item, fields: request.fields.map(f => f.name) }, true, { result: `${items.length} items` })
662
+ return { count: items.length, items }
663
+ }
664
+ }