dsh-builtin-browser 1.0.0 → 1.0.3

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 (364) hide show
  1. package/CHANGELOG.md +61 -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/pr64-maintenance.md +1 -1
  19. package/docs/tool-reference.md +1 -1
  20. package/docs/user-guide.md +1 -1
  21. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  22. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  23. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  24. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  25. package/dsh-host-patch/README.md +4 -0
  26. package/dsh-host-patch/apply.mjs +61 -13
  27. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  28. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  29. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  30. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  31. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  32. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  33. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  34. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  35. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  36. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  37. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  38. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  39. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  40. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  41. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  42. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  43. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  44. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  45. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  46. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  47. package/dsh-host-patch/sources/manifest.json +218 -0
  48. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  49. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  50. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  51. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  52. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  53. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  54. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  55. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  56. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  57. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  58. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  59. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  60. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  61. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  62. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  63. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  64. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  65. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  66. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  67. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  68. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  69. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  70. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  71. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  72. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  73. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  74. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  75. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  76. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  77. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  78. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  79. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  80. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  81. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  82. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  83. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  84. package/dsh-host-patch/sources/series.json +260 -0
  85. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  86. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  87. package/dsh-host-patch/tauri-revision1.json +39 -0
  88. package/dsh-host-patch/tauri.json +43 -0
  89. package/dsh-host-patch/v023-alpha2.json +153 -0
  90. package/lib/browser/anti-bot.js +215 -0
  91. package/lib/browser/deep-dom.js +39 -0
  92. package/lib/browser/runtime.js +15 -0
  93. package/lib/browser/takeover-target.js +13 -6
  94. package/lib/browser/types.js +30 -1
  95. package/lib/browser-electron/authenticated-route.js +16 -2
  96. package/lib/browser-electron/automatic-maintenance.js +16 -10
  97. package/lib/browser-electron/bridge-connection.js +3 -8
  98. package/lib/browser-electron/bridge-install.js +2 -1
  99. package/lib/browser-electron/bridge-status.js +55 -26
  100. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  101. package/lib/browser-electron/desktop-identity.js +28 -5
  102. package/lib/browser-electron/desktop-shell.js +64 -0
  103. package/lib/browser-electron/electron-provision.js +105 -18
  104. package/lib/browser-electron/entry.js +129 -46
  105. package/lib/browser-electron/extension-browser.js +4 -4
  106. package/lib/browser-electron/foreground-watch.js +134 -0
  107. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  108. package/lib/browser-electron/guest-route.js +181 -32
  109. package/lib/browser-electron/guest-runtime.js +61 -10
  110. package/lib/browser-electron/guest-storage.js +2 -2
  111. package/lib/browser-electron/history-store.js +1 -5
  112. package/lib/browser-electron/host-main.js +8 -4
  113. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  114. package/lib/browser-electron/maintenance-route.js +2 -1
  115. package/lib/browser-electron/missing-system-browser.js +5 -9
  116. package/lib/browser-electron/preferred-browser.js +7 -3
  117. package/lib/browser-electron/preview-route.js +9 -13
  118. package/lib/browser-electron/process-ownership.js +1 -1
  119. package/lib/browser-electron/profile-command.js +2 -1
  120. package/lib/browser-electron/profile-extension.js +5 -0
  121. package/lib/browser-electron/profile-lease.js +152 -47
  122. package/lib/browser-electron/provider-core.js +527 -0
  123. package/lib/browser-electron/provider-interaction.js +963 -0
  124. package/lib/browser-electron/provider-media.js +518 -0
  125. package/lib/browser-electron/provider-navigation.js +301 -0
  126. package/lib/browser-electron/provider-observation.js +623 -0
  127. package/lib/browser-electron/provider-tabs.js +372 -0
  128. package/lib/browser-electron/provider.js +150 -3301
  129. package/lib/browser-electron/reference-route.js +9 -18
  130. package/lib/browser-electron/remote-host.js +79 -34
  131. package/lib/browser-electron/runtime-status.js +56 -6
  132. package/lib/browser-electron/settings-store.js +3 -6
  133. package/lib/browser-electron/sidebar-only-host.js +1 -1
  134. package/lib/browser-electron/system-browser.js +539 -172
  135. package/lib/browser-electron/tauri-host.js +208 -0
  136. package/lib/browser-electron/virtual-cursor.js +23 -13
  137. package/lib/browser-reference/service.js +22 -4
  138. package/lib/browser-reference/web-sources.js +1 -1
  139. package/lib/client.js +43409 -0
  140. package/lib/compat/host-features.js +75 -0
  141. package/lib/reference-source.js +1 -1
  142. package/lib/reference-text.js +23 -1
  143. package/lib/takeover-protocol.js +1 -1
  144. package/lib/tool-browser/block-recovery.js +69 -0
  145. package/lib/tool-browser/code-tool.js +170 -19
  146. package/lib/tool-browser/code-worker.js +115 -20
  147. package/lib/tool-browser/errors.js +34 -0
  148. package/lib/tool-browser/index.js +66 -3593
  149. package/lib/tool-browser/page-probe.js +227 -28
  150. package/lib/tool-browser/panel-page.js +2 -1
  151. package/lib/tool-browser/probe-client.js +157 -0
  152. package/lib/tool-browser/screenshot-annotations.js +108 -0
  153. package/lib/tool-browser/state.js +337 -0
  154. package/lib/tool-browser/takeover.js +1 -1
  155. package/lib/tool-browser/tools-debug.js +862 -0
  156. package/lib/tool-browser/tools-interaction.js +993 -0
  157. package/lib/tool-browser/tools-navigation.js +807 -0
  158. package/lib/tool-browser/tools-observation.js +461 -0
  159. package/lib/tool-browser/tools-reference.js +293 -0
  160. package/lib/web-guest.js +1 -0
  161. package/package.json +16 -54
  162. package/README.en.md +0 -89
  163. package/browser-extension/constants.mjs +0 -20
  164. package/browser-extension/controller.mjs +0 -293
  165. package/browser-extension/locales.mjs +0 -15
  166. package/browser-extension/manifest.json +0 -12
  167. package/browser-extension/options.html +0 -14
  168. package/browser-extension/options.mjs +0 -9
  169. package/browser-extension/permission-guard.mjs +0 -13
  170. package/browser-extension/worker.mjs +0 -74
  171. package/dist/client.cjs +0 -43167
  172. package/lib/browser-electron/package-removal.js +0 -5
  173. package/lib/browser-reference/submission-receipts.js +0 -139
  174. package/scripts/build.mjs +0 -66
  175. package/scripts/bundle-host.mjs +0 -28
  176. package/scripts/fix-exports.mjs +0 -50
  177. package/scripts/install-electron.mjs +0 -51
  178. package/scripts/verify-exports.mjs +0 -47
  179. package/scripts/verify-preview-sdk.mjs +0 -93
  180. package/skills/dsh-builtin-browser/SKILL.md +0 -73
  181. package/skills/dsh-builtin-browser/references/batch.md +0 -53
  182. package/skills/dsh-builtin-browser/references/deliver.md +0 -31
  183. package/skills/dsh-builtin-browser/references/locate.md +0 -11
  184. package/skills/dsh-builtin-browser/references/recover.md +0 -11
  185. package/skills/dsh-builtin-browser/references/verify.md +0 -13
  186. package/skills/dsh-debug-host/SKILL.md +0 -56
  187. package/skills/dsh-debug-self/SKILL.md +0 -50
  188. package/src/bridge-compatibility.ts +0 -39
  189. package/src/browser/handles.ts +0 -89
  190. package/src/browser/runtime.ts +0 -560
  191. package/src/browser/takeover-target.ts +0 -36
  192. package/src/browser/types.ts +0 -817
  193. package/src/browser-electron/authenticated-route.ts +0 -84
  194. package/src/browser-electron/automatic-maintenance.ts +0 -726
  195. package/src/browser-electron/bridge-auto.ts +0 -159
  196. package/src/browser-electron/bridge-connection.ts +0 -385
  197. package/src/browser-electron/bridge-endpoint.ts +0 -129
  198. package/src/browser-electron/bridge-install.ts +0 -289
  199. package/src/browser-electron/bridge-maintenance.ts +0 -189
  200. package/src/browser-electron/bridge-status.ts +0 -347
  201. package/src/browser-electron/desktop-bridge-host.ts +0 -251
  202. package/src/browser-electron/desktop-identity.ts +0 -320
  203. package/src/browser-electron/document-readiness.ts +0 -45
  204. package/src/browser-electron/electron-provision.ts +0 -261
  205. package/src/browser-electron/entry.ts +0 -1301
  206. package/src/browser-electron/ephemeral-profile.ts +0 -189
  207. package/src/browser-electron/extension-browser.ts +0 -223
  208. package/src/browser-electron/extension-setup.ts +0 -67
  209. package/src/browser-electron/file-write.ts +0 -31
  210. package/src/browser-electron/guest-cookie-jar.ts +0 -176
  211. package/src/browser-electron/guest-cookie-store.ts +0 -59
  212. package/src/browser-electron/guest-css-runtime.ts +0 -76
  213. package/src/browser-electron/guest-css.ts +0 -68
  214. package/src/browser-electron/guest-route.ts +0 -568
  215. package/src/browser-electron/guest-runtime.ts +0 -357
  216. package/src/browser-electron/guest-storage-runtime.ts +0 -54
  217. package/src/browser-electron/guest-storage.ts +0 -117
  218. package/src/browser-electron/history-store.ts +0 -227
  219. package/src/browser-electron/host-main.ts +0 -1381
  220. package/src/browser-electron/host-patch-maintenance.ts +0 -112
  221. package/src/browser-electron/http-body.ts +0 -65
  222. package/src/browser-electron/json-reply.ts +0 -47
  223. package/src/browser-electron/maintenance-broker.ts +0 -166
  224. package/src/browser-electron/maintenance-lifecycle.ts +0 -91
  225. package/src/browser-electron/maintenance-route.ts +0 -67
  226. package/src/browser-electron/missing-system-browser.ts +0 -113
  227. package/src/browser-electron/open-slot.ts +0 -49
  228. package/src/browser-electron/package-removal.ts +0 -4
  229. package/src/browser-electron/paths.ts +0 -25
  230. package/src/browser-electron/preferred-browser.ts +0 -120
  231. package/src/browser-electron/preview-route.ts +0 -218
  232. package/src/browser-electron/process-ownership.ts +0 -168
  233. package/src/browser-electron/process.ts +0 -23
  234. package/src/browser-electron/profile-checkpoint.ts +0 -187
  235. package/src/browser-electron/profile-command.ts +0 -46
  236. package/src/browser-electron/profile-extension.ts +0 -124
  237. package/src/browser-electron/profile-lease.ts +0 -115
  238. package/src/browser-electron/profile-residue.ts +0 -49
  239. package/src/browser-electron/provider.ts +0 -4571
  240. package/src/browser-electron/reference-route.ts +0 -608
  241. package/src/browser-electron/remote-host.ts +0 -1462
  242. package/src/browser-electron/rpc-input.ts +0 -13
  243. package/src/browser-electron/rpc-ops.ts +0 -41
  244. package/src/browser-electron/runtime-diagnostics.ts +0 -38
  245. package/src/browser-electron/runtime-route.ts +0 -105
  246. package/src/browser-electron/runtime-status.ts +0 -242
  247. package/src/browser-electron/settings-route.ts +0 -64
  248. package/src/browser-electron/settings-store.ts +0 -589
  249. package/src/browser-electron/shortcuts-route.ts +0 -112
  250. package/src/browser-electron/sidebar-only-host.ts +0 -298
  251. package/src/browser-electron/startpage-shortcuts.ts +0 -213
  252. package/src/browser-electron/system-browser.ts +0 -1497
  253. package/src/browser-electron/timing.ts +0 -16
  254. package/src/browser-electron/virtual-cursor.ts +0 -152
  255. package/src/browser-electron/windows-system.ts +0 -24
  256. package/src/browser-reference/delivery.ts +0 -384
  257. package/src/browser-reference/entry.ts +0 -631
  258. package/src/browser-reference/export.ts +0 -339
  259. package/src/browser-reference/import.ts +0 -303
  260. package/src/browser-reference/page-script.ts +0 -1537
  261. package/src/browser-reference/service.ts +0 -1315
  262. package/src/browser-reference/store.ts +0 -172
  263. package/src/browser-reference/submission-receipts.ts +0 -122
  264. package/src/browser-reference/text-quote.ts +0 -219
  265. package/src/browser-reference/types.ts +0 -195
  266. package/src/browser-reference/visible.ts +0 -367
  267. package/src/browser-reference/web-sources.ts +0 -103
  268. package/src/client/browser/BrowserController.ts +0 -693
  269. package/src/client/browser/BrowserFrame.ts +0 -78
  270. package/src/client/browser/BrowserNavigation.ts +0 -169
  271. package/src/client/browser/BrowserPage.ts +0 -23
  272. package/src/client/browser/BrowserPersistence.ts +0 -44
  273. package/src/client/browser/IframeImpl.ts +0 -176
  274. package/src/client/browser/child-tabs.ts +0 -14
  275. package/src/client/browser/iframe-reference.ts +0 -67
  276. package/src/client/browser/initialization.ts +0 -262
  277. package/src/client/browser/omnibox.ts +0 -243
  278. package/src/client/browser/store.ts +0 -38
  279. package/src/client/browser/takeover-channel.ts +0 -72
  280. package/src/client/browser/url.ts +0 -46
  281. package/src/client/browser/web-reference-source.ts +0 -52
  282. package/src/client/css-modules.d.ts +0 -4
  283. package/src/client/definition.tsx +0 -30
  284. package/src/client/electron/ElectronWebViewImpl.ts +0 -364
  285. package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
  286. package/src/client/electron/NativeChildPresentation.ts +0 -45
  287. package/src/client/electron/NativeViewPage.ts +0 -251
  288. package/src/client/electron/pages.ts +0 -23
  289. package/src/client/electron/reference-overlay.ts +0 -53
  290. package/src/client/electron/workspace.ts +0 -33
  291. package/src/client/index.ts +0 -293
  292. package/src/client/locales.ts +0 -857
  293. package/src/client/pages.ts +0 -28
  294. package/src/client/reference/client/BrowserRefLink.tsx +0 -142
  295. package/src/client/reference/client/draft-reference.ts +0 -167
  296. package/src/client/reference/client/index.ts +0 -7
  297. package/src/client/reference/client/ordered-submission.ts +0 -108
  298. package/src/client/reference/client/pending-delivery.ts +0 -216
  299. package/src/client/reference/client/plugin.ts +0 -189
  300. package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
  301. package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
  302. package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
  303. package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
  304. package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
  305. package/src/client/reference/client/production/ReferenceText.tsx +0 -36
  306. package/src/client/reference/client/production/assembly.ts +0 -471
  307. package/src/client/reference/client/production/asset-store.ts +0 -144
  308. package/src/client/reference/client/production/availability.ts +0 -74
  309. package/src/client/reference/client/production/bytes.ts +0 -36
  310. package/src/client/reference/client/production/delivery-client.ts +0 -211
  311. package/src/client/reference/client/production/draft-adapter.ts +0 -508
  312. package/src/client/reference/client/production/http-transport.ts +0 -217
  313. package/src/client/reference/client/production/production-submission.ts +0 -310
  314. package/src/client/reference/client/production/protocol.ts +0 -231
  315. package/src/client/reference/client/production/reference-card.ts +0 -240
  316. package/src/client/reference/client/production/reference-labels.ts +0 -29
  317. package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
  318. package/src/client/reference/client/production/reveal.ts +0 -215
  319. package/src/client/reference/client/production/runtime.ts +0 -1101
  320. package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
  321. package/src/client/reference/client/production/source-marker.ts +0 -63
  322. package/src/client/reference/client/production/source-opener.ts +0 -55
  323. package/src/client/reference/client/production/styles.ts +0 -104
  324. package/src/client/reference/client/production/user-text-rule.ts +0 -58
  325. package/src/client/reference/client/reveal.ts +0 -107
  326. package/src/client/reference/client/scheme.ts +0 -114
  327. package/src/client/reference/client/types.ts +0 -168
  328. package/src/client/reference/css-modules.d.ts +0 -4
  329. package/src/client/reference/index.ts +0 -11
  330. package/src/client/reference-capture-owner.ts +0 -162
  331. package/src/client/reference-intents.ts +0 -36
  332. package/src/client/settings/index.ts +0 -34
  333. package/src/client/settings/panel.ts +0 -2657
  334. package/src/client/shortcut-open.ts +0 -30
  335. package/src/client/startpage/binding.ts +0 -99
  336. package/src/client/startpage/controller.ts +0 -303
  337. package/src/client/startpage/model.ts +0 -279
  338. package/src/client/view/Browser.module.css +0 -751
  339. package/src/client/view/BrowserBody.tsx +0 -314
  340. package/src/client/view/BrowserPresentation.ts +0 -9
  341. package/src/client/view/BrowserTitle.tsx +0 -17
  342. package/src/client/view/IframePresentation.ts +0 -344
  343. package/src/client/view/StartPage.tsx +0 -597
  344. package/src/client/view/TakeoverBanner.tsx +0 -21
  345. package/src/index.ts +0 -110
  346. package/src/reference-owner.ts +0 -5
  347. package/src/reference-page.ts +0 -9
  348. package/src/reference-source.ts +0 -3
  349. package/src/reference-text.ts +0 -197
  350. package/src/startpage-settings.ts +0 -103
  351. package/src/startpage.ts +0 -71
  352. package/src/takeover-protocol.ts +0 -19
  353. package/src/tool-browser/code-tool.ts +0 -401
  354. package/src/tool-browser/code-worker.ts +0 -639
  355. package/src/tool-browser/element-fields.ts +0 -167
  356. package/src/tool-browser/index.ts +0 -3733
  357. package/src/tool-browser/page-probe.ts +0 -474
  358. package/src/tool-browser/panel-page.ts +0 -124
  359. package/src/tool-browser/screenshot-image.ts +0 -49
  360. package/src/tool-browser/takeover.ts +0 -198
  361. package/src/types/electron-shim.d.ts +0 -144
  362. package/src/types.ts +0 -85
  363. package/src/web-guest.ts +0 -34
  364. package/tools/accept-desktop.mjs +0 -148
