dsh-builtin-browser 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/README.en.md +89 -0
  2. package/browser-extension/constants.mjs +20 -0
  3. package/browser-extension/controller.mjs +293 -0
  4. package/browser-extension/locales.mjs +15 -0
  5. package/browser-extension/manifest.json +12 -0
  6. package/browser-extension/options.html +14 -0
  7. package/browser-extension/options.mjs +9 -0
  8. package/browser-extension/permission-guard.mjs +13 -0
  9. package/browser-extension/worker.mjs +74 -0
  10. package/package.json +20 -2
  11. package/scripts/build-client.mjs +305 -0
  12. package/scripts/build.mjs +69 -0
  13. package/scripts/bundle-host.mjs +28 -0
  14. package/scripts/fix-exports.mjs +40 -0
  15. package/scripts/install-electron.mjs +101 -0
  16. package/scripts/pack.mjs +99 -0
  17. package/scripts/publish-manifest.mjs +56 -0
  18. package/scripts/verify-exports.mjs +58 -0
  19. package/scripts/verify-preview-sdk.mjs +93 -0
  20. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  21. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  22. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  23. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  24. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  25. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  26. package/skills/dsh-debug-host/SKILL.md +56 -0
  27. package/skills/dsh-debug-self/SKILL.md +50 -0
  28. package/src/bridge-compatibility.ts +39 -0
  29. package/src/browser/anti-bot.ts +251 -0
  30. package/src/browser/deep-dom.ts +40 -0
  31. package/src/browser/handles.ts +89 -0
  32. package/src/browser/runtime.ts +578 -0
  33. package/src/browser/takeover-target.ts +45 -0
  34. package/src/browser/types.ts +870 -0
  35. package/src/browser-electron/authenticated-route.ts +109 -0
  36. package/src/browser-electron/automatic-maintenance.ts +736 -0
  37. package/src/browser-electron/bridge-auto.ts +159 -0
  38. package/src/browser-electron/bridge-connection.ts +386 -0
  39. package/src/browser-electron/bridge-endpoint.ts +129 -0
  40. package/src/browser-electron/bridge-install.ts +290 -0
  41. package/src/browser-electron/bridge-maintenance.ts +189 -0
  42. package/src/browser-electron/bridge-status.ts +386 -0
  43. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  44. package/src/browser-electron/desktop-identity.ts +353 -0
  45. package/src/browser-electron/desktop-shell.ts +100 -0
  46. package/src/browser-electron/document-readiness.ts +45 -0
  47. package/src/browser-electron/electron-provision.ts +347 -0
  48. package/src/browser-electron/entry.ts +1378 -0
  49. package/src/browser-electron/ephemeral-profile.ts +189 -0
  50. package/src/browser-electron/extension-browser.ts +230 -0
  51. package/src/browser-electron/extension-setup.ts +67 -0
  52. package/src/browser-electron/file-write.ts +31 -0
  53. package/src/browser-electron/foreground-watch.ts +142 -0
  54. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  55. package/src/browser-electron/guest-cookie-store.ts +59 -0
  56. package/src/browser-electron/guest-css-runtime.ts +76 -0
  57. package/src/browser-electron/guest-css.ts +68 -0
  58. package/src/browser-electron/guest-route.ts +716 -0
  59. package/src/browser-electron/guest-runtime.ts +408 -0
  60. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  61. package/src/browser-electron/guest-storage.ts +120 -0
  62. package/src/browser-electron/history-store.ts +224 -0
  63. package/src/browser-electron/host-main.ts +1385 -0
  64. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  65. package/src/browser-electron/http-body.ts +65 -0
  66. package/src/browser-electron/json-reply.ts +47 -0
  67. package/src/browser-electron/maintenance-broker.ts +166 -0
  68. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  69. package/src/browser-electron/maintenance-route.ts +68 -0
  70. package/src/browser-electron/missing-system-browser.ts +114 -0
  71. package/src/browser-electron/open-slot.ts +49 -0
  72. package/src/browser-electron/paths.ts +25 -0
  73. package/src/browser-electron/preferred-browser.ts +130 -0
  74. package/src/browser-electron/preview-route.ts +215 -0
  75. package/src/browser-electron/process-ownership.ts +174 -0
  76. package/src/browser-electron/process.ts +23 -0
  77. package/src/browser-electron/profile-checkpoint.ts +187 -0
  78. package/src/browser-electron/profile-command.ts +47 -0
  79. package/src/browser-electron/profile-extension.ts +129 -0
  80. package/src/browser-electron/profile-lease.ts +211 -0
  81. package/src/browser-electron/profile-residue.ts +49 -0
  82. package/src/browser-electron/provider-core.ts +1107 -0
  83. package/src/browser-electron/provider-interaction.ts +1034 -0
  84. package/src/browser-electron/provider-media.ts +589 -0
  85. package/src/browser-electron/provider-navigation.ts +323 -0
  86. package/src/browser-electron/provider-observation.ts +664 -0
  87. package/src/browser-electron/provider-tabs.ts +372 -0
  88. package/src/browser-electron/provider.ts +666 -0
  89. package/src/browser-electron/reference-route.ts +598 -0
  90. package/src/browser-electron/remote-host.ts +1538 -0
  91. package/src/browser-electron/rpc-input.ts +13 -0
  92. package/src/browser-electron/rpc-ops.ts +41 -0
  93. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  94. package/src/browser-electron/runtime-route.ts +105 -0
  95. package/src/browser-electron/runtime-status.ts +309 -0
  96. package/src/browser-electron/settings-route.ts +64 -0
  97. package/src/browser-electron/settings-store.ts +593 -0
  98. package/src/browser-electron/shortcuts-route.ts +112 -0
  99. package/src/browser-electron/sidebar-only-host.ts +300 -0
  100. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  101. package/src/browser-electron/system-browser.ts +1850 -0
  102. package/src/browser-electron/tauri-host.ts +194 -0
  103. package/src/browser-electron/timing.ts +16 -0
  104. package/src/browser-electron/virtual-cursor.ts +162 -0
  105. package/src/browser-electron/windows-system.ts +24 -0
  106. package/src/browser-reference/delivery.ts +384 -0
  107. package/src/browser-reference/entry.ts +631 -0
  108. package/src/browser-reference/export.ts +339 -0
  109. package/src/browser-reference/import.ts +303 -0
  110. package/src/browser-reference/page-script.ts +1537 -0
  111. package/src/browser-reference/service.ts +1346 -0
  112. package/src/browser-reference/store.ts +172 -0
  113. package/src/browser-reference/text-quote.ts +219 -0
  114. package/src/browser-reference/types.ts +195 -0
  115. package/src/browser-reference/visible.ts +367 -0
  116. package/src/browser-reference/web-sources.ts +106 -0
  117. package/src/client/apply-guard.ts +22 -0
  118. package/src/client/browser/BrowserController.ts +693 -0
  119. package/src/client/browser/BrowserFrame.ts +78 -0
  120. package/src/client/browser/BrowserNavigation.ts +169 -0
  121. package/src/client/browser/BrowserPage.ts +23 -0
  122. package/src/client/browser/BrowserPersistence.ts +44 -0
  123. package/src/client/browser/IframeImpl.ts +182 -0
  124. package/src/client/browser/child-tabs.ts +14 -0
  125. package/src/client/browser/frame-history.ts +125 -0
  126. package/src/client/browser/frame-state.ts +27 -0
  127. package/src/client/browser/iframe-reference.ts +67 -0
  128. package/src/client/browser/initialization.ts +262 -0
  129. package/src/client/browser/omnibox.ts +243 -0
  130. package/src/client/browser/store.ts +38 -0
  131. package/src/client/browser/takeover-channel.ts +72 -0
  132. package/src/client/browser/url.ts +46 -0
  133. package/src/client/browser/web-reference-source.ts +56 -0
  134. package/src/client/css-modules.d.ts +4 -0
  135. package/src/client/definition.tsx +36 -0
  136. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  137. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  138. package/src/client/electron/NativeChildPresentation.ts +53 -0
  139. package/src/client/electron/NativeViewPage.ts +265 -0
  140. package/src/client/electron/pages.ts +23 -0
  141. package/src/client/electron/reference-overlay.ts +53 -0
  142. package/src/client/electron/workspace.ts +33 -0
  143. package/src/client/index.ts +333 -0
  144. package/src/client/locales.ts +860 -0
  145. package/src/client/pages.ts +28 -0
  146. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  147. package/src/client/reference/client/draft-reference.ts +167 -0
  148. package/src/client/reference/client/index.ts +7 -0
  149. package/src/client/reference/client/ordered-submission.ts +108 -0
  150. package/src/client/reference/client/pending-delivery.ts +216 -0
  151. package/src/client/reference/client/plugin.ts +208 -0
  152. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  153. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  154. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  155. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  156. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  157. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  158. package/src/client/reference/client/production/assembly.ts +447 -0
  159. package/src/client/reference/client/production/asset-store.ts +144 -0
  160. package/src/client/reference/client/production/availability.ts +72 -0
  161. package/src/client/reference/client/production/bytes.ts +36 -0
  162. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  163. package/src/client/reference/client/production/delivery-client.ts +211 -0
  164. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  165. package/src/client/reference/client/production/http-transport.ts +212 -0
  166. package/src/client/reference/client/production/production-submission.ts +70 -0
  167. package/src/client/reference/client/production/protocol.ts +234 -0
  168. package/src/client/reference/client/production/reference-card.ts +240 -0
  169. package/src/client/reference/client/production/reference-labels.ts +29 -0
  170. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  171. package/src/client/reference/client/production/reveal.ts +215 -0
  172. package/src/client/reference/client/production/runtime.ts +1056 -0
  173. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  174. package/src/client/reference/client/production/source-marker.ts +99 -0
  175. package/src/client/reference/client/production/source-opener.ts +55 -0
  176. package/src/client/reference/client/production/styles.ts +104 -0
  177. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  178. package/src/client/reference/client/reveal.ts +109 -0
  179. package/src/client/reference/client/scheme.ts +114 -0
  180. package/src/client/reference/client/session-schedule.ts +36 -0
  181. package/src/client/reference/client/types.ts +168 -0
  182. package/src/client/reference/css-modules.d.ts +4 -0
  183. package/src/client/reference/index.ts +11 -0
  184. package/src/client/reference-capture-owner.ts +162 -0
  185. package/src/client/reference-intents.ts +36 -0
  186. package/src/client/settings/index.ts +42 -0
  187. package/src/client/settings/mount-guard.ts +31 -0
  188. package/src/client/settings/panel.ts +2768 -0
  189. package/src/client/shortcut-open.ts +30 -0
  190. package/src/client/startpage/binding.ts +99 -0
  191. package/src/client/startpage/controller.ts +300 -0
  192. package/src/client/startpage/model.ts +279 -0
  193. package/src/client/view/Browser.module.css +751 -0
  194. package/src/client/view/BrowserBody.tsx +315 -0
  195. package/src/client/view/BrowserPresentation.ts +9 -0
  196. package/src/client/view/BrowserTitle.tsx +17 -0
  197. package/src/client/view/IframePresentation.ts +365 -0
  198. package/src/client/view/StartPage.tsx +598 -0
  199. package/src/client/view/TakeoverBanner.tsx +21 -0
  200. package/src/compat/host-features.ts +92 -0
  201. package/src/index.ts +110 -0
  202. package/src/reference-owner.ts +5 -0
  203. package/src/reference-page.ts +9 -0
  204. package/src/reference-source.ts +3 -0
  205. package/src/reference-text.ts +219 -0
  206. package/src/startpage-settings.ts +103 -0
  207. package/src/startpage.ts +71 -0
  208. package/src/takeover-protocol.ts +28 -0
  209. package/src/tool-browser/block-recovery.ts +85 -0
  210. package/src/tool-browser/code-tool.ts +555 -0
  211. package/src/tool-browser/code-worker.ts +725 -0
  212. package/src/tool-browser/element-fields.ts +167 -0
  213. package/src/tool-browser/errors.ts +40 -0
  214. package/src/tool-browser/index.ts +265 -0
  215. package/src/tool-browser/page-probe.ts +675 -0
  216. package/src/tool-browser/panel-page.ts +126 -0
  217. package/src/tool-browser/probe-client.ts +183 -0
  218. package/src/tool-browser/screenshot-annotations.ts +131 -0
  219. package/src/tool-browser/screenshot-image.ts +49 -0
  220. package/src/tool-browser/state.ts +375 -0
  221. package/src/tool-browser/takeover.ts +199 -0
  222. package/src/tool-browser/tools-debug.ts +806 -0
  223. package/src/tool-browser/tools-interaction.ts +956 -0
  224. package/src/tool-browser/tools-navigation.ts +786 -0
  225. package/src/tool-browser/tools-observation.ts +474 -0
  226. package/src/tool-browser/tools-reference.ts +294 -0
  227. package/src/types/electron-shim.d.ts +144 -0
  228. package/src/types.ts +85 -0
  229. package/src/web-guest.ts +35 -0
  230. package/tools/accept-desktop.mjs +148 -0
  231. package/dist/client.d.cts +0 -516
  232. package/dist/client.d.mts +0 -516
  233. package/dist/index.cjs +0 -92
  234. package/dist/index.d.mts +0 -2960
  235. package/dist/index.mjs +0 -24
  236. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  237. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  238. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  239. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  240. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  241. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  242. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  243. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  244. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  245. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  246. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  247. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  248. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  249. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  250. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  256. package/dsh-host-patch/sources/manifest.json +0 -218
  257. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  258. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  259. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  260. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  261. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  262. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  263. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  264. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  265. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  266. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  267. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  268. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  269. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  293. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Panel-surface page reader.
