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,956 @@
1
+ /**
2
+ * Interaction tools: click, type, key, scroll, forms, drag, hover, upload, download and delivery.
3
+ * @module dsh-browser/tool-browser/tools-interaction
4
+ */
5
+
6
+ import { statSync } from 'node:fs'
7
+ import { defineTool } from '@deepseek-ai/dsh-tools'
8
+ import { assertAllowed, type ExecAgent, agentOf, taskKey, ensureSession, type ToolScope, type ToolDefinition } from './state.ts'
9
+ import { effectProperties, pageFingerprint, observedEffect, effectText, pageOperationValue, installProbe, probe, pause, type ProbeRow } from './probe-client.ts'
10
+
11
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
12
+
13
+ /**
14
+ * Read a target's `index`, refusing the values that cannot mean anything.
15
+ *
16
+ * The index is looked up in the page (`els[index] ?? null`), so a negative one — `-1`, the
17
+ * common "give me the last one" shorthand — matches nothing. The page script then treated
18
+ * that as "not on the page yet" and polled for its whole 10s budget before reporting
19
+ * "element not found", which reads like a slow page rather than a bad argument. Refusing it
20
+ * here names the real problem immediately.
21
+ * @param target - the caller's target, or undefined when there is none.
22
+ * @returns the index, or undefined to let the page default to 0.
23
+ */
24
+ export function targetIndex(target: { readonly index?: unknown } | undefined): number | undefined {
25
+ const index = target?.index
26
+ if (index === undefined) return undefined
27
+ if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) {
28
+ throw new Error(`target.index must be a non-negative integer (got ${JSON.stringify(index)}); it is a 0-based position among the matches, and negative values such as -1 match nothing — pass the position you want, or narrow the selector`)
29
+ }
30
+ return index
31
+ }
32
+
33
+ /** Coerce a tool-provided string value back to boolean/number only when lossless. */
34
+ export function parseFillValue(v: string | undefined): string | number | boolean {
35
+ if (v === 'true') return true
36
+ if (v === 'false') return false
37
+ // Deliberately NOT coerced to a number. The description says numbers are accepted in
38
+ // string form, and callers pass account numbers, postcodes and zero-padded ids through
39
+ // here: "007" became "7" and "1e3" became "1000", which silently rewrote the value they
40
+ // meant to type. A numeric-looking string is a string; the DOM decides how to store it.
41
+ return v ?? ''
42
+ }
43
+
44
+ /**
45
+ * Define this module's tools for one apply.
46
+ * @param scope - the apply's context, settings and per-apply state.
47
+ * @returns the tool definitions, for the entry to register.
48
+ */
49
+ export function interactionTools(scope: ToolScope): ToolDefinition[] {
50
+ const { ctx, state, settingsStore, timeoutMs, maxFillFields } = scope
51
+ const tools: ToolDefinition[] = []
52
+
53
+ tools.push(defineTool({
54
+ name: 'dsh_browser_execute',
55
+ description: 'Execute JavaScript in the shared-browser page context. This is the primary way to interact with page elements: focus, fill inputs (use the native value setter for framework-controlled inputs, then dispatch an input event), click buttons (element.click() or a constructed MouseEvent). Returns the evaluation result by value, or the exception text.',
56
+ parameters: {
57
+ script: { type: 'string', required: true, description: 'The JavaScript expression to evaluate in the page context.' },
58
+ args: { type: 'array', items: { type: 'string' }, description: 'Optional arguments injected into the script scope as arguments[0..n].' },
59
+ },
60
+ output: {
61
+ schema: {
62
+ type: 'object',
63
+ additionalProperties: false,
64
+ properties: {
65
+ ok: { type: 'boolean', required: true },
66
+ value: { type: 'string' },
67
+ exception: { type: 'string' },
68
+ },
69
+ },
70
+ // A return value is whatever the page produced, and `document.body.outerHTML` measured
71
+ // 157,350 characters — ~39-52k tokens from one call. Bounded, with the cut stated so the
72
+ // caller knows to narrow the expression rather than the value being silently short.
73
+ render: (_args, value) => {
74
+ if (!value.ok) return [{ type: 'text', text: `Exception: ${value.exception}` }]
75
+ const rendered = String(value.value ?? '')
76
+ const cap = 50_000
77
+ const text = rendered.length > cap
78
+ ? `Result: ${rendered.slice(0, cap)}\n(result truncated at ${cap} of ${rendered.length} characters — return a smaller value, or write it with dsh_browser_execute + a variable)`
79
+ : `Result: ${rendered}`
80
+ return [{ type: 'text', text }]
81
+ },
82
+ },
83
+ timeoutMs,
84
+ isConcurrencySafe: () => false, // page JS can be stateful
85
+ async execute(args, exec) {
86
+ assertAllowed(state, 'dsh_browser_execute', taskKey(exec))
87
+ const browser = ctx.get('browser')
88
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
89
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
90
+ const result = await browser.execute(session, {
91
+ script: args.script,
92
+ args: args.args ?? [],
93
+ }, exec.signal)
94
+ if (result.ok) {
95
+ const raw = result.value
96
+ const value = typeof raw === 'string' ? raw : JSON.stringify(raw ?? null)
97
+ return { ok: true, value }
98
+ }
99
+ return { ok: false, exception: result.exception }
100
+ },
101
+ }))
102
+
103
+ tools.push(defineTool({
104
+ name: 'dsh_browser_click',
105
+ description: 'Click in the shared browser. Prefer target {by: css|text|xpath, value, index?}: the element is located from the DOM, scrolled into view, and clicked at its centre — no image input needed, and the only form that works without vision. Alternatively x/y viewport coordinates, meaningful only after a vision model located the element on a dsh_browser_screenshot; refused under the non-visual strategy. Provide exactly one of target or x/y.',
106
+ parameters: {
107
+ target: {
108
+ type: 'object',
109
+ additionalProperties: false,
110
+ properties: {
111
+ by: { type: 'string', enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css). text matches an element\'s own visible text, exact first then contains.' },
112
+ value: { type: 'string', required: true, description: 'The CSS selector, visible text, or XPath expression.' },
113
+ index: { type: 'number', description: '0-based index of the match (default 0).' },
114
+ },
115
+ description: 'Locate the element semantically and click it (css/text/xpath).',
116
+ },
117
+ x: { type: 'number', description: 'Viewport x coordinate (CSS px), taken from a dsh_browser_screenshot read by a vision model. Prefer a semantic target — it works without image input.' },
118
+ y: { type: 'number', description: 'Viewport y coordinate (CSS px), taken from the same screenshot as x.' },
119
+ },
120
+ output: {
121
+ schema: { type: 'object', additionalProperties: false, properties: { clicked: { type: 'boolean', required: true }, ...effectProperties } },
122
+ render: (_args, value) => [{ type: 'text', text: value.clicked ? 'Clicked.' + effectText(value) : 'Click failed.' }],
123
+ },
124
+ timeoutMs,
125
+ isConcurrencySafe: () => false,
126
+ async execute(args, exec) {
127
+ assertAllowed(state, 'dsh_browser_click', taskKey(exec))
128
+ const browser = ctx.get('browser')
129
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
130
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
131
+ const target = args.target as { by?: string; value?: string; index?: number } | undefined
132
+ // A target whose value is empty is a caller mistake, not a request to fall back.
133
+ // Degrading silently sent typed text to whatever held focus — possibly a password
134
+ // field — or dropped the semantic target in favour of coordinates.
135
+ if (target !== undefined && typeof target.value === 'string' && target.value === '') {
136
+ throw new Error('target.value is empty; pass a css selector, visible text or XPath, or omit target entirely to use x/y')
137
+ }
138
+ const index = targetIndex(target)
139
+ const before = await pageFingerprint(browser, session)
140
+ if (target !== undefined && typeof target.value === 'string' && target.value !== '') {
141
+ await browser.click(session, {
142
+ target: {
143
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
144
+ value: target.value,
145
+ ...index !== undefined ? { index } : {},
146
+ },
147
+ }, exec.signal)
148
+ } else {
149
+ if (typeof args.x !== 'number' || typeof args.y !== 'number') {
150
+ throw new Error('dsh_browser_click: provide a target (css/text/xpath) or x/y coordinates')
151
+ }
152
+ await browser.click(session, { x: args.x, y: args.y }, exec.signal)
153
+ }
154
+ return { clicked: true, ...await observedEffect(browser, session, before) }
155
+ },
156
+ }))
157
+
158
+ tools.push(defineTool({
159
+ name: 'dsh_browser_click_sequence',
160
+ description: 'Click many points in order, in one call. Use this instead of repeated dsh_browser_click when a page needs a run of coordinate clicks — a canvas board, a map, a drawing surface. Each point is clicked with the same real input sequence the single click uses; between points the call waits intervalMs (default 40 ms), which is what stops a page from reading two presses as a double click. Stops at the first point that fails and says where, so a run that half-landed is reported rather than looking complete.',
161
+ parameters: {
162
+ points: {
163
+ type: 'array',
164
+ required: true,
165
+ description: 'Points to click, in order, in viewport CSS pixels — the same space dsh_browser_screenshot reports.',
166
+ items: {
167
+ type: 'object',
168
+ additionalProperties: false,
169
+ properties: {
170
+ x: { type: 'number', required: true, description: 'Viewport x in CSS px.' },
171
+ y: { type: 'number', required: true, description: 'Viewport y in CSS px.' },
172
+ },
173
+ },
174
+ },
175
+ intervalMs: { type: 'number', description: 'Milliseconds between points (default 40).' },
176
+ },
177
+ output: {
178
+ schema: {
179
+ type: 'object',
180
+ additionalProperties: false,
181
+ properties: {
182
+ clicked: { type: 'number', required: true, description: 'How many points landed.' },
183
+ ...effectProperties,
184
+ failedAt: { type: 'number', description: 'Index of the point that failed, when one did.' },
185
+ error: { type: 'string', description: 'Why that point failed.' },
186
+ },
187
+ },
188
+ render: (_args, value) => [{
189
+ type: 'text',
190
+ text: value.failedAt === undefined
191
+ ? `Clicked ${String(value.clicked)} point(s).` + effectText(value)
192
+ : `Clicked ${String(value.clicked)} point(s), then stopped at index ${String(value.failedAt)}: ${String(value.error ?? 'unknown')}`,
193
+ }],
194
+ },
195
+ timeoutMs,
196
+ isConcurrencySafe: () => false,
197
+ async execute(args, exec) {
198
+ assertAllowed(state, 'dsh_browser_click_sequence', taskKey(exec))
199
+ const browser = ctx.get('browser')
200
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
201
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
202
+ const points = Array.isArray(args.points) ? args.points : []
203
+ const intervalMs = typeof args.intervalMs === 'number' ? args.intervalMs : undefined
204
+ const before = await pageFingerprint(browser, session)
205
+ const result = await browser.clickSequence(session, { points, ...intervalMs === undefined ? {} : { intervalMs } })
206
+ return { ...result, ...await observedEffect(browser, session, before) }
207
+ },
208
+ }))
209
+
210
+ tools.push(defineTool({
211
+ name: 'dsh_browser_type',
212
+ description: 'Type text into the focused element of the shared browser, or into a located element (pass target {by: css|text|xpath, value, index?} to focus it first). Text is inserted at the focus via CDP Input.insertText. For setting whole field values (and React-controlled inputs) prefer dsh_browser_set_value; use dsh_browser_key for Enter/Tab/arrows.',
213
+ parameters: {
214
+ text: { type: 'string', required: true, description: 'The text to insert.' },
215
+ target: {
216
+ type: 'object',
217
+ additionalProperties: false,
218
+ properties: {
219
+ by: { type: 'string', enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css).' },
220
+ value: { type: 'string', required: true, description: 'The CSS selector, visible text, or XPath expression.' },
221
+ index: { type: 'number', description: '0-based index of the match (default 0).' },
222
+ },
223
+ description: 'Focus this element first, then type (css/text/xpath).',
224
+ },
225
+ },
226
+ output: {
227
+ schema: { type: 'object', additionalProperties: false, properties: { typed: { type: 'boolean', required: true }, ...effectProperties } },
228
+ render: (_args, value) => [{ type: 'text', text: value.typed ? `Typed ${String(_args.text).length} chars.` + effectText(value) : 'Type failed.' }],
229
+ },
230
+ timeoutMs,
231
+ isConcurrencySafe: () => false,
232
+ async execute(args, exec) {
233
+ assertAllowed(state, 'dsh_browser_type', taskKey(exec))
234
+ const browser = ctx.get('browser')
235
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
236
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
237
+ const target = args.target as { by?: string; value?: string; index?: number } | undefined
238
+ // A target whose value is empty is a caller mistake, not a request to fall back.
239
+ // Degrading silently sent typed text to whatever held focus — possibly a password
240
+ // field — or dropped the semantic target in favour of coordinates.
241
+ if (target !== undefined && typeof target.value === 'string' && target.value === '') {
242
+ throw new Error('target.value is empty; pass a css selector, visible text or XPath, or omit target entirely to use x/y')
243
+ }
244
+ const index = targetIndex(target)
245
+ const before = await pageFingerprint(browser, session)
246
+ if (target !== undefined && typeof target.value === 'string' && target.value !== '') {
247
+ await browser.type(session, {
248
+ text: args.text,
249
+ target: {
250
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
251
+ value: target.value,
252
+ ...index !== undefined ? { index } : {},
253
+ },
254
+ }, exec.signal)
255
+ } else {
256
+ await browser.type(session, { text: args.text }, exec.signal)
257
+ }
258
+ return { typed: true, ...await observedEffect(browser, session, before) }
259
+ },
260
+ }))
261
+
262
+ tools.push(defineTool({
263
+ name: 'dsh_browser_scroll',
264
+ description: 'Scroll the shared-browser page: by pixel deltas (deltaX/deltaY), to a CSS selector\'s element, or to the top/bottom. Use to reveal below-the-fold content before snapshotting or clicking.',
265
+ parameters: {
266
+ deltaX: { type: 'number', description: 'Horizontal scroll delta in CSS pixels.' },
267
+ deltaY: { type: 'number', description: 'Vertical scroll delta in CSS pixels.' },
268
+ selector: { type: 'string', description: 'Scroll the element matching this CSS selector into view.' },
269
+ toTop: { type: 'boolean', description: 'Scroll to the top of the page.' },
270
+ toBottom: { type: 'boolean', description: 'Scroll to the bottom of the page.' },
271
+ },
272
+ output: {
273
+ schema: { type: 'object', additionalProperties: false, properties: { scrolled: { type: 'boolean', required: true }, ...effectProperties } },
274
+ render: (_args, value) => [{ type: 'text', text: value.scrolled ? 'Scrolled.' + effectText(value) : 'Scroll failed.' }],
275
+ },
276
+ timeoutMs,
277
+ isConcurrencySafe: () => false, // mutates page scroll state; exclusive within a task
278
+ async execute(args, exec) {
279
+ assertAllowed(state, 'dsh_browser_scroll', taskKey(exec))
280
+ const browser = ctx.get('browser')
281
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
282
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
283
+ const before = await pageFingerprint(browser, session)
284
+ await browser.scroll(session, {
285
+ ...args.deltaX !== undefined ? { deltaX: args.deltaX } : {},
286
+ ...args.deltaY !== undefined ? { deltaY: args.deltaY } : {},
287
+ ...args.selector !== undefined ? { selector: args.selector } : {},
288
+ ...args.toTop === true ? { toTop: true } : {},
289
+ ...args.toBottom === true ? { toBottom: true } : {},
290
+ }, exec.signal)
291
+ return { scrolled: true, ...await observedEffect(browser, session, before) }
292
+ },
293
+ }))
294
+
295
+ tools.push(defineTool({
296
+ name: 'dsh_browser_key',
297
+ description: 'Press one named key in the shared-browser page (Enter, Tab, Escape, Backspace, Delete, ArrowUp/Down/Left/Right, Home, End, PageUp, PageDown, Space). Use after focusing an input to submit a chat box (Enter), move focus (Tab), or navigate a list (arrows).',
298
+ parameters: {
299
+ key: { type: 'string', required: true, enum: ['Enter', 'Tab', 'Escape', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Space'], description: 'The key to press.' },
300
+ },
301
+ output: {
302
+ schema: { type: 'object', additionalProperties: false, properties: { pressed: { type: 'boolean', required: true }, ...effectProperties } },
303
+ render: (_args, value) => [{ type: 'text', text: value.pressed ? `Pressed ${String(_args.key)}.` + effectText(value) : 'Key press failed.' }],
304
+ },
305
+ timeoutMs,
306
+ isConcurrencySafe: () => false, // mutates page state; exclusive within a task
307
+ async execute(args, exec) {
308
+ assertAllowed(state, 'dsh_browser_key', taskKey(exec))
309
+ const browser = ctx.get('browser')
310
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
311
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
312
+ const before = await pageFingerprint(browser, session)
313
+ await browser.key(session, { key: args.key }, exec.signal)
314
+ return { pressed: true, ...await observedEffect(browser, session, before) }
315
+ },
316
+ }))
317
+
318
+ tools.push(defineTool({
319
+ name: 'dsh_browser_fill',
320
+ description: 'Fill a form in one batch: each field takes a CSS selector or name/label/placeholder text plus its value (boolean for checkbox/radio; option value or visible text for selects and radio groups). The native setter plus input/change events fire, so React/Vue controlled inputs update. Optionally submit the form. Prefer this over hand-written dsh_browser_execute; per-field failures are reported instead of throwing.',
321
+ parameters: {
322
+ fields: {
323
+ type: 'array',
324
+ required: true,
325
+ items: {
326
+ type: 'object',
327
+ additionalProperties: true,
328
+ properties: {
329
+ selector: { type: 'string', description: 'CSS selector; when present, candidates are scoped to it.' },
330
+ name: { type: 'string', description: 'Match by the field\'s name attribute.' },
331
+ label: { type: 'string', description: 'Match by associated <label> text or aria-label.' },
332
+ placeholder: { type: 'string', description: 'Match by placeholder text.' },
333
+ kind: { type: 'string', enum: ['text', 'textarea', 'checkbox', 'radio', 'select'], description: 'Field kind; defaults to text.' },
334
+ value: { type: 'string', required: true, description: 'Value to set (string form; booleans/numbers accepted as strings). Required: omitting it would be read as "set empty", which unchecks a checkbox and clears a text field while still reporting success.' },
335
+ },
336
+ },
337
+ },
338
+ submit: { type: 'boolean', description: 'Submit the containing form after filling (default false).' },
339
+ },
340
+ output: {
341
+ schema: {
342
+ type: 'object',
343
+ additionalProperties: false,
344
+ properties: {
345
+ fields: {
346
+ type: 'array',
347
+ required: true,
348
+ items: {
349
+ type: 'object',
350
+ additionalProperties: false,
351
+ properties: {
352
+ ok: { type: 'boolean', required: true },
353
+ target: { type: 'string', required: true },
354
+ method: { type: 'string' },
355
+ error: { type: 'string' },
356
+ },
357
+ },
358
+ },
359
+ submitted: { type: 'boolean', required: true },
360
+ },
361
+ },
362
+ render: (_args, value) => [{
363
+ type: 'text',
364
+ text: (() => {
365
+ const fields = value.fields as { ok: boolean; target: string; method?: string; error?: string }[]
366
+ const failed = fields.filter(f => !f.ok)
367
+ const lines = fields.map(f => `${f.ok ? 'OK' : 'FAIL'} ${f.target}${f.ok ? ` (${f.method ?? 'input'})` : `: ${f.error ?? 'unknown error'}`}`)
368
+ const head = failed.length === 0
369
+ ? `Filled ${fields.length}/${fields.length} fields${value.submitted ? ' and submitted the form' : ''}.`
370
+ : `Filled ${fields.length - failed.length}/${fields.length} fields; ${failed.length} failed:`
371
+ return head + '\n' + lines.join('\n')
372
+ })(),
373
+ }],
374
+ },
375
+ timeoutMs,
376
+ isConcurrencySafe: () => false,
377
+ async execute(args, exec) {
378
+ assertAllowed(state, 'dsh_browser_fill', taskKey(exec))
379
+ const browser = ctx.get('browser')
380
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
381
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
382
+ const requested = args.fields ?? []
383
+ if (requested.length > maxFillFields) {
384
+ throw new Error(`dsh_browser_fill: ${requested.length} fields in one call exceeds the ${maxFillFields}-field limit; split it into several calls so each one can report per-field results instead of timing out as a batch`)
385
+ }
386
+ const fields = requested.map((f: { selector?: string; name?: string; label?: string; placeholder?: string; kind?: string; value?: string }) => {
387
+ // A missing value is a caller mistake, not a request to clear the field. Turning
388
+ // it into '' silently unchecks a checkbox or empties a text input while the tool
389
+ // still reports success, so it fails loudly. The schema marks value required, but
390
+ // a call can still arrive without it.
391
+ if (f.value === undefined) {
392
+ const matcher = f.selector ?? f.name ?? f.label ?? f.placeholder ?? '(no matcher)'
393
+ throw new Error(`dsh_browser_fill: field "${matcher}" has no "value"; pass one (use "false" to uncheck, or "" to clear deliberately)`)
394
+ }
395
+ return {
396
+ ...f.selector !== undefined ? { selector: f.selector } : {},
397
+ ...f.name !== undefined ? { name: f.name } : {},
398
+ ...f.label !== undefined ? { label: f.label } : {},
399
+ ...f.placeholder !== undefined ? { placeholder: f.placeholder } : {},
400
+ ...f.kind !== undefined ? { kind: f.kind as 'text' | 'textarea' | 'checkbox' | 'radio' | 'select' } : {},
401
+ value: parseFillValue(f.value),
402
+ }
403
+ })
404
+ const result = await browser.fillForm(session, {
405
+ fields,
406
+ ...args.submit === true ? { submit: true } : {},
407
+ }, exec.signal)
408
+ return {
409
+ fields: result.fields.map(f => ({ ok: f.ok, target: f.target, ...f.method !== undefined ? { method: f.method } : {}, ...f.error !== undefined ? { error: f.error } : {} })),
410
+ submitted: result.submitted,
411
+ }
412
+ },
413
+ }))
414
+
415
+ // ---------------------------------------------------------------------------
416
+ // Single-control form primitives, all target-based (css/text/xpath).
417
+ // ---------------------------------------------------------------------------
418
+ const targetParam = {
419
+ type: 'object' as const,
420
+ required: true as const,
421
+ additionalProperties: false as const,
422
+ properties: {
423
+ by: { type: 'string' as const, enum: ['css', 'text', 'xpath'], description: 'Locator kind (default css). text matches an element\'s own visible text, exact first then contains.' },
424
+ value: { type: 'string' as const, required: true as const, description: 'The CSS selector, visible text, or XPath expression.' },
425
+ index: { type: 'number' as const, description: '0-based index of the match (default 0).' },
426
+ },
427
+ description: 'Locate the element (css/text/xpath).',
428
+ }
429
+
430
+ tools.push(defineTool({
431
+ name: 'dsh_browser_set_value',
432
+ description: 'Set the value of ONE input/textarea/select/contenteditable, located by css/text/xpath. Uses the native setter plus input/change events, so React/Vue controlled inputs update correctly. For selects pass the option value or visible text. For a whole form at once prefer dsh_browser_fill.',
433
+ parameters: {
434
+ target: targetParam,
435
+ value: { type: 'string', required: true, description: 'The value to set (string form; numbers/booleans accepted).' },
436
+ },
437
+ output: {
438
+ schema: {
439
+ type: 'object',
440
+ additionalProperties: false,
441
+ properties: {
442
+ method: { type: 'string', required: true, description: 'How the value was applied: input/textarea/select/contenteditable.' },
443
+ value: { type: 'string', required: true },
444
+ },
445
+ },
446
+ render: (_args, value) => [{ type: 'text', text: `Set via ${value.method}.` }],
447
+ },
448
+ timeoutMs,
449
+ isConcurrencySafe: () => false, // mutates a field; exclusive within a task
450
+ async execute(args, exec) {
451
+ assertAllowed(state, 'dsh_browser_set_value', taskKey(exec))
452
+ const browser = ctx.get('browser')
453
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
454
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
455
+ const target = args.target as { by?: string; value: string; index?: number }
456
+ const result = await browser.setValue(session, {
457
+ target: {
458
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
459
+ value: target.value,
460
+ ...target.index !== undefined ? { index: target.index } : {},
461
+ },
462
+ value: parseFillValue(args.value),
463
+ }, exec.signal)
464
+ return { method: result.method, value: result.value }
465
+ },
466
+ }))
467
+
468
+ tools.push(defineTool({
469
+ name: 'dsh_browser_check',
470
+ description: 'Check (or uncheck, with checked=false) a checkbox or radio button, located by css/text/xpath.',
471
+ parameters: {
472
+ target: targetParam,
473
+ checked: { type: 'boolean', description: 'Desired state (default true = check).' },
474
+ },
475
+ output: {
476
+ schema: { type: 'object', additionalProperties: false, properties: { checked: { type: 'boolean', required: true } } },
477
+ render: (_args, value) => [{ type: 'text', text: value.checked ? 'Checked.' : 'Unchecked.' }],
478
+ },
479
+ timeoutMs,
480
+ isConcurrencySafe: () => false, // mutates a field; exclusive within a task
481
+ async execute(args, exec) {
482
+ assertAllowed(state, 'dsh_browser_check', taskKey(exec))
483
+ const browser = ctx.get('browser')
484
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
485
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
486
+ const target = args.target as { by?: string; value: string; index?: number }
487
+ const result = await browser.check(session, {
488
+ target: {
489
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
490
+ value: target.value,
491
+ ...target.index !== undefined ? { index: target.index } : {},
492
+ },
493
+ ...args.checked !== undefined ? { checked: args.checked } : {},
494
+ }, exec.signal)
495
+ return { checked: result.checked }
496
+ },
497
+ }))
498
+
499
+ tools.push(defineTool({
500
+ name: 'dsh_browser_select',
501
+ description: 'Select one option of a <select>, located by css/text/xpath — by option value, visible text, or 0-based index (provide exactly one).',
502
+ parameters: {
503
+ target: targetParam,
504
+ optionValue: { type: 'string', description: 'Match the option by its value attribute.' },
505
+ optionText: { type: 'string', description: 'Match the option by its visible text.' },
506
+ optionIndex: { type: 'number', description: 'Match the option by its 0-based index.' },
507
+ },
508
+ output: {
509
+ schema: {
510
+ type: 'object',
511
+ additionalProperties: false,
512
+ properties: {
513
+ value: { type: 'string', required: true },
514
+ text: { type: 'string', required: true },
515
+ },
516
+ },
517
+ render: (_args, value) => [{ type: 'text', text: `Selected "${value.text}".` }],
518
+ },
519
+ timeoutMs,
520
+ isConcurrencySafe: () => false, // mutates a field; exclusive within a task
521
+ async execute(args, exec) {
522
+ assertAllowed(state, 'dsh_browser_select', taskKey(exec))
523
+ const browser = ctx.get('browser')
524
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
525
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
526
+ const target = args.target as { by?: string; value: string; index?: number }
527
+ const result = await browser.selectOption(session, {
528
+ target: {
529
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
530
+ value: target.value,
531
+ ...target.index !== undefined ? { index: target.index } : {},
532
+ },
533
+ ...args.optionValue !== undefined ? { optionValue: args.optionValue } : {},
534
+ ...args.optionText !== undefined ? { optionText: args.optionText } : {},
535
+ ...args.optionIndex !== undefined ? { optionIndex: args.optionIndex } : {},
536
+ }, exec.signal)
537
+ return { value: result.value, text: result.text }
538
+ },
539
+ }))
540
+
541
+ tools.push(defineTool({
542
+ name: 'dsh_browser_clear',
543
+ description: 'Clear an input/textarea/contenteditable, or uncheck a checkbox/radio, located by css/text/xpath.',
544
+ parameters: {
545
+ target: targetParam,
546
+ },
547
+ output: {
548
+ schema: { type: 'object', additionalProperties: false, properties: { cleared: { type: 'boolean', required: true } } },
549
+ render: (_args, value) => [{ type: 'text', text: value.cleared ? 'Cleared.' : 'Failed.' }],
550
+ },
551
+ timeoutMs,
552
+ isConcurrencySafe: () => false, // mutates a field; exclusive within a task
553
+ async execute(args, exec) {
554
+ assertAllowed(state, 'dsh_browser_clear', taskKey(exec))
555
+ const browser = ctx.get('browser')
556
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
557
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
558
+ const target = args.target as { by?: string; value: string; index?: number }
559
+ await browser.clearField(session, {
560
+ target: {
561
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
562
+ value: target.value,
563
+ ...target.index !== undefined ? { index: target.index } : {},
564
+ },
565
+ }, exec.signal)
566
+ return { cleared: true }
567
+ },
568
+ }))
569
+
570
+ tools.push(defineTool({
571
+ name: 'dsh_browser_get_value',
572
+ description: 'Read the current value of one input/textarea/select/contenteditable, located by css/text/xpath. Use to VERIFY that a fill worked (e.g. before submitting).',
573
+ parameters: {
574
+ target: targetParam,
575
+ },
576
+ output: {
577
+ schema: {
578
+ type: 'object',
579
+ additionalProperties: false,
580
+ properties: {
581
+ value: { type: 'string' },
582
+ checked: { type: 'boolean', description: 'For checkbox/radio.' },
583
+ selectedText: { type: 'string', description: 'For <select>.', },
584
+ },
585
+ },
586
+ render: (_args, value) => [{ type: 'text', text: (() => {
587
+ if (value.checked !== undefined) return `checked=${value.checked}`
588
+ if (value.selectedText !== undefined) return `selected: ${value.selectedText}`
589
+ return `value: ${value.value ?? '(none)'}`
590
+ })() }],
591
+ },
592
+ timeoutMs,
593
+ isConcurrencySafe: () => true,
594
+ async execute(args, exec) {
595
+ assertAllowed(state, 'dsh_browser_get_value', taskKey(exec))
596
+ const browser = ctx.get('browser')
597
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
598
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
599
+ const target = args.target as { by?: string; value: string; index?: number }
600
+ const result = await browser.getValue(session, {
601
+ target: {
602
+ by: (target.by === 'text' || target.by === 'xpath' ? target.by : 'css') as 'css' | 'text' | 'xpath',
603
+ value: target.value,
604
+ ...target.index !== undefined ? { index: target.index } : {},
605
+ },
606
+ }, exec.signal)
607
+ return {
608
+ ...result.value !== null ? { value: result.value } : {},
609
+ ...result.checked !== undefined ? { checked: result.checked } : {},
610
+ ...result.selectedText !== undefined ? { selectedText: result.selectedText } : {},
611
+ }
612
+ },
613
+ }))
614
+
615
+ tools.push(defineTool({
616
+ name: 'dsh_browser_download',
617
+ description: 'Download a URL to a local file, keeping the browser session\'s cookies and login state. Use for fetching files behind authentication or from the current page context. Available on the self-hosted browser; the desktop shell delegates downloads to the real browser UI.',
618
+ parameters: {
619
+ url: { type: 'string', required: true, description: 'The URL to download.' },
620
+ savePath: { type: 'string', required: true, description: 'Absolute path of the file to write. Must resolve inside the configured downloadDir (default: the system Downloads folder, localized names such as ~/下载 included); an existing file is never overwritten.' },
621
+ },
622
+ output: {
623
+ schema: {
624
+ type: 'object',
625
+ additionalProperties: false,
626
+ properties: {
627
+ path: { type: 'string', required: true },
628
+ handoff: { type: 'object', additionalProperties: true },
629
+ remoteError: { type: 'string' },
630
+ remoteResult: { type: 'object', additionalProperties: true },
631
+ },
632
+ },
633
+ render: (_args, value) => {
634
+ const lines = [`Downloaded to ${value.path}.`]
635
+ if (value.handoff !== undefined) lines.push(`Handed to ${String((value.handoff as Record<string, unknown>).tool)}: ${String((value.handoff as Record<string, unknown>).result ?? 'ok')}`)
636
+ if (value.remoteError !== undefined) lines.push(`The local file is intact; the remote side did not take it: ${String(value.remoteError)}`)
637
+ return [{ type: 'text', text: lines.join('\n') }]
638
+ },
639
+ },
640
+ timeoutMs,
641
+ isConcurrencySafe: () => false,
642
+ async execute(args, exec) {
643
+ assertAllowed(state, 'dsh_browser_download', taskKey(exec))
644
+ const browser = ctx.get('browser')
645
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
646
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
647
+ const result = await browser.download(session, { url: args.url, savePath: args.savePath }, exec.signal)
648
+ // Delivery is an attribute of the download: empty tool = the old behaviour, byte for byte.
649
+ const plan = deliveryPlan(args.url as string, result.path)
650
+ if (plan === undefined) return { path: result.path }
651
+ let remoteValue: JsonValue | undefined
652
+ try {
653
+ const tools = (ctx as unknown as { get?: (name: string) => {
654
+ execute?: (input: unknown) => Promise<unknown>
655
+ setExecutor?: unknown
656
+ } | undefined }).get?.('tools')
657
+ if (tools?.execute === undefined) throw new Error('the tools service is not available on this surface')
658
+ if (plan.tool === 'dsh_browser_download') throw new Error('the delivery tool must be a different tool from dsh_browser_download')
659
+ exec.signal.throwIfAborted()
660
+ const callId = 'handoff-' + globalThis.crypto.randomUUID()
661
+ // DSH's executor service accepts raw batches. Earlier runtimes accept one parsed call.
662
+ // Select the API before dispatch so a retry can never upload the same file twice.
663
+ const batched = typeof tools.setExecutor === 'function'
664
+ const answer = await tools.execute(batched ? {
665
+ calls: [{ type: 'tool-call', id: callId, name: plan.tool, arguments: JSON.stringify(plan.args) }],
666
+ agent: exec.agent,
667
+ toolSet: (exec as typeof exec & { readonly toolSet?: unknown }).toolSet,
668
+ signal: exec.signal,
669
+ } : {
670
+ callId,
671
+ rootCallId: exec.rootCallId,
672
+ parent: exec.token,
673
+ name: plan.tool,
674
+ arguments: plan.args,
675
+ agent: exec.agent,
676
+ signal: exec.signal,
677
+ })
678
+ let outcome = answer
679
+ let concluded = false
680
+ if (batched) {
681
+ const batch = answer as { results?: { callId?: string; result?: unknown }[]; additionalContexts?: unknown[]; concluded?: boolean } | null
682
+ if (!Array.isArray(batch?.results) || batch.results.length !== 1 || batch.results[0]?.callId !== callId) {
683
+ throw new Error('the delivery executor returned no matching tool result')
684
+ }
685
+ for (const context of batch.additionalContexts ?? []) {
686
+ exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
687
+ }
688
+ concluded = batch.concluded === true
689
+ outcome = batch.results[0].result
690
+ }
691
+ const settled = outcome as { value?: JsonValue; additionalContexts?: unknown[]; concludesTurn?: boolean } | null
692
+ remoteValue = settled?.value
693
+ const summary = summariseToolResult(outcome)
694
+ if (!batched) {
695
+ for (const context of settled?.additionalContexts ?? []) {
696
+ exec.deferContext(context as Parameters<typeof exec.deferContext>[0])
697
+ }
698
+ concluded = settled?.concludesTurn === true
699
+ }
700
+ if (concluded) exec.concludeTurn()
701
+ return { path: result.path, handoff: { tool: plan.tool, result: summary, value: remoteValue ?? null } }
702
+ } catch (error) {
703
+ exec.signal.throwIfAborted()
704
+ const reason = error instanceof Error ? error.message : String(error)
705
+ if (plan.onFail === 'stop') throw new Error(`dsh_browser_download: saved to ${result.path} locally, but the handoff to "${plan.tool}" failed: ${reason}`)
706
+ return {
707
+ path: result.path,
708
+ remoteError: plan.tool + ': ' + reason,
709
+ ...remoteValue === undefined ? {} : { remoteResult: { tool: plan.tool, value: remoteValue } },
710
+ }
711
+ }
712
+ },
713
+ }))
714
+
715
+ /**
716
+ * What to do with a saved file, from the settings document.
717
+ *
718
+ * Read here rather than threaded through the provider on purpose: delivery is a property of how
719
+ * this deployment saves files, not of which browser carries the page, so every carrier gets it
720
+ * for free and no seam grows a method for it.
721
+ *
722
+ * @param url - the downloaded address, used to pick a per-site override by host.
723
+ * @param path - the absolute local path just written.
724
+ * @returns the plan, or undefined when nothing is configured (the old behaviour).
725
+ */
726
+ function deliveryPlan(url: string, path: string): { tool: string; args: Record<string, string>; onFail: 'keep-local' | 'stop' } | undefined {
727
+ let settings
728
+ try { settings = settingsStore.get() } catch { return undefined }
729
+ const delivery = settings.delivery
730
+ if (delivery === undefined) return undefined
731
+ let host = ''
732
+ try { host = new URL(url).hostname.toLowerCase() } catch { host = '' }
733
+ const override = host === '' ? undefined : (delivery.sites[host] ?? delivery.sites['*'])
734
+ const tool = override ?? delivery.tool
735
+ if (typeof tool !== 'string' || tool.trim() === '') return undefined
736
+ const name = path.split(/[\\/]/).pop() ?? path
737
+ const size = (() => { try { return String(statSync(path).size) } catch { return '' } })()
738
+ const args: Record<string, string> = {}
739
+ for (const [key, value] of Object.entries(delivery.args)) {
740
+ args[key] = String(value).split('{path}').join(path).split('{name}').join(name).split('{size}').join(size)
741
+ }
742
+ if (Object.keys(args).length === 0) args.file_path = path
743
+ return { tool: tool.trim(), args, onFail: delivery.onFail }
744
+ }
745
+
746
+ /** Check the canonical outcome before describing a completed delivery. */
747
+ function summariseToolResult(answer: unknown): string {
748
+ const outcome = answer as { isError?: boolean; value?: unknown; error?: { message?: string }; content?: { text?: string }[] } | null
749
+ if (outcome === null || typeof outcome !== 'object' || typeof outcome.isError !== 'boolean') {
750
+ throw new Error('the delivery executor returned an invalid tool result')
751
+ }
752
+ if (outcome.isError) {
753
+ throw new Error(outcome.error?.message || outcome.content?.map(block => block.text ?? '').join(' ') || 'the delivery tool failed')
754
+ }
755
+ if (!('value' in outcome)) throw new Error('the delivery executor returned an invalid tool result')
756
+ const failure = deliveryFailure(outcome.value)
757
+ if (failure !== undefined) throw new Error(failure)
758
+ const text = typeof outcome.value === 'string' ? outcome.value : JSON.stringify(outcome.value)
759
+ return text.length > 200 ? text.slice(0, 200) + '…' : text
760
+ }
761
+
762
+ /** Read explicit failure markers in common MCP structured or JSON text responses. */
763
+ function deliveryFailure(value: unknown): string | undefined {
764
+ const object = (candidate: unknown): Record<string, unknown> | undefined => {
765
+ if (typeof candidate === 'string') {
766
+ try { candidate = JSON.parse(candidate) } catch { return undefined }
767
+ }
768
+ return candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
769
+ ? candidate as Record<string, unknown> : undefined
770
+ }
771
+ const response = object(value)
772
+ if (response === undefined) return undefined
773
+ const blocks = Array.isArray(response.content) ? response.content : []
774
+ const candidates = [
775
+ response,
776
+ object(response.structuredContent),
777
+ ...blocks.map(block => {
778
+ const content = object(block)
779
+ return content?.type === 'text' ? object(content.text) : undefined
780
+ }),
781
+ ]
782
+ for (const candidate of candidates) {
783
+ if (candidate === undefined) continue
784
+ if (candidate.isError !== true && candidate.ok !== false && candidate.success !== false
785
+ && candidate.status !== 'error' && candidate.status !== 'failed') continue
786
+ const error = object(candidate.error)
787
+ const detail = [candidate.message, candidate.error, error?.message].find(item => typeof item === 'string' && item !== '')
788
+ return typeof detail === 'string' ? detail : 'the delivery tool reported a failed upload'
789
+ }
790
+ return undefined
791
+ }
792
+
793
+ tools.push(defineTool({
794
+ name: 'dsh_browser_drag',
795
+ description: 'Drag from one viewport point to another using trusted browser pointer input. Coordinates are CSS pixels from the top-left of the current viewport. Use for sliders, sortable lists, HTML drag-and-drop and canvas drawing. Check the resulting control value or page state after the gesture.',
796
+ parameters: {
797
+ fromX: { type: 'number', required: true, description: 'Start x in viewport CSS pixels.' },
798
+ fromY: { type: 'number', required: true, description: 'Start y in viewport CSS pixels.' },
799
+ toX: { type: 'number', required: true, description: 'End x.' },
800
+ toY: { type: 'number', required: true, description: 'End y.' },
801
+ steps: { type: 'number', description: 'Intermediate moves (default 12, max 60); more steps make a slider follow the path.' },
802
+ },
803
+ output: {
804
+ schema: {
805
+ type: 'object',
806
+ additionalProperties: false,
807
+ properties: {
808
+ ok: { type: 'boolean', required: true },
809
+ reason: { type: 'string', required: true },
810
+ },
811
+ },
812
+ render: (_args, value) => [{ type: 'text', text: value.ok === true ? 'Dragged.' : `Drag failed: ${String(value.reason)}` }],
813
+ },
814
+ timeoutMs,
815
+ isConcurrencySafe: () => false, // a pointer gesture; exclusive within a task
816
+ async execute(args, exec) {
817
+ assertAllowed(state, 'dsh_browser_drag', taskKey(exec))
818
+ const browser = ctx.get('browser')
819
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
820
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
821
+ const text = await pageOperationValue(browser, session, {
822
+ operation: 'drag',
823
+ from: { x: args.fromX, y: args.fromY },
824
+ to: { x: args.toX, y: args.toY },
825
+ steps: args.steps ?? 12,
826
+ }, exec.signal)
827
+ const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; moved?: number }
828
+ return { ok: parsed.ok === true, reason: parsed.ok === true ? `moved ${String(parsed.moved)} steps` : String(parsed.reason ?? 'unknown') }
829
+ },
830
+ }))
831
+
832
+ tools.push(defineTool({
833
+ name: 'dsh_browser_upload',
834
+ description: 'Put a local file into a file input on the page (attachment, avatar, import form). The path must be a file INSIDE the current workspace, and only the bytes of that one file are read. The file is rebuilt in the page as a File and attached through a DataTransfer, so a form that reads input.files and a drop handler both see it; the change event is fired for you. Oversized files are refused rather than truncated.',
835
+ parameters: {
836
+ target: { type: 'object', required: true, additionalProperties: true, description: 'The input: {by: "css"|"text"|"xpath", value} — a text target is resolved to the element at that point and then to a nested input[type=file].' },
837
+ path: { type: 'string', required: true, description: 'Absolute path of a file inside the workspace.' },
838
+ mime: { type: 'string', description: 'MIME type (default guessed from the extension, else application/octet-stream).' },
839
+ },
840
+ output: {
841
+ schema: {
842
+ type: 'object',
843
+ additionalProperties: false,
844
+ properties: {
845
+ ok: { type: 'boolean', required: true },
846
+ name: { type: 'string' },
847
+ size: { type: 'number' },
848
+ reason: { type: 'string' },
849
+ },
850
+ },
851
+ render: (_args, value) => [{ type: 'text', text: value.ok === true ? `Attached ${String(value.name)} (${String(value.size)} bytes).` : `Upload failed: ${String(value.reason)}` }],
852
+ },
853
+ timeoutMs,
854
+ isConcurrencySafe: () => false,
855
+ async execute(args, exec) {
856
+ assertAllowed(state, 'dsh_browser_upload', taskKey(exec))
857
+ const browser = ctx.get('browser')
858
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
859
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
860
+ const target = args.target as { by?: unknown; value?: unknown }
861
+ const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
862
+ if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_upload: target.value is required')
863
+ const { open, realpath, stat } = await import('node:fs/promises')
864
+ const { resolve, relative, isAbsolute, extname, basename, sep } = await import('node:path')
865
+ if (!isAbsolute(args.path)) throw new Error('dsh_browser_upload: path must be absolute')
866
+ const agent = agentOf(exec) as (ExecAgent & { session?: { header?: { cwd?: string } } }) | undefined
867
+ const directory = (agent?.ctx?.get?.('workingDirectory') ?? ctx.get('workingDirectory')) as {
868
+ ensure(agent: unknown, signal?: AbortSignal): Promise<string>
869
+ } | undefined
870
+ const workspacePath = directory && agent
871
+ ? await directory.ensure(agent, exec.signal)
872
+ : agent?.session?.header?.cwd ?? process.cwd()
873
+ if (!isAbsolute(workspacePath)) throw new Error('dsh_browser_upload: the task workspace must be absolute')
874
+ const workspace = await realpath(workspacePath)
875
+ const resolved = await realpath(resolve(args.path))
876
+ const offset = relative(workspace, resolved)
877
+ if (offset === '..' || offset.startsWith('..' + sep) || isAbsolute(offset)) {
878
+ throw new Error('dsh_browser_upload: refusing to read a file outside the task workspace')
879
+ }
880
+ const expected = await stat(resolved)
881
+ const LIMIT = 20 * 1024 * 1024
882
+ if (!expected.isFile()) throw new Error('dsh_browser_upload: path must name a regular file')
883
+ if (expected.size > LIMIT) throw new Error('dsh_browser_upload: file is over the 20 MB limit')
884
+ const file = await open(resolved, 'r')
885
+ let bytes: Buffer
886
+ try {
887
+ const opened = await file.stat()
888
+ if (opened.dev !== expected.dev || opened.ino !== expected.ino
889
+ || opened.size !== expected.size || !opened.isFile()
890
+ || await realpath(resolve(args.path)) !== resolved) {
891
+ throw new Error('dsh_browser_upload: file changed while opening; retry')
892
+ }
893
+ const chunks: Buffer[] = []
894
+ let length = 0
895
+ for await (const chunk of file.createReadStream({ autoClose: false, start: 0, end: LIMIT, signal: exec.signal })) {
896
+ length += chunk.length
897
+ if (length > LIMIT) throw new Error('dsh_browser_upload: file grew over the 20 MB limit')
898
+ chunks.push(chunk as Buffer)
899
+ }
900
+ const after = await file.stat()
901
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || length !== opened.size
902
+ || await realpath(resolve(args.path)) !== resolved) {
903
+ throw new Error('dsh_browser_upload: file changed while reading; retry')
904
+ }
905
+ bytes = Buffer.concat(chunks, length)
906
+ } finally {
907
+ await file.close()
908
+ }
909
+ const guess: Record<string, string> = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.pdf': 'application/pdf', '.txt': 'text/plain', '.csv': 'text/csv', '.json': 'application/json', '.zip': 'application/zip' }
910
+ const mime = args.mime ?? guess[extname(resolved).toLowerCase()] ?? 'application/octet-stream'
911
+ await installProbe(browser, session, exec.signal)
912
+ const text = await pageOperationValue(browser, session, {
913
+ operation: 'upload',
914
+ target: { by, value: target.value },
915
+ file: { name: basename(resolved), mime, base64: bytes.toString('base64') },
916
+ }, exec.signal)
917
+ const parsed = JSON.parse(text) as { ok?: boolean; reason?: string; name?: string; size?: number }
918
+ return parsed.ok === true
919
+ ? { ok: true, name: String(parsed.name ?? ''), size: Number(parsed.size ?? 0) }
920
+ : { ok: false, reason: String(parsed.reason ?? 'unknown') }
921
+ },
922
+ }))
923
+
924
+ tools.push(defineTool({
925
+ name: 'dsh_browser_hover',
926
+ description: 'Scroll an element into view and move the browser pointer to its centre. Supports CSS hover styles and JavaScript mouseover handlers. Use before reading or clicking a hover menu.',
927
+ parameters: {
928
+ target: { type: 'object', required: true, additionalProperties: true, description: 'The element: {by: "css"|"text"|"xpath", value}.' },
929
+ settleMs: { type: 'number', description: 'How long to let the menu appear before returning (default 150).' },
930
+ },
931
+ output: {
932
+ schema: { type: 'object', additionalProperties: false, properties: { hovered: { type: 'boolean', required: true }, at: { type: 'object', additionalProperties: true } } },
933
+ render: (_args, value) => [{ type: 'text', text: value.hovered === true ? 'Pointer moved over the element.' : 'No element at that target.' }],
934
+ },
935
+ timeoutMs,
936
+ isConcurrencySafe: () => false,
937
+ async execute(args, exec) {
938
+ assertAllowed(state, 'dsh_browser_hover', taskKey(exec))
939
+ const browser = ctx.get('browser')
940
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
941
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
942
+ const target = args.target as { by?: unknown; value?: unknown }
943
+ const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css'
944
+ if (typeof target?.value !== 'string' || target.value === '') throw new Error('dsh_browser_hover: target.value is required')
945
+ await installProbe(browser, session, exec.signal)
946
+ const where = await probe<{ x?: number; y?: number; described?: string } | null>(browser, session, 'find', [{ [by]: target.value }, true], exec.signal)
947
+ if (!where || typeof where.x !== 'number' || typeof where.y !== 'number') return { hovered: false, at: {} as ProbeRow }
948
+ const fired = await probe<boolean>(browser, session, 'hoverAt', [where.x, where.y], exec.signal)
949
+ await pause(Math.min(args.settleMs ?? 150, 2_000))
950
+ const at: ProbeRow = { x: where.x, y: where.y, described: String(where.described ?? '') }
951
+ return { hovered: fired === true, at }
952
+ },
953
+ }))
954
+
955
+ return tools
956
+ }