@@ -1,4571 +0,0 @@
1
- import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
- import { hostMessages } from '../../assets/browser-messages.mjs'
3
- /**
4
- * Electron-backed browser provider: `WebContentsView` sessions driven over
5
- * `webContents.debugger` (CDP). The provider itself does not import Electron — it operates through the {@link ElectronBrowserViewHost} seam, which the
6
- * desktop shell implements with real Electron objects. That keeps this
7
- * package testable under plain Node and leaves the Electron dependency to the
8
- * shell that owns the `BrowserWindow`.
9
- * @module dsh-browser/browser-electron
10
- */
11
-
12
- import { pageOperationScript } from '../tool-browser/page-probe.ts'
13
- import { dispatchReferenceCaptureAction } from '../browser-reference/service.ts'
14
- import {
15
- MAX_REFERENCE_COMMENT, REFERENCE_INTENT_CHANNEL, overlayScript, standaloneScript,
16
- } from '../browser-reference/entry.ts'
17
- import { noticeScript, validateFrozenCapture, type RawCaptureResult } from '../browser-reference/page-script.ts'
18
- import { randomUUID } from 'node:crypto'
19
- import { setLastOpen } from './open-slot.ts'
20
- import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs'
21
- import { writeFileNoReplace } from './file-write.ts'
22
- import { homedir } from 'node:os'
23
- import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
24
- import { HistoryStore, type VisitedPage } from './history-store.ts'
25
- import type { BrowserSettings } from './settings-store.ts'
26
- import { forgetCursor, paintCursor, type CursorAction } from './virtual-cursor.ts'
27
- import { documentReady, mainDocument, type DocumentIdentity } from './document-readiness.ts'
28
- import type {
29
- BrowserA11yRequest,
30
- BrowserA11yResult,
31
- BrowserChallenge,
32
- BrowserCheckRequest,
33
- BrowserClearRequest,
34
- BrowserClickRequest,
35
- BrowserClickSequenceRequest,
36
- BrowserClickSequenceResult,
37
- BrowserContentRequest,
38
- BrowserContentResult,
39
- BrowserElementTarget,
40
- BrowserExecuteRequest,
41
- BrowserPageOperationRequest,
42
- BrowserExecuteResult,
43
- BrowserFillRequest,
44
- BrowserFillResult,
45
- BrowserGetValueRequest,
46
- BrowserGetValueResult,
47
- BrowserHistoryEntry,
48
- BrowserOpenRequest,
49
- BrowserProvider,
50
- BrowserScrapeRequest,
51
- BrowserScrapeResult,
52
- BrowserScreenshotRequest,
53
- BrowserSelectRequest,
54
- BrowserSelectResult,
55
- BrowserSessionId,
56
- BrowserSetValueRequest,
57
- BrowserSetValueResult,
58
- BrowserSnapshotResult,
59
- BrowserTab,
60
- BrowserTypeRequest,
61
- BrowserWaitRequest,
62
- BrowserWaitResult,
63
- BrowserScrollRequest,
64
- BrowserKeyRequest,
65
- ExportedCookie,
66
- } from '../browser/types.ts'
67
- import { BrowserError } from '../browser/types.ts'
68
- import { browserSessionHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId, type BrowserTabWireId } from '../browser/handles.ts'
69
- import type { CarrierPage, CarrierLossReason } from '../browser/types.ts'
70
- import type { BrowserReferenceTarget } from '../browser-reference/types.ts'
71
-
72
- /**
73
- * Consecutive failed evaluations after which the reference pump forgets an
74
- * adopted sidebar tab. One or two misses are a navigation; five (≈6 s at the
75
- * pump's 1.2 s tick) mean the page the human had is gone.
76
- */
77
- const DEAD_REFERENCE_TAB_MISSES = 5
78
- /** How long a tab that stopped answering waits before the pump tries it again. */
79
- const DEAD_REFERENCE_TAB_RETRY_MS = 15_000
80
- const PROVIDER_TIMEOUTS = Object.freeze({
81
- evaluation: 3_000,
82
- interaction: 5_000,
83
- lookup: 10_000,
84
- action: 15_000,
85
- prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
86
- download: 60_000,
87
- })
88
-
89
- /**
90
- * Page-context human-verification (CAPTCHA / bot-detection) detection. Runs
91
- * inside the page; returns `{ blocked, kind?, reason? }`. Marker-based and
92
- * best-effort: checks for Cloudflare's interstitial, hCaptcha, reCAPTCHA,
93
- * Turnstile, and generic challenge wording.
94
- */
95
- const CHALLENGE_DETECT_EXPRESSION = `(() => {
96
- const title = (document.title || '').trim()
97
- const bodyText = (document.body && document.body.innerText || '').slice(0, 4000)
98
- // Challenge widgets often live in same-origin iframes or shadow roots;
99
- // scan those too (cross-origin frames stay opaque).
100
- let extraText = ''
101
- try {
102
- const seen = new Set()
103
- const scan = (doc) => {
104
- if (seen.has(doc)) return
105
- seen.add(doc)
106
- for (const el of doc.querySelectorAll('*')) {
107
- if (el.shadowRoot) {
108
- extraText += (el.shadowRoot.textContent || '').slice(0, 2000)
109
- scan(el.shadowRoot)
110
- }
111
- if (el.tagName === 'IFRAME') {
112
- try {
113
- const d = el.contentDocument
114
- if (d) {
115
- extraText += ((d.body && d.body.innerText) || '').slice(0, 2000)
116
- scan(d)
117
- }
118
- } catch { /* cross-origin */ }
119
- }
120
- }
121
- }
122
- scan(document)
123
- } catch { /* never fail the challenge check */ }
124
- const lower = (title + '\\n' + bodyText + '\\n' + extraText).toLowerCase()
125
- const frameSrcs = [...document.querySelectorAll('iframe')].map(f => f.src || '').join(' ')
126
- const framesLower = frameSrcs.toLowerCase()
127
- const hasCfInterstitial = /just a moment|checking your browser|attention required|cf_chl/i.test(lower)
128
- || !!document.querySelector('#challenge-running, #challenge-stage, #cf-chl-container')
129
- const hasHCaptcha = !!window.hcaptcha || !!document.querySelector('.h-captcha') || /hcaptcha\\.com/i.test(framesLower)
130
- const hasRecaptcha = !!window.grecaptcha || !!document.querySelector('.g-recaptcha') || /recaptcha\\/api|google\\.com\\/recaptcha/i.test(framesLower)
131
- const hasTurnstile = !!window.turnstile || /challenges\\.cloudflare\\.com/i.test(framesLower) || /turnstile|challenge-platform/i.test(lower)
132
- const verifyWording = /verify you are human|verify you are not a robot|\\u4eba\\u673a\\u9a8c\\u8bc1|\\u5b89\\u5168\\u9a8c\\u8bc1|enable javascript and cookies|\\u8bf7.*\\u9a8c\\u8bc1/i.test(lower)
133
- if (hasCfInterstitial) return { blocked: true, kind: 'cloudflare', reason: 'Cloudflare "Just a moment" interstitial' }
134
- if (hasHCaptcha) return { blocked: true, kind: 'hcaptcha', reason: 'hCaptcha verification' }
135
- if (hasRecaptcha) return { blocked: true, kind: 'recaptcha', reason: 'Google reCAPTCHA verification' }
136
- if (hasTurnstile) return { blocked: true, kind: 'turnstile', reason: 'Cloudflare Turnstile verification' }
137
- if (verifyWording && /challenge|captcha|verification|security check|access denied|blocked|\\u9a8c\\u8bc1/i.test(lower)) {
138
- return { blocked: true, kind: 'generic', reason: 'Human-verification challenge' }
139
- }
140
- return { blocked: false }
141
- })()`
142
-
143
- /** Stable provider id registered with `ctx.browser`. */
144
- export const ELECTRON_BROWSER_PROVIDER_ID = 'electron'
145
-
146
- /**
147
- * The minimal Electron surface this provider needs. Implemented by the
148
- * desktop shell with a real `WebContentsView`; a fake implements it in tests.
149
- */
150
- export interface ElectronBrowserViewHost {
151
- prepare?(scope?: BrowserSessionId): Promise<void>
152
- readonly referenceOverlayOwner?: 'client'
153
- referenceOverlayOwnerFor?(scope: BrowserSessionId): 'client' | undefined
154
- retireSession?(scope: BrowserSessionId): Promise<void>
155
- /**
156
- * Create a new browser view and return a handle to its webContents-like
157
- * surface. The host owns windowing (adding the view to the window, sizing,
158
- * removal); the provider owns CDP-driven behavior.
159
- * @param owner - the conversation this view serves. A host shared by several conversations
160
- * needs it to keep one conversation's page out of another's; a host with one conversation per
161
- * process may ignore it. It is per VIEW and not per host on purpose: the desktop's host is a
162
- * single instance that every conversation runs through, so an owner held there would be one
163
- * conversation's id applied to all of them.
164
- */
165
- createView(identity: BrowserTabWireId): ElectronViewHandle
166
- /**
167
- * Destroy a view created by this host. Called on session close; idempotent
168
- * for an already-destroyed view.
169
- * @param handle - the handle returned by {@link createView}.
170
- */
171
- destroyView(handle: ElectronViewHandle, options?: { readonly keepPage?: boolean }): void
172
- /**
173
- * Show one view as the session's visible surface. The host keeps exactly
174
- * one visible; switching tabs reorders visibility without losing state.
175
- * Optional: a host without visible-tab switching treats every view as
176
- * always present (acceptable for headless/probe hosts).
177
- * @param handle - the handle to make visible.
178
- * @param label - human-readable session/task label, when the provider knows
179
- * one; the host may surface it (e.g. in the window title) so a human can
180
- * tell which task's page is currently visible.
181
- * @param options - presentation policy; `quiet` asks for a surface without taking
182
- * over the screen (see {@link PresentOptions}).
183
- */
184
- showView?(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void
185
- /**
186
- * Optional: (re)present a view and WAIT until the host confirms it. Chromium
187
- * silently drops CDP-synthesized input (`Input.*`) for a view that has no
188
- * display surface, which made clicks/typing report success while the page
189
- * received nothing (and made the first input after a navigation vanish,
190
- * because the replaced renderer has no surface yet). Unlike
191
- * {@link showView}, this round-trips an RPC barrier that is ordered AFTER
192
- * the show on the same socket, so its reply means the view is on screen.
193
- * Rejects when the view cannot be presented; a host without this method is
194
- * assumed to present every view (headless/probe hosts).
195
- * @param handle - the handle to present.
196
- * @param label - human-readable session/task label, as in {@link showView}.
197
- * @param options - presentation policy, as in {@link showView}.
198
- */
199
- presentView?(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void>
200
- /**
201
- * Optional: pages this carrier holds that the provider never created.
202
- *
203
- * A sidebar panel and an installed browser both own their own page creation. Clicking a link
204
- * that opens a new page — or any `window.open` the page performs — produces a page the provider
205
- * did not ask for and therefore never recorded. Those pages are real: they are what the human
206
- * sees, they hold memory, and they persist until something closes them. Without this the tab
207
- * model reports only what the provider itself made, so the extras are invisible to
208
- * `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`, accumulating for the
209
- * life of the browser.
210
- *
211
- * Views the host itself opened are NOT included. That exclusion belongs to the host, which is the
212
- * only side that can make it: a provider tab is identified by the provider's own id and a carrier
213
- * page by the carrier's, so a caller comparing the two matches nothing and reports every page
214
- * twice. Measured on the sidebar carrier: three clicks produced three webview guests while
215
- * `dsh_browser_list_tabs` reported one tab; on the installed-browser carrier the window held four
216
- * pages and the tool reported one.
217
- * @param owner - the calling task/conversation; shared sidebar hosts must scope to it.
218
- * @param options - `requireRunning` lists only from a carrier that is already
219
- * running. A background scan (the reference-bar pump) must use it: opening
220
- * the human's installed browser just to look for a page is a side effect
221
- * nobody asked for.
222
- * @returns every page this conversation's carrier holds that this host did not open.
223
- */
224
- listPages?(scope: BrowserSessionId, options?: { readonly requireRunning?: boolean }): Promise<readonly CarrierPage[]>
225
- /**
226
- * Optional: take over one page reported by {@link listPages}, so it becomes a page this provider
227
- * drives rather than one it can only see.
228
- *
229
- * Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
230
- * produced a SECOND page — the human's own tab was listed (under `page:`) and closable, but not
231
- * readable, which is the opposite of "the page you are looking at". A carrier that cannot do this
232
- * must leave it undefined rather than pretend: a switch that reported success and then read
233
- * nothing is the failure this removes.
234
- * @param viewId - the view to bind the page to.
235
- * @param id - the carrier's own page id, as {@link listPages} reported it.
236
- * @returns a handle for that page, usable for commands like any other view's.
237
- */
238
- adoptPage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<ElectronViewHandle>
239
- /**
240
- * Optional: close one page reported by {@link listPages}.
241
- *
242
- * The pair exists because listing a page the caller cannot close is worse than not listing it:
243
- * `dsh_browser_list_tabs` would report pages that `dsh_browser_close_tab` answers "not open in
244
- * this session" about, which reads as a contradiction rather than a boundary.
245
- * @param id - the carrier's own page id, as {@link listPages} reported it.
246
- * @param owner - the same task/conversation used for listing; never a global fallback.
247
- */
248
- closePage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<void>
249
- /**
250
- * Optional cheap usability probe (no network): whether the host can back
251
- * views at all right now. The self-hosted host checks for a usable Electron
252
- * binary; a host without the probe is assumed usable. Lets the seam's
253
- * provider selection (BROWSER_PROVIDER_UNAVAILABLE etc.) be real instead
254
- * of failing only at first use.
255
- */
256
- available?(): boolean
257
- /**
258
- * Tell the human that a toolbar action the agent could not complete has failed.
259
- *
260
- * Optional. Declared rather than reached through a cast because this is what issue #16 was:
261
- * the call used to be unbound, so `this` inside the host's implementation was undefined and
262
- * its first statement threw — inside an async catch, which turned it into an unhandled
263
- * rejection that took the whole DSH process down. A declared member is checkable; a cast is
264
- * not.
265
- * @param windowId - the window the action came from.
266
- * @param message - what to show the human.
267
- */
268
- notifyUserActionError?(windowId: string, message: string): void
269
- /**
270
- * Optional: associate a view with a window group. Views grouped under the
271
- * same `windowId` share one window (one window per browser session); a host
272
- * without this keeps a single shared window. Called right after
273
- * `createView`, so the host may route the view to its own window even
274
- * before the first command materializes it.
275
- * @param handle - the view to group.
276
- * @param windowId - the group (session) key.
277
- * @param label - human-readable label for the window title.
278
- */
279
- groupView?(handle: ElectronViewHandle, windowId: string, label?: string): void
280
- /**
281
- * Optional: receive user-initiated browser actions from the host's own UI
282
- * (e.g. a toolbar address bar, back/forward buttons, tab strip). The
283
- * provider routes them into the session model so the agent and the human
284
- * always see the same tabs and navigation state.
285
- * @param handler - called for every user action; must not throw.
286
- */
287
- onUserAction?(handler: (action: BrowserUserAction) => void): void
288
- /**
289
- * Optional: receive notice that the human closed a browser window. Closing the
290
- * interface ends the session it showed — the next call opens a clean one —
291
- * while browsing history and login state survive on disk.
292
- * @param handler - called with the group (session) key; must not throw.
293
- */
294
- onViewClosed?(handler: (windowId: string) => void): void
295
- /**
296
- * Release the service's page(s) without ending the plugin's own lifetime.
297
- *
298
- * Only carriers that outlive a browser session need this. A self-hosted window
299
- * dies with its view, but the desktop shell's sidebar keeps running no matter
300
- * what the plugin does — so "release the browser when the session ends"
301
- * (settings: ui.closeWithSession) has to be asked for explicitly there.
302
- * @returns a promise that settles once the release was attempted.
303
- */
304
- /**
305
- * Release this carrier's browser pages for one conversation.
306
- * @param owner - the conversation whose pages to close. Omit to close every conversation's,
307
- * which is only correct from a teardown that is itself global.
308
- */
309
- releasePage?(scope?: BrowserSessionId): Promise<void>
310
- /**
311
- * Report that this carrier can no longer serve anything, so its owner may replace it.
312
- *
313
- * A carrier that borrows an outside process can lose it: the desktop shell exits, and every call
314
- * after that would dial a port nobody owns. Without this signal the swap happens only at
315
- * startup, so the choice made then is final for the process's life — which is what a user
316
- * experiences as "the browser stopped working until I restart DSH". Optional: a carrier that
317
- * owns its own lifetime has nothing to report.
318
- *
319
- * The listener receives WHY, because the fallback's message has to match what happened: a shell
320
- * that exited and a shell whose panel cannot provide a page both reach the same fallback, and
321
- * announcing "the shell has exited" for the second tells the user their desktop crashed when it
322
- * did not.
323
- * @param listener - called once, when the carrier concludes it is gone.
324
- */
325
- onLost?(listener: (reason: CarrierLossReason) => void): void
326
- /**
327
- * Fold the carrier's presentation away while keeping the page alive.
328
- *
329
- * The desktop sidebar keeps running regardless of the plugin, so "do not take
330
- * over the screen" (settings: ui.autoExpandOnce = false) can only be honoured by
331
- * asking the shell to fold it. A self-hosted window has no such state and simply
332
- * does not implement this.
333
- * @returns a promise that settles once the fold was attempted.
334
- */
335
- collapse?(): Promise<void>
336
- /**
337
- * Release everything the carrier owns (a spawned browser, a socket, a child).
338
- * Called when the plugin stops using it, never while it is still in service.
339
- */
340
- dispose?(): void
341
- }
342
-
343
- /**
344
- * A user-initiated browser action from the host's own UI (toolbar). The
345
- * `windowId` is the session id the view was grouped under, so the provider
346
- * can route the action to the right session.
347
- */
348
- export type BrowserUserAction =
349
- | { readonly type: 'navigate'; readonly windowId: string; readonly url: string }
350
- | { readonly type: 'newTab'; readonly windowId: string; readonly url?: string }
351
- | { readonly type: 'activateTab'; readonly windowId: string; readonly viewId: string }
352
- | { readonly type: 'closeTab'; readonly windowId: string; readonly viewId: string }
353
- | { readonly type: 'back'; readonly windowId: string }
354
- | { readonly type: 'forward'; readonly windowId: string }
355
- | { readonly type: 'reload'; readonly windowId: string }
356
- | {
357
- readonly type: 'capture-reference'
358
- readonly windowId: string
359
- readonly entry: 'native-menu' | 'page-overlay'
360
- readonly frameSelector?: string
361
- /** The exact image/table the human right-clicked, if any. */
362
- readonly target?: BrowserReferenceTarget
363
- /** The note typed in the selection bar. */
364
- readonly comment?: string
365
- /**
366
- * The selection text the bar froze before its comment field took focus.
367
- * Used to locate the capture again when the live selection is gone.
368
- */
369
- readonly selectionText?: string
370
- /**
371
- * The complete ordered capture the bar froze at that same moment (text
372
- * runs, assets, table ranges, anchors). Preferred over `selectionText`.
373
- */
374
- readonly capture?: RawCaptureResult
375
- }
376
-
377
- /**
378
- * A CDP-capable view handle. This is the subset of Electron's
379
- * `WebContents`/`WebContentsView` the provider drives; the shell's real
380
- * implementation adapts `webContents.debugger` to it.
381
- */
382
- export interface ElectronViewHandle {
383
- /** Unique id of the backing view, used for diagnostics. */
384
- readonly id: string
385
- /**
386
- * Send one CDP command and resolve with its result. Rejects when the
387
- * debugger is not attached or the command fails.
388
- * @param method - CDP method, e.g. `Page.navigate`.
389
- * @param params - CDP command parameters.
390
- * @returns the CDP `result` object.
391
- */
392
- sendCommand(method: string, params?: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>
393
- /**
394
- * Whether this view's CDP can encode JPEG and honour a quality setting.
395
- *
396
- * Electron 43's CDP hangs on `Page.captureScreenshot` with `format: 'jpeg'`, so a view
397
- * backed by Electron must leave this unset and the provider keeps to PNG. A view backed
398
- * by an installed Chrome or Edge is the real browser, where JPEG works, and sets it so
399
- * the requested format is not silently downgraded.
400
- */
401
- readonly supportsCdpJpeg?: boolean
402
- /**
403
- * Give the backing view web focus so keyboard input reaches its page.
404
- * Optional: an adapter that cannot focus a view omits it, and the provider
405
- * then behaves exactly as before.
406
- */
407
- focus?(options?: PresentOptions): Promise<void>
408
- /**
409
- * Save a URL straight to disk, when the backing view can do that itself.
410
- *
411
- * Optional. Declared here rather than reached through a structural cast at the call site:
412
- * a cast tells the compiler nothing, so a host that implements the interface without this
413
- * method compiles and then silently does nothing.
414
- * @param url - the URL to fetch.
415
- * @param savePath - where to write it.
416
- */
417
- download?(url: string, savePath: string): Promise<void>
418
- /**
419
- * Export this view's cookies. Optional; see {@link download} for why it is declared.
420
- * @returns the cookies, scoped to the view's own page.
421
- */
422
- flushAuth?(): Promise<readonly ExportedCookie[]>
423
- /**
424
- * Import cookies into this view. Optional.
425
- * @param cookies - the cookies to write.
426
- * @returns how many were accepted.
427
- */
428
- restoreAuth?(cookies: readonly ExportedCookie[]): Promise<number>
429
- /**
430
- * Capture this view natively, returning the image and its measured size.
431
- *
432
- * Optional. The size is part of the contract because the caller's own tool schema declares
433
- * `width`/`height`; a host that can measure the image should say so here rather than leaving
434
- * the provider to guess.
435
- * @param opts - format, quality and downscale bounds.
436
- * @returns the encoded image and the pixel size the caller will receive.
437
- */
438
- capture?(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string; width?: number; height?: number }>
439
- }
440
-
441
- /**
442
- * One tab inside a session: its view, a stable id, and the last URL this provider accepted.
443
- *
444
- * `url` does two jobs. It separates "never navigated" from "navigated, but the URL could not be
445
- * read" — the two used to collapse into the same empty string — and it lets `listTabs` skip
446
- * probing a tab it already knows is blank, where a probe is a round trip on an uncommitted view
447
- * that can only answer nothing.
448
- *
449
- * A failed guest stays attached to its tab until the caller explicitly closes or resets it.
450
- */
451
- interface Tab {
452
- readonly id: BrowserTabWireId
453
- readonly handle: ElectronViewHandle
454
- url: string
455
- navigation?: symbol
456
- navigationAbort?: AbortController
457
- failure?: BrowserError
458
- /**
459
- * Consecutive failed page evaluations, used only by the reference pump to tell
460
- * "mid-navigation" (retried) from "this page is gone for now" (backed off).
461
- */
462
- misses?: number
463
- /** Earliest time the reference pump may try this page again. */
464
- retryAt?: number
465
- }
466
-
467
- /** One live browser session: an ordered list of tabs, one active. */
468
- interface Session {
469
- readonly id: BrowserSessionId
470
- /** Human-readable label (usually the DSH task/session id) for the window title. */
471
- readonly label?: string
472
- readonly tabs: Tab[]
473
- activeIndex: number
474
- /** Chronological operation log (navigate/execute/click/type/fill/download/auth). */
475
- readonly history: BrowserHistoryEntry[]
476
- /** Monotonic sequence counter for history entries (survives truncation). */
477
- nextSeq: number
478
- }
479
-
480
- /** Provider config: navigation admission defaults and snapshot caps. */
481
- export interface ElectronBrowserProviderConfig {
482
- /** Allow navigation only to HTTP(S) URLs; reject anything else. Default true. */
483
- readonly httpOnly?: boolean
484
- /**
485
- * Persistent browsing history (visited pages), independent of session
486
- * lifetime. `enabled: false` keeps the browser working but records nothing;
487
- * the retained limits ride along so a user's choice from the settings panel
488
- * reaches the store without a second configuration path.
489
- */
490
- readonly history?: {
491
- readonly enabled?: boolean
492
- readonly maxEntries?: number
493
- readonly maxAgeDays?: number
494
- /**
495
- * Explicit history file path. Default: beside the browser profile
496
- * (`$DSH_HOME/dsh-builtin-browser-host/history.jsonl`).
497
- */
498
- readonly file?: string
499
- }
500
- /**
501
- * Live settings source (the settings panel's document). When present it wins
502
- * over the static `history` config, so a switch flipped in the UI takes effect
503
- * without restarting DSH.
504
- */
505
- readonly settings?: () => BrowserSettings
506
- /** Maximum snapshot elements before truncation. Default 60. */
507
- readonly snapshotMaxElements?: number
508
- /**
509
- * Explicit content cap, overriding the per-format default when set.
510
- *
511
- * Honoured again, and it is worth saying why that is a fix rather than a feature: this was
512
- * `config.contentMaxChars ?? 100_000`, one number for every format, and when the caps became
513
- * per-format (html and json 50 000, otherwise 20 000) the field was left assigned and never
514
- * read. A configuration knob that silently does nothing is worse than no knob — it is an
515
- * operator's decision that quietly went nowhere. Leaving it unset means the per-format
516
- * default; setting it means the operator meant it.
517
- */
518
- readonly contentMaxChars?: number
519
- /**
520
- * Directory `dsh_browser_download` save paths must resolve inside (prevents a
521
- * prompt-injected agent from writing arbitrary machine paths). Default:
522
- * `~/Downloads`. NOTE: this default is a convenience, not a security
523
- * boundary — on Windows it may resolve to OneDrive/redirected paths;
524
- * a production deployment should set an explicit, verified path.
525
- */
526
- readonly downloadDir?: string
527
- /**
528
- * The conversation this process serves, when the composition knows it.
529
- *
530
- * The reference entry needs it to find the page the human has open in THIS
531
- * conversation's sidebar: the shell exposes a panel's pages by conversation id,
532
- * and a page bound under the wrong id would either be refused or wired into
533
- * another conversation's draft. Absent on hosts that do not name it (a plain
534
- * `dsh web`), where the sidebar entry simply does not apply.
535
- */
536
- readonly referenceLabel?: string | (() => string | undefined)
537
- }
538
-
539
- /**
540
- * CDP method/params for `Page.navigate`, as sent to {@link ElectronViewHandle.sendCommand}.
541
- */
542
- export interface CdpNavigateParams {
543
- readonly url: string
544
- }
545
-
546
- /**
547
- * CDP method/params for `Input.dispatchMouseEvent`: a pointer move, or one half
548
- * of a click's press+release pair. `button`/`clickCount` belong to the press and
549
- * release halves; a move carries only the position.
550
- *
551
- * `buttons` is a BITMASK of what is held down at the moment of the event, and it is not the same
552
- * field as `button` — `button` says which one this event is about, `buttons` says which ones are
553
- * down. Chromium needs both to recognise a synthesized press as a real button press: with
554
- * `buttons` omitted (0), the event still reaches the page and a `click` listener still fires, but
555
- * the element's DEFAULT ACTION does not run. Measured on the sidebar carrier: a click on an
556
- * anchor sent `mousedown`/`mouseup`/`click` to the page with `isTrusted: true` and
557
- * `defaultPrevented: false`, and the browser did not follow the link — including for an anchor
558
- * injected by the test itself, so the page was not responsible.
559
- */
560
- export interface CdpMouseParams {
561
- readonly type: 'mouseMoved' | 'mousePressed' | 'mouseReleased'
562
- readonly x: number
563
- readonly y: number
564
- readonly button?: 'left'
565
- readonly clickCount?: number
566
- /** Buttons held during the event: 1 = primary down. A move carries 0. */
567
- readonly buttons?: number
568
- }
569
-
570
- /** CDP method/params for `Input.insertText`. */
571
- export interface CdpInsertTextParams {
572
- readonly text: string
573
- }
574
-
575
- /** CDP method/params for `Runtime.evaluate`. */
576
- export interface CdpEvaluateParams {
577
- readonly expression: string
578
- readonly returnByValue: boolean
579
- readonly awaitPromise?: boolean
580
- }
581
-
582
- /** CDP method for a full-page screenshot capture. */
583
- export const CDP_PAGE_CAPTURE_SCREENSHOT = 'Page.captureScreenshot'
584
-
585
- /** One cookie as CDP reports it (`Storage.getCookies`). */
586
- interface CdpCookie {
587
- readonly name?: unknown
588
- readonly value?: unknown
589
- readonly domain?: unknown
590
- readonly path?: unknown
591
- readonly expires?: unknown
592
- readonly httpOnly?: unknown
593
- readonly secure?: unknown
594
- readonly sameSite?: unknown
595
- }
596
-
597
- /**
598
- * The document size out of a `Page.getLayoutMetrics` response.
599
- *
600
- * CDP returns `cssContentSize` (the whole document) and `cssLayoutViewport` (what is
601
- * visible); the newer spellings `contentSize` / `layoutViewport` appear on some
602
- * versions, so both are accepted. Returns undefined when neither is usable, leaving the
603
- * caller to capture unscaled rather than guess.
604
- * @param metrics - the raw CDP response.
605
- * @returns the document and viewport size in CSS pixels.
606
- */
607
- export function layoutSize(metrics: Record<string, unknown>): { width: number; height: number; viewportHeight: number } | undefined {
608
- const pick = (candidates: readonly unknown[]): { width: number; height: number } | undefined => {
609
- for (const candidate of candidates) {
610
- if (typeof candidate !== 'object' || candidate === null) continue
611
- const box = candidate as { width?: unknown; height?: unknown }
612
- if (typeof box.width === 'number' && typeof box.height === 'number' && box.width > 0 && box.height > 0) {
613
- return { width: box.width, height: box.height }
614
- }
615
- }
616
- return undefined
617
- }
618
- const content = pick([metrics.cssContentSize, metrics.contentSize])
619
- const viewport = pick([metrics.cssLayoutViewport, metrics.layoutViewport])
620
- if (content === undefined) return undefined
621
- return { width: content.width, height: content.height, viewportHeight: viewport?.height ?? content.height }
622
- }
623
-
624
- /**
625
- * Map CDP cookies onto the shape `dsh_browser_auth` exports.
626
- *
627
- * CDP reports a cookie as domain + path rather than a URL, and in seconds rather than
628
- * milliseconds, so both are converted. Entries missing a name, value or domain are
629
- * dropped rather than exported as broken cookies the caller cannot restore.
630
- * @param raw - the `cookies` array from a CDP response, of unknown shape.
631
- * @returns the mappable cookies.
632
- */
633
- export function toExportedCookies(raw: unknown): ExportedCookie[] {
634
- if (!Array.isArray(raw)) return []
635
- const out: ExportedCookie[] = []
636
- for (const entry of raw) {
637
- if (typeof entry !== 'object' || entry === null) continue
638
- const cookie = entry as CdpCookie
639
- // An empty domain is as unusable as a missing one: it cannot form a cookie URL, so
640
- // exporting it would hand the caller something that fails to restore.
641
- if (typeof cookie.name !== 'string' || cookie.name === '') continue
642
- if (typeof cookie.value !== 'string') continue
643
- if (typeof cookie.domain !== 'string' || cookie.domain === '') continue
644
- const path = typeof cookie.path === 'string' && cookie.path !== '' ? cookie.path : '/'
645
- // A leading dot means "this domain and its subdomains"; a cookie URL must not keep it.
646
- const host = cookie.domain.replace(/^\./, '')
647
- out.push({
648
- url: `${cookie.secure === true ? 'https' : 'http'}://${host}${path}`,
649
- name: cookie.name,
650
- value: cookie.value,
651
- domain: cookie.domain,
652
- path,
653
- ...cookie.secure === true ? { secure: true } : {},
654
- ...cookie.httpOnly === true ? { httpOnly: true } : {},
655
- ...typeof cookie.expires === 'number' && cookie.expires > 0 ? { expirationDate: cookie.expires } : {},
656
- })
657
- }
658
- return out
659
- }
660
-
661
- /**
662
- * Map an exported cookie onto the fields `Storage.setCookies` expects.
663
- *
664
- * An exported cookie may carry only a URL, so the domain and path are recovered from it
665
- * when they are absent; without either, CDP cannot place the cookie and it is skipped.
666
- * @param cookie - the cookie to convert.
667
- * @returns the CDP cookie, or undefined when it lacks a usable domain.
668
- */
669
- export function toCdpCookie(cookie: ExportedCookie): Record<string, unknown> | undefined {
670
- let domain = cookie.domain
671
- let path = cookie.path
672
- if (domain === undefined || domain === '') {
673
- try {
674
- const parsed = new URL(cookie.url)
675
- domain = parsed.hostname
676
- if (path === undefined || path === '') path = parsed.pathname === '' ? '/' : parsed.pathname
677
- } catch {
678
- return undefined
679
- }
680
- }
681
- if (typeof domain !== 'string' || domain === '') return undefined
682
- return {
683
- name: cookie.name,
684
- value: cookie.value,
685
- domain,
686
- path: path === undefined || path === '' ? '/' : path,
687
- ...cookie.secure === true ? { secure: true } : {},
688
- ...cookie.httpOnly === true ? { httpOnly: true } : {},
689
- ...typeof cookie.expirationDate === 'number' ? { expires: cookie.expirationDate } : {},
690
- }
691
- }
692
-
693
- /**
694
- * How the carrier should present a view before it is used.
695
- *
696
- * `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
697
- * synthesized `Input.*` for a view without a display surface, so input still needs one. It means
698
- * the carrier must get that surface without taking the screen over — no application activation
699
- * and no operating-system keyboard focus. New windows open inactive; a minimized window and the
700
- * foreground window's selected page remain under the operator's control. DOM focus and CDP input
701
- * still target the task's page. Explicit sidebar navigation can select the task's pane.
702
- */
703
- export interface PresentOptions {
704
- readonly quiet?: boolean
705
- /** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
706
- readonly select?: boolean
707
- }
708
-
709
- /**
710
- * How a command should reach its page.
711
- *
712
- * Reported as issue #46: opening the live preview pushed the conversation's sidebar browser panel
713
- * to the front — a read-only "look at it" action changing the reader's layout. The chain was
714
- * `capturePassive` → `sendCommand('Page.captureScreenshot')` → the host's guest lookup → the bridge's
715
- * `ensureSidebar` → a retry that asked the client half to `openSession`, which is exactly what a tool
716
- * call is allowed to do and a preview is not.
717
- *
718
- * `present: false` says "this command must not make anything visible": use the page this
719
- * conversation already has, and treat "not displayed" as a state to report rather than a condition
720
- * to fix.
721
- */
722
- export interface CommandOptions {
723
- readonly deadline?: number
724
- readonly signal?: AbortSignal
725
- /** Present the view first (default), or only use a page that is already there. */
726
- readonly present?: boolean
727
- /** Only use a guest already attached to this handle, without sidebar initialization. */
728
- readonly initialize?: boolean
729
- }
730
-
731
- /** Native capture options the self-hosted view handle understands. */
732
- export interface ScreenshotOptions {
733
- readonly format?: 'png' | 'jpeg'
734
- readonly quality?: number
735
- readonly maxWidth?: number
736
- readonly maxHeight?: number
737
- /**
738
- * Capture without presenting the window first (`ui.quiet`).
739
- *
740
- * The self-hosted host answers this by skipping its restore/show/focus step: a visible window
741
- * still captures through `capturePage()`, and a minimized or hidden one falls through to the
742
- * CDP path, which needs no display surface.
743
- */
744
- readonly quiet?: boolean
745
- }
746
- /** CDP method for runtime evaluation (the execute path). */
747
- export const CDP_RUNTIME_EVALUATE = 'Runtime.evaluate'
748
- /** CDP method for navigation. */
749
- export const CDP_PAGE_NAVIGATE = 'Page.navigate'
750
-
751
- /** Cap on content returned by a snapshot fetch to keep the wire bounded. */
752
- const SNAPSHOT_LABEL_MAX = 120
753
-
754
- /** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
755
- const KEY_SPECS: Readonly<Record<string, { readonly key: string; readonly code: string; readonly vk: number; readonly text?: string }>> = {
756
- // `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
757
- // submission depends on the character: pressing Enter in a text field submits the form because
758
- // the browser processes a carriage return, not because a key went down. Without `text` the event
759
- // still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
760
- // issue #36, where `requestSubmit()` worked and this did not.
761
- //
762
- // The same omission is why Space used to pass only its key event; that one was already fixed and
763
- // is the reason the table has a `text` column at all.
764
- Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
765
- Tab: { key: 'Tab', code: 'Tab', vk: 9 },
766
- Escape: { key: 'Escape', code: 'Escape', vk: 27 },
767
- Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
768
- Delete: { key: 'Delete', code: 'Delete', vk: 46 },
769
- ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', vk: 38 },
770
- ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', vk: 40 },
771
- ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
772
- ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
773
- Home: { key: 'Home', code: 'Home', vk: 36 },
774
- End: { key: 'End', code: 'End', vk: 35 },
775
- PageUp: { key: 'PageUp', code: 'PageUp', vk: 33 },
776
- PageDown: { key: 'PageDown', code: 'PageDown', vk: 34 },
777
- // Space is the one printable key: CDP needs `text` on the keyDown for the
778
- // character to land in a focused input; without it the key only scrolls.
779
- Space: { key: ' ', code: 'Space', vk: 32, text: ' ' },
780
- }
781
-
782
- /** Supported key names, exported for the tool's enum and error messages. */
783
- export const BROWSER_KEY_NAMES: readonly string[] = Object.keys(KEY_SPECS)
784
-
785
- /**
786
- * Localized names a system Downloads folder may carry, in probe order: the
787
- * English default first, then the Chinese spellings — a zh-CN desktop calls
788
- * the folder `下载`, a zh-TW one `下載`, and neither is `Downloads`.
789
- */
790
- const DOWNLOAD_DIR_NAMES: readonly string[] = ['Downloads', '下载', '下載']
791
-
792
- /**
793
- * Resolve the default download directory when the config names none: an
794
- * existing `XDG_DOWNLOAD_DIR` wins (the freedesktop standard, which is what a
795
- * localized Linux desktop writes), then the first localized `Downloads` folder
796
- * that exists under the home directory, and finally the English name — created
797
- * on first use — when none exists yet.
798
- * @returns the absolute default download directory.
799
- */
800
- function defaultDownloadDir(): string {
801
- const xdg = process.env.XDG_DOWNLOAD_DIR
802
- if (typeof xdg === 'string' && xdg !== '' && existsSync(xdg)) return xdg
803
- for (const name of DOWNLOAD_DIR_NAMES) {
804
- const candidate = join(homedir(), name)
805
- if (existsSync(candidate)) return candidate
806
- }
807
- return join(homedir(), DOWNLOAD_DIR_NAMES[0] ?? 'Downloads')
808
- }
809
-
810
- /**
811
- * Whether a directory entry exists at `path`, judging the ENTRY rather than what it
812
- * points at.
813
- *
814
- * `existsSync` follows links, so a DANGLING symlink — a link whose target does not
815
- * exist — reads as "nothing here", and a write to that path creates the target
816
- * instead: outside `downloadDir` whenever the link points out of it. `lstatSync`
817
- * sees the link itself, which is the only correct answer to "is this name free".
818
- * @param path - the path to judge.
819
- * @returns true when any entry (file, directory, link) occupies the name.
820
- */
821
- function entryExists(path: string): boolean {
822
- try {
823
- lstatSync(path)
824
- return true
825
- } catch {
826
- return false
827
- }
828
- }
829
-
830
- /**
831
- * The real path of the deepest existing ancestor of `path` — `path` itself when it
832
- * exists, otherwise the nearest directory above it that does.
833
- *
834
- * `resolve()` normalizes `..` but never follows a link, so nothing textual can tell
835
- * that `<downloadDir>/link/x.png` leaves the directory through `link`. The first
836
- * ancestor that exists (judged by lstat, so a dangling link counts — the write would
837
- * go through it) is the last component whose real location still determines where
838
- * the bytes land, so that is the one to resolve and check.
839
- * @param path - an absolute path that may not exist yet.
840
- * @returns the resolved real path of its deepest existing ancestor.
841
- */
842
- function realAncestorOf(path: string): string {
843
- let current = path
844
- for (let depth = 0; depth < 64; depth += 1) {
845
- if (entryExists(current)) {
846
- try {
847
- return realpathSync(current)
848
- } catch {
849
- // The entry vanished between the two calls, or cannot be resolved: the
850
- // textual path is the best available answer, and the write reports the rest.
851
- return current
852
- }
853
- }
854
- const parent = dirname(current)
855
- if (parent === current) return current
856
- current = parent
857
- }
858
- return current
859
- }
860
-
861
- /**
862
- * Browser provider over Electron views. Sessions hold an ordered list of
863
- * tabs; each tab is one view created by the host. The active tab receives
864
- * every operation; switching tabs calls the host's optional `showView` and
865
- * never loses state. Navigation is admitted only for HTTP(S) targets unless
866
- * {@link ElectronBrowserProviderConfig.httpOnly} is disabled.
867
- */
868
- export class ElectronBrowserProvider implements BrowserProvider {
869
- readonly id = ELECTRON_BROWSER_PROVIDER_ID
870
-
871
- private readonly sessions = new Map<BrowserSessionId, Session>()
872
- private carrierLaunchError: unknown
873
- /**
874
- * Tick that installs the selection bar in every live tab and collects what the
875
- * human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
876
- * the page has no preload bridge and the bridge protocol carries no user-action
877
- * channel, so the bar leaves its intent in `window.__dshRefIntents` and this
878
- * pump takes it over CDP. Without it the sidebar has no reference entry.
879
- */
880
- private referencePump: ReturnType<typeof setInterval> | undefined
881
- /** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
882
- private referencePumping = false
883
- /**
884
- * Set once the carrier swapped to a newer provider. `onUserAction` and
885
- * `onViewClosed` return void and cannot be unsubscribed, so the callbacks
886
- * themselves must go inert: otherwise one human click is handled by every
887
- * old provider still retained by the view host, producing duplicate cards.
888
- */
889
- private disposed = false
890
- /**
891
- * The session bound to the page the human has open, created on first sight.
892
- *
893
- * A reference is captured from a browser SESSION, and a page the human opened from
894
- * the sidebar's own address bar belongs to no session of ours. Adopting it into one
895
- * is what makes the selection bar appear there at all — and it is done here, inside
896
- * the pump, so it needs nothing from the human and nothing from the agent.
897
- */
898
- private referenceSession: BrowserSessionId | undefined
899
- /** Ticks between sidebar page scans while nothing is adopted yet. */
900
- private referenceScanCountdown = 0
901
- /** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
902
- private readonly referenceScan: { label?: string; pages: number; lastError?: string } = { pages: 0 }
903
- private readonly httpOnly: boolean
904
- private readonly snapshotMaxElements: number
905
- private readonly contentMaxChars: number | undefined
906
- private readonly downloadDir: string | undefined
907
- /**
908
- * Persistent browsing history, or `undefined` when the user turned it off.
909
- * Sessions come and go; this record outlives all of them.
910
- */
911
- private readonly historyStore: HistoryStore | undefined
912
- /** Live settings source; absent when nothing owns a settings document. */
913
- private readonly settingsSource: (() => BrowserSettings) | undefined
914
-
915
- constructor(
916
- private readonly host: ElectronBrowserViewHost,
917
- private readonly config: ElectronBrowserProviderConfig = {},
918
- ) {
919
- this.httpOnly = config.httpOnly ?? true
920
- this.snapshotMaxElements = config.snapshotMaxElements ?? 60
921
- this.contentMaxChars = config.contentMaxChars
922
- // Confine downloads AND screenshot saves to a dedicated directory by
923
- // default: the OS Downloads folder is the human-visible, browser-natural
924
- // place for written files, and it is the one directory the DSH file
925
- // sandbox does not have to arbitrate. The localized name is probed so a
926
- // Chinese desktop (`~/下载`) works without configuring `downloadDir`.
927
- this.downloadDir = config.downloadDir ?? defaultDownloadDir()
928
- this.settingsSource = config.settings
929
- // Browsing history follows the browser profile's persistence rules (close
930
- // the interface, lose nothing), and can be switched off from settings.
931
- this.historyStore = config.history?.enabled === false
932
- ? undefined
933
- : new HistoryStore(config.history?.file, {
934
- ...config.history?.maxEntries !== undefined ? { maxEntries: config.history.maxEntries } : {},
935
- ...config.history?.maxAgeDays !== undefined ? { maxAgeDays: config.history.maxAgeDays } : {},
936
- })
937
- // Route toolbar (host UI) actions into the session model: the human and
938
- // the agent then always drive the same tabs, history, and navigation.
939
- this.host.onUserAction?.(action => { if (!this.disposed) void this.handleUserAction(action) })
940
- // A window the human closed ends the session it showed: the next call opens a
941
- // clean one instead of driving a page nobody can see.
942
- this.host.onViewClosed?.(windowId => { if (!this.disposed) void this.handleViewClosed(windowId) })
943
- this.startReferenceEntryPump()
944
- }
945
-
946
- /** Retire a provider after a carrier swap; its listeners must not act again. */
947
- dispose(): void {
948
- this.disposed = true
949
- this.stopReferenceEntryPump()
950
- }
951
-
952
- /** Start the page-bar pump; idempotent, unref'd so it never holds the process. */
953
- private startReferenceEntryPump(): void {
954
- if (this.host.referenceOverlayOwner === 'client' || this.referencePump !== undefined) return
955
- this.referencePump = setInterval(() => { void this.pumpReferenceEntry() }, 1200)
956
- this.referencePump.unref?.()
957
- }
958
-
959
- /** Stop the pump (session teardown / tests). */
960
- stopReferenceEntryPump(): void {
961
- if (this.referencePump === undefined) return
962
- clearInterval(this.referencePump)
963
- this.referencePump = undefined
964
- }
965
-
966
- /**
967
- * Install the bar where it is missing and forward one confirmed intent.
968
- *
969
- * Re-injection is what makes this survive navigation: a new document has no
970
- * `__dshRefOverlayInstalled`, so the next tick installs the bar again.
971
- *
972
- * One run at a time: `setInterval` fires again whether or not the previous
973
- * run finished, and a page that stopped answering would otherwise stack CDP
974
- * commands behind the wedged renderer on every tick.
975
- */
976
- private async pumpReferenceEntry(): Promise<void> {
977
- if (this.referencePumping) return
978
- this.referencePumping = true
979
- try {
980
- await this.adoptSidebarPageForReference().catch(() => undefined)
981
- for (const session of [...this.sessions.values()]) {
982
- if (this.host.referenceOverlayOwnerFor?.(session.id) === 'client') continue
983
- for (const tab of [...session.tabs]) {
984
- await this.pumpOneTab(session, tab)
985
- // A tab is never dropped for being unreachable: the page is the
986
- // person's own sidebar page, and the host excludes every page it
987
- // adopted from later listings, so letting go of the handle would
988
- // close our only route back to it.
989
- }
990
- }
991
- } finally {
992
- this.referencePumping = false
993
- }
994
- }
995
-
996
- /**
997
- * Install or collect on one tab.
998
- * @returns false when the page failed enough consecutive times to be gone.
999
- */
1000
- private async pumpOneTab(session: Session, tab: Tab): Promise<boolean> {
1001
- if (tab.failure !== undefined) return false
1002
- // A page that stopped answering is retried on a slow timer instead of being
1003
- // dropped: navigations and renderer swaps both look like death for a moment.
1004
- if (tab.retryAt !== undefined && Date.now() < tab.retryAt) return true
1005
- try {
1006
- // One round-trip per tab: a missing bar answers "install"; otherwise the
1007
- // same evaluation hands back a confirmed intent.
1008
- const probe = await this.evaluateInTab(tab, [
1009
- 'window.__dshRefOverlayInstalled !== true ? "install"',
1010
- ': (window.__dshRefTake ? window.__dshRefTake() : null)',
1011
- ].join(''), PROVIDER_TIMEOUTS.evaluation)
1012
- tab.misses = 0
1013
- tab.retryAt = undefined
1014
- if (probe === 'install') {
1015
- await this.evaluateInTab(tab, standaloneScript(overlayScript(), {}), PROVIDER_TIMEOUTS.interaction)
1016
- return true
1017
- }
1018
- if (probe === null || probe === undefined) return true
1019
- try {
1020
- if (typeof probe !== 'object') throw new Error('reference intent is invalid')
1021
- const record = probe as Record<string, unknown>
1022
- if (record.type !== REFERENCE_INTENT_CHANNEL) throw new Error('reference intent channel is invalid')
1023
- const rawComment = typeof record.comment === 'string' ? record.comment.trim() : ''
1024
- const rawSelection = typeof record.selectionText === 'string' ? record.selectionText.trim() : ''
1025
- const capture = validateFrozenCapture(record.capture)
1026
- if (capture === undefined) throw new Error('reference intent has no captured content')
1027
- await this.handleUserAction({
1028
- type: 'capture-reference',
1029
- windowId: session.id,
1030
- entry: 'page-overlay',
1031
- ...rawComment !== '' ? { comment: rawComment.slice(0, MAX_REFERENCE_COMMENT) } : {},
1032
- ...rawSelection !== '' ? { selectionText: rawSelection } : {},
1033
- capture,
1034
- }, true)
1035
- } catch (error) {
1036
- this.referenceScan.lastError = 'capture refused: ' + (error instanceof Error ? error.message : String(error))
1037
- process.stderr.write(`[dsh-browser] ${this.referenceScan.lastError}\n`)
1038
- try {
1039
- await this.evaluateInTab(tab, standaloneScript(noticeScript(hostMessages.zh.referenceFailed)), PROVIDER_TIMEOUTS.evaluation)
1040
- } catch { /* The failure remains in host diagnostics when the guest disappears. */ }
1041
- }
1042
- return true
1043
- } catch {
1044
- // A tab mid-navigation has no execution context yet; the next tick retries.
1045
- // A page that keeps failing backs off instead of being forgotten: the
1046
- // handle is the only way back to a page this host adopted, and dropping it
1047
- // made the bar stop delivering for the rest of the conversation.
1048
- tab.misses = (tab.misses ?? 0) + 1
1049
- if (tab.misses >= DEAD_REFERENCE_TAB_MISSES) {
1050
- tab.misses = 0
1051
- tab.retryAt = Date.now() + DEAD_REFERENCE_TAB_RETRY_MS
1052
- }
1053
- return true
1054
- }
1055
- }
1056
-
1057
- /** Forget one dead adopted tab; the conversation's next page starts a fresh session. */
1058
-
1059
- /**
1060
- * Bind the page the human has open in this conversation's sidebar into a session.
1061
- *
1062
- * Why this is the whole entry: the sidebar page is the shell's, opened by a person
1063
- * through the address bar, so no session of ours names it and nothing injects the
1064
- * selection bar into it. The shell DOES expose the panel's pages by conversation id
1065
- * (`listPages`), and can hand one over (`adoptPage`) — the same pair the tools use
1066
- * for `dsh_browser_list_tabs`. Doing it on a timer means the bar appears on a page
1067
- * the human opened themselves, which is the only entry they actually take.
1068
- *
1069
- * Rescans are spaced by one idle tick, not five: the listing crosses the
1070
- * bridge, and a page the human just opened must get its entry within a
1071
- * couple of seconds rather than five.
1072
- */
1073
- private async adoptSidebarPageForReference(): Promise<void> {
1074
- const configured = this.config.referenceLabel
1075
- const label = typeof configured === 'function' ? configured() : configured
1076
- this.referenceScan.label = label
1077
- if (label === undefined || label === '') return
1078
- if (this.host.listPages === undefined || this.host.adoptPage === undefined) {
1079
- this.referenceScan.lastError = 'this carrier cannot list or adopt a page it did not open'
1080
- return
1081
- }
1082
- if (this.referenceScanCountdown > 0) { this.referenceScanCountdown -= 1; return }
1083
- // One idle tick between scans: a page the human opens must get its entry
1084
- // within a couple of seconds (measured: the shell creates the guest, then
1085
- // the next scan adopts it). The listing is a local bridge call, not a
1086
- // network request, so this is cheap.
1087
- this.referenceScanCountdown = 1
1088
- let session = this.referenceSession === undefined ? undefined : this.sessions.get(this.referenceSession)
1089
- if (session?.label !== label) session = undefined
1090
- const candidate: Session = session ?? {
1091
- id: sessionWireId(browserSessionHandle(label, randomUUID())), label,
1092
- tabs: [], activeIndex: 0, history: [], nextSeq: 1,
1093
- }
1094
- let pages: readonly CarrierPage[]
1095
- try {
1096
- // `requireRunning` is what keeps a scan from launching the human's
1097
- // installed browser: only a carrier that is already up can have pages.
1098
- pages = await this.host.listPages(this.carrierScope(candidate), { requireRunning: true })
1099
- } catch (error) {
1100
- this.referenceScan.lastError = error instanceof Error ? error.message : String(error)
1101
- return
1102
- }
1103
- this.referenceScan.pages = pages.length
1104
- const live = pages.filter(candidate => /^https?:\/\//iu.test(candidate.url))
1105
- // NOT pruned. The host's listing already EXCLUDES the pages this process
1106
- // adopted (that exclusion is what keeps `listTabs` from reporting one page
1107
- // twice), so "absent from the listing" means "already adopted" as often as
1108
- // it means "closed". Dropping those tabs would lose the bar on every page
1109
- // the human switches away from and re-adopt it under a new handle on the
1110
- // way back. A closed page's handle simply stops answering, and the pump
1111
- // already skips a tab it cannot evaluate.
1112
- if (live.length === 0) {
1113
- this.referenceScan.lastError = 'no http page is open in this conversation\'s sidebar'
1114
- return
1115
- }
1116
- let refused: string | undefined
1117
- for (const page of live) {
1118
- const tabId = this.carrierTab(candidate, page.id)
1119
- const existing = session?.tabs.find(tab => tab.id === tabId)
1120
- if (existing !== undefined) {
1121
- // A navigation changes the URL of a page we already hold.
1122
- if (existing.url !== page.url) existing.url = page.url
1123
- continue
1124
- }
1125
- try {
1126
- // The owner is passed so the adopted view is released with THIS
1127
- // conversation and not swept up by, or lost to, another one.
1128
- const handle = await this.host.adoptPage(this.carrierTab(candidate, page.id), this.carrierScope(candidate))
1129
- if (session === undefined) {
1130
- session = candidate
1131
- this.sessions.set(session.id, session)
1132
- this.referenceSession = session.id
1133
- }
1134
- // Append only: discovery must never switch the page the human is
1135
- // looking at, nor open a tab they did not ask for.
1136
- session.tabs.push({ id: tabId, handle, url: page.url })
1137
- } catch (error) {
1138
- refused = error instanceof Error ? error.message : String(error)
1139
- }
1140
- }
1141
- if (session !== undefined) {
1142
- session.activeIndex = Math.min(session.activeIndex, Math.max(0, session.tabs.length - 1))
1143
- }
1144
- this.referenceScan.lastError = session === undefined
1145
- ? refused ?? 'no page could be adopted'
1146
- : refused
1147
- }
1148
-
1149
- /**
1150
- * What the sidebar reference entry is doing right now.
1151
- *
1152
- * Served on the reference route so "there is no selection bar on my page" has an
1153
- * answer that is not a guess: which conversation this process thinks it serves,
1154
- * whether a page was adopted, how many the shell reported, and the last refusal.
1155
- */
1156
- referenceStatus(): { readonly label?: string; readonly session?: string; readonly pages: number; readonly lastError?: string } {
1157
- return {
1158
- ...this.referenceScan.label === undefined ? {} : { label: this.referenceScan.label },
1159
- ...this.referenceSession === undefined ? {} : { session: this.referenceSession },
1160
- pages: this.referenceScan.pages,
1161
- ...this.referenceScan.lastError === undefined ? {} : { lastError: this.referenceScan.lastError },
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * Evaluate one expression in a tab and return its value.
1167
- *
1168
- * Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
1169
- * would otherwise hold the whole tick (and every later one) forever.
1170
- * @param tab - the tab to evaluate in.
1171
- * @param expression - the JS expression.
1172
- * @param timeoutMs - how long to wait before treating the page as not answering.
1173
- */
1174
- private async evaluateInTab(tab: Tab, expression: string, timeoutMs: number = PROVIDER_TIMEOUTS.evaluation): Promise<unknown> {
1175
- const raw = await withTimeout(
1176
- tab.handle.sendCommand('Runtime.evaluate', {
1177
- expression, returnByValue: true, awaitPromise: true,
1178
- }),
1179
- timeoutMs,
1180
- undefined,
1181
- `browser: reference probe timed out after ${timeoutMs}ms`,
1182
- )
1183
- const result = (raw as { result?: { value?: unknown } }).result
1184
- return result?.value
1185
- }
1186
-
1187
- /**
1188
- * Usable when the host says it can back views (the self-hosted host probes
1189
- * for a usable Electron binary; the desktop shell is assumed usable).
1190
- */
1191
- available(): boolean {
1192
- return this.host.available?.() ?? true
1193
- }
1194
-
1195
- /**
1196
- * Open a NEW browser session with its own view. Every call mints a fresh
1197
- * session id and backing view; per-task reuse is owned by the caller (the
1198
- * tool layer caches one session per DSH task). Sessions are isolated from
1199
- * each other: each keeps its own tabs, active tab, and history, and only
1200
- * the active tab of a session is made visible.
1201
- * @param label - optional human-readable label (e.g. the DSH task id) shown
1202
- * in the window title so a human can tell which task's page is visible.
1203
- */
1204
- open(label?: string): Promise<BrowserSessionId> {
1205
- // The label is the calling DSH task, and it is handed to the view as its owner: a host shared
1206
- // by several conversations (the desktop's) keeps one conversation's page out of another's on
1207
- // the strength of it, so it is not decoration.
1208
- const id = sessionWireId(browserSessionHandle(label || 'default', randomUUID()))
1209
- const tabId = tabWireId({ ...resolveSessionHandle(id), tab: randomUUID() })
1210
- const handle = this.host.createView(tabId)
1211
- // Group the session's views under its own window (one window per
1212
- // session), carrying the label for the window title. Hosts without
1213
- // groupView keep the shared-window behavior.
1214
- this.host.groupView?.(handle, id, label)
1215
- this.sessions.set(id, { id, label, tabs: [{ id: tabId, handle, url: '' }], activeIndex: 0, history: [], nextSeq: 1 })
1216
- return Promise.resolve(id)
1217
- }
1218
-
1219
- private async prepareCarrier(signal?: AbortSignal, scope?: BrowserSessionId): Promise<void> {
1220
- if (this.host.prepare === undefined) return
1221
- signal?.throwIfAborted()
1222
- try {
1223
- await withTimeout(this.host.prepare(scope), PROVIDER_TIMEOUTS.prepare, signal, 'browser: carrier launch timed out before navigating a guest')
1224
- this.carrierLaunchError = undefined
1225
- } catch (error) {
1226
- if (!signal?.aborted) this.carrierLaunchError = error
1227
- throw error
1228
- }
1229
- }
1230
-
1231
- async bindPage(session: BrowserSessionId, pageId: BrowserTabWireId): Promise<void> {
1232
- const s = this.session(session)
1233
- if (this.host.adoptPage === undefined || !s.label) throw new Error('sidebar page binding unsupported')
1234
- if (s.tabs.some(tab => tab.url !== '')) throw new Error('source binding requires a fresh browser session')
1235
- const id = tabWireId(resolveTabHandle(resolveSessionHandle(s.id), pageId))
1236
- const handle = await this.host.adoptPage(id, this.carrierScope(s))
1237
- const previous = [...s.tabs]
1238
- s.tabs.splice(0, s.tabs.length, { id: this.carrierTab(s, id), handle, url: '' })
1239
- s.activeIndex = 0
1240
- for (const tab of previous) this.destroyTab(tab)
1241
- }
1242
-
1243
- /**
1244
- * The most recent open request, for the Web sidebar.
1245
- *
1246
- * On the desktop shell the host half tells the shell to place a tab (`__dshBuiltinBrowser.openPanel`)
1247
- * through the bridge. The Web shell has no such channel, so a tool-opened page lived only in the
1248
- * plugin's own browser while the panel stayed empty — and "open it in the sidebar" took several manual
1249
- * steps. The client polls this one slot and places the tab itself.
1250
- * @returns the last request and when it arrived, or undefined when nothing was opened yet.
1251
- */
1252
- lastOpenRequest(): { readonly url: string; readonly at: number } | undefined {
1253
- return this.lastOpen
1254
- }
1255
-
1256
- /** Set by {@link openUrl}; read by the client through the HTTP surface. */
1257
- private lastOpen: { readonly url: string; readonly at: number } | undefined
1258
-
1259
- async openUrl(session: BrowserSessionId, request: BrowserOpenRequest, signal?: AbortSignal): Promise<void> {
1260
- try { setLastOpen(request.url, Date.now()) } catch { /* best effort */ }
1261
- const s = this.session(session)
1262
- await this.prepareCarrier(signal, s.id)
1263
- if (request.newTab === true) {
1264
- this.newTab(s)
1265
- }
1266
- // A page the human already has, at the URL being asked for, is the page they mean.
1267
- //
1268
- // Reported as a defect: they opened a page by hand, then a tool call drove the plugin's own
1269
- // blank tab instead and reported nothing about the page on screen — so the obvious conclusion
1270
- // was "the page is broken", and opening the same URL again produced a SECOND tab. Reusing the
1271
- // existing page is both what the request says and what a person expects.
1272
- //
1273
- // Only an exact match after normalisation: a deliberate navigation to a different URL must not
1274
- // be redirected to whatever page happens to be open.
1275
- const tab = this.activeTab(s)
1276
- const transaction = this.beginNavigation(tab, signal)
1277
- const { navigation } = transaction
1278
- signal = transaction.signal
1279
- if (request.newTab !== true && await this.adoptMatchingPage(s, request.url, tab, navigation, signal)) return
1280
- await this.navigateTab(s, tab, request.url, navigation, signal)
1281
- }
1282
-
1283
- /**
1284
- * Bind the carrier page that already shows this URL, if there is one.
1285
- *
1286
- * Compare the part of a URL that says WHICH page it is: scheme, host, path and query. A hash is a
1287
- * position inside a document, and a trailing slash is spelling, so neither makes a different page.
1288
- * @param s - the session to bind the page into.
1289
- * @param url - the URL being opened.
1290
- * @returns whether an existing page was taken over.
1291
- */
1292
- private async adoptMatchingPage(s: Session, url: string, target: Tab, navigation: symbol, signal?: AbortSignal): Promise<boolean> {
1293
- if (this.host.adoptPage === undefined || this.host.listPages === undefined) return false
1294
- const wanted = this.comparableUrl(url)
1295
- if (wanted === undefined) return false
1296
- let pages: readonly CarrierPage[]
1297
- try {
1298
- pages = await this.host.listPages(this.carrierScope(s))
1299
- } catch {
1300
- // A listing must not turn "nothing to reuse" into "open failed".
1301
- return false
1302
- }
1303
- this.checkNavigation(target, navigation)
1304
- const match = pages.find(page => this.comparableUrl(page.url) === wanted)
1305
- if (match === undefined) return false
1306
- let handle: ElectronViewHandle
1307
- try {
1308
- handle = await this.host.adoptPage(this.carrierTab(s, match.id), this.carrierScope(s))
1309
- } catch {
1310
- // The page went away between listing and adopting: fall through to an ordinary navigation.
1311
- return false
1312
- }
1313
- if (target.navigation !== navigation) {
1314
- this.host.destroyView(handle, { keepPage: true })
1315
- this.checkNavigation(target, navigation)
1316
- }
1317
- const tab: Tab = { id: this.carrierTab(s, match.id), handle, url: match.url, navigation, navigationAbort: target.navigationAbort }
1318
- delete target.navigationAbort
1319
- s.tabs.push(tab)
1320
- s.activeIndex = s.tabs.length - 1
1321
- const document = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) })
1322
- await this.settleDocument(handle, document, signal, { frameId: document.id, loaderId: document.loaderId },
1323
- () => { this.checkNavigation(tab, navigation) })
1324
- this.showActive(s, true)
1325
- return true
1326
- }
1327
-
1328
- /** The parts of a URL that decide identity, or undefined when it cannot be parsed. */
1329
- private comparableUrl(url: string): string | undefined {
1330
- if (url === '' || url === 'about:blank') return undefined
1331
- try {
1332
- const parsed = new URL(url)
1333
- return `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}${parsed.search}`
1334
- } catch {
1335
- return undefined
1336
- }
1337
- }
1338
-
1339
- /** List the session's tabs with their titles. */
1340
- async listTabs(session: BrowserSessionId): Promise<readonly BrowserTab[]> {
1341
- const s = this.session(session)
1342
- const result: BrowserTab[] = []
1343
- for (let i = 0; i < s.tabs.length; i++) {
1344
- const tab = s.tabs[i]
1345
- if (tab === undefined) continue // defensive: array can shift under concurrency
1346
- // A tab we know has never navigated is NOT probed: its view has committed no document, so
1347
- // the round trip can only answer nothing — and it is the round trip that costs. A tab that
1348
- // HAS navigated is re-read, because the page may have moved itself since; a read that fails
1349
- // keeps the last accepted URL rather than reporting the tab as blank.
1350
- const liveUrl = tab.failure !== undefined ? tab.url : tab.url === '' ? '' : await this.currentUrl(tab.handle).catch(() => tab.url)
1351
- if (liveUrl !== '') tab.url = liveUrl
1352
- result.push({
1353
- id: tab.id,
1354
- url: liveUrl,
1355
- active: i === s.activeIndex,
1356
- })
1357
- }
1358
- // Pages the CARRIER holds that this provider never created.
1359
- //
1360
- // A sidebar panel and an installed browser both open pages on their own: a click on a link
1361
- // that targets a new page, or any `window.open`, produces a page nothing tells us about.
1362
- // Reporting only our own tabs made those invisible to this tool and unclosable through
1363
- // `dsh_browser_close_tab`, so they accumulated for the life of the browser. Measured on the
1364
- // sidebar carrier: three clicks produced three webview guests while this listed one tab.
1365
- //
1366
- // Hosts exclude pages already attached to provider views.
1367
- const pages = await this.host.listPages?.(this.carrierScope(s)) ?? []
1368
- for (const page of pages) {
1369
- // A page with no URL is a blank one the carrier opened for itself. Listing it would invite a
1370
- // caller to act on nothing, and the blank normalisation already closes those.
1371
- if (page.url === '' || page.url === 'about:blank') continue
1372
- result.push({ id: this.carrierTab(s, page.id), url: page.url, active: false })
1373
- }
1374
- return result
1375
- }
1376
-
1377
- /** Switch to a tab by id, making its view visible. */
1378
- async switchTab(session: BrowserSessionId, tabId: BrowserTabWireId): Promise<void> {
1379
- const s = this.session(session)
1380
- // A page the carrier owns. Before this, switching to one threw "not open in this session" —
1381
- // while `dsh_browser_list_tabs` was happily listing it, so the two tools disagreed and the
1382
- // page the human was looking at could not be reached (reported as a defect).
1383
- const carrierId = this.carrierId(s, tabId)
1384
- if (carrierId !== undefined) {
1385
- const existing = s.tabs.findIndex(tab => tab.id === tabId)
1386
- if (existing !== -1) {
1387
- await this.host.presentView?.(s.tabs[existing]!.handle, s.label, { quiet: this.isQuiet(), select: true })
1388
- s.activeIndex = existing
1389
- this.showActive(s, true)
1390
- return
1391
- }
1392
- const id = carrierId
1393
- if (this.host.adoptPage === undefined) {
1394
- throw new BrowserError(
1395
- 'browser: this carrier cannot hand over a page it opened itself, so that page cannot be driven. '
1396
- + 'Open the URL through dsh_browser_open instead — that creates a page this plugin owns.',
1397
- 'BROWSER_TAB_NOT_FOUND',
1398
- )
1399
- }
1400
- const pages = await this.host.listPages?.(this.carrierScope(s)).catch(() => []) ?? []
1401
- const page = pages.find(candidate => candidate.id === id)
1402
- const handle = await this.host.adoptPage(id, this.carrierScope(s))
1403
- try {
1404
- // An adopted guest already has a document. Marking it as our never-opened
1405
- // blank view makes the first snapshot/a11y return without reading it.
1406
- const url = page?.url || await this.currentUrl(handle)
1407
- if (url === '') throw new BrowserError('browser: the adopted page did not report its document URL', 'BROWSER_TAB_NOT_FOUND')
1408
- const tab: Tab = { id: tabId, handle, url }
1409
- await this.host.presentView?.(handle, s.label, { quiet: this.isQuiet(), select: true })
1410
- s.tabs.push(tab)
1411
- s.activeIndex = s.tabs.length - 1
1412
- this.showActive(s, true)
1413
- } catch (error) {
1414
- this.host.destroyView(handle, { keepPage: true })
1415
- throw error
1416
- }
1417
- return
1418
- }
1419
- const found = this.locateTab(session, tabId)
1420
- found.s.activeIndex = found.index
1421
- this.showActive(found.s, true)
1422
- }
1423
-
1424
- /** Close one tab; closing the active tab activates the next. */
1425
- async closeTab(session: BrowserSessionId, tabId: BrowserTabWireId): Promise<void> {
1426
- const current = this.session(session)
1427
- const carrierId = this.carrierId(current, tabId)
1428
- // A page the carrier owns rather than a view we created. It was reported by `listTabs` under
1429
- // this prefix, so closing it here is what keeps the two tools consistent — a page that can be
1430
- // listed must be closable, or the listing reads as a contradiction.
1431
- if (carrierId !== undefined) {
1432
- const id = carrierId
1433
- if (this.host.closePage === undefined) {
1434
- return Promise.reject(new BrowserError(
1435
- 'browser: this carrier does not expose the pages it opens on its own, so that page cannot be closed',
1436
- 'BROWSER_TAB_NOT_FOUND',
1437
- ))
1438
- }
1439
- await this.host.closePage(id, this.carrierScope(current))
1440
- if (!this.session(session).tabs.some(tab => tab.id === tabId)) return
1441
- }
1442
- const found = this.locateTab(session, tabId)
1443
- const s = found.s
1444
- const index = found.index
1445
- const removed = s.tabs[index]
1446
- if (removed !== undefined) {
1447
- s.tabs.splice(index, 1)
1448
- this.destroyTab(removed, { keepPage: carrierId !== undefined })
1449
- }
1450
- if (s.tabs.length === 0) {
1451
- // Session keeps one blank tab so it stays usable.
1452
- this.newTab(s)
1453
- } else if (index < s.activeIndex) {
1454
- // Closing a tab before the active one shifts the array left; keep the
1455
- // same tab active by decrementing the index.
1456
- s.activeIndex -= 1
1457
- } else if (index === s.activeIndex) {
1458
- // The active tab itself was closed; activate the next tab (the one that
1459
- // shifted into its place), or the last one when the closed tab was the
1460
- // last.
1461
- s.activeIndex = Math.min(index, s.tabs.length - 1)
1462
- }
1463
- this.showActive(s)
1464
- return Promise.resolve()
1465
- }
1466
-
1467
- /**
1468
- * Find a canonical tab within the calling session.
1469
- */
1470
- private locateTab(session: BrowserSessionId, tabId: string): { s: Session; index: number } {
1471
- const s = this.session(session)
1472
- resolveTabHandle(resolveSessionHandle(session), tabId)
1473
- const own = s.tabs.findIndex(tab => tab.id === tabId)
1474
- if (own >= 0) return { s, index: own }
1475
- const ownIds = s.tabs.map(t => t.id).join(', ') || '(none)'
1476
- throw new BrowserError(
1477
- `browser: tab "${tabId}" is not open in this session (session tabs: ${ownIds})`,
1478
- 'BROWSER_TAB_UNKNOWN',
1479
- )
1480
- }
1481
-
1482
- /** Close every tab and reset to one blank tab. */
1483
- reset(session: BrowserSessionId): Promise<void> {
1484
- const s = this.session(session)
1485
- for (const tab of s.tabs) this.destroyTab(tab)
1486
- s.tabs.length = 0
1487
- this.newTab(s)
1488
- s.activeIndex = 0
1489
- this.showActive(s)
1490
- return Promise.resolve()
1491
- }
1492
-
1493
- /** Navigate the active tab's view to a URL, honoring HTTP(S)-only admission. */
1494
- async navigate(session: BrowserSessionId, request: { readonly url: string }, signal?: AbortSignal): Promise<void> {
1495
- const s = this.session(session)
1496
- await this.prepareCarrier(signal, s.id)
1497
- const tab = this.activeTab(s)
1498
- const transaction = this.beginNavigation(tab, signal)
1499
- const { navigation } = transaction
1500
- signal = transaction.signal
1501
- await this.navigateTab(s, tab, request.url, navigation, signal)
1502
- }
1503
-
1504
- private beginNavigation(tab: Tab, signal?: AbortSignal): { navigation: symbol; signal: AbortSignal } {
1505
- signal?.throwIfAborted()
1506
- const previous = tab.navigationAbort
1507
- tab.navigation = Symbol()
1508
- tab.navigationAbort = new AbortController()
1509
- previous?.abort(Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' }))
1510
- return { navigation: tab.navigation, signal: signal === undefined ? tab.navigationAbort.signal : AbortSignal.any([signal, tab.navigationAbort.signal]) }
1511
- }
1512
-
1513
- private checkNavigation(tab: Tab, navigation: symbol): void {
1514
- if (tab.failure !== undefined) throw tab.failure
1515
- if (![...this.sessions.values()].some(session => session.tabs.includes(tab))) {
1516
- throw new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED')
1517
- }
1518
- if (tab.navigation !== navigation) {
1519
- throw Object.assign(new Error('a newer navigation was requested for this browser tab'), { code: 'panel-navigation-superseded' })
1520
- }
1521
- }
1522
-
1523
- private async navigateTab(s: Session, tab: Tab, url: string, navigation: symbol, signal?: AbortSignal): Promise<void> {
1524
- const { handle } = tab
1525
- this.checkNavigation(tab, navigation)
1526
- try {
1527
- if (this.httpOnly) {
1528
- let parsed: URL
1529
- try {
1530
- parsed = new URL(url)
1531
- } catch {
1532
- throw new BrowserError(`browser: refusing navigation to unparseable URL "${url}"`, 'BROWSER_NAVIGATION_BLOCKED')
1533
- }
1534
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
1535
- throw new BrowserError(`browser: refusing navigation to non-HTTP(S) URL "${url}"`, 'BROWSER_NAVIGATION_BLOCKED')
1536
- }
1537
- }
1538
- signal?.throwIfAborted()
1539
- // Page.navigate can hang on an unreachable/slow host; bound it like the
1540
- // evaluate paths so a wedged navigation surfaces as an error instead of
1541
- // blocking the tool call forever.
1542
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
1543
- const deadline = Date.now() + timeoutMs
1544
- // Document identity of the page we are leaving (see settleDocument).
1545
- const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline).catch(() => undefined)
1546
- this.checkNavigation(tab, navigation)
1547
- signal?.throwIfAborted()
1548
- const result = await withTimeout(
1549
- handle.sendCommand(CDP_PAGE_NAVIGATE, { url } satisfies CdpNavigateParams, { deadline, signal }),
1550
- Math.max(1, deadline - Date.now()),
1551
- signal,
1552
- `browser: navigation timed out after ${timeoutMs}ms`,
1553
- // Best-effort: cancel the in-flight navigation so a wedged load does
1554
- // not leave the debugger queue busy.
1555
- timedOut => { if (tab.navigation === navigation) this.interrupt(handle, timedOut) },
1556
- )
1557
- // Page.navigate resolves even when the navigation fails; surface the
1558
- // failure instead of leaving a silent white screen.
1559
- this.checkNavigation(tab, navigation)
1560
- const errorText = (result as { errorText?: string } | undefined)?.errorText
1561
- if (typeof errorText === 'string' && errorText !== '') {
1562
- throw new BrowserError(`browser: navigation to "${url}" failed: ${errorText}`, 'BROWSER_NAVIGATION_FAILED')
1563
- }
1564
- signal?.throwIfAborted()
1565
- const acknowledgement = result as { frameId?: string; loaderId?: string } | undefined
1566
- if (typeof acknowledgement?.frameId !== 'string' || acknowledgement.frameId === '') {
1567
- throw new BrowserError('browser: navigation returned no frame acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED')
1568
- }
1569
- if (acknowledgement.loaderId === undefined ? before === undefined
1570
- : typeof acknowledgement.loaderId !== 'string' || acknowledgement.loaderId === '') {
1571
- throw new BrowserError('browser: navigation returned no document acknowledgement', 'BROWSER_DOCUMENT_UNACKNOWLEDGED')
1572
- }
1573
- tab.url = url
1574
- await this.settleDocument(handle, before, signal, acknowledgement, () => { this.checkNavigation(tab, navigation) }, undefined, deadline)
1575
- this.checkNavigation(tab, navigation)
1576
- this.record(s, 'navigate', { url }, true)
1577
- this.recordVisit(s, handle)
1578
- this.showActive(s, true)
1579
- } catch (error) {
1580
- const code = (error as { code?: string })?.code
1581
- if (tab.navigation === navigation && (code === 'BROWSER_DOCUMENT_TIMEOUT' || code === 'BROWSER_DOCUMENT_UNACKNOWLEDGED')) {
1582
- this.quarantine(handle)
1583
- }
1584
- if (!(error instanceof BrowserError && (error as { code?: string }).code === 'BROWSER_NAVIGATION_BLOCKED')) {
1585
- this.record(s, 'navigate', { url }, false, { error: String(error) })
1586
- }
1587
- throw error
1588
- }
1589
- }
1590
-
1591
- private async documentIdentity(handle: ElectronViewHandle, signal?: AbortSignal, checkCurrent?: () => void,
1592
- deadline = Date.now() + PROVIDER_TIMEOUTS.evaluation, allowErrorDocument = false): Promise<DocumentIdentity> {
1593
- signal?.throwIfAborted()
1594
- checkCurrent?.()
1595
- return mainDocument(await withTimeout(
1596
- handle.sendCommand('Page.getFrameTree', undefined, { present: false, initialize: false }),
1597
- Math.max(1, Math.min(PROVIDER_TIMEOUTS.evaluation, deadline - Date.now())), signal, 'browser: document identity timed out', timedOut => {
1598
- try { checkCurrent?.() } catch { return }
1599
- this.interrupt(handle, timedOut)
1600
- },
1601
- ), { allowErrorDocument })
1602
- }
1603
-
1604
- /**
1605
- * Page.navigate resolves at navigation COMMIT, not at load: the new document
1606
- * is already current (so location.href and document.title are the new page's)
1607
- * while its DOM is still being parsed. dsh_browser_open snapshots immediately
1608
- * after navigating, which is why it could report the right title with zero
1609
- * interactive elements — and why a separate dsh_browser_snapshot right after
1610
- * always found them.
1611
- *
1612
- * The CDP frame/loader acknowledgement, not elapsed time or URL equality,
1613
- * identifies the document whose parse readiness can complete the transaction.
1614
- */
1615
- private async settleDocument(handle: ElectronViewHandle, before: DocumentIdentity | undefined, signal?: AbortSignal,
1616
- acknowledgement?: { readonly frameId?: string; readonly loaderId?: string }, checkCurrent?: () => void,
1617
- historyEntry?: number, deadline = Date.now() + DEFAULT_OPERATION_TIMEOUT_MS, allowErrorDocument = false): Promise<void> {
1618
- // The document is being replaced, so the synthetic pointer drawn into the old one
1619
- // is gone. Dropping the remembered position is what lets it be painted again:
1620
- // without this, a paint at coincidentally identical coordinates would be skipped
1621
- // and the pointer would never come back after a navigation.
1622
- forgetCursor(handle)
1623
- for (;;) {
1624
- signal?.throwIfAborted()
1625
- checkCurrent?.()
1626
- const remaining = deadline - Date.now()
1627
- if (remaining <= 0) {
1628
- this.quarantine(handle)
1629
- throw new BrowserError('browser: the navigation document was not ready within its deadline', 'BROWSER_DOCUMENT_TIMEOUT')
1630
- }
1631
- const ready = await withTimeout((async () => {
1632
- if (historyEntry !== undefined) {
1633
- const history = await handle.sendCommand('Page.getNavigationHistory') as { entries?: Array<{ id?: number }>; currentIndex?: number }
1634
- if (history.entries?.[history.currentIndex ?? -1]?.id !== historyEntry) return false
1635
- }
1636
- const current = await this.documentIdentity(handle, signal, checkCurrent, deadline, allowErrorDocument)
1637
- if (acknowledgement?.frameId !== undefined && current.id !== acknowledgement.frameId) {
1638
- throw new BrowserError('browser: navigation frame was superseded', 'BROWSER_NAVIGATION_SUPERSEDED')
1639
- }
1640
- const loader = acknowledgement?.loaderId ?? (acknowledgement === undefined ? undefined : before?.loaderId)
1641
- if (loader !== undefined && current.loaderId !== loader) {
1642
- if (current.loaderId === before?.loaderId) return false
1643
- throw new BrowserError('browser: navigation document was superseded', 'BROWSER_NAVIGATION_SUPERSEDED')
1644
- }
1645
- if (acknowledgement === undefined && current.loaderId === before?.loaderId) return false
1646
- return documentReady(handle, current, () => {
1647
- signal?.throwIfAborted()
1648
- checkCurrent?.()
1649
- if (Date.now() >= deadline) {
1650
- this.quarantine(handle)
1651
- throw new BrowserError('browser: document readiness deadline expired', 'BROWSER_DOCUMENT_TIMEOUT')
1652
- }
1653
- })
1654
- })(), remaining, signal, 'browser: document readiness timed out', timedOut => {
1655
- try { checkCurrent?.() } catch { return }
1656
- this.interrupt(handle, timedOut)
1657
- })
1658
- signal?.throwIfAborted()
1659
- checkCurrent?.()
1660
- if (ready) return
1661
- await delay(Math.min(SETTLE_POLL_MS, Math.max(0, deadline - Date.now())), signal)
1662
- }
1663
- }
1664
-
1665
- /**
1666
- * Make sure the active tab's view can actually receive synthesized input.
1667
- * Chromium drops `Input.*` events for a view with no display surface, so this
1668
- * runs before click/type/key and fails loudly (BROWSER_VIEW_NOT_PRESENTED)
1669
- * rather than reporting a success the page never saw.
1670
- * @param s - the session whose active view must be presented.
1671
- * @param signal - optional cancellation.
1672
- * @returns the view the session's active tab has AFTER the presentation barrier.
1673
- */
1674
- private async present(s: Session, signal?: AbortSignal): Promise<ElectronViewHandle> {
1675
- const { handle } = this.activeTab(s)
1676
- const present = this.host.presentView?.bind(this.host)
1677
- if (present === undefined) {
1678
- this.showActive(s)
1679
- return this.activeTab(s).handle
1680
- }
1681
- signal?.throwIfAborted()
1682
- const timeoutMs = PROVIDER_TIMEOUTS.lookup
1683
- try {
1684
- await withTimeout(
1685
- present(handle, s.label, { quiet: this.isQuiet() }),
1686
- timeoutMs,
1687
- signal,
1688
- `browser: presenting the page view timed out after ${timeoutMs}ms`,
1689
- )
1690
- this.showActive(s)
1691
- } catch (error) {
1692
- throw new BrowserError(
1693
- `browser: the page view is not presented, so synthesized input would be silently dropped (${String(error)})`,
1694
- 'BROWSER_VIEW_NOT_PRESENTED',
1695
- { cause: error },
1696
- )
1697
- }
1698
- // Read the active tab AGAIN. `present` is a round-trip that can take up to the budget
1699
- // above, and the human is invited to drive the same window (a toolbar tab switch, a
1700
- // closed window) while the agent waits. Chromium answers `Input.*` with success even
1701
- // for a view that has no display surface, so dispatching to a handle that is no longer
1702
- // the visible one does not fail — it silently lands nowhere, or on the wrong page.
1703
- //
1704
- // Returning the re-read handle was wrong, though: `handle` above is the one that was
1705
- // actually presented, and if the active tab changed during the round trip then the
1706
- // re-read one was never presented at all. Handing it back meant the caller dispatched
1707
- // to a view with no display surface — the exact failure this method exists to prevent,
1708
- // arrived at from the other side. Either the presented view is still the active one, or
1709
- // the caller must be told rather than given something else to aim at.
1710
- const live = this.activeTab(s).handle
1711
- if (live !== handle) {
1712
- throw new BrowserError(
1713
- 'browser: the active tab changed while the page view was being presented, so synthesized input would go to an unshown view — retry, and the new page will be presented instead',
1714
- 'BROWSER_VIEW_CHANGED',
1715
- )
1716
- }
1717
- return handle
1718
- }
1719
-
1720
- /**
1721
- * Refuse to send synthesized input to a view that is no longer the one it was located
1722
- * against.
1723
- *
1724
- * `locateHandle` was captured before a page-side locate that can consume its whole
1725
- * 10s budget; the session's active tab is re-read afterwards. If they differ, the human
1726
- * switched tabs mid-flight (the product's whole point is that they can take over), and
1727
- * the coordinates belong to one page while the dispatch would go to another. Comparing
1728
- * the handles turns that into a loud, retryable error instead of input the caller
1729
- * believes landed.
1730
- * @param session - the session id, for the message.
1731
- * @param locateHandle - the view the locate ran in.
1732
- * @param liveHandle - the view that is active now.
1733
- */
1734
- private assertSameView(session: BrowserSessionId, locateHandle: ElectronViewHandle, liveHandle: ElectronViewHandle): void {
1735
- if (locateHandle === liveHandle) return
1736
- throw new BrowserError(
1737
- `browser: the session's active view changed while the element was being located (session ${session}); the operation was not dispatched — retry it`,
1738
- 'BROWSER_VIEW_CHANGED',
1739
- )
1740
- }
1741
-
1742
- /**
1743
- * Give the view web focus before synthesizing keyboard input.
1744
- *
1745
- * A renderer only delivers key events to the view that holds web focus. A
1746
- * view that was created but never clicked holds none — and `Input` events
1747
- * injected over CDP do not grant it — so the FIRST `dsh_browser_key` of a fresh
1748
- * session vanished inside the renderer while the command still answered
1749
- * success. Hosts that cannot focus a view (a test double, a different shell
1750
- * adapter) simply have no `focus`, and nothing changes for them.
1751
- */
1752
- private async focusView(handle: ElectronViewHandle): Promise<void> {
1753
- if (handle.focus === undefined) return
1754
- const quiet = this.isQuiet()
1755
- try {
1756
- // Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
1757
- // and this runs before typing, so an unresponsive child would hang dsh_browser_key for
1758
- // good. A timeout is caught below exactly like any other focus failure, so the
1759
- // best-effort contract is unchanged.
1760
- await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out')
1761
- } catch (error) {
1762
- if (quiet) throw error
1763
- // Best-effort: a view that refuses focus must not fail the caller's key
1764
- // press; the dispatch below reports a real channel failure itself.
1765
- }
1766
- }
1767
-
1768
- /** Execute JS in the active tab's page context. */
1769
- async execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1770
- this.assertActionAllowed('execute')
1771
- return this.evaluatePage(session, request, signal)
1772
- }
1773
-
1774
- /** Run a fixed browser operation; the request cannot contain a script. */
1775
- async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1776
- const script = pageOperationScript(request)
1777
- if (request.operation === 'drag') {
1778
- return this.dispatchPointer(session, request.from, request.to, request.steps, signal)
1779
- }
1780
- if (request.operation === 'probe' && request.method === 'hoverAt') {
1781
- const point = { x: Number(request.args?.[0]), y: Number(request.args?.[1]) }
1782
- return this.dispatchPointer(session, point, undefined, 1, signal)
1783
- }
1784
- return this.evaluatePage(session, { script }, signal)
1785
- }
1786
-
1787
- /** Send page pointer input through CDP while preserving presentation and cancellation policy. */
1788
- private async dispatchPointer(
1789
- session: BrowserSessionId,
1790
- from: { readonly x: number; readonly y: number },
1791
- to: { readonly x: number; readonly y: number } | undefined,
1792
- steps: number,
1793
- signal?: AbortSignal,
1794
- ): Promise<BrowserExecuteResult> {
1795
- const coordinates = [from.x, from.y, ...to === undefined ? [] : [to.x, to.y]]
1796
- if (coordinates.some(value => !Number.isFinite(value) || value < 0)) {
1797
- throw new BrowserError('browser: pointer coordinates must be finite nonnegative viewport pixels', 'BROWSER_POINTER_INVALID')
1798
- }
1799
- if (to !== undefined && this.settingsSource?.().vision.strategy === 'nonVisual') {
1800
- throw new BrowserError('browser: coordinate dragging requires the visual strategy', 'BROWSER_NON_VISUAL_COORDINATES')
1801
- }
1802
- const s = this.session(session)
1803
- const handle = await this.present(s, signal)
1804
- const viewport = await withTimeout(
1805
- handleSendEvaluate(handle, '({width:innerWidth,height:innerHeight})'),
1806
- PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer viewport check timed out',
1807
- )
1808
- if (!viewport.ok) throw new BrowserError('browser: could not read the pointer viewport', 'BROWSER_POINTER_INVALID')
1809
- const size = viewport.value as { width: number; height: number }
1810
- if (from.x >= size.width || from.y >= size.height || (to !== undefined && (to.x >= size.width || to.y >= size.height))) {
1811
- return { ok: true, value: JSON.stringify(to === undefined ? false : { ok: false, reason: 'drag points must be inside the current viewport' }) }
1812
- }
1813
- const send = async (params: CdpMouseParams): Promise<void> => {
1814
- signal?.throwIfAborted()
1815
- this.assertSameView(session, handle, this.activeTab(s).handle)
1816
- await withTimeout(handle.sendCommand('Input.dispatchMouseEvent', { ...params }), PROVIDER_TIMEOUTS.interaction, signal, 'browser: pointer input timed out')
1817
- }
1818
- await send({ type: 'mouseMoved', x: from.x, y: from.y, buttons: 0 })
1819
- if (to === undefined) return { ok: true, value: 'true' }
1820
- let at = from
1821
- let held = true
1822
- try {
1823
- await send({ type: 'mousePressed', x: from.x, y: from.y, button: 'left', buttons: 1, clickCount: 1 })
1824
- const count = Math.max(1, Math.min(Math.trunc(steps) || 12, 60))
1825
- for (let step = 1; step <= count; step += 1) {
1826
- const next = { x: from.x + (to.x - from.x) * step / count, y: from.y + (to.y - from.y) * step / count }
1827
- await send({ type: 'mouseMoved', ...next, button: 'left', buttons: 1 })
1828
- at = next
1829
- }
1830
- // Native HTML drag targets need a final drag-over before releasing at the destination.
1831
- await send({ type: 'mouseMoved', ...to, button: 'left', buttons: 1 })
1832
- await send({ type: 'mouseReleased', ...to, button: 'left', buttons: 0, clickCount: 1 })
1833
- held = false
1834
- return { ok: true, value: JSON.stringify({ ok: true, moved: count, at: to }) }
1835
- } finally {
1836
- if (held) {
1837
- await withTimeout(
1838
- handle.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, button: 'left', buttons: 0, clickCount: 1 }),
1839
- 1_000, undefined, 'browser: pointer release timed out',
1840
- ).catch(() => {})
1841
- }
1842
- }
1843
- }
1844
-
1845
- private async evaluatePage(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
1846
- const s = this.session(session)
1847
- const { handle } = this.activeTab(s)
1848
- signal?.throwIfAborted()
1849
- try {
1850
- // Wrap the script in a Function so `return` statements are legal and
1851
- // request.args arrive as `arguments[0..n]`. A bare script handed to CDP
1852
- // Runtime.evaluate is an expression context — a leading `return` would
1853
- // be a syntax error, and an object-literal script (`{...}`) would parse
1854
- // as a block. So: if the script already starts with `return`, use it as
1855
- // the body verbatim; otherwise wrap it as `return (expr)` so both
1856
- // expression and object-literal forms evaluate to their value. Args are
1857
- // embedded as a JSON array literal; unserializable members become null.
1858
- const body = /^\s*return\b/.test(request.script)
1859
- ? request.script
1860
- : `return (${request.script})`
1861
- const hasArgs = request.args !== undefined && request.args.length > 0
1862
- const expression = hasArgs
1863
- ? `(function(){ const __dshArgs = ${JSON.stringify(request.args)}; return Function(${JSON.stringify(body)}).apply(null, __dshArgs) })()`
1864
- : `(function(){ return Function(${JSON.stringify(body)})() })()`
1865
- // CDP Runtime.evaluate can hang indefinitely on a not-yet-loaded page
1866
- // (navigate returned but the renderer has not committed). Bound it so a
1867
- // stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
1868
- // whole tool call. The caller's signal wins when it fires first.
1869
- const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
1870
- const result = await withTimeout(
1871
- handle.sendCommand(CDP_RUNTIME_EVALUATE, {
1872
- expression,
1873
- returnByValue: true,
1874
- awaitPromise: true,
1875
- } satisfies CdpEvaluateParams),
1876
- timeoutMs,
1877
- signal,
1878
- `browser: execute timed out after ${timeoutMs}ms`,
1879
- // Best-effort: kill the wedged page script so the renderer (and the
1880
- // debugger queue) is not stuck behind a busy loop forever.
1881
- timedOut => { this.interrupt(handle, timedOut) },
1882
- )
1883
- if (result.exceptionDetails !== undefined) {
1884
- const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
1885
- const exception = detail.exception?.description ?? detail.text ?? 'unknown exception'
1886
- this.record(s, 'execute', { script: request.script }, false, { error: exception })
1887
- return { ok: false, exception }
1888
- }
1889
- const value = (result.result as { value?: unknown } | undefined)?.value ?? null
1890
- this.record(s, 'execute', {
1891
- script: request.script,
1892
- ...request.args !== undefined && request.args.length > 0 ? { args: request.args } : {},
1893
- }, true, { result: typeof value === 'string' ? value.slice(0, 500) : JSON.stringify(value).slice(0, 500) })
1894
- return { ok: true, value }
1895
- } catch (error) {
1896
- // A caller that aborted is not a failure of the page: report its own reason, or the
1897
- // cancellation surfaces as "execute failed: AbortError" and — if the caller's reason
1898
- // happens to be named TimeoutError — as "timed out after 30000ms", quoting a budget
1899
- // that belongs to the caller rather than to this call.
1900
- if (signal?.aborted) throw signal.reason
1901
- if (error instanceof Error && error.name === 'TimeoutError') {
1902
- throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error })
1903
- }
1904
- throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error })
1905
- }
1906
- }
1907
-
1908
- /**
1909
- * Poll until the active tab's page is ready (and optional URL/selector
1910
- * match), or the budget runs out. Returns a verdict instead of throwing on
1911
- * timeout — the caller (model) decides what a miss means. Polling evaluates
1912
- * in the CURRENT document, so after a navigation the old document may
1913
- * briefly answer; pass the expected `url` to disambiguate.
1914
- */
1915
- async waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult> {
1916
- const tab = this.activeTab(this.session(session))
1917
- signal?.throwIfAborted()
1918
- const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
1919
- const deadline = Date.now() + timeoutMs
1920
- const url = request.url ?? ''
1921
- const selector = request.selector ?? ''
1922
- const checkLoaded = request.loaded !== false
1923
- const expression = `(() => {
1924
- const wantUrl = ${JSON.stringify(url)}
1925
- const wantSelector = ${JSON.stringify(selector)}
1926
- const inDoc = (doc, sel) => {
1927
- if (doc.querySelector(sel)) return true
1928
- for (const el of doc.querySelectorAll('iframe')) {
1929
- try { const d = el.contentDocument; if (d && inDoc(d, sel)) return true } catch { /* cross-origin */ }
1930
- }
1931
- return false
1932
- }
1933
- const href = location.href
1934
- // Exact match wins; otherwise prefix-match within the SAME origin only,
1935
- // so wantUrl "https://a.com" never matches a cross-origin page whose
1936
- // host merely starts with the same characters ("https://a.com.evil.com").
1937
- let urlOk = wantUrl === '' || href === wantUrl
1938
- if (!urlOk && wantUrl !== '') {
1939
- try {
1940
- const want = new URL(wantUrl)
1941
- const got = new URL(href)
1942
- urlOk = want.origin === got.origin && href.startsWith(wantUrl)
1943
- } catch { urlOk = false }
1944
- }
1945
- const loadedOk = document.readyState === 'complete' || document.readyState === 'interactive'
1946
- const foundOk = wantSelector === '' || inDoc(document, wantSelector)
1947
- return { urlOk, loadedOk, foundOk }
1948
- })()`
1949
- for (;;) {
1950
- const result = await withTimeout(
1951
- handleSendEvaluate(tab.handle, expression),
1952
- Math.min(PROVIDER_TIMEOUTS.interaction, Math.max(250, deadline - Date.now())),
1953
- signal,
1954
- 'browser: wait poll timed out',
1955
- timedOut => { this.interrupt(tab.handle, timedOut) },
1956
- )
1957
- if (!result.ok) {
1958
- throw new BrowserError(`browser: wait failed: ${result.exception}`, 'BROWSER_WAIT_FAILED')
1959
- }
1960
- const state = result.value as { urlOk: boolean; loadedOk: boolean; foundOk: boolean }
1961
- const urlOk = url === '' || state.urlOk === true
1962
- const loadedOk = !checkLoaded || state.loadedOk === true
1963
- const foundOk = selector === '' || state.foundOk === true
1964
- if (urlOk && loadedOk && foundOk) {
1965
- return { ready: true, reason: 'condition met' }
1966
- }
1967
- if (Date.now() >= deadline) {
1968
- const misses: string[] = []
1969
- if (!urlOk) misses.push(`url not yet "${url}"`)
1970
- if (!loadedOk) misses.push('page not loaded')
1971
- if (!foundOk) misses.push(`selector "${selector}" not found`)
1972
- return { ready: false, reason: misses.join('; ') }
1973
- }
1974
- // Sleep between polls, abortable by the caller.
1975
- // Sleep between polls; delay() removes its abort listener on both paths, which the
1976
- // hand-rolled version here did not — a 30s wait leaked about 150 of them.
1977
- await delay(200, signal)
1978
- }
1979
- }
1980
-
1981
- /** Produce an AI-friendly snapshot of the active tab. */
1982
- async snapshot(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserSnapshotResult> {
1983
- const s = this.session(session)
1984
- const tab = this.activeTab(s)
1985
- signal?.throwIfAborted()
1986
- // A tab that has never navigated is a blank, uncommitted view. The collector cannot answer in
1987
- // it — there is no document to commit — so the call would sit out its whole budget before
1988
- // saying anything. Answering the empty page immediately is both faster and more truthful.
1989
- //
1990
- // `about:blank` needs the same answer for a different reason: it HAS a document, so the collector
1991
- // runs, finds nothing, and returns zero elements — indistinguishable from a real page with nothing
1992
- // interactive. A caller then acts on it and receives success values, which is how a carrier swap
1993
- // that started a fresh window looked like working tools operating on the wrong page (issue #37).
1994
- const blankUrl = tab.url === '' || tab.url === 'about:blank'
1995
- if (blankUrl) {
1996
- return {
1997
- url: tab.url,
1998
- elements: [],
1999
- truncated: false,
2000
- blank: true,
2001
- note: tab.url === ''
2002
- ? 'no page has been opened in this browser yet'
2003
- : 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
2004
- }
2005
- }
2006
- const script = `(() => {
2007
- const cap = ${String(this.snapshotMaxElements)}
2008
- const url = location.href
2009
- const title = document.title || undefined
2010
- // Collect interactive elements from the top document AND from shadow
2011
- // roots and same-origin iframes (cross-origin iframes stay opaque — the
2012
- // browser forbids reading them, and so does this snapshot). Elements
2013
- // inside iframes carry a frame flag so the model knows DOM selectors
2014
- // are frame-scoped; coordinates below are always top-document.
2015
- const SELECTOR = 'input, textarea, select, button, a[href], [role="button"], [role="searchbox"], [contenteditable="true"]'
2016
- const els = []
2017
- const seen = new Set()
2018
- const collect = (doc, inFrame) => {
2019
- if (seen.has(doc)) return
2020
- seen.add(doc)
2021
- const hosts = []
2022
- for (const el of doc.querySelectorAll('*')) {
2023
- if (el.matches(SELECTOR)) els.push({ el, inFrame })
2024
- if (el.shadowRoot) hosts.push({ doc: el.shadowRoot, inFrame })
2025
- if (el.tagName === 'IFRAME') {
2026
- try { const d = el.contentDocument; if (d) hosts.push({ doc: d, inFrame: true }) } catch { /* cross-origin */ }
2027
- }
2028
- }
2029
- for (const h of hosts) collect(h.doc, h.inFrame)
2030
- }
2031
- collect(document, false)
2032
- // Absolute viewport coordinates in the TOP document: iframe content is
2033
- // offset by each ancestor iframe's rect, so coordinate clicks land on
2034
- // the right element no matter which frame it lives in.
2035
- const absRect = (el, doc) => {
2036
- const r = el.getBoundingClientRect()
2037
- let x = r.x, y = r.y
2038
- let d = doc
2039
- while (d && d.defaultView && d.defaultView.frameElement) {
2040
- const fr = d.defaultView.frameElement.getBoundingClientRect()
2041
- x += fr.x; y += fr.y
2042
- d = d.defaultView.frameElement.ownerDocument
2043
- }
2044
- return { x, y, w: r.width, h: r.height }
2045
- }
2046
- const out = []
2047
- for (const { el, inFrame } of els) {
2048
- if (out.length >= cap) break
2049
- const r = el.getBoundingClientRect()
2050
- // Cheap layout check first; only force style recalc when it passes.
2051
- if (r.width < 4 || r.height < 4) continue
2052
- const cs = getComputedStyle(el)
2053
- if (cs.visibility === 'hidden' || cs.display === 'none') continue
2054
- const kind = el.tagName === 'INPUT' ? (el.type === 'checkbox' ? 'checkbox' : (el.type === 'submit' || el.type === 'button' ? 'button' : 'input'))
2055
- : el.tagName === 'TEXTAREA' ? 'textarea'
2056
- : el.tagName === 'SELECT' ? 'select'
2057
- : el.tagName === 'BUTTON' ? 'button'
2058
- : el.tagName === 'A' ? 'link' : 'other'
2059
- // An anchor wrapping only an image has no text: 4399.com's 1608 game links are all
2060
- // <a href><img alt="名字"></a>, so every label came out empty and the whole page read as
2061
- // "no interactive elements" while it was full of them.
2062
- const imageAlt = el.tagName === 'A' || el.tagName === 'BUTTON'
2063
- ? (el.querySelector('img[alt]')?.getAttribute('alt') ?? '')
2064
- : ''
2065
- const label = (el.getAttribute('aria-label') || el.placeholder || el.textContent || imageAlt
2066
- || el.value || el.name || el.id || '').toString().replace(/\\s+/g, ' ').trim().slice(0, ${String(SNAPSHOT_LABEL_MAX)})
2067
- if (!label && kind !== 'link') continue
2068
- const a = absRect(el, el.ownerDocument)
2069
- out.push({
2070
- ref: out.length + 1,
2071
- kind,
2072
- label,
2073
- selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
2074
- x: Math.round(a.x + a.w / 2),
2075
- y: Math.round(a.y + a.h / 2),
2076
- ...inFrame ? { frame: true } : {},
2077
- })
2078
- }
2079
- const challenge = ${CHALLENGE_DETECT_EXPRESSION}
2080
- // The page's own URL is the authority on whether there is a document. The tracked tab.url is
2081
- // a bookkeeping copy that can lag behind a navigation the browser performed itself, and a
2082
- // stale copy made this check miss on a real about:blank tab.
2083
- const blankPage = out.length === 0 && (url === '' || url === 'about:blank')
2084
- // Independent of the element list: a page can mix DOM controls with a canvas that holds the
2085
- // part the caller actually needs. Measured on sudoku.com — 60 links were collected and the
2086
- // board, drawn on a canvas, was invisible in the same result.
2087
- //
2088
- // The thresholds keep a decorative canvas from claiming a page: at least 80x80 per canvas and
2089
- // 10% of the viewport in total. Anything smaller is reported by nothing, which is right.
2090
- let canvas
2091
- if (blankPage !== true) {
2092
- let area = 0
2093
- let count = 0
2094
- for (const c of document.querySelectorAll('canvas')) {
2095
- const r = c.getBoundingClientRect()
2096
- if (r.width < 80 || r.height < 80) continue
2097
- count += 1
2098
- area += r.width * r.height
2099
- }
2100
- const view = window.innerWidth * window.innerHeight
2101
- if (count > 0 && view > 0 && area / view >= 0.1) canvas = true
2102
- }
2103
- return {
2104
- url,
2105
- title,
2106
- elements: out,
2107
- truncated: out.length >= cap,
2108
- challenge,
2109
- ...blankPage === true
2110
- ? {
2111
- blank: true,
2112
- note: 'the page is about:blank — nothing has been opened in this browser, so there is nothing to read or drive',
2113
- }
2114
- : {},
2115
- ...canvas === true
2116
- ? {
2117
- canvas: true,
2118
- note: out.length === 0
2119
- ? 'this page draws its interface on a canvas, so there is no DOM content for a snapshot. '
2120
- + 'Use dsh_browser_screenshot to see it, and coordinates with dsh_browser_click to act on it.'
2121
- : 'part of this page is drawn on a canvas, which no element list can describe. The elements '
2122
- + 'below are real; anything inside the canvas is only visible in dsh_browser_screenshot.',
2123
- }
2124
- : {},
2125
- }
2126
- })()`
2127
- // Same hang guard as execute: a renderer that has not committed after
2128
- // navigate would otherwise block snapshot forever.
2129
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2130
- let result: { ok: true; value: unknown } | { ok: false; exception: string }
2131
- try {
2132
- result = await withTimeout(
2133
- handleSendEvaluate(tab.handle, script),
2134
- timeoutMs,
2135
- signal,
2136
- `browser: snapshot timed out after ${timeoutMs}ms`,
2137
- timedOut => { this.interrupt(tab.handle, timedOut) },
2138
- ) as { ok: true; value: unknown } | { ok: false; exception: string }
2139
- } catch (error) {
2140
- if (error instanceof Error && error.name === 'TimeoutError') {
2141
- this.quarantine(tab.handle)
2142
- throw new BrowserError(
2143
- 'browser: snapshot timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
2144
- 'BROWSER_SNAPSHOT_TIMEOUT',
2145
- { cause: error },
2146
- )
2147
- }
2148
- throw error
2149
- }
2150
- if (!result.ok) throw new BrowserError(`browser: snapshot evaluation failed: ${result.exception}`, 'BROWSER_SNAPSHOT_FAILED')
2151
- const value = result.value as BrowserSnapshotResult
2152
- return value
2153
- }
2154
-
2155
- /**
2156
- * Read the active tab's accessibility tree: semantic roles/names/states for
2157
- * every interactive node (Chrome's `computedRole`/`computedName` when
2158
- * available, tag/attribute inference otherwise). Pierces same-origin
2159
- * iframes and shadow roots like the snapshot; cross-origin frames stay
2160
- * opaque. Coordinates are top-document viewport-relative, so a node can
2161
- * also be driven by click/type.
2162
- */
2163
- async a11y(session: BrowserSessionId, request: BrowserA11yRequest, signal?: AbortSignal): Promise<BrowserA11yResult> {
2164
- const s = this.session(session)
2165
- const tab = this.activeTab(s)
2166
- signal?.throwIfAborted()
2167
- // Same short-circuit as `snapshot`: a tab that never navigated has no committed document, so
2168
- // the tree cannot be read and the call would spend its whole budget discovering that.
2169
- if (tab.url === '') return { url: '', title: undefined, count: 0, nodes: [], truncated: false }
2170
- const includeHidden = request.includeHidden === true
2171
- // 150 rather than 500. The cap fills on any real page, and 500 nodes measured 38,953
2172
- // characters — 10k-13k tokens for a single call. A caller that needs more asks for it.
2173
- const maxNodes = Math.max(10, Math.min(5000, Math.floor(request.maxNodes ?? 150)))
2174
- const script = `(() => {
2175
- const includeHidden = ${String(includeHidden)}
2176
- const maxNodes = ${String(maxNodes)}
2177
- const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK', 'TITLE'])
2178
- const ACTIONABLE = new Set(['button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'listbox', 'slider', 'spinbutton', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'switch', 'option', 'summary', 'treeitem', 'scrollbar'])
2179
- const CONTENT_NAMED = new Set(['button', 'link', 'heading', 'summary', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'treeitem', 'option', 'listitem', 'switch', 'checkbox', 'radio', 'searchbox', 'textbox'])
2180
- const out = []
2181
- const seen = new Set()
2182
- const ownText = (el) => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
2183
- const visible = (el) => {
2184
- const r = el.getBoundingClientRect()
2185
- const cs = getComputedStyle(el)
2186
- return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
2187
- }
2188
- const roleOf = (el) => {
2189
- const computed = el.computedRole
2190
- if (typeof computed === 'string' && computed && computed !== 'none' && computed !== 'generic') return computed
2191
- const tag = el.tagName.toLowerCase()
2192
- if (el instanceof HTMLAnchorElement) return el.hasAttribute('href') ? 'link' : 'generic'
2193
- if (tag === 'button') return 'button'
2194
- if (tag === 'textarea') return 'textbox'
2195
- if (tag === 'select') return el.hasAttribute('multiple') ? 'listbox' : 'combobox'
2196
- if (tag === 'img') return el.getAttribute('alt') === '' ? 'presentation' : 'img'
2197
- if (/^h[1-6]$/.test(tag)) return 'heading'
2198
- if (tag === 'ul' || tag === 'ol') return 'list'
2199
- if (tag === 'li') return 'listitem'
2200
- if (tag === 'nav') return 'navigation'
2201
- if (tag === 'main') return 'main'
2202
- if (tag === 'form') return 'form'
2203
- if (tag === 'table') return 'table'
2204
- if (tag === 'tr') return 'row'
2205
- if (tag === 'td') return 'cell'
2206
- if (tag === 'th') return 'columnheader'
2207
- if (tag === 'dialog') return 'dialog'
2208
- if (tag === 'summary') return 'button'
2209
- if (tag === 'input') {
2210
- const t = el.type
2211
- if (t === 'checkbox') return 'checkbox'
2212
- if (t === 'radio') return 'radio'
2213
- if (t === 'range') return 'slider'
2214
- if (t === 'number') return 'spinbutton'
2215
- if (t === 'button' || t === 'submit' || t === 'reset' || t === 'image') return 'button'
2216
- if (t === 'hidden') return 'none'
2217
- if (t === 'search') return 'searchbox'
2218
- return 'textbox'
2219
- }
2220
- return 'generic'
2221
- }
2222
- const nameOf = (el, role) => {
2223
- const computed = el.computedName
2224
- if (typeof computed === 'string' && computed && computed.trim() !== '') return computed.trim()
2225
- const aria = el.getAttribute('aria-label')
2226
- if (aria) return aria
2227
- const labelledby = el.getAttribute('aria-labelledby')
2228
- if (labelledby) {
2229
- const ref = document.getElementById(labelledby.split(/\\s+/)[0])
2230
- if (ref) {
2231
- const t = (ref.textContent || '').trim()
2232
- if (t) return t
2233
- }
2234
- }
2235
- if (el.hasAttribute('alt')) return el.getAttribute('alt')
2236
- if (el.hasAttribute('title')) return el.getAttribute('title')
2237
- if (el.placeholder) return el.placeholder
2238
- if (CONTENT_NAMED.has(role)) {
2239
- const t = ownText(el)
2240
- if (t) return t
2241
- }
2242
- if (el.id) {
2243
- const lbl = document.querySelector('label[for=' + JSON.stringify(el.id) + ']')
2244
- if (lbl) {
2245
- const t = (lbl.textContent || '').trim()
2246
- if (t) return t
2247
- }
2248
- }
2249
- return ''
2250
- }
2251
- const valueOf = (el) => {
2252
- if (el instanceof HTMLInputElement) return el.type === 'checkbox' || el.type === 'radio' ? null : el.value
2253
- if (el instanceof HTMLTextAreaElement) return el.value
2254
- if (el instanceof HTMLSelectElement) {
2255
- const o = el.options[el.selectedIndex]
2256
- return o ? (o.textContent || '').trim() : null
2257
- }
2258
- if (el.isContentEditable) return (el.textContent || '').trim()
2259
- return null
2260
- }
2261
- const statesOf = (el) => {
2262
- const st = []
2263
- if (!el.disabled) st.push('enabled'); else st.push('disabled')
2264
- if (el.checked) st.push('checked'); else if (el.getAttribute('aria-checked') === 'false') st.push('unchecked')
2265
- const expanded = el.getAttribute('aria-expanded')
2266
- if (expanded === 'true') st.push('expanded')
2267
- if (expanded === 'false') st.push('collapsed')
2268
- if (el.required) st.push('required')
2269
- if (el.readOnly) st.push('readonly')
2270
- if (el.selected) st.push('selected')
2271
- const pressed = el.getAttribute('aria-pressed')
2272
- if (pressed === 'true') st.push('pressed')
2273
- return st
2274
- }
2275
- const depthOf = (el) => {
2276
- let d = 0
2277
- let p = el.parentElement
2278
- while (p) { d++; p = p.parentElement }
2279
- return d
2280
- }
2281
- const absRect = (el, doc) => {
2282
- const r = el.getBoundingClientRect()
2283
- let x = r.x, y = r.y
2284
- let d = doc
2285
- while (d && d.defaultView && d.defaultView.frameElement) {
2286
- const fr = d.defaultView.frameElement.getBoundingClientRect()
2287
- x += fr.x; y += fr.y
2288
- d = d.defaultView.frameElement.ownerDocument
2289
- }
2290
- return { x, y, w: r.width, h: r.height }
2291
- }
2292
- const walk = (doc, inFrame, baseDepth) => {
2293
- if (seen.has(doc)) return
2294
- seen.add(doc)
2295
- for (const el of doc.querySelectorAll('*')) {
2296
- if (out.length >= maxNodes) return
2297
- if (SKIP.has(el.tagName)) continue
2298
- if (el.shadowRoot) walk(el.shadowRoot, inFrame, baseDepth + 1)
2299
- if (el.tagName === 'IFRAME') {
2300
- try { const d = el.contentDocument; if (d) walk(d, true, baseDepth + 1) } catch { /* cross-origin */ }
2301
- }
2302
- const role = roleOf(el)
2303
- if (role === 'none' || role === 'presentation' || role === 'generic') continue
2304
- if (!includeHidden && !visible(el)) continue
2305
- const name = nameOf(el, role)
2306
- if (!name && !ACTIONABLE.has(role)) continue
2307
- const a = absRect(el, el.ownerDocument)
2308
- out.push({
2309
- ref: out.length + 1,
2310
- role,
2311
- name: name.slice(0, 120),
2312
- value: valueOf(el),
2313
- states: statesOf(el),
2314
- depth: baseDepth + depthOf(el),
2315
- // Same derivation as the snapshot collector: an id or a name is what makes a node
2316
- // something the caller can point at without guessing at its text. The tool-layer
2317
- // schema declared this field before this line existed, so the schema was promising
2318
- // a value the tool never sent.
2319
- selector: el.id ? '#' + CSS.escape(el.id) : (el.name ? '[name=' + JSON.stringify(el.name) + ']' : ''),
2320
- tag: el.tagName.toLowerCase(),
2321
- x: Math.round(a.x + a.w / 2),
2322
- y: Math.round(a.y + a.h / 2),
2323
- ...inFrame ? { frame: true } : {},
2324
- })
2325
- }
2326
- }
2327
- walk(document, false, 0)
2328
- return { url: location.href, title: document.title || undefined, count: out.length, nodes: out, truncated: out.length >= maxNodes }
2329
- })()`
2330
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2331
- let result: { ok: true; value: unknown } | { ok: false; exception: string }
2332
- try {
2333
- result = await withTimeout(
2334
- handleSendEvaluate(tab.handle, script),
2335
- timeoutMs,
2336
- signal,
2337
- `browser: a11y timed out after ${timeoutMs}ms`,
2338
- timedOut => { this.interrupt(tab.handle, timedOut) },
2339
- ) as { ok: true; value: unknown } | { ok: false; exception: string }
2340
- } catch (error) {
2341
- if (error instanceof Error && error.name === 'TimeoutError') {
2342
- this.quarantine(tab.handle)
2343
- throw new BrowserError(
2344
- 'browser: a11y timed out; the guest is quarantined. Close this tab or explicitly reset the session.',
2345
- 'BROWSER_A11Y_TIMEOUT',
2346
- { cause: error },
2347
- )
2348
- }
2349
- throw error
2350
- }
2351
- if (!result.ok) throw new BrowserError(`browser: a11y evaluation failed: ${result.exception}`, 'BROWSER_A11Y_FAILED')
2352
- const value = result.value as BrowserA11yResult
2353
- this.record(s, 'a11y', { includeHidden, maxNodes }, true, { result: `${value.count} nodes` })
2354
- return value
2355
- }
2356
-
2357
- /** Check whether a human-verification challenge is blocking the active tab. */
2358
- async detectChallenge(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserChallenge> {
2359
- const s = this.session(session)
2360
- const tab = this.activeTab(s)
2361
- signal?.throwIfAborted()
2362
- const timeoutMs = PROVIDER_TIMEOUTS.action
2363
- const result = await withTimeout(
2364
- handleSendEvaluate(tab.handle, CHALLENGE_DETECT_EXPRESSION),
2365
- timeoutMs,
2366
- signal,
2367
- `browser: challenge detection timed out after ${timeoutMs}ms`,
2368
- timedOut => { this.interrupt(tab.handle, timedOut) },
2369
- )
2370
- if (!result.ok) {
2371
- throw new BrowserError(`browser: challenge detection failed: ${result.exception}`, 'BROWSER_CHALLENGE_DETECT_FAILED')
2372
- }
2373
- const value = result.value as BrowserChallenge
2374
- return { blocked: value.blocked === true, kind: value.kind, reason: value.reason }
2375
- }
2376
-
2377
- /** Fetch page content in a requested format. */
2378
- async content(session: BrowserSessionId, request: BrowserContentRequest, signal?: AbortSignal): Promise<BrowserContentResult> {
2379
- const tab = this.activeTab(this.session(session))
2380
- signal?.throwIfAborted()
2381
- const selector = request.selector ?? ''
2382
- const format = request.format
2383
- // Per-format caps. A full HTML document is enormous, but the same limit applied to
2384
- // plain text is no limit at all (a whole page of text measured 25,882 characters).
2385
- // This bounds the common case instead of letting one call spend 25k-33k tokens.
2386
- //
2387
- // The plugin config overrides the lot when it is set — see `contentMaxChars`. The caller's
2388
- // own `maxChars` still outranks both: an explicit per-call bound is the most specific
2389
- // statement of intent there is.
2390
- const maxChars = request.maxChars
2391
- ?? this.contentMaxChars
2392
- ?? (format === 'html' || format === 'json' ? 50_000 : 20_000)
2393
- const script = `(() => {
2394
- const root = ${selector === '' ? 'document.body' : `document.querySelector(${JSON.stringify(selector)})`}
2395
- if (!root) return { ok: false, reason: 'selector not found' }
2396
- const fmt = ${JSON.stringify(format)}
2397
- // Both walkers pierce shadow roots and same-origin iframes (cross-origin
2398
- // iframes stay opaque — the browser forbids reading them).
2399
- let content = ''
2400
- if (fmt === 'txt') {
2401
- // Prefer the browser's own rendered text.
2402
- //
2403
- // Walking text nodes and joining them is not equivalent: pages that wrap
2404
- // every character in its own element — one-character spans for a
2405
- // per-character animation, which is common — produce one text node per
2406
- // letter, and joining those with spaces turns every word into a column of
2407
- // letters. The rendered text reassembles them the way a reader sees them,
2408
- // and it also honours visibility, so hidden text does not leak out.
2409
- // (No backticks in this comment: it lives inside a template literal.)
2410
- const rendered = typeof root.innerText === 'string' ? root.innerText : ''
2411
- if (rendered.trim() !== '') {
2412
- content = rendered
2413
- } else {
2414
- // Fallback for nodes without layout (a detached root, or a fragment):
2415
- // collect text directly, still piercing shadow roots and same-origin
2416
- // iframes, and join without inventing separators beyond what the markup
2417
- // already implies.
2418
- const parts = []
2419
- const textWalk = (node) => {
2420
- if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
2421
- if (node.nodeType !== Node.ELEMENT_NODE) return
2422
- const tag = node.tagName.toLowerCase()
2423
- if (tag === 'script' || tag === 'style' || tag === 'noscript') return
2424
- if (tag === 'iframe') {
2425
- try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) textWalk(c) } catch { /* cross-origin */ }
2426
- return
2427
- }
2428
- if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) textWalk(c)
2429
- for (const child of node.childNodes) textWalk(child)
2430
- }
2431
- textWalk(root)
2432
- content = parts.join(' ')
2433
- }
2434
- }
2435
- else if (fmt === 'html') content = root.outerHTML || ''
2436
- // A DOM element has no own enumerable properties — everything lives on the prototype
2437
- // chain — so JSON.stringify(root) is always "{}". That is not a structured view of
2438
- // the page, it is an empty object the caller will read as "no data here" and then
2439
- // retry with other selectors. Serialise the markup instead, which is what a caller
2440
- // asking for JSON of an element can actually use.
2441
- else if (fmt === 'json') content = JSON.stringify({ html: root.outerHTML, tag: root.tagName.toLowerCase() })
2442
- else {
2443
- // markdown: headings, paragraphs, links, lists (best-effort)
2444
- const parts = []
2445
- const walk = (node) => {
2446
- if (node.nodeType === Node.TEXT_NODE) { const t = (node.textContent || '').trim(); if (t) parts.push(t); return }
2447
- if (node.nodeType !== Node.ELEMENT_NODE) return
2448
- const tag = node.tagName.toLowerCase()
2449
- if (tag === 'script' || tag === 'style' || tag === 'noscript') return
2450
- if (tag === 'iframe') {
2451
- try { const d = node.contentDocument; if (d && d.body) for (const c of d.body.childNodes) walk(c) } catch { /* cross-origin */ }
2452
- return
2453
- }
2454
- if (node.shadowRoot) for (const c of node.shadowRoot.childNodes) walk(c)
2455
- if (tag === 'h1' || tag === 'h2' || tag === 'h3' || tag === 'h4') parts.push('\\n' + '#'.repeat(Number(tag[1])) + ' ' + (node.textContent || '').trim() + '\\n')
2456
- else if (tag === 'a') { const t = (node.textContent || '').trim(); if (t) parts.push('[' + t + '](' + (node.href || '') + ')') }
2457
- else if (tag === 'li') parts.push(' - ' + (node.textContent || '').trim())
2458
- else if (tag === 'p' || tag === 'div' || tag === 'section' || tag === 'article') { const t = (node.textContent || '').trim(); if (t) parts.push(t + '\\n') }
2459
- else { for (const child of node.childNodes) walk(child) }
2460
- }
2461
- walk(root)
2462
- // Join without a separator: each part already carries its own trailing
2463
- // newline, so a space join would smear headings/links into run-on text.
2464
- content = parts.join('')
2465
- }
2466
- const truncated = content.length > ${String(maxChars)}
2467
- return { ok: true, content: content.slice(0, ${String(maxChars)}), truncated }
2468
- })()`
2469
- // Honor a per-call timeout: content evaluation can hang on a heavy page,
2470
- // so a caller-supplied budget bounds it. Unlike a bare signal entry check,
2471
- // withTimeout also interrupts a call already in flight.
2472
- const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
2473
- const result = await withTimeout(
2474
- handleSendEvaluate(tab.handle, script),
2475
- timeoutMs,
2476
- signal,
2477
- `browser: content timed out after ${timeoutMs}ms`,
2478
- timedOut => { this.interrupt(tab.handle, timedOut) },
2479
- )
2480
- if (!result.ok) throw new BrowserError(`browser: content evaluation failed: ${result.exception}`, 'BROWSER_CONTENT_FAILED')
2481
- const value = result.value as { ok: boolean; reason?: string; content?: string; truncated?: boolean }
2482
- if (!value.ok) throw new BrowserError(`browser: content fetch failed: ${value.reason ?? 'unknown'}`, 'BROWSER_CONTENT_FAILED')
2483
- return { content: value.content ?? '', truncated: value.truncated ?? false }
2484
- }
2485
-
2486
- /**
2487
- * Click at viewport coordinates, or at a located element's center when a
2488
- * `target` (css/text/xpath) is given. CDP mousePressed + mouseReleased.
2489
- */
2490
- async click(
2491
- session: BrowserSessionId,
2492
- request: BrowserClickRequest | { readonly target: BrowserElementTarget },
2493
- signal?: AbortSignal,
2494
- ): Promise<void> {
2495
- const s = this.session(session)
2496
- // The view the locate runs against. It can stop being the session's active view while
2497
- // the locate waits (see prepareTarget), so every dispatch below re-reads the live one.
2498
- const locateHandle = this.activeTab(s).handle
2499
- signal?.throwIfAborted()
2500
- let x = 0
2501
- let y = 0
2502
- if ('target' in request) {
2503
- // Semantic targeting (②): locate the element in-page, scroll it into
2504
- // view, and click its center — no coordinate guessing needed.
2505
- const locateMs = PROVIDER_TIMEOUTS.lookup
2506
- const body = `
2507
- el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' })
2508
- const r = el.getBoundingClientRect()
2509
- return { ok: true, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }
2510
- `
2511
- const script = this.buildTargetScript(request.target, locateMs, body)
2512
- const out = await this.runTargetScript(this.activeTab(s), script, locateMs, signal, 'BROWSER_CLICK_FAILED', 'browser: click')
2513
- x = Number(out.x)
2514
- y = Number(out.y)
2515
- } else {
2516
- // A coordinate only exists because somebody read a picture. Under the
2517
- // non-visual strategy the plugin must not accept one: a model that cannot
2518
- // see cannot have produced it, so the coordinates are either copied from an
2519
- // earlier vision pass or invented, and honouring them turns a silent
2520
- // mis-click into a mystery. Refusing here, with a message that says what to
2521
- // do instead, converts that into a usable instruction.
2522
- if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
2523
- throw new BrowserError(
2524
- 'browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead, e.g. target { by: "text", value: "Sign in" }, which locates the element from the DOM and clicks its centre',
2525
- 'BROWSER_NON_VISUAL_COORDINATES',
2526
- )
2527
- }
2528
- x = request.x
2529
- y = request.y
2530
- }
2531
- // Input.* is only delivered to a view with a current display surface; the
2532
- // barrier also re-presents after a navigation replaced the renderer. It returns the
2533
- // handle that may still be receiving input when it settles.
2534
- const handle = await this.present(s, signal)
2535
- // The locate (up to 10s) and the present barrier both ran against the view captured
2536
- // earlier; if the human switched tabs meanwhile, these coordinates belong to one page
2537
- // and the dispatch would go to another — and Chromium answers success either way.
2538
- if ('target' in request) this.assertSameView(session, locateHandle, handle)
2539
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2540
- const send = (params: Record<string, unknown>, label: string): Promise<unknown> =>
2541
- withTimeout(
2542
- handle.sendCommand('Input.dispatchMouseEvent', params),
2543
- timeoutMs,
2544
- signal,
2545
- `browser: click ${label} timed out after ${timeoutMs}ms`,
2546
- )
2547
- // Chromium routes a synthesized `mousePressed` to the widget's *current*
2548
- // hover target rather than hit-testing the coordinates, and a real pointer
2549
- // click is always preceded by movement. A view that has never received a
2550
- // mouse event has no hover target yet, so the press of the FIRST click on a
2551
- // fresh tab went nowhere while CDP still answered success; the second click
2552
- // landed because the first had quietly established the target. Move the
2553
- // pointer first so a click is self-contained.
2554
- try {
2555
- await send({ type: 'mouseMoved', x, y, buttons: 0 } satisfies CdpMouseParams, 'move')
2556
- } catch (error) {
2557
- throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
2558
- }
2559
- // Paint before the press so the ripple is already on screen when the click
2560
- // lands — the cursor exists to show the human WHERE the agent acts.
2561
- // Name the operation in the overlay: the pointer is the "agent is driving this
2562
- // tab" signal, so the bubble is what lets a human follow along without the log.
2563
- this.showCursor(handle, x, y, 'click', 'click', true)
2564
- const release = (): void => {
2565
- // Back to the handle the PRESS may have landed on, deliberately not to the currently
2566
- // active tab: this only runs after a failed press/release, and re-targeting a
2567
- // compensating half of a click to a view the human just switched to would press a
2568
- // button there. Best-effort either way.
2569
- void handle
2570
- .sendCommand('Input.dispatchMouseEvent', {
2571
- type: 'mouseReleased',
2572
- x,
2573
- y,
2574
- button: 'left',
2575
- buttons: 0,
2576
- clickCount: 1,
2577
- } satisfies CdpMouseParams)
2578
- .catch(() => {})
2579
- }
2580
- try {
2581
- await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 }, 'press')
2582
- } catch (error) {
2583
- // The press may still land late; release best-effort so the button is
2584
- // never left in a stuck pressed state.
2585
- release()
2586
- throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
2587
- }
2588
- try {
2589
- await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 }, 'release')
2590
- } catch (error) {
2591
- // The press already landed; retry the release so the button is not
2592
- // left pressed before surfacing the failure.
2593
- release()
2594
- throw new BrowserError(`browser: click failed: ${String(error)}`, 'BROWSER_CLICK_FAILED', { cause: error })
2595
- }
2596
- this.record(s, 'click', 'target' in request ? { target: request.target } : { x, y }, true)
2597
- }
2598
-
2599
- /**
2600
- * Click many points in order, once.
2601
- *
2602
- * The same wire sequence as {@link click}, looped — only the round-trip count changes. Presenting
2603
- * happens ONCE: the display-surface barrier is per view, not per press, and paying it for every
2604
- * point is what made an 86-cell board expensive.
2605
- *
2606
- * Stops at the first point that fails and reports where: a run that pressed through a page which
2607
- * had navigated or lost its surface would fill the wrong cells and still answer success.
2608
- * @param session - the session to click in.
2609
- * @param request - the points and the interval between them.
2610
- * @param signal - cancellation between points.
2611
- * @returns how many points landed, and where it stopped if it did not finish.
2612
- */
2613
- async clickSequence(
2614
- session: BrowserSessionId,
2615
- request: BrowserClickSequenceRequest,
2616
- signal?: AbortSignal,
2617
- ): Promise<BrowserClickSequenceResult> {
2618
- const s = this.session(session)
2619
- const points = Array.isArray(request.points) ? request.points : []
2620
- if (points.length === 0) return { clicked: 0 }
2621
- if (this.settingsSource !== undefined && this.settingsSource().vision.strategy === 'nonVisual') {
2622
- throw new BrowserError(
2623
- 'browser: the configured non-visual strategy refuses coordinate clicks — pass a semantic target instead.',
2624
- 'BROWSER_NON_VISUAL_COORDINATES',
2625
- )
2626
- }
2627
- // One barrier for the whole run: cheap, and it is the view that needs a surface, not each press.
2628
- const handle = await this.present(s, signal)
2629
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2630
- // 40 ms is above one frame at 30 fps, which is what keeps the page from reading two presses as a
2631
- // double click. Faster runs were measured dropping presses outright.
2632
- const gap = typeof request.intervalMs === 'number' && request.intervalMs >= 0 ? request.intervalMs : 40
2633
- const send = (params: Record<string, unknown>, label: string): Promise<unknown> =>
2634
- withTimeout(
2635
- handle.sendCommand('Input.dispatchMouseEvent', params),
2636
- timeoutMs,
2637
- signal,
2638
- `browser: click sequence ${label} timed out after ${timeoutMs}ms`,
2639
- )
2640
- let clicked = 0
2641
- for (const [index, point] of points.entries()) {
2642
- signal?.throwIfAborted()
2643
- const x = Number(point?.x)
2644
- const y = Number(point?.y)
2645
- if (!Number.isFinite(x) || !Number.isFinite(y)) {
2646
- return { clicked, failedAt: index, error: `point ${index} has no finite x/y` }
2647
- }
2648
- try {
2649
- // The move is load-bearing: Chromium routes a synthesized press to the CURRENT hover target,
2650
- // and a view that has never received a mouse event has none — the first press would go nowhere
2651
- // while CDP still answered success.
2652
- await send({ type: 'mouseMoved', x, y, buttons: 0 } satisfies CdpMouseParams, 'move')
2653
- await send({ type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1 } satisfies CdpMouseParams, 'press')
2654
- await send({ type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 } satisfies CdpMouseParams, 'release')
2655
- clicked += 1
2656
- } catch (error) {
2657
- // Best-effort release so a failed press cannot leave the button stuck down.
2658
- void handle
2659
- .sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1 })
2660
- .catch(() => {})
2661
- return { clicked, failedAt: index, error: String(error instanceof Error ? error.message : error) }
2662
- }
2663
- if (index < points.length - 1 && gap > 0) await new Promise(resolve => setTimeout(resolve, gap))
2664
- }
2665
- return { clicked }
2666
- }
2667
-
2668
- /**
2669
- * Type into the focused element, or focus a located element (css/text/xpath)
2670
- * first and then insert the text.
2671
- */
2672
- async type(
2673
- session: BrowserSessionId,
2674
- request: BrowserTypeRequest | { readonly target: BrowserElementTarget },
2675
- signal?: AbortSignal,
2676
- ): Promise<void> {
2677
- const s = this.session(session)
2678
- // The view the locate runs against. It can stop being the session's active view while
2679
- // the locate waits (the human is invited to drive the same window), so the input below
2680
- // goes to the handle `present` reports instead of this one.
2681
- const locateHandle = this.activeTab(s).handle
2682
- signal?.throwIfAborted()
2683
- const hasTarget = 'target' in request
2684
- if (hasTarget) {
2685
- const locateMs = PROVIDER_TIMEOUTS.lookup
2686
- const script = this.buildTargetScript(request.target, locateMs, `
2687
- el.focus()
2688
- return { ok: true }
2689
- `)
2690
- const locateTab = this.activeTab(s)
2691
- const out = await this.runTargetScript(locateTab, script, locateMs, signal, 'BROWSER_TYPE_FAILED', 'browser: type')
2692
- const cursorPoint = scriptPoint(out)
2693
- if (cursorPoint !== undefined) this.showCursor(locateTab.handle, cursorPoint.x, cursorPoint.y, 'click', 'type', true)
2694
- }
2695
- const text = 'text' in request ? request.text : ''
2696
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2697
- // Input.insertText goes through the Input domain: same display-surface
2698
- // requirement as click/key. It also reports which view is active once the barrier has
2699
- // settled, which is what makes the tab-switch check below meaningful.
2700
- const handle = await this.present(s, signal)
2701
- // Focusing one page and inserting into another is exactly the silent mis-target this
2702
- // refuses: the element was focused in the located view, and the text would have gone to
2703
- // whichever page is now visible — possibly a password field there.
2704
- if (hasTarget) this.assertSameView(session, locateHandle, handle)
2705
- try {
2706
- await withTimeout(
2707
- handle.sendCommand('Input.insertText', { text } satisfies CdpInsertTextParams),
2708
- timeoutMs,
2709
- signal,
2710
- `browser: type timed out after ${timeoutMs}ms`,
2711
- )
2712
- } catch (error) {
2713
- throw new BrowserError(`browser: type failed: ${String(error)}`, 'BROWSER_TYPE_FAILED', { cause: error })
2714
- }
2715
- // Store the full text so replay re-issues the same input; the history
2716
- // tool truncates long values when rendering.
2717
- this.record(s, 'type', { text, ...hasTarget ? { target: request.target } : {} }, true)
2718
- }
2719
-
2720
- /** Scroll the page: by deltas, to a selector, or to top/bottom. */
2721
- async scroll(session: BrowserSessionId, request: BrowserScrollRequest, signal?: AbortSignal): Promise<void> {
2722
- const s = this.session(session)
2723
- const tab = this.activeTab(s)
2724
- signal?.throwIfAborted()
2725
- const selector = request.selector ?? ''
2726
- const script = `(() => {
2727
- const sel = ${JSON.stringify(selector)}
2728
- if (sel !== '') {
2729
- const el = document.querySelector(sel)
2730
- if (!el) return { ok: false, reason: 'selector not found' }
2731
- el.scrollIntoView({ behavior: 'instant', block: 'center' })
2732
- return { ok: true }
2733
- }
2734
- if (${request.toTop === true}) { window.scrollTo(0, 0); return { ok: true } }
2735
- if (${request.toBottom === true}) { window.scrollTo(0, document.body.scrollHeight); return { ok: true } }
2736
- window.scrollBy({ top: ${request.deltaY ?? 0}, left: ${request.deltaX ?? 0} })
2737
- return { ok: true }
2738
- })()`
2739
- const timeoutMs = PROVIDER_TIMEOUTS.action
2740
- const result = await withTimeout(
2741
- handleSendEvaluate(tab.handle, script),
2742
- timeoutMs,
2743
- signal,
2744
- `browser: scroll timed out after ${timeoutMs}ms`,
2745
- timedOut => { this.interrupt(tab.handle, timedOut) },
2746
- )
2747
- if (!result.ok) throw new BrowserError(`browser: scroll failed: ${result.exception}`, 'BROWSER_SCROLL_FAILED')
2748
- const value = result.value as { ok?: boolean; reason?: string }
2749
- if (value.ok !== true) throw new BrowserError(`browser: scroll failed: ${value.reason ?? 'unknown'}`, 'BROWSER_SCROLL_FAILED')
2750
- this.record(s, 'scroll', { ...request }, true)
2751
- }
2752
-
2753
- /** Go back (-1) or forward (+1) in the active tab's navigation history. */
2754
- private async historyStep(session: BrowserSessionId, direction: -1 | 1, signal?: AbortSignal): Promise<void> {
2755
- const s = this.session(session)
2756
- const tab = this.activeTab(s)
2757
- const { handle } = tab
2758
- const transaction = this.beginNavigation(tab, signal)
2759
- const { navigation } = transaction
2760
- signal = transaction.signal
2761
- signal?.throwIfAborted()
2762
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2763
- const deadline = Date.now() + timeoutMs
2764
- const hist = await withTimeout(
2765
- handle.sendCommand('Page.getNavigationHistory'),
2766
- timeoutMs,
2767
- signal,
2768
- `browser: history read timed out after ${timeoutMs}ms`,
2769
- ) as { entries?: Array<{ id?: number; url?: string }>; currentIndex?: number }
2770
- this.checkNavigation(tab, navigation)
2771
- const entries = hist.entries ?? []
2772
- const currentIndex = hist.currentIndex ?? -1
2773
- const target = currentIndex + direction
2774
- if (target < 0 || target >= entries.length) {
2775
- // Nothing to step to; treat it as a successful no-op so the agent can
2776
- // proceed without an error dance.
2777
- this.record(s, direction === -1 ? 'back' : 'forward', {}, true)
2778
- return
2779
- }
2780
- const entry = entries[target]
2781
- if (entry?.id === undefined) throw new BrowserError('browser: history entry missing id', 'BROWSER_HISTORY_INVALID')
2782
- // A history step is a navigation too: the classic A→B→A redirect would
2783
- // otherwise read the outgoing document's identity (see settleDocument).
2784
- const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline, true)
2785
- const inPage = await withTimeout(handleSendEvaluate(handle, `(() => {
2786
- if (typeof navigation === 'undefined') return false;
2787
- const entry = navigation.entries().find(entry => entry.index === navigation.currentEntry.index + ${direction});
2788
- return entry?.url === ${JSON.stringify(entry.url)} && entry.sameDocument === true;
2789
- })()`), Math.max(1, deadline - Date.now()), signal, 'browser: history document identity timed out', timedOut => { this.interrupt(handle, timedOut) })
2790
- this.checkNavigation(tab, navigation)
2791
- signal?.throwIfAborted()
2792
- await withTimeout(
2793
- handle.sendCommand('Page.navigateToHistoryEntry', { entryId: entry.id }),
2794
- Math.max(1, deadline - Date.now()),
2795
- signal,
2796
- `browser: history navigation timed out after ${timeoutMs}ms`,
2797
- () => { if (tab.navigation === navigation) void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2798
- )
2799
- await this.settleDocument(handle, before, signal,
2800
- inPage.ok && inPage.value === true ? { frameId: before.id, loaderId: before.loaderId } : undefined,
2801
- () => { this.checkNavigation(tab, navigation) }, entry.id, deadline, true)
2802
- this.record(s, direction === -1 ? 'back' : 'forward', {}, true)
2803
- this.recordVisit(s, handle)
2804
- this.showActive(s)
2805
- }
2806
-
2807
- /** Go back in the active tab's history. */
2808
- async back(session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
2809
- return this.historyStep(session, -1, signal)
2810
- }
2811
-
2812
- /** Go forward in the active tab's history. */
2813
- async forward(session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
2814
- return this.historyStep(session, 1, signal)
2815
- }
2816
-
2817
- /** Reload the active tab. */
2818
- async reload(session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
2819
- const s = this.session(session)
2820
- const tab = this.activeTab(s)
2821
- const { handle } = tab
2822
- const transaction = this.beginNavigation(tab, signal)
2823
- const { navigation } = transaction
2824
- signal = transaction.signal
2825
- signal?.throwIfAborted()
2826
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
2827
- const deadline = Date.now() + timeoutMs
2828
- // Same-URL reload: only the per-load document identity can tell the new
2829
- // document from the old one, so capture it before reloading.
2830
- const before = await this.documentIdentity(handle, signal, () => { this.checkNavigation(tab, navigation) }, deadline, true)
2831
- this.checkNavigation(tab, navigation)
2832
- signal?.throwIfAborted()
2833
- await withTimeout(
2834
- handle.sendCommand('Page.reload', { ignoreCache: false }),
2835
- Math.max(1, deadline - Date.now()),
2836
- signal,
2837
- `browser: reload timed out after ${timeoutMs}ms`,
2838
- // Best-effort: cancel the reload if it wedges the debugger queue.
2839
- () => { if (tab.navigation === navigation) void handle.sendCommand('Page.stopLoading').catch(() => {}) },
2840
- )
2841
- await this.settleDocument(handle, before, signal, undefined, () => { this.checkNavigation(tab, navigation) }, undefined, deadline, true)
2842
- this.record(s, 'reload', {}, true)
2843
- this.recordVisit(s, handle)
2844
- this.showActive(s)
2845
- }
2846
-
2847
- /** Press one named key (Enter/Tab/arrows/…) via CDP key events. */
2848
- async key(session: BrowserSessionId, request: BrowserKeyRequest, signal?: AbortSignal): Promise<void> {
2849
- const s = this.session(session)
2850
- signal?.throwIfAborted()
2851
- const spec = KEY_SPECS[request.key]
2852
- if (spec === undefined) {
2853
- throw new BrowserError(`browser: unsupported key "${request.key}" (supported: ${BROWSER_KEY_NAMES.join(', ')})`, 'BROWSER_KEY_UNSUPPORTED')
2854
- }
2855
- const params = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk, ...spec.text !== undefined ? { text: spec.text } : {} }
2856
- const timeoutMs = PROVIDER_TIMEOUTS.action
2857
- // Input.dispatchKeyEvent is subject to the same display-surface rule. The handle comes
2858
- // back from the presentation barrier rather than from a capture taken before it: this
2859
- // session is shared with the human, who may switch tabs while the barrier round-trips,
2860
- // and a key sent to the view they left is silently dropped (or lands on the new page).
2861
- const handle = await this.present(s, signal)
2862
- // Focus the SAME view the key is dispatched to; focusing the pre-switch handle would
2863
- // grant web focus to a page that then receives nothing.
2864
- await this.focusView(handle)
2865
- const release = (): Promise<Record<string, unknown>> =>
2866
- handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyUp', ...params })
2867
- try {
2868
- await withTimeout(handle.sendCommand('Input.dispatchKeyEvent', { type: 'keyDown', ...params }), timeoutMs, signal, `browser: key press timed out after ${timeoutMs}ms`)
2869
- } catch (error) {
2870
- // The press may still land late; release best-effort so the key is
2871
- // never left in a stuck pressed state.
2872
- void release().catch(() => {})
2873
- throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error })
2874
- }
2875
- try {
2876
- await withTimeout(release(), timeoutMs, signal, `browser: key release timed out after ${timeoutMs}ms`)
2877
- } catch (error) {
2878
- // The press already landed; retry the release before surfacing.
2879
- void release().catch(() => {})
2880
- throw new BrowserError(`browser: key "${request.key}" failed: ${String(error)}`, 'BROWSER_KEY_FAILED', { cause: error })
2881
- }
2882
- this.record(s, 'key', { key: request.key }, true)
2883
- }
2884
-
2885
- /**
2886
- * Fill a form's fields in one batch. Runs one page-context script that
2887
- * resolves each field (selector, or name/label/placeholder among visible
2888
- * controls), sets its value with the native prototype setter (React/Vue
2889
- * controlled inputs included) plus input/change events, handles
2890
- * select/checkbox/radio/contenteditable, and optionally submits the form.
2891
- */
2892
- async fillForm(session: BrowserSessionId, request: BrowserFillRequest, signal?: AbortSignal): Promise<BrowserFillResult> {
2893
- const s = this.session(session)
2894
- const tab = this.activeTab(s)
2895
- signal?.throwIfAborted()
2896
- const specs = JSON.stringify(request.fields.map(f => ({
2897
- selector: f.selector ?? null,
2898
- name: f.name ?? null,
2899
- label: f.label ?? null,
2900
- placeholder: f.placeholder ?? null,
2901
- // A field with NO kind is a field with no kind FILTER: absent, not 'text'. Defaulting
2902
- // it to 'text' here made `if (spec.kind)` above always true, so every unspecified
2903
- // field was narrowed to an <input> — dsh_browser_fill on a <textarea> reported
2904
- // `no "text" control matched`, and a contenteditable could not match any kind at all.
2905
- // The value stays a string or null (never undefined): the in-page check tests truthiness,
2906
- // and JSON drops an undefined member entirely, which is the same thing here.
2907
- kind: f.kind ?? null,
2908
- value: f.value,
2909
- })))
2910
- const submitFlag = request.submit === true
2911
- const script = `(() => {
2912
- const specs = ${specs}
2913
- const out = []
2914
- const setNative = (el, proto, value) => {
2915
- const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
2916
- if (setter) setter.call(el, value)
2917
- else el.value = value
2918
- }
2919
- const visible = (el) => {
2920
- const r = el.getBoundingClientRect()
2921
- const cs = getComputedStyle(el)
2922
- return r.width >= 4 && r.height >= 4 && cs.visibility !== 'hidden' && cs.display !== 'none'
2923
- }
2924
- const describe = (spec) => spec.selector || spec.name || spec.label || spec.placeholder || '(unspecified)'
2925
- const matches = (el, spec) => {
2926
- if (spec.selector) { try { return el.matches(spec.selector) } catch { return false } }
2927
- if (spec.name && el.name === spec.name) return true
2928
- if (spec.placeholder && el.placeholder === spec.placeholder) return true
2929
- if (spec.label) {
2930
- if (el.getAttribute('aria-label') === spec.label) return true
2931
- if (el.id) {
2932
- const lbl = document.querySelector('label[for=' + JSON.stringify(el.id) + ']')
2933
- if (lbl && (lbl.textContent || '').trim() === spec.label) return true
2934
- }
2935
- const wrap = el.closest('label')
2936
- if (wrap && (wrap.textContent || '').trim() === spec.label) return true
2937
- }
2938
- return false
2939
- }
2940
- // Every root this page exposes: the top document plus its shadow trees (recursively)
2941
- // and same-origin iframes. The snapshot and waitFor already walk all of them, so an
2942
- // element inside one is shown to the model and can be waited for — resolving a click or
2943
- // a fill used to look at the top document alone and answer "not found" for something
2944
- // the model had just been handed a reference to. The two must agree about what exists.
2945
- // (Kept in step with the collector in the snapshot script above.)
2946
- const allRoots = () => {
2947
- const roots = []
2948
- const seen = new Set()
2949
- const visit = doc => {
2950
- if (seen.has(doc)) return
2951
- seen.add(doc)
2952
- roots.push(doc)
2953
- for (const el of doc.querySelectorAll('*')) {
2954
- if (el.shadowRoot) visit(el.shadowRoot)
2955
- if (el.tagName === 'IFRAME') {
2956
- try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
2957
- }
2958
- }
2959
- }
2960
- visit(document)
2961
- return roots
2962
- }
2963
- const roots = allRoots()
2964
- const candidates = (spec) => {
2965
- const all = spec.selector
2966
- ? roots.flatMap(root => [...root.querySelectorAll(spec.selector)])
2967
- : roots.flatMap(root => [...root.querySelectorAll('input, textarea, select, [contenteditable="true"]')]).filter(el => matches(el, spec))
2968
- const vis = all.filter(visible)
2969
- return vis.length > 0 ? vis : all
2970
- }
2971
- for (const spec of specs) {
2972
- let els
2973
- try {
2974
- els = candidates(spec)
2975
- } catch (e) {
2976
- // A malformed selector must not abort the whole batch; report the
2977
- // field as failed and continue with the rest.
2978
- out.push({ ok: false, error: String(e), target: describe(spec) })
2979
- continue
2980
- }
2981
- if (els.length === 0) { out.push({ ok: false, error: 'field not found', target: describe(spec) }); continue }
2982
- let el = els[0]
2983
- // The caller may name a kind. Honor it: the branches below read the element's own
2984
- // tag/type, so without this a selector matching two different controls acted on
2985
- // whichever came first — usually right, which is what hid the mistake. A field that
2986
- // names NO kind gets no filter at all: the element's own tag then decides the
2987
- // branch, which is what "kind defaults to text" was always trying to say.
2988
- if (spec.kind) {
2989
- const matchesKind = (node) => {
2990
- const nodeTag = node.tagName
2991
- const nodeType = (node.type || '').toLowerCase()
2992
- if (spec.kind === 'select') return nodeTag === 'SELECT'
2993
- if (spec.kind === 'textarea') return nodeTag === 'TEXTAREA'
2994
- if (spec.kind === 'checkbox' || spec.kind === 'radio') return nodeType === spec.kind
2995
- // 'text': the plain-value branch covers <input> AND <textarea>, and the batch
2996
- // already collects [contenteditable="true"] as a settable control — so all three
2997
- // must match. Requiring nodeTag === 'INPUT' here reported "no text control
2998
- // matched" for a textarea and left the contenteditable branch below unreachable.
2999
- if (nodeTag === 'TEXTAREA') return true
3000
- if (node.isContentEditable === true) return true
3001
- return nodeTag === 'INPUT' && nodeType !== 'checkbox' && nodeType !== 'radio' && nodeType !== 'file'
3002
- }
3003
- const wanted = els.find(matchesKind)
3004
- if (wanted === undefined) {
3005
- out.push({ ok: false, error: 'no "' + spec.kind + '" control matched', target: describe(spec) })
3006
- continue
3007
- }
3008
- els.length = 0
3009
- els.push(wanted)
3010
- // el was bound before the filter narrowed els, so the branches below would still
3011
- // read the first match — the very silent wrong-element behaviour this filter exists
3012
- // to remove.
3013
- el = els[0]
3014
- }
3015
- const tag = el.tagName
3016
- const type = (el.type || '').toLowerCase()
3017
- try {
3018
- if (tag === 'SELECT') {
3019
- const wanted = String(spec.value)
3020
- if (el.multiple) {
3021
- const wantedList = wanted.split(',').map(x => x.trim())
3022
- let hit = false
3023
- for (const o of [...el.options]) {
3024
- o.selected = wantedList.includes(o.value) || wantedList.includes((o.textContent || '').trim())
3025
- if (o.selected) hit = true
3026
- }
3027
- if (!hit) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
3028
- } else {
3029
- let opt = [...el.options].find(o => o.value === wanted)
3030
- if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
3031
- if (!opt) { out.push({ ok: false, error: 'option not found: ' + wanted, target: describe(spec) }); continue }
3032
- setNative(el, HTMLSelectElement.prototype, opt.value)
3033
- }
3034
- el.dispatchEvent(new Event('input', { bubbles: true }))
3035
- el.dispatchEvent(new Event('change', { bubbles: true }))
3036
- out.push({ ok: true, method: 'select', target: describe(spec) })
3037
- } else if (type === 'file') {
3038
- out.push({ ok: false, error: 'file inputs cannot be set from script; use dsh_browser_download or ask the human', target: describe(spec) })
3039
- } else if (type === 'checkbox') {
3040
- const want = spec.value === true || spec.value === 'true' || spec.value === 'on'
3041
- if (el.checked !== want) el.click()
3042
- out.push({ ok: true, method: 'checkbox', target: describe(spec) })
3043
- } else if (type === 'radio') {
3044
- const wanted = String(spec.value)
3045
- const radio = [...document.querySelectorAll('input[type="radio"][name=' + JSON.stringify(el.name || '') + ']')]
3046
- .find(r => r.value === wanted || (r === el && (spec.value === true || spec.value === 'true')))
3047
- if (!radio) { out.push({ ok: false, error: 'radio option not found: ' + wanted, target: describe(spec) }); continue }
3048
- if (!radio.checked) radio.click()
3049
- out.push({ ok: true, method: 'radio', target: describe(spec) })
3050
- } else if (el.isContentEditable) {
3051
- el.textContent = String(spec.value)
3052
- el.dispatchEvent(new Event('input', { bubbles: true }))
3053
- out.push({ ok: true, method: 'contenteditable', target: describe(spec) })
3054
- } else if (tag === 'TEXTAREA') {
3055
- setNative(el, HTMLTextAreaElement.prototype, String(spec.value))
3056
- el.dispatchEvent(new Event('input', { bubbles: true }))
3057
- el.dispatchEvent(new Event('change', { bubbles: true }))
3058
- out.push({ ok: true, method: 'textarea', target: describe(spec) })
3059
- } else {
3060
- setNative(el, HTMLInputElement.prototype, String(spec.value))
3061
- el.dispatchEvent(new Event('input', { bubbles: true }))
3062
- el.dispatchEvent(new Event('change', { bubbles: true }))
3063
- out.push({ ok: true, method: 'input', target: describe(spec) })
3064
- }
3065
- } catch (e) {
3066
- out.push({ ok: false, error: String(e), target: describe(spec) })
3067
- }
3068
- }
3069
- let submitted = false
3070
- if (${submitFlag}) {
3071
- let last = null
3072
- for (const spec of specs) {
3073
- try { const els = candidates(spec); if (els.length > 0) { last = els[0]; break } } catch { /* skip */ }
3074
- }
3075
- const form = last && (last.form || last.closest('form'))
3076
- if (form) { form.requestSubmit(); submitted = true }
3077
- }
3078
- return { fields: out, submitted }
3079
- })()`
3080
- const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
3081
- const result = await withTimeout(
3082
- handleSendEvaluate(tab.handle, script),
3083
- timeoutMs,
3084
- signal,
3085
- `browser: fillForm timed out after ${timeoutMs}ms`,
3086
- timedOut => { this.interrupt(tab.handle, timedOut) },
3087
- )
3088
- if (!result.ok) {
3089
- throw new BrowserError(`browser: fillForm evaluation failed: ${result.exception}`, 'BROWSER_FILL_FAILED')
3090
- }
3091
- const value = result.value as BrowserFillResult
3092
- const okCount = value.fields.filter(f => f.ok).length
3093
- this.record(s, 'fill', { fields: request.fields.length, submit: submitFlag }, okCount === value.fields.length, {
3094
- result: `${okCount}/${value.fields.length} fields filled${value.submitted ? ', form submitted' : ''}`,
3095
- })
3096
- return { fields: value.fields, submitted: value.submitted === true }
3097
- }
3098
-
3099
- /**
3100
- * Build an in-page async IIFE that locates ONE element by css/text/xpath
3101
- * (polling until it appears or the budget runs out) and then runs `body`
3102
- * with `el` in scope. Shared by the target-based tools: click/type (②),
3103
- * setValue/check/select/clear/getValue (③), and the scrape item wait.
3104
- * A selector that fails to PARSE is reported immediately instead of being
3105
- * polled until the budget expires — see the comment in `match`.
3106
- */
3107
- private buildTargetScript(spec: BrowserElementTarget, timeoutMs: number, body: string): string {
3108
- // `by` defaults to css in-page; report the strategy that WAS used, or a
3109
- // miss says only `{"value":"Learn more"}` and the caller cannot tell that a
3110
- // plain label was queried as a CSS selector.
3111
- const resolvedSpec = { ...spec, by: spec.by ?? 'css' }
3112
- return `(async () => {
3113
- const spec = ${JSON.stringify(resolvedSpec)}
3114
- const timeoutMs = ${String(timeoutMs)}
3115
- const sleep = ms => new Promise(r => setTimeout(r, ms))
3116
- const isVisible = el => el instanceof HTMLElement && (el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0)
3117
- const ownText = el => Array.from(el.childNodes).filter(n => n.nodeType === Node.TEXT_NODE).map(n => n.textContent || '').join('').trim()
3118
- const depth = el => { let d = 0; let p = el.parentElement; while (p) { d++; p = p.parentElement } return d }
3119
- const match = () => {
3120
- const by = typeof spec.by === 'string' ? spec.by : 'css'
3121
- const value = String(spec.value ?? '')
3122
- // Named matchIndex rather than index: this whole function is one host-side template
3123
- // literal, so a bare name declared here can silently shadow a host binding of the
3124
- // same name and turn an inner reference into a type error.
3125
- const matchIndex = typeof spec.index === 'number' ? spec.index : 0
3126
- // An index that cannot address an element can never match on a later poll, exactly
3127
- // like a selector that fails to parse — so it must not look like a miss either. A
3128
- // negative index, the common "last one" shorthand, otherwise burned the caller's
3129
- // whole locate budget (10s) and then reported "element not found", which reads like a
3130
- // slow page rather than a bad argument.
3131
- // (No backticks in this comment: it lives inside a template literal.)
3132
- if (!Number.isInteger(matchIndex) || matchIndex < 0) {
3133
- throw new Error('target.index must be a non-negative integer, got ' + JSON.stringify(spec.index))
3134
- }
3135
- let els = []
3136
- // Every root this page exposes: the top document plus its shadow trees (recursively)
3137
- // and same-origin iframes. The snapshot and waitFor already walk all of them, so an
3138
- // element inside one is shown to the model and can be waited for — resolving a click or
3139
- // a fill used to look at the top document alone and answer "not found" for something
3140
- // the model had just been handed a reference to. The two must agree about what exists.
3141
- // (Kept in step with the collector in the snapshot script above.)
3142
- const allRoots = () => {
3143
- const roots = []
3144
- const seen = new Set()
3145
- const visit = doc => {
3146
- if (seen.has(doc)) return
3147
- seen.add(doc)
3148
- roots.push(doc)
3149
- for (const el of doc.querySelectorAll('*')) {
3150
- if (el.shadowRoot) visit(el.shadowRoot)
3151
- if (el.tagName === 'IFRAME') {
3152
- try { const d = el.contentDocument; if (d) visit(d) } catch { /* cross-origin */ }
3153
- }
3154
- }
3155
- }
3156
- visit(document)
3157
- return roots
3158
- }
3159
- const roots = allRoots()
3160
- if (by === 'css') {
3161
- // A selector that does not PARSE can never match on a later poll, so
3162
- // it must not look like a miss: the old "return null" kept the caller
3163
- // polling until the whole budget was gone, and "element not found
3164
- // after 10s" reads like a slow page while the real cause is a
3165
- // malformed selector (a label or plain text passed where one belongs).
3166
- // Parse on the top document first: a selector that does not PARSE must still be
3167
- // reported as a bad argument rather than as a miss, and that check is about syntax,
3168
- // not about which root holds the element.
3169
- try { document.querySelectorAll(value) }
3170
- catch (error) { throw new Error('invalid CSS selector ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
3171
- for (const root of roots) els.push(...root.querySelectorAll(value))
3172
- } else if (by === 'xpath') {
3173
- try {
3174
- for (const root of roots) {
3175
- const snap = document.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
3176
- for (let i = 0; i < snap.snapshotLength; i++) {
3177
- const n = snap.snapshotItem(i)
3178
- if (n instanceof Element) els.push(n)
3179
- }
3180
- }
3181
- } catch (error) { throw new Error('invalid XPath ' + JSON.stringify(value) + ' (' + String((error && error.message) || error) + ')') }
3182
- } else {
3183
- // '*' rather than 'body *': a shadow root and an iframe document have no body of
3184
- // their own to anchor to, and the visibility and own-text predicates below are what
3185
- // actually decide whether an element counts.
3186
- const all = roots.flatMap(root => [...root.querySelectorAll('*')])
3187
- const exact = all.filter(el => isVisible(el) && ownText(el) === value)
3188
- // Exact first, then contains; deepest element preferred (so a
3189
- // button inside a card wins over the card itself).
3190
- const pool = exact.length > 0 ? exact : all.filter(el => isVisible(el) && ownText(el).includes(value))
3191
- els = pool.sort((a, b) => depth(b) - depth(a))
3192
- }
3193
- return els[matchIndex] ?? null
3194
- }
3195
- const deadline = Date.now() + timeoutMs
3196
- let el = null
3197
- for (;;) {
3198
- // Only a parse error escapes the poll: see the comment in match() above.
3199
- try { el = match() } catch (error) { return { ok: false, error: String((error && error.message) || error) } }
3200
- if (el !== null) break
3201
- if (Date.now() >= deadline) return { ok: false, error: 'element not found: ' + JSON.stringify(spec) + ' (looked for ' + timeoutMs + 'ms)' }
3202
- await sleep(100)
3203
- }
3204
- const __result = await (async () => {
3205
- ${body}
3206
- })()
3207
- // Report the operated element's viewport center next to the script's own
3208
- // verdict: the synthetic cursor (and any future feedback) needs the point,
3209
- // and no individual body should have to compute it a second time. Kept
3210
- // under a distinct key so a body that already returns x/y keeps them.
3211
- const __rect = el.getBoundingClientRect()
3212
- return {
3213
- ...(typeof __result === 'object' && __result !== null ? __result : { ok: true }),
3214
- __point: { x: Math.round(__rect.x + __rect.width / 2), y: Math.round(__rect.y + __rect.height / 2) },
3215
- }
3216
- })()`
3217
- }
3218
-
3219
- /**
3220
- * Shared evaluate wrapper for the target-based tools. Runs the in-page
3221
- * script and returns its result object; throws a typed BrowserError on
3222
- * evaluation failure or an in-page `{ ok: false, error }` verdict.
3223
- */
3224
- private async runTargetScript(
3225
- tab: Tab,
3226
- script: string,
3227
- timeoutMs: number,
3228
- signal: AbortSignal | undefined,
3229
- errorCode: string,
3230
- errorLabel: string,
3231
- ): Promise<Record<string, unknown>> {
3232
- // The script polls for its whole `timeoutMs` and only then answers, so an
3233
- // outer budget of the same size fires at the same instant and wins: the
3234
- // caller saw `click timed out after 10000ms` while the page had already
3235
- // decided WHY (selector not found / malformed). Give the answer a chance to
3236
- // get back before the generic timeout replaces it.
3237
- const result = await withTimeout(
3238
- handleSendEvaluate(tab.handle, script),
3239
- timeoutMs + TARGET_SCRIPT_GRACE_MS,
3240
- signal,
3241
- `${errorLabel} timed out after ${timeoutMs}ms`,
3242
- timedOut => { this.interrupt(tab.handle, timedOut) },
3243
- )
3244
- if (!result.ok) throw new BrowserError(`${errorLabel} failed: ${result.exception}`, errorCode)
3245
- const value = result.value as { ok?: boolean; error?: string } | undefined
3246
- if (value?.ok !== true) throw new BrowserError(`${errorLabel} failed: ${value?.error ?? 'unknown'}`, errorCode)
3247
- return value as Record<string, unknown>
3248
- }
3249
-
3250
- /** Set one element's value (native setter + input/change, React-friendly). */
3251
- async setValue(session: BrowserSessionId, request: BrowserSetValueRequest, signal?: AbortSignal): Promise<BrowserSetValueResult> {
3252
- const s = this.session(session)
3253
- const tab = this.activeTab(s)
3254
- signal?.throwIfAborted()
3255
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3256
- const body = `
3257
- const value = ${JSON.stringify(String(request.value))}
3258
- const setNative = (el, proto, v) => {
3259
- const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
3260
- if (setter) setter.call(el, v)
3261
- else el.value = v
3262
- }
3263
- const tag = el.tagName
3264
- const type = (el.type || '').toLowerCase()
3265
- if (tag === 'SELECT') {
3266
- const wanted = value
3267
- let opt = [...el.options].find(o => o.value === wanted)
3268
- if (!opt) opt = [...el.options].find(o => (o.textContent || '').trim() === wanted)
3269
- if (!opt) return { ok: false, error: 'option not found: ' + wanted }
3270
- setNative(el, HTMLSelectElement.prototype, opt.value)
3271
- el.dispatchEvent(new Event('input', { bubbles: true }))
3272
- el.dispatchEvent(new Event('change', { bubbles: true }))
3273
- return { ok: true, method: 'select', value: opt.value }
3274
- }
3275
- if (el.isContentEditable) {
3276
- el.textContent = value
3277
- el.dispatchEvent(new Event('input', { bubbles: true }))
3278
- return { ok: true, method: 'contenteditable', value }
3279
- }
3280
- if (tag === 'TEXTAREA') {
3281
- setNative(el, HTMLTextAreaElement.prototype, value)
3282
- el.dispatchEvent(new Event('input', { bubbles: true }))
3283
- el.dispatchEvent(new Event('change', { bubbles: true }))
3284
- return { ok: true, method: 'textarea', value }
3285
- }
3286
- setNative(el, HTMLInputElement.prototype, value)
3287
- el.dispatchEvent(new Event('input', { bubbles: true }))
3288
- el.dispatchEvent(new Event('change', { bubbles: true }))
3289
- return { ok: true, method: 'input', value }
3290
- `
3291
- const script = this.buildTargetScript(request.target, timeoutMs, body)
3292
- const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SET_VALUE_FAILED', 'browser: setValue')
3293
- const cursorPoint = scriptPoint(out)
3294
- if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
3295
- this.record(s, 'setValue', { target: request.target, value: String(request.value) }, true, { result: out.method as string })
3296
- return { method: out.method as string, value: out.value as string }
3297
- }
3298
-
3299
- /** Check or uncheck one checkbox/radio. */
3300
- async check(session: BrowserSessionId, request: BrowserCheckRequest, signal?: AbortSignal): Promise<{ readonly checked: boolean }> {
3301
- const s = this.session(session)
3302
- const tab = this.activeTab(s)
3303
- signal?.throwIfAborted()
3304
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3305
- const want = request.checked ?? true
3306
- const body = `
3307
- const want = ${String(want)}
3308
- const type = (el.type || '').toLowerCase()
3309
- if (type === 'checkbox') {
3310
- if (el.checked !== want) el.click()
3311
- return { ok: true, checked: el.checked }
3312
- }
3313
- if (type === 'radio') {
3314
- if (want && !el.checked) el.click()
3315
- return { ok: true, checked: el.checked }
3316
- }
3317
- return { ok: false, error: 'element is not a checkbox or radio (' + el.tagName + ')' }
3318
- `
3319
- const script = this.buildTargetScript(request.target, timeoutMs, body)
3320
- const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CHECK_FAILED', 'browser: check')
3321
- const cursorPoint = scriptPoint(out)
3322
- if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
3323
- this.record(s, 'check', { target: request.target, checked: want }, true)
3324
- return { checked: out.checked === true }
3325
- }
3326
-
3327
- /** Select one option of a <select>, by value, visible text, or index. */
3328
- async selectOption(session: BrowserSessionId, request: BrowserSelectRequest, signal?: AbortSignal): Promise<BrowserSelectResult> {
3329
- const s = this.session(session)
3330
- const tab = this.activeTab(s)
3331
- signal?.throwIfAborted()
3332
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3333
- const body = `
3334
- if (el.tagName !== 'SELECT') return { ok: false, error: 'element is not a <select> (' + el.tagName + ')' }
3335
- const optionValue = ${JSON.stringify(request.optionValue ?? null)}
3336
- const optionText = ${JSON.stringify(request.optionText ?? null)}
3337
- const optionIndex = ${String(request.optionIndex ?? -1)}
3338
- let opt = null
3339
- if (optionValue !== null) opt = [...el.options].find(o => o.value === optionValue)
3340
- if (!opt && optionText !== null) opt = [...el.options].find(o => (o.textContent || '').trim() === optionText)
3341
- if (!opt && optionIndex >= 0) opt = el.options[optionIndex] ?? null
3342
- if (!opt) return { ok: false, error: 'option not found' }
3343
- const setNative = (el, proto, v) => {
3344
- const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
3345
- if (setter) setter.call(el, v)
3346
- else el.value = v
3347
- }
3348
- setNative(el, HTMLSelectElement.prototype, opt.value)
3349
- el.dispatchEvent(new Event('input', { bubbles: true }))
3350
- el.dispatchEvent(new Event('change', { bubbles: true }))
3351
- return { ok: true, value: opt.value, text: (opt.textContent || '').trim() }
3352
- `
3353
- const script = this.buildTargetScript(request.target, timeoutMs, body)
3354
- const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_SELECT_FAILED', 'browser: select')
3355
- const cursorPoint = scriptPoint(out)
3356
- if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
3357
- this.record(s, 'select', { target: request.target, optionValue: request.optionValue ?? null, optionText: request.optionText ?? null, optionIndex: request.optionIndex ?? null }, true)
3358
- return { value: out.value as string, text: out.text as string }
3359
- }
3360
-
3361
- /** Clear one input/textarea/contenteditable (or uncheck a checkbox/radio). */
3362
- async clearField(session: BrowserSessionId, request: BrowserClearRequest, signal?: AbortSignal): Promise<{ readonly cleared: boolean }> {
3363
- const s = this.session(session)
3364
- const tab = this.activeTab(s)
3365
- signal?.throwIfAborted()
3366
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3367
- const body = `
3368
- const setNative = (el, proto) => {
3369
- const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set
3370
- if (setter) setter.call(el, '')
3371
- else el.value = ''
3372
- }
3373
- if (el.isContentEditable) {
3374
- el.textContent = ''
3375
- el.dispatchEvent(new Event('input', { bubbles: true }))
3376
- } else if (el.tagName === 'TEXTAREA') {
3377
- setNative(el, HTMLTextAreaElement.prototype)
3378
- el.dispatchEvent(new Event('input', { bubbles: true }))
3379
- el.dispatchEvent(new Event('change', { bubbles: true }))
3380
- } else if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {
3381
- if (el.checked) el.click()
3382
- } else {
3383
- setNative(el, HTMLInputElement.prototype)
3384
- el.dispatchEvent(new Event('input', { bubbles: true }))
3385
- el.dispatchEvent(new Event('change', { bubbles: true }))
3386
- }
3387
- return { ok: true }
3388
- `
3389
- const script = this.buildTargetScript(request.target, timeoutMs, body)
3390
- const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_CLEAR_FAILED', 'browser: clear')
3391
- const cursorPoint = scriptPoint(out)
3392
- if (cursorPoint !== undefined) this.showCursor(tab.handle, cursorPoint.x, cursorPoint.y, 'click')
3393
- this.record(s, 'clear', { target: request.target }, true)
3394
- return { cleared: true }
3395
- }
3396
-
3397
- /** Read one element's current value (for verification). */
3398
- async getValue(session: BrowserSessionId, request: BrowserGetValueRequest, signal?: AbortSignal): Promise<BrowserGetValueResult> {
3399
- const s = this.session(session)
3400
- const tab = this.activeTab(s)
3401
- signal?.throwIfAborted()
3402
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3403
- const body = `
3404
- const type = (el.type || '').toLowerCase()
3405
- if (type === 'checkbox' || type === 'radio') return { ok: true, value: null, checked: el.checked }
3406
- if (el.tagName === 'SELECT') {
3407
- const o = el.options[el.selectedIndex]
3408
- return { ok: true, value: el.value, selectedText: o ? (o.textContent || '').trim() : null }
3409
- }
3410
- const v = el.value !== undefined ? el.value : el.textContent
3411
- return { ok: true, value: v === undefined || v === null ? null : String(v) }
3412
- `
3413
- const script = this.buildTargetScript(request.target, timeoutMs, body)
3414
- const out = await this.runTargetScript(tab, script, timeoutMs, signal, 'BROWSER_GET_VALUE_FAILED', 'browser: getValue')
3415
- this.record(s, 'getValue', { target: request.target }, true)
3416
- return {
3417
- value: out.value === null || out.value === undefined ? null : String(out.value),
3418
- ...out.checked !== undefined ? { checked: out.checked === true } : {},
3419
- ...out.selectedText !== undefined && out.selectedText !== null ? { selectedText: String(out.selectedText) } : {},
3420
- }
3421
- }
3422
-
3423
- /**
3424
- * Extract structured data from repeated DOM items (static CSS, CSP-safe —
3425
- * no arbitrary code runs). Waits for the item selector, then maps each item
3426
- * through the field selectors; `selector@attr` reads an attribute instead
3427
- * of text (`a@href` yields an absolute URL).
3428
- */
3429
- async scrape(session: BrowserSessionId, request: BrowserScrapeRequest, signal?: AbortSignal): Promise<BrowserScrapeResult> {
3430
- const s = this.session(session)
3431
- const tab = this.activeTab(s)
3432
- signal?.throwIfAborted()
3433
- const timeoutMs = request.timeoutMs ?? PROVIDER_TIMEOUTS.interaction
3434
- const script = `(async () => {
3435
- const itemSel = ${JSON.stringify(request.item)}
3436
- const fields = ${JSON.stringify(request.fields)}
3437
- const timeoutMs = ${String(timeoutMs)}
3438
- const sleep = ms => new Promise(r => setTimeout(r, ms))
3439
- const parseField = f => {
3440
- const m = /^(.*)@([A-Za-z][A-Za-z0-9_-]*)$/.exec(f.selector.trim())
3441
- if (m) return { base: m[1].trim(), attr: m[2] }
3442
- return { base: f.selector, attr: null }
3443
- }
3444
- const deadline = Date.now() + timeoutMs
3445
- let items = []
3446
- for (;;) {
3447
- // Immediate, like match() above: an unparseable selector can never match.
3448
- try { items = Array.from(document.querySelectorAll(itemSel)) }
3449
- catch (error) { return { ok: false, error: 'invalid CSS selector ' + JSON.stringify(itemSel) + ' (' + String((error && error.message) || error) + ')' } }
3450
- if (items.length > 0) break
3451
- if (Date.now() >= deadline) return { ok: false, error: 'no elements matched: ' + itemSel }
3452
- await sleep(100)
3453
- }
3454
- const out = []
3455
- for (const it of items) {
3456
- const row = {}
3457
- for (const f of fields) {
3458
- const { base, attr } = parseField(f)
3459
- let el = null
3460
- try { el = base === '' ? it : it.querySelector(base) } catch { el = null }
3461
- if (!el) { row[f.name] = null; continue }
3462
- if (attr !== null) {
3463
- const v = el.getAttribute(attr)
3464
- row[f.name] = attr === 'href' && el.tagName === 'A' && v ? new URL(v, location.href).href : v
3465
- continue
3466
- }
3467
- row[f.name] = (el.textContent || '').trim()
3468
- }
3469
- out.push(row)
3470
- }
3471
- return { ok: true, count: out.length, items: out }
3472
- })()`
3473
- const result = await withTimeout(
3474
- handleSendEvaluate(tab.handle, script),
3475
- timeoutMs + TARGET_SCRIPT_GRACE_MS,
3476
- signal,
3477
- `browser: scrape timed out after ${timeoutMs}ms`,
3478
- timedOut => { this.interrupt(tab.handle, timedOut) },
3479
- )
3480
- if (!result.ok) throw new BrowserError(`browser: scrape evaluation failed: ${result.exception}`, 'BROWSER_SCRAPE_FAILED')
3481
- const value = result.value as { ok?: boolean; error?: string; count?: number; items?: Record<string, string | null>[] }
3482
- if (value.ok !== true) throw new BrowserError(`browser: scrape failed: ${value.error ?? 'unknown'}`, 'BROWSER_SCRAPE_FAILED')
3483
- const items = value.items ?? []
3484
- this.record(s, 'scrape', { item: request.item, fields: request.fields.map(f => f.name) }, true, { result: `${items.length} items` })
3485
- return { count: items.length, items }
3486
- }
3487
-
3488
- /**
3489
- * Refuse an action the settings have switched off.
3490
- *
3491
- * These switches belong to the OPERATOR. The settings document is written through the
3492
- * plugin's own panel and no tool can reach it, so — unlike `dsh_browser_restrict`, which the
3493
- * model owns and can lift at will — a refusal here stands for as long as the setting does.
3494
- * That is the point of them: a deployment can take page-script execution, downloads, or
3495
- * login-state writes off the table without relying on the model's cooperation.
3496
- *
3497
- * Read through `settingsSource` on every call rather than captured at construction, so
3498
- * flipping a switch applies to the next command instead of the next restart — the same
3499
- * rule the credentials gate follows.
3500
- * @param action - which switch to consult.
3501
- * @throws BrowserError when that switch is off.
3502
- */
3503
- private assertActionAllowed(action: 'execute' | 'download' | 'credentialWrite'): void {
3504
- const settings = this.settingsSource?.()
3505
- if (settings === undefined) return
3506
- if (action === 'execute' && !settings.actions.allowExecute) {
3507
- throw new BrowserError('browser: running page scripts is switched off in settings (Browser → actions)', 'BROWSER_EXECUTE_DISABLED')
3508
- }
3509
- if (action === 'download' && !settings.actions.allowDownload) {
3510
- throw new BrowserError('browser: downloads are switched off in settings (Browser → actions)', 'BROWSER_DOWNLOAD_DISABLED')
3511
- }
3512
- if (action === 'credentialWrite' && !settings.actions.allowCredentialWrite) {
3513
- throw new BrowserError('browser: writing cookies is switched off in settings (Browser → actions)', 'BROWSER_AUTH_WRITE_DISABLED')
3514
- }
3515
- }
3516
-
3517
- /**
3518
- * Admit a caller-supplied save path for a file the browser writes to disk.
3519
- * ONE gate for both `dsh_browser_download` and `dsh_browser_screenshot`: the path
3520
- * must be absolute, must resolve inside `downloadDir`, and must not already
3521
- * exist. Without it a prompt-injected agent could write — or silently
3522
- * replace — any file the DSH process can reach, which also escapes the file
3523
- * sandbox every other tool in the set runs under.
3524
- * @param savePath - the caller's target path.
3525
- * @param kind - the operation, used in the error code and message.
3526
- * @returns the resolved absolute target path.
3527
- * @throws BrowserError when the path is relative, outside the directory, or occupied.
3528
- */
3529
- private admitSavePath(savePath: string, kind: 'download' | 'screenshot'): string {
3530
- const code = kind === 'download' ? 'BROWSER_DOWNLOAD_BLOCKED' : 'BROWSER_SCREENSHOT_BLOCKED'
3531
- if (!isAbsolute(savePath)) {
3532
- throw new BrowserError(`browser: ${kind} savePath must be an absolute path`, code)
3533
- }
3534
- const file = resolve(savePath)
3535
- if (this.downloadDir !== undefined) {
3536
- const dir = resolve(this.downloadDir)
3537
- // Windows paths are case-insensitive and resolve() does not normalize case, so there
3538
- // the containment check folds case — otherwise C:\Users\X\Downloads and
3539
- // c:\users\x\downloads would read as different roots. Everywhere else the fold is
3540
- // REMOVED: a case-sensitive filesystem (Linux) treats /home/u/DOWNLOADS and
3541
- // /home/u/Downloads as different directories, so folding case there let a savePath
3542
- // that merely differed in case pass admission — a directory-confinement escape, and
3543
- // one that mkdirSync below would then happily create.
3544
- const fold = process.platform === 'win32' ? (value: string): string => value.toLowerCase() : (value: string): string => value
3545
- const dirKey = fold(dir)
3546
- const fileKey = fold(file)
3547
- // The directory ITSELF is refused, not accepted: a save path that IS downloadDir names
3548
- // a directory, so there is no file to write — and mkdirSync would have created the
3549
- // directory when it did not exist. Two paths are "inside" only when the file path is
3550
- // strictly below the directory, which the separator check below already expresses.
3551
- if (!fileKey.startsWith(dirKey + fold(sep))) {
3552
- throw new BrowserError(`browser: ${kind} savePath must be inside downloadDir "${dir}"`, code)
3553
- }
3554
- // The check above is textual, and a symlink defeats it: resolve() normalizes `..`
3555
- // but never follows a link, so `<downloadDir>/out/x.png` passed every test above
3556
- // while `out` pointed at a directory outside the gate — and the write then landed
3557
- // there. Resolve the REAL location of the deepest existing ancestor (which is what
3558
- // decides where the bytes go) and require it to be inside the real directory too.
3559
- // A legitimate path is unaffected: its ancestor resolves to the directory itself.
3560
- //
3561
- // The directory is created first so that it can be resolved at all — mkdirSync is a
3562
- // no-op for one that already exists — and a directory that cannot be created or
3563
- // resolved falls back to its textual form, leaving the real filesystem error to the
3564
- // write instead of inventing one here.
3565
- let realDir: string
3566
- try {
3567
- mkdirSync(dir, { recursive: true })
3568
- realDir = fold(realpathSync(dir))
3569
- } catch {
3570
- realDir = fold(dir)
3571
- }
3572
- const realAncestor = fold(realAncestorOf(file))
3573
- if (realAncestor !== realDir && !realAncestor.startsWith(realDir + fold(sep))) {
3574
- throw new BrowserError(`browser: ${kind} savePath resolves outside downloadDir "${dir}" (a symlink leaves it)`, code)
3575
- }
3576
- }
3577
- // Never replace an existing file: its previous content is unrecoverable,
3578
- // and the admitted directory may hold files the human put there. A new
3579
- // name is one tool call away.
3580
- //
3581
- // Judged with lstat (see {@link entryExists}), not existsSync: existsSync FOLLOWS
3582
- // links, so a DANGLING symlink read as "nothing here" and the write below created
3583
- // its target — outside the directory whenever the link pointed out of it. It is the
3584
- // directory entry that has to be free, whatever that entry points at.
3585
- if (entryExists(file)) {
3586
- throw new BrowserError(`browser: refusing to overwrite existing file "${file}" — use another name`, code)
3587
- }
3588
- return file
3589
- }
3590
-
3591
- /**
3592
- * Download an HTTP(S) URL with the session's cookies to a local file.
3593
- * Admission is the shared {@link admitSavePath} gate. The carrier downloads
3594
- * with its own authenticated browser session. Both admitted paths and screenshots are confined
3595
- * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
3596
- * machine paths.
3597
- * @param session - the session whose cookies are used.
3598
- * @param request - the URL plus the absolute target path.
3599
- * @param signal - optional cancellation.
3600
- * @returns the path the file was written to.
3601
- */
3602
- async download(session: BrowserSessionId, request: { readonly url: string; readonly savePath: string }, signal?: AbortSignal): Promise<{ readonly path: string }> {
3603
- // Before admission, and before the session is even resolved: a switched-off action is
3604
- // not a path problem, and the caller should hear the real reason.
3605
- this.assertActionAllowed('download')
3606
- const s = this.session(session)
3607
- const { handle } = this.activeTab(s)
3608
- signal?.throwIfAborted()
3609
- // URL admission: HTTP(S) only (mirrors the navigation guard). The seam
3610
- // intentionally does not block private/localhost targets — a shared real
3611
- // browser legitimately reaches local dev servers.
3612
- let parsed: URL
3613
- try {
3614
- parsed = new URL(request.url)
3615
- } catch {
3616
- throw new BrowserError(`browser: refusing download of unparseable URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED')
3617
- }
3618
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
3619
- throw new BrowserError(`browser: refusing download of non-HTTP(S) URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED')
3620
- }
3621
- // savePath admission: the shared gate — absolute, inside `downloadDir`,
3622
- // and never an existing file. Screenshots use the very same one.
3623
- const savePath = this.admitSavePath(request.savePath, 'download')
3624
- const downloadable = handle
3625
- if (typeof downloadable.download !== 'function') {
3626
- throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED')
3627
- }
3628
- // The child fetches and writes the file; a slow/hung network can block
3629
- // it well past the tool budget, so bound it. NOTE: unlike CDP calls,
3630
- // there is no child-side abort mechanism for the RPC download — when the
3631
- // parent's timeout fires the child continues writing. The parent's pending
3632
- // entry is cleaned up (the promise settles) and the child's eventual
3633
- // reply is harmlessly consumed by the RPC layer.
3634
- const timeoutMs = PROVIDER_TIMEOUTS.download
3635
- await withTimeout(
3636
- downloadable.download(request.url, savePath),
3637
- timeoutMs,
3638
- signal,
3639
- `browser: download timed out after ${timeoutMs}ms`,
3640
- )
3641
- this.record(s, 'download', { url: request.url, savePath }, true, { result: savePath })
3642
- return { path: savePath }
3643
- }
3644
-
3645
- /**
3646
- * Export the session's cookies (login state) as serializable objects.
3647
- * Self-hosted only; the desktop shell's embedded views use the real profile.
3648
- */
3649
- async flushAuth(session: BrowserSessionId): Promise<readonly ExportedCookie[]> {
3650
- // The settings panel offers "allow the agent to read cookies / export login state".
3651
- // Until now nothing read that switch, so turning it off changed nothing at all —
3652
- // the tool exported every cookie regardless.
3653
- if (this.settingsSource?.().credentials.allowRead === false) {
3654
- throw new BrowserError('browser: reading cookies is switched off in settings (Browser → credentials)', 'BROWSER_AUTH_DISABLED')
3655
- }
3656
- const s = this.session(session)
3657
- const { handle } = this.activeTab(s)
3658
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3659
- // The self-hosted carrier has a native path (the child reads its own session), which
3660
- // is worth preferring: it reports exactly what the browser persisted.
3661
- const native = handle
3662
- if (typeof native.flushAuth === 'function') {
3663
- const cookies = await withTimeout(native.flushAuth(), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`)
3664
- this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies` })
3665
- return cookies
3666
- }
3667
- // Every other carrier drives a real browser over CDP, and cookies are part of CDP —
3668
- // the sidebar goes through the shell's webContents.debugger, an installed Chrome or
3669
- // Edge is the browser itself. So this works everywhere rather than only self-hosted.
3670
- // Scoped to the page this session is on. The jar itself is SHARED on purpose — every
3671
- // window and every task drives the same browser, so signing in once works everywhere,
3672
- // which is the whole point of "use your own browser". What must not be shared is the
3673
- // HANDING OVER: an unfiltered read puts every domain every task has visited, plus
3674
- // whatever the human is signed into, in front of one task's caller. Least exposure,
3675
- // not isolation.
3676
- //
3677
- // Two corrections to the previous attempt. It called Storage.getCookies with a `urls`
3678
- // parameter, but that method takes only browserContextId and ignores everything else, so
3679
- // the filter did nothing and the whole jar was still exported; `urls` belongs to
3680
- // Network.getCookies. And it silently fell back to an unfiltered read when the page URL
3681
- // was unavailable — an error path that asked for MORE than the normal one. Both are
3682
- // fixed: the method that honours the filter, and a failure that refuses instead of
3683
- // widening.
3684
- const cookiesUrl = await this.currentUrl(handle).catch(() => '')
3685
- if (cookiesUrl === '') {
3686
- throw new BrowserError(
3687
- 'browser: cannot export cookies without knowing which page this session is on — the URL was unavailable, and reading the whole cookie jar would expose every other session\'s logins',
3688
- 'BROWSER_AUTH_SCOPE_UNKNOWN',
3689
- )
3690
- }
3691
- const result = await withTimeout(
3692
- handle.sendCommand('Network.getCookies', { urls: [cookiesUrl] }),
3693
- timeoutMs,
3694
- undefined,
3695
- `browser: auth export timed out after ${timeoutMs}ms`,
3696
- )
3697
- const cookies = toExportedCookies(result.cookies)
3698
- this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies (CDP)` })
3699
- return cookies
3700
- }
3701
-
3702
- /** Import cookies into the session (restore login state). Self-hosted only. */
3703
- async restoreAuth(session: BrowserSessionId, cookies: readonly ExportedCookie[]): Promise<number> {
3704
- // Restore WRITES cookies, so it answers to the write switch — not to
3705
- // `credentials.allowRead`. It used to consult the read switch and report "reading
3706
- // cookies is switched off", which is both the wrong gate and the wrong sentence: an
3707
- // operator who allowed reading but wanted logins left alone had no switch at all,
3708
- // and one who turned reading off lost the restore path for the wrong reason.
3709
- this.assertActionAllowed('credentialWrite')
3710
- const s = this.session(session)
3711
- const { handle } = this.activeTab(s)
3712
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3713
- const native = handle
3714
- if (typeof native.restoreAuth === 'function') {
3715
- const restored = await withTimeout(native.restoreAuth(cookies), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`)
3716
- this.record(s, 'restoreAuth', { count: cookies.length }, true, { result: `${restored} cookies` })
3717
- return restored
3718
- }
3719
- // CDP again, for the same reason as the export: any carrier that drives a real
3720
- // browser can set cookies on it. Storage.setCookies needs the cookie fields spelled
3721
- // the CDP way, including the sameSite spelling and seconds rather than milliseconds.
3722
- //
3723
- // toCdpCookie returns undefined for a cookie it cannot place (no usable domain), and
3724
- // `cookies.map(...)` passed that undefined straight through: the array then held a
3725
- // JSON `null`, CDP rejected the WHOLE call, and every valid cookie failed with an error
3726
- // naming none of them. Filter the unusable ones out and say how many went.
3727
- const mapped = cookies.map(toCdpCookie)
3728
- const convertible = mapped.filter((cookie): cookie is Record<string, unknown> => cookie !== undefined)
3729
- const dropped = mapped.length - convertible.length
3730
- if (dropped > 0) {
3731
- process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`)
3732
- }
3733
- await withTimeout(
3734
- handle.sendCommand('Storage.setCookies', { cookies: convertible }),
3735
- timeoutMs,
3736
- undefined,
3737
- `browser: auth restore timed out after ${timeoutMs}ms`,
3738
- )
3739
- // Storage.setCookies returns nothing, so the count comes from what was actually sent.
3740
- // An earlier version read result.cookies here; it was always undefined and rendered as
3741
- // "Restored 0 cookies." even though the write had succeeded.
3742
- const restored = convertible.length
3743
- this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` })
3744
- return restored
3745
- }
3746
-
3747
- /**
3748
- * Capture the active page WITHOUT presenting it.
3749
- *
3750
- * `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
3751
- * that the human sees what the model just captured. It is also what makes that path unusable for a
3752
- * live preview: presenting on every frame would move focus, switch tabs and expand windows on the
3753
- * host's screen — exactly the side effects a viewer must not cause (issue #34).
3754
- *
3755
- * So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
3756
- * preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
3757
- * preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
3758
- * design forbids: no page means "nothing to watch", not "open one".
3759
- * @param session - the session whose active page to capture.
3760
- * @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
3761
- * is not painted, which the caller turns into a "paused" state rather than an error.
3762
- */
3763
- async capturePassive(session: BrowserSessionId): Promise<{
3764
- readonly dataUrl: string
3765
- readonly width?: number
3766
- readonly height?: number
3767
- }> {
3768
- const s = this.session(session)
3769
- const { handle } = this.activeTab(s)
3770
- const timeoutMs = PREVIEW_CAPTURE_MS
3771
- const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`
3772
- // The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
3773
- // produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
3774
- if (typeof handle.capture === 'function') {
3775
- const shot = await withTimeout(
3776
- handle.capture({
3777
- format: 'jpeg',
3778
- quality: PREVIEW_QUALITY,
3779
- maxWidth: PREVIEW_MAX_WIDTH,
3780
- maxHeight: PREVIEW_MAX_HEIGHT,
3781
- }),
3782
- timeoutMs,
3783
- undefined,
3784
- timeoutMessage,
3785
- )
3786
- if (shot.base64 === '') {
3787
- // A hidden or minimized window is not a failure to report as one: the design says the
3788
- // viewer shows pause and does not open a window to fix it.
3789
- throw new BrowserError(
3790
- 'browser: preview unavailable (the page is not painted; the window may be hidden or minimized)',
3791
- 'BROWSER_PREVIEW_UNAVAILABLE',
3792
- )
3793
- }
3794
- return {
3795
- dataUrl: `data:${shot.mime};base64,${shot.base64}`,
3796
- ...shot.width !== undefined && shot.height !== undefined
3797
- ? { width: shot.width, height: shot.height }
3798
- : {},
3799
- }
3800
- }
3801
- // Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
3802
- // the whole document, which is neither what a viewer shows nor bounded in size.
3803
- //
3804
- // `present: false` is load-bearing (issue #46): a preview is read-only, so it must not reach the
3805
- // carrier's present path, which for the sidebar asks the shell to display this conversation —
3806
- // the reported symptom was the sidebar browser panel jumping to the front when someone opened
3807
- // the preview. A page that is not displayed now reads as "unavailable", which the route already
3808
- // turns into the panel's paused state.
3809
- const result = await withTimeout(
3810
- handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
3811
- format: 'jpeg',
3812
- quality: PREVIEW_QUALITY,
3813
- fromSurface: true,
3814
- captureBeyondViewport: false,
3815
- }, { present: false }),
3816
- timeoutMs,
3817
- undefined,
3818
- timeoutMessage,
3819
- ) as { data?: unknown }
3820
- const base64 = typeof result?.data === 'string' ? result.data : ''
3821
- if (base64 === '') {
3822
- throw new BrowserError(
3823
- 'browser: preview unavailable (the carrier returned no image)',
3824
- 'BROWSER_PREVIEW_UNAVAILABLE',
3825
- )
3826
- }
3827
- return { dataUrl: `data:image/jpeg;base64,${base64}` }
3828
- }
3829
-
3830
- /** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
3831
- async screenshot( session: BrowserSessionId,
3832
- request?: BrowserScreenshotRequest,
3833
- signal?: AbortSignal,
3834
- ): Promise<{ readonly dataUrl: string; readonly path?: string; readonly width?: number; readonly height?: number }> {
3835
- const s = this.session(session)
3836
- const { handle } = this.activeTab(s)
3837
- signal?.throwIfAborted()
3838
- const format = request?.format ?? 'png'
3839
- // Native capturePage path (self-hosted): CDP Page.captureScreenshot can
3840
- // hang indefinitely on a view once another (hidden) WebContentsView exists
3841
- // in the window; capturePage is fast for visible views and resolves
3842
- // immediately (empty) for hidden ones. JPEG and downscaling are encoded
3843
- // in the child from the NativeImage, so this path is the only one that
3844
- // can produce JPEG (CDP JPEG hangs on Electron 43).
3845
- const capturable = handle
3846
- // A region capture must go through CDP: the native NativeImage path has no
3847
- // clip and would present/activate the window (a quiet-mode violation).
3848
- if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
3849
- // Ensure the target view is the visible one before capturing — unless quiet mode is on.
3850
- // There, presenting the view is exactly what the user asked to avoid (it restores and
3851
- // raises the window); the host switches the visible tab inside the window and, if the
3852
- // window has no surface to capture, falls through to CDP.
3853
- if (!this.isQuiet()) this.showActive(s)
3854
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3855
- const shot = await withTimeout(
3856
- capturable.capture({
3857
- ...format === 'jpeg' ? { format, quality: request?.quality } : {},
3858
- ...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
3859
- ...request?.maxHeight !== undefined ? { maxHeight: request.maxHeight } : {},
3860
- quiet: this.isQuiet(),
3861
- }),
3862
- timeoutMs,
3863
- signal,
3864
- `browser: screenshot timed out after ${timeoutMs}ms`,
3865
- )
3866
- if (shot.base64 === '') {
3867
- throw new BrowserError('browser: capture returned an empty image (view not painted); retry shortly', 'BROWSER_SCREENSHOT_FAILED')
3868
- }
3869
- return this.saveScreenshot(
3870
- shot.base64,
3871
- request?.savePath,
3872
- shot.mime ?? 'image/png',
3873
- // The child measured these after applying any downscale, and they describe the image
3874
- // the caller receives. Without them this path — the default self-hosted one — could
3875
- // never answer the width/height its own tool schema declares.
3876
- shot.width !== undefined && shot.height !== undefined
3877
- ? { width: shot.width, height: shot.height }
3878
- : undefined,
3879
- )
3880
- }
3881
- // Fallback: a handle without a native capture() (the sidebar, or an installed Chrome
3882
- // or Edge) uses CDP; full-page needs `captureBeyondViewport`, which capturePage lacks.
3883
- //
3884
- // JPEG: Electron 43's CDP hangs on it, which is why the sidebar stays PNG. An
3885
- // installed Chrome or Edge is the real browser and has no such defect, so it says so
3886
- // through `supportsCdpJpeg` and gets the format it asked for, and the same for
3887
- // downscaling, which CDP performs through a full-document clip.
3888
- const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS
3889
- const params: Record<string, unknown> = {}
3890
- const region = request?.clip
3891
- if (region !== undefined) {
3892
- const valid = [region.x, region.y, region.width, region.height].every(
3893
- value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192,
3894
- ) && region.width > 0 && region.height > 0
3895
- if (!valid) throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED')
3896
- params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 }
3897
- params.fromSurface = true
3898
- params.captureBeyondViewport = false
3899
- }
3900
- if (region === undefined && request?.fullPage === true) {
3901
- // `captureBeyondViewport` captures the full scrollable content; without
3902
- // a clip this yields the full-page image (CDP default is the viewport).
3903
- params.captureBeyondViewport = true
3904
- }
3905
- const supportsJpeg = (handle as { supportsCdpJpeg?: boolean }).supportsCdpJpeg === true
3906
- if (format === 'jpeg' && supportsJpeg) {
3907
- params.format = 'jpeg'
3908
- // CDP range is 0-100 and defaults to 80 when omitted.
3909
- if (request?.quality !== undefined) params.quality = request.quality
3910
- }
3911
- // Downscaling on this path: CDP scales through `clip.scale`, and a clip only applies
3912
- // to the region it names, so it has to cover the whole document. The page's own size
3913
- // is read first; when that is unavailable the capture proceeds unscaled rather than
3914
- // failing — an image the caller can shrink itself beats no image at all.
3915
- let rendered: { width: number; height: number } | undefined
3916
- if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
3917
- const metrics = await withTimeout(
3918
- handle.sendCommand('Page.getLayoutMetrics', {}),
3919
- timeoutMs,
3920
- signal,
3921
- `browser: screenshot timed out after ${timeoutMs}ms`,
3922
- )
3923
- const size = layoutSize(metrics)
3924
- if (size !== undefined) {
3925
- const height = request.fullPage === true ? size.height : size.viewportHeight
3926
- const byWidth = request.maxWidth !== undefined && size.width > 0 ? request.maxWidth / size.width : 1
3927
- const byHeight = request.maxHeight !== undefined && height > 0 ? request.maxHeight / height : 1
3928
- const scale = Math.min(1, byWidth, byHeight)
3929
- // What the caller will actually receive. Recorded before the branch below, because the
3930
- // size is worth reporting even when no scaling happened (scale 1).
3931
- rendered = { width: Math.round(size.width * scale), height: Math.round(height * scale) }
3932
- if (scale < 1) {
3933
- params.clip = { x: 0, y: 0, width: size.width, height, scale }
3934
- // The clip defines the captured area; captureBeyondViewport must not also apply.
3935
- delete params.captureBeyondViewport
3936
- }
3937
- }
3938
- }
3939
- // A region capture is a read: it must never present the conversation or
3940
- // raise a window. Every other screenshot keeps the original call shape.
3941
- const result = await withTimeout(
3942
- region === undefined
3943
- ? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
3944
- : handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }),
3945
- timeoutMs,
3946
- signal,
3947
- `browser: screenshot timed out after ${timeoutMs}ms`,
3948
- )
3949
- const data = result.data
3950
- if (typeof data !== 'string') {
3951
- throw new BrowserError('browser: screenshot returned no image data', 'BROWSER_SCREENSHOT_FAILED')
3952
- }
3953
- // The mime must name the format that was ACTUALLY requested (params.format), not PNG
3954
- // unconditionally: a carrier that sets supportsCdpJpeg asks for `format: 'jpeg'`, so
3955
- // hardcoding the PNG mime announced a JPEG body as a PNG — the data URL then carried a
3956
- // mislabelled image, and a caller that decodes by mime wrote the wrong file.
3957
- const mime = params.format === 'jpeg' ? 'image/jpeg' : 'image/png'
3958
- return this.saveScreenshot(data, request?.savePath, mime, rendered)
3959
- }
3960
-
3961
- /**
3962
- * Build the data URL and optionally write the image to disk. The caller's
3963
- * path goes through the SAME {@link admitSavePath} gate as a download — it
3964
- * must be absolute, resolve inside `downloadDir`, and not be an existing
3965
- * file — so a screenshot cannot be used to write to, or silently replace,
3966
- * files anywhere the DSH process happens to have permission (issue #13).
3967
- */
3968
- private saveScreenshot(
3969
- base64: string,
3970
- savePath: string | undefined,
3971
- mime: string,
3972
- rendered?: { width: number; height: number },
3973
- ): { dataUrl: string; path?: string; width?: number; height?: number } {
3974
- if (savePath !== undefined) {
3975
- // Admission failures propagate unchanged: they describe the caller's
3976
- // path, not a disk problem.
3977
- const target = this.admitSavePath(savePath, 'screenshot')
3978
- try {
3979
- writeFileNoReplace(target, Buffer.from(base64, 'base64'))
3980
- return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered }
3981
- } catch (error) {
3982
- // Report the write problem but keep the capture usable.
3983
- throw new BrowserError(`browser: screenshot save to "${target}" failed: ${String(error)}`, 'BROWSER_SCREENSHOT_SAVE_FAILED', { cause: error })
3984
- }
3985
- }
3986
- return { dataUrl: `data:${mime};base64,${base64}`, ...rendered }
3987
- }
3988
-
3989
- /** Append one operation to the session's history. */
3990
- private record(
3991
- s: Session,
3992
- action: string,
3993
- params: Record<string, unknown>,
3994
- ok: boolean,
3995
- detail?: { result?: string; error?: string },
3996
- ): void {
3997
- const entry: BrowserHistoryEntry = {
3998
- seq: s.nextSeq++,
3999
- action,
4000
- params,
4001
- ok,
4002
- ...detail?.result !== undefined ? { result: detail.result } : {},
4003
- ...detail?.error !== undefined ? { error: detail.error } : {},
4004
- at: Date.now(),
4005
- }
4006
- s.history.push(entry)
4007
- // Bound memory: keep the last 500 operations.
4008
- if (s.history.length > 500) s.history.splice(0, s.history.length - 500)
4009
- }
4010
-
4011
- /** Return the session's chronological operation log (newest last). */
4012
- async history(session: BrowserSessionId): Promise<readonly BrowserHistoryEntry[]> {
4013
- return this.session(session).history
4014
- }
4015
-
4016
- /**
4017
- * Record one page visit in the persistent browsing history. Fire-and-forget by
4018
- * design: a visit must never delay or fail the navigation that produced it,
4019
- * and the title is only worth reading once the document has settled.
4020
- * @param s - the session that drove the visit.
4021
- * @param handle - the view whose document just loaded.
4022
- */
4023
- private recordVisit(s: Session, handle: ElectronViewHandle): void {
4024
- const store = this.historyStore
4025
- if (store === undefined) return
4026
- // The settings panel can switch recording off at runtime; the static config
4027
- // only supplies the startup default. The RETENTION limits are read here too: they were
4028
- // parsed and stored but never handed to the store, so editing maxEntries or maxAgeDays in
4029
- // the file changed nothing — the switch worked and the numbers beside it did not.
4030
- if (this.settingsSource !== undefined) {
4031
- const live = this.settingsSource().history
4032
- if (!live.enabled) return
4033
- store.updateLimits({ maxEntries: live.maxEntries, maxAgeDays: live.maxAgeDays })
4034
- }
4035
- void handleSendEvaluate(handle, 'location.href + "\\u0000" + (document.title || "")')
4036
- .then(result => {
4037
- if (!result.ok || typeof result.value !== 'string') return
4038
- const [url = '', title = ''] = result.value.split('\u0000')
4039
- // Internal documents are not visits: an untouched browser is not history.
4040
- if (url === '' || url.startsWith('about:') || url.startsWith('devtools:')) return
4041
- store.append({
4042
- at: Date.now(),
4043
- url,
4044
- ...title.trim() !== '' ? { title: title.trim() } : {},
4045
- ...s.label !== undefined ? { session: s.label } : {},
4046
- })
4047
- store.prune()
4048
- })
4049
- .catch(() => { /* best-effort: history is never worth surfacing an error */ })
4050
- }
4051
-
4052
- /**
4053
- * List persisted visits, newest first — what `dsh_browser_visited` reads back.
4054
- * @param options - result cap and an optional hostname filter.
4055
- * @returns the matching visits, or an empty list when history is disabled.
4056
- */
4057
- visited(options: { readonly limit?: number; readonly domain?: string; readonly query?: string; readonly session?: string } = {}): readonly VisitedPage[] {
4058
- return this.historyStore?.list(options) ?? []
4059
- }
4060
-
4061
- /**
4062
- * Show the synthetic pointer on a view, unless the user switched it off. The
4063
- * cursor is the "the agent has taken over this tab" signal, so it is painted
4064
- * for every operation that has a landing point — including DOM-level ones that
4065
- * move no real pointer.
4066
- * @param handle - the view to paint into.
4067
- * @param x - viewport x in CSS pixels.
4068
- * @param y - viewport y in CSS pixels.
4069
- * @param action - click pulses a ripple; move only relocates.
4070
- * @param label - short description of the operation, shown beside the pointer.
4071
- * @param force - paint even when the pointer is already there (a click ripple must
4072
- * always play; a bare move need not repeat).
4073
- */
4074
- private showCursor(handle: ElectronViewHandle, x: number, y: number, action: CursorAction, label?: string, force = false): void {
4075
- if (this.settingsSource !== undefined && !this.settingsSource().ui.virtualCursor) return
4076
- paintCursor(handle, x, y, action, (target, expression) => handleSendEvaluate(target, expression), label, force)
4077
- }
4078
-
4079
- /**
4080
- * Replay one recorded operation by sequence number. Navigate/click/type are
4081
- * re-issued against the current page; execute re-runs its script. The
4082
- * replayed step is appended to history as a new entry.
4083
- * @param session - the session id.
4084
- * @param seq - the recorded entry's sequence number to replay.
4085
- */
4086
- async replay(session: BrowserSessionId, seq: number): Promise<void> {
4087
- const s = this.session(session)
4088
- const entry = s.history.find(e => e.seq === seq)
4089
- if (entry === undefined) {
4090
- throw new BrowserError(`browser: no history entry with seq ${seq}`, 'BROWSER_HISTORY_UNKNOWN')
4091
- }
4092
- switch (entry.action) {
4093
- case 'navigate': {
4094
- const url = entry.params.url
4095
- if (typeof url !== 'string') throw new BrowserError(`browser: history seq ${seq} navigate has no url`, 'BROWSER_HISTORY_INVALID')
4096
- await this.navigate(session, { url })
4097
- this.record(s, 'replay', { seq, of: entry.action, url }, true)
4098
- return
4099
- }
4100
- case 'click': {
4101
- const target = entry.params.target as BrowserElementTarget | undefined
4102
- if (target !== undefined) {
4103
- await this.click(session, { target })
4104
- this.record(s, 'replay', { seq, of: entry.action, target }, true)
4105
- return
4106
- }
4107
- const x = entry.params.x
4108
- const y = entry.params.y
4109
- if (typeof x !== 'number' || typeof y !== 'number') throw new BrowserError(`browser: history seq ${seq} click has no coordinates`, 'BROWSER_HISTORY_INVALID')
4110
- await this.click(session, { x, y })
4111
- this.record(s, 'replay', { seq, of: entry.action, x, y }, true)
4112
- return
4113
- }
4114
- case 'type': {
4115
- const text = entry.params.text
4116
- if (typeof text !== 'string') throw new BrowserError(`browser: history seq ${seq} type has no text`, 'BROWSER_HISTORY_INVALID')
4117
- const target = entry.params.target as BrowserElementTarget | undefined
4118
- await this.type(session, { text, ...target !== undefined ? { target } : {} })
4119
- this.record(s, 'replay', { seq, of: entry.action, text, ...target !== undefined ? { target } : {} }, true)
4120
- return
4121
- }
4122
- case 'scroll': {
4123
- await this.scroll(session, entry.params as BrowserScrollRequest)
4124
- this.record(s, 'replay', { seq, of: entry.action }, true)
4125
- return
4126
- }
4127
- case 'key': {
4128
- const key = entry.params.key
4129
- if (typeof key !== 'string') throw new BrowserError(`browser: history seq ${seq} key has no key`, 'BROWSER_HISTORY_INVALID')
4130
- await this.key(session, { key })
4131
- this.record(s, 'replay', { seq, of: entry.action, key }, true)
4132
- return
4133
- }
4134
- case 'execute': {
4135
- const script = entry.params.script
4136
- if (typeof script !== 'string') throw new BrowserError(`browser: history seq ${seq} execute has no script`, 'BROWSER_HISTORY_INVALID')
4137
- const recordedArgs = entry.params.args
4138
- const args = Array.isArray(recordedArgs)
4139
- ? recordedArgs.filter((a): a is string | number | boolean => typeof a === 'string' || typeof a === 'number' || typeof a === 'boolean')
4140
- : undefined
4141
- const result = await this.execute(session, { script, ...args !== undefined && args.length > 0 ? { args } : {} })
4142
- this.record(s, 'replay', { seq, of: entry.action, script, ...args !== undefined && args.length > 0 ? { args } : {} }, result.ok, result.ok ? { result: String(result.value) } : { error: result.exception })
4143
- return
4144
- }
4145
- default:
4146
- throw new BrowserError(`browser: history seq ${seq} action "${entry.action}" is not replayable`, 'BROWSER_HISTORY_NOT_REPLAYABLE')
4147
- }
4148
- }
4149
-
4150
- /** Close the session and destroy all its views. Idempotent. */
4151
- async close(session: BrowserSessionId): Promise<void> {
4152
- const existing = this.sessions.get(session)
4153
- if (existing !== undefined) {
4154
- this.sessions.delete(session)
4155
- for (const tab of existing.tabs) this.destroyTab(tab)
4156
- // Releasing the browser at session end is a setting, not fixed behaviour
4157
- // (requirements §3). A self-hosted carrier already tore its window down with
4158
- // the views above; the desktop's sidebar does not, so it is asked explicitly
4159
- // — and its cookies plus the browsing history outlive the page either way.
4160
- try {
4161
- if (this.settingsSource !== undefined && this.settingsSource().ui.closeWithSession) {
4162
- // Never release another conversation's pages.
4163
- await this.host.releasePage?.(this.carrierScope(existing))
4164
- }
4165
- } finally {
4166
- await this.host.retireSession?.(session)
4167
- }
4168
- }
4169
- }
4170
-
4171
- /** Look up a session or throw the unknown-session error. */
4172
- private session(session: BrowserSessionId): Session {
4173
- const existing = this.sessions.get(session)
4174
- if (existing === undefined) {
4175
- throw new BrowserError(`browser: session "${session}" is not open`, 'BROWSER_SESSION_UNKNOWN')
4176
- }
4177
- return existing
4178
- }
4179
-
4180
- /** The active tab of a session. */
4181
- private activeTab(s: Session): Tab {
4182
- if (this.carrierLaunchError !== undefined) throw this.carrierLaunchError
4183
- const tab = s.tabs[s.activeIndex]
4184
- if (tab === undefined) throw new BrowserError('browser: session has no active tab', 'BROWSER_TAB_UNKNOWN')
4185
- if (tab.failure !== undefined) throw tab.failure
4186
- return tab
4187
- }
4188
-
4189
- /** Append a fresh tab and make it active. */
4190
- private newTab(s: Session): void {
4191
- const id = tabWireId({ ...resolveSessionHandle(s.id), tab: randomUUID() })
4192
- const handle = this.host.createView(id)
4193
- // Same window as the session's other tabs.
4194
- this.host.groupView?.(handle, s.id, s.label)
4195
- s.tabs.push({ id, handle, url: '' })
4196
- s.activeIndex = s.tabs.length - 1
4197
- this.showActive(s)
4198
- }
4199
-
4200
- private carrierScope(s: Session): BrowserSessionId {
4201
- return s.id
4202
- }
4203
-
4204
- private carrierTab(s: Session, id: string): BrowserTabWireId {
4205
- const scope = resolveSessionHandle(s.id)
4206
- return tabWireId(resolveTabHandle(scope, id))
4207
- }
4208
-
4209
- private carrierId(s: Session, id: BrowserTabWireId): BrowserTabWireId | undefined {
4210
- const tab = resolveTabHandle(resolveSessionHandle(s.id), id).tab
4211
- if (!tab.startsWith('page:') && this.host.closePage === undefined) return undefined
4212
- return id
4213
- }
4214
-
4215
- private destroyTab(tab: Tab, options?: { readonly keepPage?: boolean }): void {
4216
- tab.navigationAbort?.abort(new BrowserError('browser: the navigation guest was closed', 'BROWSER_GUEST_CLOSED'))
4217
- this.host.destroyView(tab.handle, options)
4218
- }
4219
-
4220
- private interrupt(handle: ElectronViewHandle, timedOut: boolean): void {
4221
- if (timedOut) this.quarantine(handle)
4222
- else terminatePage(handle)
4223
- }
4224
-
4225
- private quarantine(handle: ElectronViewHandle): void {
4226
- for (const session of this.sessions.values()) {
4227
- const tab = session.tabs.find(tab => tab.handle === handle)
4228
- if (tab === undefined || tab.failure !== undefined) continue
4229
- tab.failure = new BrowserError('browser: this guest stopped acknowledging operations and is quarantined; close this tab or explicitly reset the session before retrying', 'BROWSER_GUEST_QUARANTINED')
4230
- terminatePage(handle)
4231
- }
4232
- }
4233
-
4234
- /** Find a session's tab by its backing view id (toolbar actions carry view ids). */
4235
- private tabByViewId(s: Session, viewId: string): Tab | undefined {
4236
- return s.tabs.find(tab => tab.handle.id === viewId)
4237
- }
4238
-
4239
- /**
4240
- * Whether a session is still live. The human closing a window ends its session
4241
- * (see {@link handleViewClosed}), so callers that cache ids must ask first.
4242
- * @param session - the session id to test.
4243
- */
4244
- exists(session: BrowserSessionId): boolean {
4245
- return this.sessions.has(session)
4246
- }
4247
-
4248
- /**
4249
- * The sessions a viewer may watch, which is exactly the sessions that exist.
4250
- *
4251
- * Served so the browser page can build a frame URL without guessing: the provider names its
4252
- * sessions, and an id invented by a client is refused at the route. Ids only — no URL, no title,
4253
- * no target handle — because the point is to let the panel address a session, not to describe
4254
- * what is in it.
4255
- * @returns the live session ids.
4256
- */
4257
- watchableSessions(): readonly BrowserSessionId[] {
4258
- return [...this.sessions.keys()]
4259
- }
4260
-
4261
- takeoverTargets(owner: string): readonly { session: BrowserSessionId; owner: string; tabId: string; pageId: string; url: string }[] {
4262
- return [...this.sessions.values()].filter(s => (s.label ?? 'default').replace(/^session-/u, '') === owner).flatMap(s => {
4263
- const tab = s.tabs[s.activeIndex]
4264
- return tab && !tab.failure && /^https?:\/\//u.test(tab.url)
4265
- ? [{ session: s.id, owner: s.label ?? 'default', tabId: tab.id, pageId: tab.id, url: tab.url }] : []
4266
- })
4267
- }
4268
-
4269
- /**
4270
- * The human closed a browser window: the session that window showed is over.
4271
- * Ending it here is what makes the next call a clean start rather than a
4272
- * resurrection of an invisible window. Browsing history and login state live
4273
- * on disk, so nothing the human cares about is lost with it.
4274
- * @param windowId - the group key the host reported, which is the session id.
4275
- */
4276
- private async handleViewClosed(windowId: string): Promise<void> {
4277
- if (typeof windowId !== 'string' || windowId === '') return
4278
- const s = this.sessions.get(windowId as BrowserSessionId)
4279
- if (s === undefined) return
4280
- await this.close(s.id).catch(() => { /* the window is already gone */ })
4281
- }
4282
-
4283
- /**
4284
- * Route a user-initiated action from the host's UI into the session model.
4285
- * Fire-and-forget by design: a user action failing (e.g. an unreachable
4286
- * URL typed into the address bar) must never crash the host UI loop — it
4287
- * is reported to the host (toolbar) when the host supports it, else logged.
4288
- */
4289
- private async handleUserAction(action: BrowserUserAction, propagate = false): Promise<void> {
4290
- const s = this.sessions.get(action.windowId as BrowserSessionId)
4291
- if (s === undefined) {
4292
- // The window the human clicked in has no live session here (session
4293
- // closed, or a child restart changed identity). Never swallow the click
4294
- // silently — surface it so the toolbar can tell the human what happened.
4295
- const message = `action ${action.type} failed: no live browser session for window "${action.windowId}"`
4296
- process.stderr.write(`[dsh-browser] ${message}\n`)
4297
- this.notifyUserActionError(action, new Error('no live browser session'))
4298
- if (propagate) throw new Error('no live browser session')
4299
- return
4300
- }
4301
- try {
4302
- switch (action.type) {
4303
- case 'capture-reference':
4304
- // The human clicked a native menu item or the page's floating entry.
4305
- // Delivery is owned by the plugin entry, which holds the reference
4306
- // service; the provider only routes the action to the right session.
4307
- await dispatchReferenceCaptureAction({
4308
- windowId: action.windowId,
4309
- entry: action.entry,
4310
- ...action.frameSelector !== undefined ? { frameSelector: action.frameSelector } : {},
4311
- ...action.target !== undefined ? { target: action.target } : {},
4312
- ...action.comment !== undefined ? { comment: action.comment } : {},
4313
- ...action.selectionText !== undefined ? { selectionText: action.selectionText } : {},
4314
- ...action.capture !== undefined ? { capture: action.capture } : {},
4315
- })
4316
- return
4317
- case 'navigate':
4318
- await this.openUrl(s.id, { url: action.url })
4319
- return
4320
- case 'newTab':
4321
- this.newTab(s)
4322
- if (action.url !== undefined && action.url !== '') {
4323
- await this.navigate(s.id, { url: action.url })
4324
- }
4325
- return
4326
- case 'activateTab': {
4327
- const tab = this.tabByViewId(s, action.viewId)
4328
- if (tab !== undefined) await this.switchTab(s.id, tab.id)
4329
- return
4330
- }
4331
- case 'closeTab': {
4332
- const tab = this.tabByViewId(s, action.viewId)
4333
- if (tab !== undefined) await this.closeTab(s.id, tab.id)
4334
- return
4335
- }
4336
- case 'back':
4337
- await this.back(s.id)
4338
- return
4339
- case 'forward':
4340
- await this.forward(s.id)
4341
- return
4342
- case 'reload':
4343
- await this.reload(s.id)
4344
- return
4345
- }
4346
- } catch (error) {
4347
- this.notifyUserActionError(action, error)
4348
- if (propagate) throw error
4349
- }
4350
- }
4351
-
4352
- /**
4353
- * Report a failed user action to the host UI (toolbar), when supported.
4354
- *
4355
- * Two properties matter here, because this runs inside the catch of an async
4356
- * handler (issue #16):
4357
- * - the receiver must be preserved. Reading the method off the host and calling
4358
- * it unbound runs the host's implementation with `this === undefined`, so its
4359
- * very first statement (`void this.ready()`) throws, the throw escapes the
4360
- * async catch as an unhandled rejection, and the whole DSH host exits;
4361
- * - this method must be incapable of throwing. Reporting a failed action is
4362
- * diagnostics: it can never be allowed to become the failure.
4363
- */
4364
- private notifyUserActionError(action: BrowserUserAction, error: unknown): void {
4365
- const message = `action ${action.type} failed: ${String(error)}`
4366
- let reported = false
4367
- try {
4368
- const notify = this.host.notifyUserActionError?.bind(this.host)
4369
- if (notify !== undefined) {
4370
- // Bound at the call: an unbound call here kills the host process (issue #16).
4371
- notify(action.windowId, message)
4372
- reported = true
4373
- }
4374
- } catch (notifyError) {
4375
- // Contained on purpose; the log line below still carries the original cause.
4376
- process.stderr.write(`[dsh-browser] host notify failed: ${String(notifyError)}\n`)
4377
- }
4378
- if (!reported) process.stderr.write(`[dsh-browser] user action failed: ${message}\n`)
4379
- }
4380
-
4381
- /**
4382
- * Whether the operator asked for quiet mode (`ui.quiet`).
4383
- *
4384
- * Read live on every call rather than captured at construction: the panel writes the document
4385
- * and the next operation is expected to honour it, without a restart.
4386
- * @returns true when the carrier must present views without taking the screen over.
4387
- */
4388
- private isQuiet(): boolean {
4389
- return this.settingsSource?.().ui.quiet === true
4390
- }
4391
-
4392
- /**
4393
- * Ask the host to show the active tab's view, carrying the session label.
4394
- *
4395
- * The two halves are sequential, not alternatives. `showView` makes the view the
4396
- * visible one — which is what keeps what the human sees in step with what the agent
4397
- * drives, and what lets `capturePage` return an image at all (a hidden view captures
4398
- * empty) — while `collapse` folds the carrier's own chrome away when the user asked
4399
- * for no auto-expand. Making them exclusive meant that with auto-expand off this
4400
- * method did nothing at all on carriers without `collapse` (the self-hosted one),
4401
- * silently desynchronising the two and failing every screenshot.
4402
- */
4403
- private showActive(s: Session, select = false): void {
4404
- const quiet = this.isQuiet()
4405
- const active = s.tabs[s.activeIndex]
4406
- if (active !== undefined) this.host.showView?.(active.handle, s.label, { quiet, ...select ? { select: true } : {} })
4407
- if (quiet || select) return
4408
- const autoExpand = this.settingsSource === undefined || this.settingsSource().ui.autoExpandOnce
4409
- if (autoExpand) return
4410
- // Best effort: a carrier that owns no presentation (self-hosted) simply has none.
4411
- void this.host.collapse?.().catch(() => undefined)
4412
- }
4413
-
4414
- /** Read the current URL of a view through CDP. */
4415
- private async currentUrl(handle: ElectronViewHandle): Promise<string> {
4416
- // Bound the read: a wedged renderer would otherwise hang listTabs.
4417
- const timeoutMs = PROVIDER_TIMEOUTS.lookup
4418
- const result = await withTimeout(
4419
- handleSendEvaluate(handle, 'location.href'),
4420
- timeoutMs,
4421
- undefined,
4422
- `browser: url read timed out after ${timeoutMs}ms`,
4423
- timedOut => { this.interrupt(handle, timedOut) },
4424
- )
4425
- return result.ok && typeof result.value === 'string' ? result.value : ''
4426
- }
4427
- }
4428
-
4429
- /**
4430
- * Bounds for one passive preview frame.
4431
- *
4432
- * The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
4433
- * enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
4434
- * behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
4435
- * target is what lets several viewers share a single capture.
4436
- */
4437
- const PREVIEW_CAPTURE_MS = 2_000
4438
- const PREVIEW_QUALITY = 70
4439
- const PREVIEW_MAX_WIDTH = 1280
4440
- const PREVIEW_MAX_HEIGHT = 720
4441
-
4442
- /** Poll interval for the document-settle loop. */
4443
- const SETTLE_POLL_MS = 25
4444
-
4445
- /**
4446
- * Extra time the transport gets over an in-page locate script's own budget: the
4447
- * script polls for `timeoutMs` and answers only afterwards, so the outer wait
4448
- * must outlast it or its generic timeout hides the in-page reason.
4449
- */
4450
- const TARGET_SCRIPT_GRACE_MS = 2_000
4451
-
4452
-
4453
- /** Abortable sleep used by the settle loop. */
4454
- function delay(ms: number, signal?: AbortSignal): Promise<void> {
4455
- return new Promise<void>((resolve) => {
4456
- const timer = setTimeout(() => {
4457
- if (signal !== undefined) signal.removeEventListener('abort', onAbort)
4458
- resolve()
4459
- }, ms)
4460
- const onAbort = (): void => { clearTimeout(timer); resolve() }
4461
- if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
4462
- })
4463
- }
4464
-
4465
- /**
4466
- * Bound a promise so a wedged CDP call surfaces as an error instead of
4467
- * hanging the tool call forever. The caller's signal, when provided, wins
4468
- * over the timeout if it fires first.
4469
- * @param promise - the operation to bound.
4470
- * @param ms - the timeout budget.
4471
- * @param signal - optional caller signal.
4472
- * @param message - the timeout error message.
4473
- * @returns the promise's value, or a rejected promise on timeout/abort.
4474
- */
4475
- function withTimeout<T>(
4476
- promise: Promise<T>,
4477
- ms: number,
4478
- signal: AbortSignal | undefined,
4479
- message: string,
4480
- onCancel?: (timedOut: boolean) => void,
4481
- ): Promise<T> {
4482
- return new Promise<T>((resolve, reject) => {
4483
- let done = false
4484
- const timer = setTimeout(() => {
4485
- if (done) return
4486
- done = true
4487
- // A fired timeout must also release the abort listener; { once: true }
4488
- // only releases it on the next abort, which may never come.
4489
- if (signal !== undefined) signal.removeEventListener('abort', onAbort)
4490
- const error = new Error(message)
4491
- error.name = 'TimeoutError'
4492
- reject(error)
4493
- // Best-effort interrupt of the underlying CDP call (see onCancel).
4494
- onCancel?.(true)
4495
- }, ms)
4496
- const finish = (fn: () => void): void => {
4497
- if (done) return
4498
- done = true
4499
- clearTimeout(timer)
4500
- if (signal !== undefined) signal.removeEventListener('abort', onAbort)
4501
- fn()
4502
- }
4503
- const onAbort = (): void => {
4504
- if (done) return
4505
- done = true
4506
- clearTimeout(timer)
4507
- reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'))
4508
- onCancel?.(false)
4509
- }
4510
- if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
4511
- promise.then(
4512
- value => finish(() => resolve(value)),
4513
- error => finish(() => reject(error)),
4514
- )
4515
- })
4516
- }
4517
-
4518
- /**
4519
- * Best-effort interrupt of a wedged page-script evaluation. `Runtime.evaluate`
4520
- * with `awaitPromise` can hold the renderer (and the target's debugger queue)
4521
- * behind a busy loop or a never-settling promise; terminating kills the
4522
- * running script so subsequent commands are not stuck forever. Fire-and-forget:
4523
- * if the interrupt itself hangs, it is ignored. Capped at
4524
- * MAX_PENDING_TERMINATIONS per view to prevent unbounded pending entries
4525
- * when the child is truly stuck.
4526
- * @param handle - the view handle to terminate in.
4527
- */
4528
- const pendingTerminations = new WeakMap<ElectronViewHandle, number>()
4529
- const MAX_PENDING_TERMINATIONS = 3
4530
- function terminatePage(handle: ElectronViewHandle): void {
4531
- const count = pendingTerminations.get(handle) ?? 0
4532
- if (count >= MAX_PENDING_TERMINATIONS) return
4533
- pendingTerminations.set(handle, count + 1)
4534
- void handle.sendCommand('Runtime.terminateExecution', undefined, { present: false, initialize: false }).finally(() => {
4535
- pendingTerminations.set(handle, Math.max(0, (pendingTerminations.get(handle) ?? 1) - 1))
4536
- }).catch(() => {})
4537
- }
4538
-
4539
- /**
4540
- * Run a `Runtime.evaluate` through a view handle and normalize the result.
4541
- * Shared by execute, snapshot, content, and internal URL reads.
4542
- * @param handle - the view handle to evaluate in.
4543
- * @param expression - the JS expression.
4544
- * @param signal - optional abort signal; a fired signal rejects the call.
4545
- */
4546
- /** Viewport point a target script reported, when it reported one. */
4547
- function scriptPoint(out: Record<string, unknown> | undefined): { x: number; y: number } | undefined {
4548
- const point = out?.__point as { x?: unknown; y?: unknown } | undefined
4549
- const x = Number(point?.x)
4550
- const y = Number(point?.y)
4551
- return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined
4552
- }
4553
-
4554
- async function handleSendEvaluate(
4555
- handle: ElectronViewHandle,
4556
- expression: string,
4557
- signal?: AbortSignal,
4558
- options?: CommandOptions,
4559
- ): Promise<BrowserExecuteResult> {
4560
- signal?.throwIfAborted()
4561
- const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
4562
- expression,
4563
- returnByValue: true,
4564
- awaitPromise: true,
4565
- } satisfies CdpEvaluateParams, options)
4566
- if (result.exceptionDetails !== undefined) {
4567
- const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
4568
- return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' }
4569
- }
4570
- return { ok: true, value: (result.result as { value?: unknown } | undefined)?.value ?? null }
4571
- }