3
+ *
4
+ * The Web sidebar renders pages through the plugin's own same-origin proxy, so there is no CDP
5
+ * target behind it. `dsh_browser_open` on the panel surface therefore only hands the address to the
6
+ * sidebar, and every read tool afterwards answered "nothing is open in this task yet" — the model
7
+ * could open a page but never look at it.
8
+ *
9
+ * This module gives those tools something real to read: it fetches the proxied document from
10
+ * loopback (the proxy route is same-origin and loopback-authorized) and parses the parts a snapshot
11
+ * needs — title, text, and the interactive nodes with their labels. It cannot run page script, so
12
+ * actions that need JS still belong to the `builtin` surface; reads do not.
13
+ *
14
+ * @module dsh-builtin-browser/tool-browser/panel-page
15
+ */
16
+
17
+ import { GUEST_ROUTE } from '../../assets/browser-policy.mjs'
18
+
19
+ /** One interactive node found in the proxied document. */
20
+ export interface PanelElement {
21
+ readonly index: number
22
+ /** `link` | `button` | `input` | `select` | `textarea` */
23
+ readonly kind: string
24
+ /** Accessible-ish name: text content, aria-label, placeholder or value. */
25
+ readonly name: string
26
+ /** Destination for links, or the control's type. */
27
+ readonly detail?: string
28
+ }
29
+
30
+ /** What a panel read returns. */
31
+ export interface PanelPage {
32
+ readonly url: string
33
+ readonly title: string
34
+ readonly text: string
35
+ readonly elements: readonly PanelElement[]
36
+ readonly truncated: boolean
37
+ }
38
+
39
+ /** Decode the handful of entities that matter for labels. */
40
+ function decodeEntities(raw: string): string {
41
+ return raw
42
+ .replace(/ /gu, ' ')
43
+ .replace(/&/gu, '&')
44
+ .replace(/&lt;/gu, '<')
45
+ .replace(/&gt;/gu, '>')
46
+ .replace(/&quot;/gu, '"')
47
+ .replace(/&#(\d+);/gu, (_match, code: string) => String.fromCodePoint(Number(code)))
48
+ }
49
+
50
+ /** Strip tags and collapse whitespace. */
51
+ function plain(raw: string): string {
52
+ return decodeEntities(raw.replace(/<[^>]*>/gu, ' ')).replace(/\s+/gu, ' ').trim()
53
+ }
54
+
55
+ /**
56
+ * Read one attribute out of a tag's source text.
57
+ * @param tag - the tag source (e.g. `<a href="x" aria-label="y">`).
58
+ * @param name - attribute name.
59
+ * @returns the attribute value, or undefined.
60
+ */
61
+ function attribute(tag: string, name: string): string | undefined {
62
+ const match = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, 'iu').exec(tag)
63
+ if (match === null) return undefined
64
+ const value = match[2] ?? match[3] ?? match[4] ?? ''
65
+ return decodeEntities(value).trim()
66
+ }
67
+
68
+ /**
69
+ * Fetch the proxied document for an address and parse it.
70
+ * @param pageUrl - the real page address (what the sidebar is showing).
71
+ * @param origin - this host's origin, used to reach the proxy.
72
+ * @param options - optional element cap.
73
+ * @returns the parsed page.
74
+ */
75
+ export async function readPanelPage(
76
+ pageUrl: string,
77
+ origin: string,
78
+ options: { readonly limit?: number; readonly signal?: AbortSignal } = {},
79
+ ): Promise<PanelPage> {
80
+ const limit = options.limit ?? 120
81
+ const proxied = `${origin}${GUEST_ROUTE}?u=${encodeURIComponent(pageUrl)}`
82
+ const response = await fetch(proxied, {
83
+ headers: {
84
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
85
+ 'accept': 'text/html,application/xhtml+xml',
86
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
87
+ },
88
+ ...options.signal === undefined ? {} : { signal: options.signal },
89
+ })
90
+ const html = await response.text()
91
+ if (!response.ok) {
92
+ throw new Error(`panel read failed: HTTP ${response.status} for ${pageUrl}`)
93
+ }
94
+
95
+ const titleMatch = /<title[^>]*>([\s\S]*?)<\/title>/iu.exec(html)
96
+ const title = titleMatch === null ? '' : plain(titleMatch[1] ?? '')
97
+ const withoutScripts = html
98
+ .replace(/<script[\s\S]*?<\/script>/giu, ' ')
99
+ .replace(/<style[\s\S]*?<\/style>/giu, ' ')
100
+ const text = plain(withoutScripts).slice(0, 4000)
101
+
102
+ const elements: PanelElement[] = []
103
+ const pattern = /<(a|button|input|select|textarea)\b([^>]*)>/giu
104
+ let match: RegExpExecArray | null
105
+ while ((match = pattern.exec(html)) !== null && elements.length < limit) {
106
+ const tagName = (match[1] ?? '').toLowerCase()
107
+ const tag = match[0]
108
+ if (tagName === 'a') {
109
+ const href = attribute(tag, 'href')
110
+ const label = attribute(tag, 'aria-label') ?? ''
111
+ if (href === undefined || href.startsWith('javascript:')) continue
112
+ elements.push({ index: elements.length + 1, kind: 'link', name: label === '' ? href : label, detail: href })
113
+ continue
114
+ }
115
+ if (tagName === 'button') {
116
+ const label = attribute(tag, 'aria-label') ?? attribute(tag, 'title') ?? ''
117
+ elements.push({ index: elements.length + 1, kind: 'button', name: label === '' ? '(button)' : label })
118
+ continue
119
+ }
120
+ const type = attribute(tag, 'type') ?? tagName
121
+ const label = attribute(tag, 'aria-label') ?? attribute(tag, 'placeholder') ?? attribute(tag, 'name') ?? ''
122
+ elements.push({ index: elements.length + 1, kind: tagName, name: label === '' ? `(${tagName})` : label, detail: type })
123
+ }
124
+
125
+ return { url: pageUrl, title, text, elements, truncated: elements.length >= limit || text.length >= 4000 }
126
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Page-side probe client: fingerprints, observed effects, the installed probe, polling, and checks.
3
+ * @module dsh-browser/tool-browser/probe-client
4
+ */
5
+
6
+ import type { Context } from '@deepseek-ai/cordis'
7
+ import { pageOperationScript } from './page-probe.ts'
8
+ import { CURSOR_ID } from '../browser-electron/virtual-cursor.ts'
9
+ import type { BrowserSessionId, BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.ts'
10
+
11
+ export const effectProperties = {
12
+ verified: { type: 'boolean' as const, description: 'Whether a visible change was observed. Absent when it could not be checked.' },
13
+ note: { type: 'string' as const, description: 'Why the effect is uncertain.' },
14
+ }
15
+
16
+ export async function pageFingerprint(browser: NonNullable<Context['browser']>, session: BrowserSessionId): Promise<string | undefined> {
17
+ try {
18
+ const result = await browser.execute(session, {
19
+ script: `(() => {
20
+ const a = document.activeElement
21
+ const b = document.body
22
+ const c = typeof document.getElementById === 'function' ? document.getElementById(${JSON.stringify(CURSOR_ID)}) : null
23
+ const own = b && c && c.parentNode === b ? c : null
24
+ return JSON.stringify([
25
+ location.href, document.title,
26
+ a ? [a.tagName, a.id || a.getAttribute('name') || a.className || '',
27
+ typeof a.value === 'string' ? a.value.length : null, a.checked, a.selectedIndex,
28
+ a.selectionStart, a.selectionEnd, a.scrollLeft, a.scrollTop] : null,
29
+ window.scrollX, window.scrollY,
30
+ b ? b.childElementCount - (own ? 1 : 0) : 0,
31
+ b ? b.innerHTML.length - (own ? own.outerHTML.length : 0) : 0,
32
+ ])
33
+ })()`,
34
+ })
35
+ return result.ok && typeof result.value === 'string' ? result.value : undefined
36
+ } catch {
37
+ return undefined
38
+ }
39
+ }
40
+
41
+ export async function observedEffect(browser: NonNullable<Context['browser']>, session: BrowserSessionId, before: string | undefined): Promise<{ verified?: boolean; note?: string }> {
42
+ const after = await pageFingerprint(browser, session)
43
+ if (before === undefined || after === undefined) return { note: 'The effect could not be checked.' }
44
+ return before !== after
45
+ ? { verified: true }
46
+ : { verified: false, note: 'No visible change observed; the effect is uncertain.' }
47
+ }
48
+
49
+ export function effectText(value: { verified?: boolean; note?: string }): string {
50
+ return value.verified === true ? ' Visible change observed.' : ` ${value.note ?? 'The effect could not be checked.'}`
51
+ }
52
+
53
+ /** Run a script in the page and return its value as text. */
54
+ export async function pageValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, script: string, signal?: AbortSignal): Promise<string> {
55
+ const result = await browser.execute(session, { script }, signal)
56
+ if (!result.ok) throw new Error(`page script failed: ${result.exception}`)
57
+ const raw = result.value
58
+ return typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
59
+ }
60
+
61
+ /** Fixed operations keep their inputs as data and preserve arbitrary-script permissions. */
62
+ export async function pageOperationValue(browser: NonNullable<Context['browser']>, session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<string> {
63
+ const result = typeof browser.pageOperation === 'function'
64
+ ? await browser.pageOperation(session, request, signal)
65
+ : await browser.execute(session, { script: pageOperationScript(request) }, signal)
66
+ if (!result.ok) throw new Error('page operation failed: ' + result.exception)
67
+ return typeof result.value === 'string' ? result.value : JSON.stringify(result.value ?? null)
68
+ }
69
+
70
+ /** Install the fixed probe and report page failures immediately. */
71
+ export async function installProbe(browser: NonNullable<Context['browser']>, session: BrowserSessionId, signal?: AbortSignal): Promise<void> {
72
+ await pageOperationValue(browser, session, { operation: 'install' }, signal)
73
+ }
74
+
75
+ /** One probe call, parsed. Throws when the probe is absent or the call failed. */
76
+ export async function probe<T = unknown>(
77
+ browser: NonNullable<Context['browser']>,
78
+ session: BrowserSessionId,
79
+ method: BrowserProbeMethod,
80
+ args: readonly unknown[] = [],
81
+ signal?: AbortSignal,
82
+ ): Promise<T> {
83
+ const text = await pageOperationValue(browser, session, { operation: 'probe', method, args }, signal)
84
+ let parsed: unknown
85
+ try { parsed = JSON.parse(text) } catch { throw new Error(`page probe returned unreadable JSON: ${text.slice(0, 120)}`) }
86
+ if (parsed !== null && typeof parsed === 'object' && 'error' in (parsed as Record<string, unknown>)) {
87
+ throw new Error(`page probe: ${String((parsed as Record<string, unknown>).error)}`)
88
+ }
89
+ return parsed as T
90
+ }
91
+
92
+ /**
93
+ * A probe call that survives a navigation inside a batch.
94
+ *
95
+ * Submitting a form replaces the document, and the probe with it, so a later step in the same
96
+ * batch would fail with `probe-not-installed` — measured on the first real benchmark run. One
97
+ * reinstall and one retry is enough: a second failure is a real absence, not a stale context.
98
+ */
99
+ export async function probeLive<T = unknown>(
100
+ browser: NonNullable<Context['browser']>,
101
+ session: BrowserSessionId,
102
+ method: BrowserProbeMethod,
103
+ args: readonly unknown[] = [],
104
+ signal?: AbortSignal,
105
+ ): Promise<T> {
106
+ try {
107
+ return await probe<T>(browser, session, method, args, signal)
108
+ } catch (error) {
109
+ if (!/probe-not-installed|probe-method-missing/.test(String(error))) throw error
110
+ await installProbe(browser, session, signal)
111
+ return await probe<T>(browser, session, method, args, signal)
112
+ }
113
+ }
114
+
115
+ /** Sleep. Long waits are capped by the caller, and the tool timeout still applies. */
116
+ export async function pause(ms: number): Promise<void> {
117
+ await new Promise<void>(resolve => { setTimeout(resolve, ms) })
118
+ }
119
+
120
+ /** Poll until the callback returns something, or the budget runs out. */
121
+ export async function poll<T>(check: () => Promise<T | undefined>, budgetMs: number, intervalMs = 200): Promise<T | undefined> {
122
+ const deadline = Date.now() + budgetMs
123
+ for (;;) {
124
+ const value = await check()
125
+ if (value !== undefined) return value
126
+ const left = deadline - Date.now()
127
+ if (left <= 0) return undefined
128
+ // Timers may fire a millisecond before `Date.now()` reaches the deadline; the pause that
129
+ // reaches it is the last one, so it is followed by exactly one final check.
130
+ if (left <= intervalMs) {
131
+ await pause(left)
132
+ return await check()
133
+ }
134
+ await pause(intervalMs)
135
+ }
136
+ }
137
+
138
+ /**
139
+ * One flat probe row: what a page can hand back through JSON.
140
+ *
141
+ * Concrete rather than `Record<string, unknown>`, because the tool output schema is a JSON value
142
+ * and the compiler (rightly) refuses to promise that an `unknown` is one.
143
+ */
144
+ export type ProbeRow = Record<string, string | number | boolean | null>
145
+
146
+ /**
147
+ * Run one `dsh_browser_check` specification against the page.
148
+ *
149
+ * Shared by the `check` tool and by the `{check: …}` step of `dsh_browser_do`, so a batch asserts
150
+ * exactly what a standalone call asserts.
151
+ */
152
+ export async function runChecks(
153
+ browser: NonNullable<Context['browser']>,
154
+ session: BrowserSessionId,
155
+ spec: { readonly selector?: string; readonly text?: string; readonly url?: string; readonly js?: string },
156
+ signal?: AbortSignal,
157
+ ): Promise<{ pass: boolean; checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> }> {
158
+ const checks: Array<{ kind: string; expected: string; actual: string; pass: boolean }> = []
159
+ if (spec.selector !== undefined) {
160
+ const found = await probeLive<{ described?: string } | null>(browser, session, 'find', [{ css: spec.selector }], signal)
161
+ checks.push({ kind: 'selector', expected: spec.selector, actual: found === null ? 'not found' : String(found.described ?? 'found'), pass: found !== null })
162
+ }
163
+ if (spec.text !== undefined) {
164
+ const present = await pageOperationValue(browser, session, { operation: 'text', text: spec.text }, signal)
165
+ const ok = present === 'true'
166
+ checks.push({ kind: 'text', expected: spec.text, actual: ok ? 'present' : 'absent', pass: ok })
167
+ }
168
+ if (spec.url !== undefined) {
169
+ const href = await pageOperationValue(browser, session, { operation: 'url' }, signal).then(text => text.replace(/^"|"$/g, ''))
170
+ const ok = href.includes(spec.url)
171
+ checks.push({ kind: 'url', expected: spec.url, actual: href, pass: ok })
172
+ }
173
+ if (spec.js !== undefined) {
174
+ try {
175
+ const value = await pageValue(browser, session, `(() => { try { return JSON.stringify({ ok: !!(${spec.js}) }) } catch (error) { return JSON.stringify({ ok: false, error: String(error) }) } })()`, signal)
176
+ const parsed = JSON.parse(value) as { ok?: boolean; error?: string }
177
+ checks.push({ kind: 'js', expected: spec.js, actual: parsed.ok === true ? 'truthy' : (parsed.error ?? 'falsy'), pass: parsed.ok === true })
178
+ } catch (error) {
179
+ checks.push({ kind: 'js', expected: spec.js, actual: String(error), pass: false })
180
+ }
181
+ }
182
+ return { pass: checks.length > 0 && checks.every(check => check.pass), checks }
183
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Annotated screenshots: numbered boxes over the interactive elements in the viewport, drawn into
3
+ * the page just for the capture and removed right after it. The same numbers come back as
4
+ * `{ id, x, y, role, label }` rows, with x/y the element's centre in viewport CSS pixels, the
5
+ * coordinates click({x, y}) takes. Elements inside open shadow roots and same-origin iframes are
6
+ * included; cross-origin frames stay opaque.
7
+ * @module dsh-browser/tool-browser/screenshot-annotations
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import type { BrowserSessionId } from '../browser/types.ts'
11
+ import { DEEP_DOM_SOURCE } from '../browser/deep-dom.ts'
12
+
13
+ /** One numbered element on an annotated screenshot. */
14
+ export interface ScreenshotAnnotation {
15
+ readonly id: number
16
+ readonly x: number
17
+ readonly y: number
18
+ readonly role: string
19
+ readonly label: string
20
+ }
21
+
22
+ const OVERLAY_ID = '__dsh_annotations__'
23
+ export const MAX_ANNOTATIONS = 80
24
+
25
+ /** Page script: draw the overlay and return the rows. Resolves after the overlay has painted. */
26
+ export const ANNOTATE_SCRIPT = `(async () => {${DEEP_DOM_SOURCE}
27
+ const OVERLAY_ID = ${JSON.stringify(OVERLAY_ID)}
28
+ const old = document.getElementById(OVERLAY_ID)
29
+ if (old) old.remove()
30
+ const SELECTOR = 'a[href], button, input:not([type=hidden]), textarea, select, summary, [role=button], [role=link], [role=checkbox], [role=radio], [role=tab], [role=menuitem], [role=option], [role=switch], [role=combobox], [role=searchbox], [role=textbox], [contenteditable=""], [contenteditable=true], [tabindex]:not([tabindex="-1"])'
31
+ const implicit = (el) => {
32
+ const tag = el.tagName.toLowerCase()
33
+ if (tag === 'a') return 'link'
34
+ if (tag === 'button' || tag === 'summary') return 'button'
35
+ if (tag === 'select') return el.multiple ? 'listbox' : 'combobox'
36
+ if (tag === 'textarea') return 'textbox'
37
+ if (tag === 'input') {
38
+ const type = (el.getAttribute('type') || 'text').toLowerCase()
39
+ if (type === 'checkbox' || type === 'radio') return type
40
+ if (type === 'submit' || type === 'button' || type === 'reset' || type === 'image') return 'button'
41
+ if (type === 'range') return 'slider'
42
+ if (type === 'search') return 'searchbox'
43
+ return 'textbox'
44
+ }
45
+ if (el.isContentEditable) return 'textbox'
46
+ return 'generic'
47
+ }
48
+ const labelOf = (el) => {
49
+ const root = el.getRootNode()
50
+ const byIds = (el.getAttribute('aria-labelledby') || '').split(/\\s+/).filter(Boolean)
51
+ .map(id => { const n = root.getElementById ? root.getElementById(id) : null; return n ? n.textContent : '' }).join(' ')
52
+ let text = el.getAttribute('aria-label') || byIds
53
+ if (!text && el.labels && el.labels.length) text = el.labels[0].textContent
54
+ // A field's value is what the user typed (possibly a password), never its label; only button inputs name themselves by value.
55
+ const buttonValue = el.tagName === 'INPUT' && /^(submit|button|reset)$/i.test(el.getAttribute('type') || '') ? el.value : ''
56
+ if (!text) text = el.innerText || buttonValue || el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || el.getAttribute('name') || ''
57
+ return String(text).replace(/\\s+/g, ' ').trim().slice(0, 80)
58
+ }
59
+ const vw = window.innerWidth, vh = window.innerHeight
60
+ // The element's box in top-viewport coordinates, clipped by every enclosing iframe's viewport.
61
+ const visibleBox = (el) => {
62
+ const r = el.getBoundingClientRect()
63
+ let box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }
64
+ let doc = el.ownerDocument
65
+ while (doc && doc.defaultView && doc.defaultView.frameElement) {
66
+ const view = doc.defaultView
67
+ box = { left: Math.max(box.left, 0), top: Math.max(box.top, 0), right: Math.min(box.right, view.innerWidth), bottom: Math.min(box.bottom, view.innerHeight) }
68
+ const f = view.frameElement.getBoundingClientRect()
69
+ box = { left: box.left + f.left, top: box.top + f.top, right: box.right + f.left, bottom: box.bottom + f.top }
70
+ doc = view.frameElement.ownerDocument
71
+ }
72
+ return { left: Math.max(box.left, 0), top: Math.max(box.top, 0), right: Math.min(box.right, vw), bottom: Math.min(box.bottom, vh) }
73
+ }
74
+ const rows = []
75
+ const boxes = []
76
+ for (const root of __dshRoots()) {
77
+ for (const el of root.querySelectorAll(SELECTOR)) {
78
+ if (rows.length >= ${MAX_ANNOTATIONS}) break
79
+ if (el.disabled) continue
80
+ const r = el.getBoundingClientRect()
81
+ if (r.width < 2 || r.height < 2) continue
82
+ const style = el.ownerDocument.defaultView.getComputedStyle(el)
83
+ if (style.visibility === 'hidden' || style.display === 'none' || Number(style.opacity) === 0) continue
84
+ const v = visibleBox(el)
85
+ if (v.right - v.left < 2 || v.bottom - v.top < 2) continue
86
+ const x = Math.round((v.left + v.right) / 2)
87
+ const y = Math.round((v.top + v.bottom) / 2)
88
+ const id = rows.length + 1
89
+ rows.push({ id, x, y, role: el.getAttribute('role') || implicit(el), label: labelOf(el) })
90
+ boxes.push({ id, left: v.left, top: v.top, width: v.right - v.left, height: v.bottom - v.top })
91
+ }
92
+ }
93
+ const host = document.createElement('div')
94
+ host.id = OVERLAY_ID
95
+ host.setAttribute('aria-hidden', 'true')
96
+ host.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647;'
97
+ const shadow = host.attachShadow ? host.attachShadow({ mode: 'closed' }) : host
98
+ const colors = ['#e6194b', '#3cb44b', '#4363d8', '#f58231', '#911eb4', '#008080', '#9a6324', '#800000']
99
+ for (const b of boxes) {
100
+ const color = colors[(b.id - 1) % colors.length]
101
+ const box = document.createElement('div')
102
+ box.style.cssText = 'position:fixed;box-sizing:border-box;border:2px solid ' + color + ';left:' + b.left + 'px;top:' + b.top + 'px;width:' + b.width + 'px;height:' + b.height + 'px;'
103
+ const tag = document.createElement('span')
104
+ tag.textContent = String(b.id)
105
+ tag.style.cssText = 'position:absolute;left:-2px;top:' + (b.top >= 14 ? '-14px' : '0') + ';background:' + color + ';color:#fff;font:bold 11px/13px monospace;padding:0 3px;'
106
+ box.appendChild(tag)
107
+ shadow.appendChild(box)
108
+ }
109
+ ;(document.body || document.documentElement).appendChild(host)
110
+ await new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))
111
+ return rows
112
+ })()`
113
+
114
+ export const CLEAR_ANNOTATIONS_SCRIPT = `(() => { const el = document.getElementById(${JSON.stringify(OVERLAY_ID)}); if (el) el.remove(); return true })()`
115
+
116
+ type Browser = NonNullable<Context['browser']>
117
+
118
+ export async function drawAnnotations(browser: Browser, session: BrowserSessionId, signal?: AbortSignal): Promise<readonly ScreenshotAnnotation[]> {
119
+ const result = await browser.execute(session, { script: ANNOTATE_SCRIPT }, signal)
120
+ if (!result.ok) throw new Error(`browser: could not annotate the page (${result.exception})`)
121
+ return Array.isArray(result.value) ? result.value as ScreenshotAnnotation[] : []
122
+ }
123
+
124
+ export async function clearAnnotations(browser: Browser, session: BrowserSessionId): Promise<void> {
125
+ try { await browser.execute(session, { script: CLEAR_ANNOTATIONS_SCRIPT }) } catch { /* the page navigated away; nothing to clear */ }
126
+ }
127
+
128
+ /** Text lines naming each numbered element. */
129
+ export function annotationLines(rows: readonly ScreenshotAnnotation[]): string[] {
130
+ return rows.map(row => ` [${row.id}] ${row.role}${row.label !== '' ? ` "${row.label}"` : ''} @ ${row.x},${row.y}`)
131
+ }
@@ -0,0 +1,49 @@
1
+ import type { ImageBlock } from '@deepseek-ai/dsh-llm'
2
+
3
+ export const SCREENSHOT_MAX_WIDTH = 1280
4
+ export const SCREENSHOT_MAX_HEIGHT = 960
5
+ export const SCREENSHOT_MAX_BYTES = 4 * 1024 * 1024
6
+
7
+ export function screenshotDimension(value: number | undefined, limit: number): number {
8
+ if (value === undefined) return limit
9
+ if (!Number.isFinite(value) || value < 1) throw new Error('Screenshot dimensions must be positive finite numbers.')
10
+ return Math.min(Math.floor(value), limit)
11
+ }
12
+
13
+ export function screenshotBytes(dataUrl: string): { data: Buffer; mediaType: 'image/png' | 'image/jpeg' } {
14
+ if (dataUrl.length > 64 + Math.ceil(SCREENSHOT_MAX_BYTES / 3) * 4) {
15
+ throw new Error('Screenshot exceeds the 4 MiB image limit; retry with smaller maxWidth/maxHeight.')
16
+ }
17
+ const match = /^data:(image\/png|image\/jpeg);base64,([A-Za-z0-9+/]+={0,2})$/.exec(dataUrl)
18
+ if (!match) throw new Error('Screenshot must contain a PNG or JPEG base64 image.')
19
+ const data = Buffer.from(match[2]!, 'base64')
20
+ if (data.length === 0 || data.toString('base64') !== match[2]) throw new Error('Screenshot contains invalid base64.')
21
+ if (data.length > SCREENSHOT_MAX_BYTES) throw new Error('Screenshot exceeds the 4 MiB image limit; retry with smaller maxWidth/maxHeight.')
22
+ return { data, mediaType: match[1] as 'image/png' | 'image/jpeg' }
23
+ }
24
+
25
+ export async function screenshotVisionEnabled(context: unknown, execution: unknown, signal?: AbortSignal): Promise<boolean> {
26
+ const ctx = context as { llm?: { resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<{ inputModalities?: readonly string[] }> } }
27
+ const exec = execution as { agent?: { model?: { current(): { provider: string; model: string } | undefined } } }
28
+ signal?.throwIfAborted()
29
+ try {
30
+ const selection = exec.agent?.model?.current()
31
+ if (!selection || !ctx.llm) return false
32
+ const info = await ctx.llm.resolveModelInfo(selection.provider, selection.model, signal)
33
+ signal?.throwIfAborted()
34
+ return info.inputModalities?.includes('image') === true
35
+ } catch (error) {
36
+ signal?.throwIfAborted()
37
+ return false
38
+ }
39
+ }
40
+
41
+ export async function saveScreenshotImage(context: unknown, image: ReturnType<typeof screenshotBytes>, maxWidth: number, maxHeight: number): Promise<ImageBlock['attachment']> {
42
+ const ctx = context as { attachments?: { saveImage(input: { data: Uint8Array; mediaType: 'image/png' | 'image/jpeg' }): Promise<ImageBlock['attachment']> } }
43
+ if (!ctx.attachments) throw new Error('Screenshot image delivery requires the host attachment service.')
44
+ const ref = await ctx.attachments.saveImage(image)
45
+ if (!(ref.bytes > 0 && ref.bytes <= SCREENSHOT_MAX_BYTES && ref.width > 0 && ref.width <= maxWidth && ref.height > 0 && ref.height <= maxHeight)) {
46
+ throw new Error('Screenshot encoder exceeded the image size/dimension limits; retry with smaller maxWidth/maxHeight.')
47
+ }
48
+ return { attachmentId: ref.attachmentId, mediaType: ref.mediaType, bytes: ref.bytes, width: ref.width, height: ref.height }
49
+ }