dsh-builtin-browser 1.0.3 → 1.1.0

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 (305) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.en.md +89 -0
  3. package/browser-extension/constants.mjs +20 -0
  4. package/browser-extension/controller.mjs +293 -0
  5. package/browser-extension/locales.mjs +15 -0
  6. package/browser-extension/manifest.json +12 -0
  7. package/browser-extension/options.html +14 -0
  8. package/browser-extension/options.mjs +9 -0
  9. package/browser-extension/permission-guard.mjs +13 -0
  10. package/browser-extension/worker.mjs +74 -0
  11. package/desktop-bridge/desktop-identity.json +10 -2
  12. package/desktop-bridge/install.mjs +28 -2
  13. package/docs/issue-replies-2026-11-28.md +141 -0
  14. package/dsh-host-patch/apply.mjs +1 -1
  15. package/dsh-host-patch/rc3.json +4 -4
  16. package/dsh-host-patch/rc5.json +4 -4
  17. package/dsh-host-patch/v023-alpha2.json +2 -2
  18. package/lib/browser-electron/bridge-status.js +24 -1
  19. package/lib/browser-electron/desktop-identity.js +47 -8
  20. package/lib/client.js +2 -1
  21. package/native-host/install.mjs +5 -0
  22. package/package.json +20 -2
  23. package/scripts/build-client.mjs +305 -0
  24. package/scripts/build.mjs +69 -0
  25. package/scripts/bundle-host.mjs +28 -0
  26. package/scripts/fix-exports.mjs +40 -0
  27. package/scripts/install-electron.mjs +101 -0
  28. package/scripts/pack.mjs +99 -0
  29. package/scripts/publish-manifest.mjs +56 -0
  30. package/scripts/verify-exports.mjs +58 -0
  31. package/scripts/verify-preview-sdk.mjs +93 -0
  32. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  33. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  34. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  35. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  36. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  37. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  38. package/skills/dsh-debug-host/SKILL.md +56 -0
  39. package/skills/dsh-debug-self/SKILL.md +50 -0
  40. package/src/bridge-compatibility.ts +39 -0
  41. package/src/browser/anti-bot.ts +251 -0
  42. package/src/browser/deep-dom.ts +40 -0
  43. package/src/browser/handles.ts +89 -0
  44. package/src/browser/runtime.ts +578 -0
  45. package/src/browser/takeover-target.ts +45 -0
  46. package/src/browser/types.ts +870 -0
  47. package/src/browser-electron/authenticated-route.ts +109 -0
  48. package/src/browser-electron/automatic-maintenance.ts +736 -0
  49. package/src/browser-electron/bridge-auto.ts +159 -0
  50. package/src/browser-electron/bridge-connection.ts +386 -0
  51. package/src/browser-electron/bridge-endpoint.ts +129 -0
  52. package/src/browser-electron/bridge-install.ts +290 -0
  53. package/src/browser-electron/bridge-maintenance.ts +189 -0
  54. package/src/browser-electron/bridge-status.ts +412 -0
  55. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  56. package/src/browser-electron/desktop-identity.ts +400 -0
  57. package/src/browser-electron/desktop-shell.ts +100 -0
  58. package/src/browser-electron/document-readiness.ts +45 -0
  59. package/src/browser-electron/electron-provision.ts +347 -0
  60. package/src/browser-electron/entry.ts +1378 -0
  61. package/src/browser-electron/ephemeral-profile.ts +189 -0
  62. package/src/browser-electron/extension-browser.ts +230 -0
  63. package/src/browser-electron/extension-setup.ts +67 -0
  64. package/src/browser-electron/file-write.ts +31 -0
  65. package/src/browser-electron/foreground-watch.ts +142 -0
  66. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  67. package/src/browser-electron/guest-cookie-store.ts +59 -0
  68. package/src/browser-electron/guest-css-runtime.ts +76 -0
  69. package/src/browser-electron/guest-css.ts +68 -0
  70. package/src/browser-electron/guest-route.ts +716 -0
  71. package/src/browser-electron/guest-runtime.ts +408 -0
  72. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  73. package/src/browser-electron/guest-storage.ts +120 -0
  74. package/src/browser-electron/history-store.ts +224 -0
  75. package/src/browser-electron/host-main.ts +1385 -0
  76. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  77. package/src/browser-electron/http-body.ts +65 -0
  78. package/src/browser-electron/json-reply.ts +47 -0
  79. package/src/browser-electron/maintenance-broker.ts +166 -0
  80. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  81. package/src/browser-electron/maintenance-route.ts +68 -0
  82. package/src/browser-electron/missing-system-browser.ts +114 -0
  83. package/src/browser-electron/open-slot.ts +49 -0
  84. package/src/browser-electron/paths.ts +25 -0
  85. package/src/browser-electron/preferred-browser.ts +130 -0
  86. package/src/browser-electron/preview-route.ts +215 -0
  87. package/src/browser-electron/process-ownership.ts +174 -0
  88. package/src/browser-electron/process.ts +23 -0
  89. package/src/browser-electron/profile-checkpoint.ts +187 -0
  90. package/src/browser-electron/profile-command.ts +47 -0
  91. package/src/browser-electron/profile-extension.ts +129 -0
  92. package/src/browser-electron/profile-lease.ts +211 -0
  93. package/src/browser-electron/profile-residue.ts +49 -0
  94. package/src/browser-electron/provider-core.ts +1107 -0
  95. package/src/browser-electron/provider-interaction.ts +1034 -0
  96. package/src/browser-electron/provider-media.ts +589 -0
  97. package/src/browser-electron/provider-navigation.ts +323 -0
  98. package/src/browser-electron/provider-observation.ts +664 -0
  99. package/src/browser-electron/provider-tabs.ts +372 -0
  100. package/src/browser-electron/provider.ts +666 -0
  101. package/src/browser-electron/reference-route.ts +598 -0
  102. package/src/browser-electron/remote-host.ts +1538 -0
  103. package/src/browser-electron/rpc-input.ts +13 -0
  104. package/src/browser-electron/rpc-ops.ts +41 -0
  105. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  106. package/src/browser-electron/runtime-route.ts +105 -0
  107. package/src/browser-electron/runtime-status.ts +309 -0
  108. package/src/browser-electron/settings-route.ts +64 -0
  109. package/src/browser-electron/settings-store.ts +593 -0
  110. package/src/browser-electron/shortcuts-route.ts +112 -0
  111. package/src/browser-electron/sidebar-only-host.ts +300 -0
  112. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  113. package/src/browser-electron/system-browser.ts +1850 -0
  114. package/src/browser-electron/tauri-host.ts +194 -0
  115. package/src/browser-electron/timing.ts +16 -0
  116. package/src/browser-electron/virtual-cursor.ts +162 -0
  117. package/src/browser-electron/windows-system.ts +24 -0
  118. package/src/browser-reference/delivery.ts +384 -0
  119. package/src/browser-reference/entry.ts +631 -0
  120. package/src/browser-reference/export.ts +339 -0
  121. package/src/browser-reference/import.ts +303 -0
  122. package/src/browser-reference/page-script.ts +1537 -0
  123. package/src/browser-reference/service.ts +1346 -0
  124. package/src/browser-reference/store.ts +172 -0
  125. package/src/browser-reference/text-quote.ts +219 -0
  126. package/src/browser-reference/types.ts +195 -0
  127. package/src/browser-reference/visible.ts +367 -0
  128. package/src/browser-reference/web-sources.ts +106 -0
  129. package/src/client/apply-guard.ts +22 -0
  130. package/src/client/browser/BrowserController.ts +693 -0
  131. package/src/client/browser/BrowserFrame.ts +78 -0
  132. package/src/client/browser/BrowserNavigation.ts +169 -0
  133. package/src/client/browser/BrowserPage.ts +23 -0
  134. package/src/client/browser/BrowserPersistence.ts +44 -0
  135. package/src/client/browser/IframeImpl.ts +182 -0
  136. package/src/client/browser/child-tabs.ts +14 -0
  137. package/src/client/browser/frame-history.ts +125 -0
  138. package/src/client/browser/frame-state.ts +27 -0
  139. package/src/client/browser/iframe-reference.ts +67 -0
  140. package/src/client/browser/initialization.ts +262 -0
  141. package/src/client/browser/omnibox.ts +243 -0
  142. package/src/client/browser/store.ts +38 -0
  143. package/src/client/browser/takeover-channel.ts +72 -0
  144. package/src/client/browser/url.ts +46 -0
  145. package/src/client/browser/web-reference-source.ts +56 -0
  146. package/src/client/css-modules.d.ts +4 -0
  147. package/src/client/definition.tsx +36 -0
  148. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  149. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  150. package/src/client/electron/NativeChildPresentation.ts +53 -0
  151. package/src/client/electron/NativeViewPage.ts +265 -0
  152. package/src/client/electron/pages.ts +23 -0
  153. package/src/client/electron/reference-overlay.ts +53 -0
  154. package/src/client/electron/workspace.ts +33 -0
  155. package/src/client/index.ts +333 -0
  156. package/src/client/locales.ts +860 -0
  157. package/src/client/pages.ts +28 -0
  158. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  159. package/src/client/reference/client/draft-reference.ts +167 -0
  160. package/src/client/reference/client/index.ts +7 -0
  161. package/src/client/reference/client/ordered-submission.ts +108 -0
  162. package/src/client/reference/client/pending-delivery.ts +216 -0
  163. package/src/client/reference/client/plugin.ts +208 -0
  164. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  165. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  166. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  167. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  168. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  169. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  170. package/src/client/reference/client/production/assembly.ts +447 -0
  171. package/src/client/reference/client/production/asset-store.ts +144 -0
  172. package/src/client/reference/client/production/availability.ts +72 -0
  173. package/src/client/reference/client/production/bytes.ts +36 -0
  174. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  175. package/src/client/reference/client/production/delivery-client.ts +211 -0
  176. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  177. package/src/client/reference/client/production/http-transport.ts +212 -0
  178. package/src/client/reference/client/production/production-submission.ts +70 -0
  179. package/src/client/reference/client/production/protocol.ts +234 -0
  180. package/src/client/reference/client/production/reference-card.ts +240 -0
  181. package/src/client/reference/client/production/reference-labels.ts +29 -0
  182. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  183. package/src/client/reference/client/production/reveal.ts +215 -0
  184. package/src/client/reference/client/production/runtime.ts +1056 -0
  185. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  186. package/src/client/reference/client/production/source-marker.ts +99 -0
  187. package/src/client/reference/client/production/source-opener.ts +55 -0
  188. package/src/client/reference/client/production/styles.ts +104 -0
  189. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  190. package/src/client/reference/client/reveal.ts +109 -0
  191. package/src/client/reference/client/scheme.ts +114 -0
  192. package/src/client/reference/client/session-schedule.ts +36 -0
  193. package/src/client/reference/client/types.ts +168 -0
  194. package/src/client/reference/css-modules.d.ts +4 -0
  195. package/src/client/reference/index.ts +11 -0
  196. package/src/client/reference-capture-owner.ts +162 -0
  197. package/src/client/reference-intents.ts +36 -0
  198. package/src/client/settings/index.ts +42 -0
  199. package/src/client/settings/mount-guard.ts +31 -0
  200. package/src/client/settings/panel.ts +2773 -0
  201. package/src/client/shortcut-open.ts +30 -0
  202. package/src/client/startpage/binding.ts +99 -0
  203. package/src/client/startpage/controller.ts +300 -0
  204. package/src/client/startpage/model.ts +279 -0
  205. package/src/client/view/Browser.module.css +751 -0
  206. package/src/client/view/BrowserBody.tsx +315 -0
  207. package/src/client/view/BrowserPresentation.ts +9 -0
  208. package/src/client/view/BrowserTitle.tsx +17 -0
  209. package/src/client/view/IframePresentation.ts +365 -0
  210. package/src/client/view/StartPage.tsx +598 -0
  211. package/src/client/view/TakeoverBanner.tsx +21 -0
  212. package/src/compat/host-features.ts +92 -0
  213. package/src/index.ts +110 -0
  214. package/src/reference-owner.ts +5 -0
  215. package/src/reference-page.ts +9 -0
  216. package/src/reference-source.ts +3 -0
  217. package/src/reference-text.ts +219 -0
  218. package/src/startpage-settings.ts +103 -0
  219. package/src/startpage.ts +71 -0
  220. package/src/takeover-protocol.ts +28 -0
  221. package/src/tool-browser/block-recovery.ts +85 -0
  222. package/src/tool-browser/code-tool.ts +555 -0
  223. package/src/tool-browser/code-worker.ts +725 -0
  224. package/src/tool-browser/element-fields.ts +167 -0
  225. package/src/tool-browser/errors.ts +40 -0
  226. package/src/tool-browser/index.ts +265 -0
  227. package/src/tool-browser/page-probe.ts +675 -0
  228. package/src/tool-browser/panel-page.ts +126 -0
  229. package/src/tool-browser/probe-client.ts +183 -0
  230. package/src/tool-browser/screenshot-annotations.ts +131 -0
  231. package/src/tool-browser/screenshot-image.ts +49 -0
  232. package/src/tool-browser/state.ts +375 -0
  233. package/src/tool-browser/takeover.ts +199 -0
  234. package/src/tool-browser/tools-debug.ts +806 -0
  235. package/src/tool-browser/tools-interaction.ts +956 -0
  236. package/src/tool-browser/tools-navigation.ts +786 -0
  237. package/src/tool-browser/tools-observation.ts +474 -0
  238. package/src/tool-browser/tools-reference.ts +294 -0
  239. package/src/types/electron-shim.d.ts +144 -0
  240. package/src/types.ts +85 -0
  241. package/src/web-guest.ts +35 -0
  242. package/tools/accept-desktop.mjs +148 -0
  243. package/dist/client.d.cts +0 -516
  244. package/dist/client.d.mts +0 -516
  245. package/dist/index.cjs +0 -92
  246. package/dist/index.d.mts +0 -2960
  247. package/dist/index.mjs +0 -24
  248. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  249. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  250. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  256. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  257. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  258. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  259. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  260. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  261. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  262. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  263. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  264. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  265. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  266. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  267. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  268. package/dsh-host-patch/sources/manifest.json +0 -218
  269. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  293. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  294. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  295. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  296. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  297. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  298. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  299. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  300. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  301. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  302. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  303. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  304. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  305. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,786 @@
1
+ /**
2
+ * Navigation, tab, history, session and start-page shortcut tools.
3
+ * @module dsh-browser/tool-browser/tools-navigation
4
+ */
5
+
6
+ import { setLastOpen } from '../browser-electron/open-slot.ts'
7
+ import { defineTool } from '@deepseek-ai/dsh-tools'
8
+ import { CHALLENGE_SCHEMA, challengeBanner, reportChallenge, type ChallengeReport } from './block-recovery.ts'
9
+ import { createShortcutStore, type ShortcutSettings } from '../browser-electron/startpage-shortcuts.ts'
10
+ import type { BrowserSessionId } from '../browser/types.ts'
11
+ import { browserSessionHandle, resolveTabHandle, scopedTabs, sessionWireId, tabWireId } from '../browser/handles.ts'
12
+ import { ELEMENT_ITEM_SCHEMA, projectElement } from './element-fields.ts'
13
+ import { readSurface, enforceSurface, assertSurfaceCanHost, assertAllowed, agentOf, taskKey, rememberSession, ensureSession, panelBound, type ToolScope, type ToolDefinition } from './state.ts'
14
+ import { formatSnapshot } from './tools-observation.ts'
15
+ import { blockRetryDelayMs } from '../browser/anti-bot.ts'
16
+
17
+ /** Sleep, cut short by the call's cancellation. */
18
+ function pause(ms: number, signal?: AbortSignal): Promise<void> {
19
+ return new Promise((resolve, reject) => {
20
+ if (signal?.aborted === true) { reject(signal.reason); return }
21
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve() }, ms)
22
+ const abort = (): void => { clearTimeout(timer); reject(signal?.reason) }
23
+ signal?.addEventListener('abort', abort, { once: true })
24
+ })
25
+ }
26
+
27
+ /**
28
+ * Refuse the bare DSH web root, which answers 401 and looks like a real page.
29
+ *
30
+ * The address comes from `DSH_WEB_URL`, which the harness exports to its children — NOT from a
31
+ * hardcoded port. This machine's GUI has run on 3080 and on 19387, so a number would stop matching
32
+ * exactly when the guard is needed, and the trap is not a port anyway: it is the SHAPE. A loopback
33
+ * address at its root with no token renders as an unauthenticated 401 page, which an agent reads
34
+ * as the site it meant to open.
35
+ * @param rawUrl - the address a caller asked to open.
36
+ */
37
+ export function assertNotBareDshWebUrl(rawUrl: string): void {
38
+ const advertised = process.env.DSH_WEB_URL
39
+ if (typeof advertised !== 'string' || advertised === '') return
40
+ let target: URL
41
+ let dsh: URL
42
+ try {
43
+ target = new URL(rawUrl)
44
+ dsh = new URL(advertised)
45
+ } catch {
46
+ return // not a URL this guard can judge; the provider's own admission is the next gate
47
+ }
48
+ if (target.origin !== dsh.origin) return
49
+ if (target.pathname !== '/') return
50
+ // The authenticated URL printed by `dsh web` carries a token; the bare root does not.
51
+ if (target.searchParams.has('token')) return
52
+ throw new Error(
53
+ 'dsh_browser_open: refusing the bare DSH web root (' + dsh.origin + '/) because it carries no '
54
+ + 'authentication token, so it answers with a 401 page that reads like a real site. Open the '
55
+ + 'target site instead; to open DSH itself, use the authenticated URL printed by `dsh web`.',
56
+ )
57
+ }
58
+
59
+ /**
60
+ * Define this module's tools for one apply.
61
+ * @param scope - the apply's context, settings and per-apply state.
62
+ * @returns the tool definitions, for the entry to register.
63
+ */
64
+ export function navigationTools(scope: ToolScope): ToolDefinition[] {
65
+ const { ctx, config, state, timeoutMs, maxWaitMs, surface } = scope
66
+ const tools: ToolDefinition[] = []
67
+
68
+ // The start page's shared shortcut list, reached through the settings section the
69
+ // sidebar edits. Built lazily for the same reason `references()` is: the settings
70
+ // service is registered by another entry and may not exist yet at apply time.
71
+ const startpageShortcuts = createShortcutStore(() => ctx.get('settings') as unknown as ShortcutSettings | undefined)
72
+
73
+ tools.push(defineTool({
74
+ name: 'dsh_browser_shortcuts',
75
+ description: 'Read or edit the Sidebar Browser start page shortcuts — the shared website entries a human sees on an empty tab. action=list returns them, action=add appends one (title + http(s) url required, http:// or https:// only, at most 48 entries), action=remove drops one by id. The list is shared with the sidebar UI: an entry added here appears on the next empty tab for every conversation, and one a human adds appears here.',
76
+ parameters: {
77
+ action: { type: 'string', required: true, enum: ['list', 'add', 'remove'], description: 'list the shortcuts, add one, or remove one by id.' },
78
+ title: { type: 'string', description: 'Display title (add). At most 80 characters.' },
79
+ url: { type: 'string', description: 'Destination (add): a full http:// or https:// address.' },
80
+ id: { type: 'string', description: 'Shortcut id (remove), as returned by list or add.' },
81
+ },
82
+ output: {
83
+ schema: {
84
+ type: 'object',
85
+ additionalProperties: false,
86
+ properties: {
87
+ shortcuts: {
88
+ type: 'array',
89
+ required: true,
90
+ items: {
91
+ type: 'object',
92
+ additionalProperties: false,
93
+ properties: {
94
+ id: { type: 'string', required: true },
95
+ title: { type: 'string', required: true },
96
+ url: { type: 'string', required: true },
97
+ iconKey: { type: 'string' },
98
+ },
99
+ },
100
+ },
101
+ changed: { type: 'string', description: 'What the call changed: added <id>, removed <id>, or empty for list.' },
102
+ },
103
+ },
104
+ render: (_args, value) => {
105
+ const rows = value.shortcuts as Array<{ id: string; title: string; url: string }>
106
+ const changed = typeof value.changed === 'string' && value.changed !== '' ? `${value.changed}\n` : ''
107
+ const body = rows.length === 0
108
+ ? '(the start page has no shortcuts)'
109
+ : rows.map(row => `- ${row.title} -> ${row.url} [${row.id}]`).join('\n')
110
+ return [{ type: 'text', text: `${changed}${rows.length} shortcut(s):\n${body}` }]
111
+ },
112
+ },
113
+ timeoutMs,
114
+ isConcurrencySafe: () => false,
115
+ async execute(args, exec) {
116
+ assertAllowed(state, 'dsh_browser_shortcuts', taskKey(exec))
117
+ try {
118
+ if (args.action === 'list') {
119
+ const reading = startpageShortcuts.list()
120
+ return { shortcuts: reading.shortcuts.map(row => ({ ...row })), changed: '' }
121
+ }
122
+ if (args.action === 'add') {
123
+ const result = await startpageShortcuts.add({ title: args.title, url: args.url })
124
+ return { shortcuts: result.shortcuts.map(row => ({ ...row })), changed: `added ${result.shortcut.id}` }
125
+ }
126
+ if (typeof args.id !== 'string' || args.id === '') throw new Error('remove needs the shortcut id')
127
+ const result = await startpageShortcuts.remove(args.id)
128
+ return {
129
+ shortcuts: result.shortcuts.map(row => ({ ...row })),
130
+ changed: result.removed ? `removed ${args.id}` : `${args.id} was not in the list`,
131
+ }
132
+ } catch (error) {
133
+ // The store reports refusals as typed errors; a tool must not answer with a stack.
134
+ throw new Error(`start page shortcuts: ${error instanceof Error ? error.message : String(error)}`)
135
+ }
136
+ },
137
+ }))
138
+
139
+ tools.push(defineTool({
140
+ name: 'dsh_browser_open',
141
+ description: 'Open a URL on the selected controllable surface (default: panel). Success returns a live snapshot and supports subsequent browser tools on that same page. A Web iframe or unavailable desktop bridge is refused; no manual-only navigation is queued. Reading tools never start another browser. newTab is optional on CDP surfaces. Never treat the bare DSH host (e.g. http://127.0.0.1:<port>/) as the target — it needs the authenticated URL printed by `dsh web`, and the bare root is refused. On a blocked page (403, access denied, bot wall), follow any CHALLENGE banner or try the site\'s JSON/API, sitemap, search results, or archives before reporting a blocker.',
142
+ parameters: {
143
+ url: { type: 'string', required: true, description: 'The URL to open (HTTP/HTTPS).' },
144
+ newTab: { type: 'boolean', description: 'Open in a new tab instead of the active one.' },
145
+ // Explicit per-call surface. "panel" (default) places the page in the DSH sidebar and opens no
146
+ // window; "builtin" drives the plugin's own browser, which is what debugging DSH itself needs.
147
+ surface: { type: 'string', enum: ['panel', 'builtin'], description: 'panel (default): the DSH sidebar only; builtin: the plugin browser, for debugging DSH itself.' },
148
+ },
149
+ output: {
150
+ schema: {
151
+ type: 'object',
152
+ additionalProperties: false,
153
+ properties: {
154
+ url: { type: 'string', required: true },
155
+ title: { type: 'string' },
156
+ carrier: { type: 'string' },
157
+ truncated: { type: 'boolean' },
158
+ elements: {
159
+ type: 'array',
160
+ required: true,
161
+ // Same shared item schema as dsh_browser_open's, so the two cannot drift apart.
162
+ items: ELEMENT_ITEM_SCHEMA,
163
+ },
164
+ challenge: CHALLENGE_SCHEMA,
165
+ },
166
+ },
167
+ // dsh_browser_open is an overview of what just loaded, not a locator: it has no
168
+ // `coords` parameter, so coordinates stay off here (dsh_browser_snapshot owns
169
+ // that switch for callers that actually target pixels).
170
+ render: (_args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
171
+ },
172
+ timeoutMs,
173
+ isConcurrencySafe: () => false, // opens tabs / navigates; exclusive within a task
174
+ async execute(args, exec) {
175
+ assertAllowed(state, 'dsh_browser_open', taskKey(exec))
176
+ assertNotBareDshWebUrl(args.url)
177
+ // ONE surface per open. On the Web shell the reader's sidebar is the browsing surface; opening the
178
+ // plugin's own browser as well produced two live views of the same page (reported as "you opened the
179
+ // built-in browser AND the sidebar at once"). `browser.surface` decides: "panel" (default on Web)
180
+ // places the page in the sidebar and opens no window; "builtin" is the debugging surface.
181
+ const surfaceHint = (args as { surface?: 'panel' | 'builtin' }).surface
182
+ const surface = enforceSurface(surfaceHint ?? readSurface(), args.url)
183
+ const browser = ctx.get('browser')
184
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
185
+ const key = taskKey(exec)
186
+ if (surface === 'panel') {
187
+ const preceding = state.pendingPanelOpens.get(key)
188
+ let previous: BrowserSessionId | undefined
189
+ let session: BrowserSessionId | undefined
190
+ const opening = (async () => {
191
+ await preceding
192
+ await state.pendingOpens.get(key)
193
+ previous = state.sessionsByTask.get(key)
194
+ const target = new URL(args.url)
195
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') throw new Error('dsh_browser_open: panel requires an HTTP/HTTPS URL')
196
+ exec.signal?.throwIfAborted()
197
+ session = panelBound(state, key) && previous !== undefined && browser.exists(previous)
198
+ ? previous : await browser.openPanel?.(key)
199
+ if (session === undefined) {
200
+ assertSurfaceCanHost(surface, args.url)
201
+ exec.signal?.throwIfAborted()
202
+ setLastOpen(args.url, Date.now(), key)
203
+ rememberSession(browser, state, key, agentOf(exec), undefined, args.url)
204
+ return { url: args.url, carrier: 'panel-iframe-navigation-requested', title: '', elements: [], truncated: false }
205
+ }
206
+ await browser.openUrl(session, { url: args.url, ...args.newTab === true ? { newTab: true } : {} }, exec.signal)
207
+ const snapshot = await browser.snapshot(session, exec.signal)
208
+ exec.signal?.throwIfAborted()
209
+ rememberSession(browser, state, key, agentOf(exec), session, args.url)
210
+ return {
211
+ url: snapshot.url,
212
+ ...snapshot.title !== undefined ? { title: snapshot.title } : {},
213
+ elements: snapshot.elements.map(el => projectElement(el)),
214
+ truncated: snapshot.truncated,
215
+ ...snapshot.challenge !== undefined ? { challenge: reportChallenge(snapshot.challenge, snapshot.url) } : {},
216
+ }
217
+ })()
218
+ const pending = opening.then(() => {})
219
+ state.pendingPanelOpens.set(key, pending)
220
+ void pending.catch(() => {})
221
+ try { return await opening } catch (error) {
222
+ if (session !== undefined && session !== previous) await browser.close(session).catch(() => {})
223
+ throw error
224
+ } finally {
225
+ if (state.pendingPanelOpens.get(key) === pending) state.pendingPanelOpens.delete(key)
226
+ }
227
+ }
228
+ await state.pendingPanelOpens.get(key)
229
+ await state.pendingOpens.get(key)
230
+ if (panelBound(state, key)) {
231
+ const previous = state.sessionsByTask.get(key)
232
+ state.sessionsByTask.delete(key)
233
+ state.panelUrlByTask.delete(key)
234
+ if (previous !== undefined) await browser.close(previous)
235
+ }
236
+ const existing = state.sessionsByTask.get(key)
237
+ const fresh = args.newTab !== true && (existing === undefined || !browser.exists(existing))
238
+ let session = await ensureSession(browser, state, key, agentOf(exec), true)
239
+ try {
240
+ await browser.openUrl(session, {
241
+ url: args.url,
242
+ ...args.newTab === true ? { newTab: true } : {},
243
+ }, exec.signal)
244
+ } catch (error) {
245
+ // The human's browser is already running on its own profile: the launch hands the request over and
246
+ // exits with code 0. A new window opened inside THEIR browser with their logins — what "use my
247
+ // Edge" means — it is simply not driveable, because their instance has no debugging port.
248
+ const message = error instanceof Error ? error.message : String(error)
249
+ if (!/exited immediately after launch \(exit code 0\)/u.test(message)) throw error
250
+ return { url: args.url, carrier: 'launched-user-profile', title: '', elements: [], truncated: false }
251
+ }
252
+ // Hand the page to the Web sidebar as well, except when the user explicitly selected an
253
+ // installed Chrome/Edge channel (issue #106: do not double-open the page in the sidebar).
254
+ const selectedChannel = scope.settingsStore.get().browser.channel
255
+ if (selectedChannel !== 'chrome' && selectedChannel !== 'edge') {
256
+ try { setLastOpen(args.url, Date.now()) } catch { /* best effort */ }
257
+ }
258
+ let snapshot: Awaited<ReturnType<typeof browser.snapshot>>
259
+ try {
260
+ snapshot = await browser.snapshot(session, exec.signal)
261
+ } catch (error) {
262
+ // The human's browser is ALREADY running on its own profile, so a launch hands the request over
263
+ // and the launcher exits with code 0. That is not a failure: a new window opened inside THEIR
264
+ // browser, with their logins, which is exactly what "use my Edge" means. It is only undriveable,
265
+ // because their instance has no debugging port. Report the page, not an error.
266
+ const message = error instanceof Error ? error.message : String(error)
267
+ if (!/exited immediately after launch \(exit code 0\)/u.test(message)) throw error
268
+ return {
269
+ url: args.url,
270
+ carrier: 'launched-user-profile',
271
+ title: '',
272
+ elements: [],
273
+ truncated: false,
274
+ }
275
+ }
276
+ // A refusal (access denied, 429, empty 403) gets exactly one more try: after a pause, and in a
277
+ // fresh session when this open started the task's browser, so nothing the first attempt left
278
+ // behind rides along. Human verifications and network blocks are never retried — the first
279
+ // goes to the human, the second is an environment limit — and a second refusal is reported
280
+ // with the fallback routes instead of being tried again.
281
+ let retried = false
282
+ if (snapshot.challenge?.blocked === true && snapshot.challenge.recovery === 'retry') {
283
+ retried = true
284
+ if (fresh) {
285
+ // The refused page goes too: a closed session leaves its pages to the browser, and the
286
+ // retry must not leave a second copy of the wall behind in the human's window.
287
+ for (const tab of await browser.listTabs(session).catch(() => [])) await browser.closeTab(session, tab.id).catch(() => {})
288
+ await browser.close(session).catch(() => {})
289
+ state.sessionsByTask.delete(key)
290
+ }
291
+ await pause(blockRetryDelayMs(), exec.signal)
292
+ if (fresh) session = await ensureSession(browser, state, key, agentOf(exec), true)
293
+ // `navigate`, not `openUrl`: an open adopts a page already showing this URL, which here is
294
+ // the refused page itself, and the retry would read it again without asking the site.
295
+ await browser.navigate(session, { url: args.url }, exec.signal)
296
+ snapshot = await browser.snapshot(session, exec.signal)
297
+ }
298
+ return {
299
+ url: snapshot.url,
300
+ carrier: String((globalThis as unknown as Record<string, unknown>).__dshBrowserCarrier ?? 'bundled'),
301
+ ...snapshot.title !== undefined ? { title: snapshot.title } : {},
302
+ elements: snapshot.elements.map(el => projectElement(el)),
303
+ truncated: snapshot.truncated,
304
+ ...snapshot.challenge !== undefined ? { challenge: reportChallenge(snapshot.challenge, snapshot.url, retried) } : {},
305
+ }
306
+ },
307
+ }))
308
+
309
+ tools.push(defineTool({
310
+ name: 'dsh_browser_wait',
311
+ description: 'Wait until the shared-browser page is ready: load complete, and optionally the expected URL and/or a CSS selector present (top document or same-origin iframes). Use after dsh_browser_open on slow sites instead of snapshotting a white page — wait for the URL you navigated to first. Returns ready=true/false with a short reason; a miss is not an error.',
312
+ parameters: {
313
+ timeoutMs: { type: 'number', description: 'Maximum wait in ms (default 30000).' },
314
+ url: { type: 'string', description: 'Expected page URL (exact or prefix), e.g. the URL you opened.' },
315
+ selector: { type: 'string', description: 'CSS selector that must exist.' },
316
+ },
317
+ output: {
318
+ schema: {
319
+ type: 'object',
320
+ additionalProperties: false,
321
+ properties: {
322
+ ready: { type: 'boolean', required: true },
323
+ reason: { type: 'string', required: true },
324
+ },
325
+ },
326
+ render: (_args, value) => [{ type: 'text', text: value.ready ? 'Page ready.' : `Wait timed out: ${value.reason}` }],
327
+ },
328
+ timeoutMs,
329
+ isConcurrencySafe: () => true,
330
+ async execute(args, exec) {
331
+ const browser = ctx.get('browser')
332
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
333
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
334
+ const result = await browser.waitFor(session, {
335
+ // Capped so an over-budget argument returns the documented verdict (see maxWaitMs)
336
+ // rather than aborting the whole tool call.
337
+ ...args.timeoutMs !== undefined ? { timeoutMs: Math.min(args.timeoutMs, maxWaitMs) } : {},
338
+ ...args.url !== undefined ? { url: args.url } : {},
339
+ ...args.selector !== undefined ? { selector: args.selector } : {},
340
+ }, exec.signal)
341
+ return { ready: result.ready, reason: result.reason }
342
+ },
343
+ }))
344
+
345
+ tools.push(defineTool({
346
+ name: 'dsh_browser_back',
347
+ description: 'Go back one step in the shared-browser page history. A no-op when there is no previous entry.',
348
+ parameters: {},
349
+ output: {
350
+ schema: { type: 'object', additionalProperties: false, properties: { back: { type: 'boolean', required: true } } },
351
+ render: (_args, value) => [{ type: 'text', text: value.back ? 'Went back.' : 'Failed.' }],
352
+ },
353
+ timeoutMs,
354
+ isConcurrencySafe: () => false, // mutates page state; exclusive within a task
355
+ async execute(_args, exec) {
356
+ assertAllowed(state, 'dsh_browser_back', taskKey(exec))
357
+ const browser = ctx.get('browser')
358
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
359
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
360
+ await browser.back(session, exec.signal)
361
+ return { back: true }
362
+ },
363
+ }))
364
+
365
+ tools.push(defineTool({
366
+ name: 'dsh_browser_forward',
367
+ description: 'Go forward one step in the shared-browser page history. A no-op when there is no next entry.',
368
+ parameters: {},
369
+ output: {
370
+ schema: { type: 'object', additionalProperties: false, properties: { forward: { type: 'boolean', required: true } } },
371
+ render: (_args, value) => [{ type: 'text', text: value.forward ? 'Went forward.' : 'Failed.' }],
372
+ },
373
+ timeoutMs,
374
+ isConcurrencySafe: () => false, // mutates page state; exclusive within a task
375
+ async execute(_args, exec) {
376
+ assertAllowed(state, 'dsh_browser_forward', taskKey(exec))
377
+ const browser = ctx.get('browser')
378
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
379
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
380
+ await browser.forward(session, exec.signal)
381
+ return { forward: true }
382
+ },
383
+ }))
384
+
385
+ tools.push(defineTool({
386
+ name: 'dsh_browser_refresh',
387
+ description: 'Reload the current page in the shared browser (like a browser\'s refresh button). Use after a page got stuck, to apply script changes, or to re-fetch a page.',
388
+ parameters: {},
389
+ output: {
390
+ schema: { type: 'object', additionalProperties: false, properties: { refreshed: { type: 'boolean', required: true } } },
391
+ render: (_args, value) => [{ type: 'text', text: value.refreshed ? 'Page reloaded.' : 'Failed.' }],
392
+ },
393
+ timeoutMs,
394
+ isConcurrencySafe: () => false, // reloads the page; exclusive within a task
395
+ async execute(_args, exec) {
396
+ assertAllowed(state, 'dsh_browser_refresh', taskKey(exec))
397
+ const browser = ctx.get('browser')
398
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
399
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
400
+ await browser.reload(session, exec.signal)
401
+ return { refreshed: true }
402
+ },
403
+ }))
404
+
405
+ if (config.tabTools !== false) {
406
+ tools.push(defineTool({
407
+ name: 'dsh_browser_list_tabs',
408
+ description: 'List the shared-browser session\'s tabs with their URLs and which is active.',
409
+ parameters: {},
410
+ output: {
411
+ schema: {
412
+ type: 'object',
413
+ additionalProperties: false,
414
+ properties: {
415
+ tabs: {
416
+ type: 'array',
417
+ required: true,
418
+ items: {
419
+ type: 'object',
420
+ additionalProperties: false,
421
+ properties: {
422
+ id: { type: 'string', required: true },
423
+ url: { type: 'string', required: true },
424
+ active: { type: 'boolean', required: true },
425
+ },
426
+ },
427
+ },
428
+ },
429
+ },
430
+ render: (_args, value) => [{
431
+ type: 'text',
432
+ text: (value.tabs as { id: string; url: string; active: boolean }[])
433
+ .map(t => `${t.active ? '*' : ' '} ${t.id} ${t.url}`).join('\n'),
434
+ }],
435
+ },
436
+ timeoutMs,
437
+ isConcurrencySafe: () => true,
438
+ async execute(_args, exec) {
439
+ const browser = ctx.get('browser')
440
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
441
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
442
+ const tabs = await browser.listTabs(session)
443
+ return { tabs: scopedTabs(browserSessionHandle(taskKey(exec), session), tabs).map(t => ({ id: t.id, url: t.url, active: t.active })) }
444
+ },
445
+ }))
446
+
447
+ tools.push(defineTool({
448
+ name: 'dsh_browser_switch_tab',
449
+ description: 'Switch the shared browser to a tab by id (from dsh_browser_list_tabs).',
450
+ parameters: {
451
+ tabId: { type: 'string', required: true, description: 'The tab id to switch to.' },
452
+ },
453
+ output: {
454
+ schema: { type: 'object', additionalProperties: false, properties: { switched: { type: 'boolean', required: true } } },
455
+ render: (_args, value) => [{ type: 'text', text: value.switched ? 'Switched.' : 'Tab not found.' }],
456
+ },
457
+ timeoutMs,
458
+ isConcurrencySafe: () => false, // mutates the active tab; exclusive within a task
459
+ async execute(args, exec) {
460
+ assertAllowed(state, 'dsh_browser_switch_tab', taskKey(exec))
461
+ const browser = ctx.get('browser')
462
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
463
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
464
+ const handle = resolveTabHandle(browserSessionHandle(taskKey(exec), session), args.tabId)
465
+ await browser.switchTab(session, tabWireId(handle))
466
+ return { switched: true }
467
+ },
468
+ }))
469
+
470
+ tools.push(defineTool({
471
+ name: 'dsh_browser_close_tab',
472
+ description: 'Close a tab in the shared browser by id. Closing the active tab activates the next.',
473
+ parameters: {
474
+ tabId: { type: 'string', required: true, description: 'The tab id to close.' },
475
+ },
476
+ output: {
477
+ schema: { type: 'object', additionalProperties: false, properties: { closed: { type: 'boolean', required: true } } },
478
+ render: (_args, value) => [{ type: 'text', text: value.closed ? 'Closed.' : 'Tab not found.' }],
479
+ },
480
+ timeoutMs,
481
+ isConcurrencySafe: () => false, // mutates the tab list; exclusive within a task
482
+ async execute(args, exec) {
483
+ assertAllowed(state, 'dsh_browser_close_tab', taskKey(exec))
484
+ const browser = ctx.get('browser')
485
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
486
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
487
+ const handle = resolveTabHandle(browserSessionHandle(taskKey(exec), session), args.tabId)
488
+ await browser.closeTab(session, tabWireId(handle))
489
+ return { closed: true }
490
+ },
491
+ }))
492
+
493
+ tools.push(defineTool({
494
+ name: 'dsh_browser_reset',
495
+ description: 'Close every tab in the shared browser and start fresh with one blank tab.',
496
+ parameters: {},
497
+ output: {
498
+ schema: { type: 'object', additionalProperties: false, properties: { reset: { type: 'boolean', required: true } } },
499
+ render: (_args, value) => [{ type: 'text', text: value.reset ? 'Browser reset.' : 'Failed.' }],
500
+ },
501
+ timeoutMs,
502
+ isConcurrencySafe: () => false, // closes every tab; exclusive within a task
503
+ async execute(_args, exec) {
504
+ assertAllowed(state, 'dsh_browser_reset', taskKey(exec))
505
+ const browser = ctx.get('browser')
506
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
507
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
508
+ await browser.reset(session)
509
+ return { reset: true }
510
+ },
511
+ }))
512
+ }
513
+
514
+ tools.push(defineTool({
515
+ name: 'dsh_browser_history',
516
+ description: 'List the shared browser session\'s recorded operation history (navigate/execute/click/type), newest last, with per-step success/error. Use to understand what the agent did and to pick a step to replay.',
517
+ parameters: {
518
+ verbose: { type: 'boolean', description: "Include each operation's parameters (default false). They are what you just sent, so they are omitted unless asked for." },
519
+ },
520
+ output: {
521
+ schema: {
522
+ type: 'object',
523
+ additionalProperties: false,
524
+ properties: {
525
+ entries: {
526
+ type: 'array',
527
+ required: true,
528
+ items: {
529
+ type: 'object',
530
+ additionalProperties: false,
531
+ properties: {
532
+ seq: { type: 'number', required: true },
533
+ action: { type: 'string', required: true },
534
+ ok: { type: 'boolean', required: true },
535
+ params: { type: 'object', additionalProperties: true, required: true },
536
+ result: { type: 'string' },
537
+ error: { type: 'string' },
538
+ },
539
+ },
540
+ },
541
+ },
542
+ },
543
+ render: (args, value) => {
544
+ const entries = value.entries as Array<{ seq: number; action: string; ok: boolean; params: Record<string, unknown>; result?: string; error?: string }>
545
+ if (entries.length === 0) return [{ type: 'text', text: '(no recorded operations yet)' }]
546
+ // The parameters are what the caller itself just sent, so echoing them back is cost
547
+ // without information — measured at 18,162 characters for 200 operations, of which the
548
+ // per-entry params dominated. Only the tail is shown by default: the recent steps are
549
+ // what a caller reasons about, and the count leads so the tail is not mistaken for all.
550
+ const recent = entries.slice(-20)
551
+ const omitted = entries.length - recent.length
552
+ const lines = recent.map(e => `#${e.seq} ${e.action} ${e.ok ? 'ok' : 'FAIL'}${e.result !== undefined ? ` -> ${e.result}` : ''}${e.error !== undefined ? ` !! ${e.error}` : ''}${args.verbose === true ? ` ${JSON.stringify(e.params)}` : ''}`)
553
+ const header = omitted > 0
554
+ ? `${entries.length} operations recorded; showing the last ${recent.length} (${args.verbose === true ? '' : ' (pass verbose: true for parameters)'}):`
555
+ : `${entries.length} operation(s):`
556
+ return [{ type: 'text', text: `${header}\n${lines.join('\n')}` }]
557
+ },
558
+ },
559
+ timeoutMs,
560
+ isConcurrencySafe: () => true,
561
+ async execute(_args, exec) {
562
+ const browser = ctx.get('browser')
563
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
564
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
565
+ const entries = await browser.history(session)
566
+ const rendered = entries.map(e => {
567
+ const params = JSON.parse(JSON.stringify(e.params)) as Record<string, unknown>
568
+ // Typed text / set values (possibly passwords) are kept verbatim in
569
+ // the provider's history so replay can re-issue them, but must not be
570
+ // echoed back to the model: mask them in the tool output, preserving
571
+ // the length.
572
+ if (e.action === 'type' && typeof params.text === 'string') {
573
+ params.text = '*'.repeat(Math.min(params.text.length, 64)) + ` (${params.text.length} chars)`
574
+ }
575
+ if (e.action === 'setValue' && typeof params.value === 'string') {
576
+ params.value = '*'.repeat(Math.min(params.value.length, 64)) + ` (${params.value.length} chars)`
577
+ }
578
+ // Replay of type/setValue carries the same sensitive fields.
579
+ if (e.action === 'replay' && params.of === 'type' && typeof params.text === 'string') {
580
+ params.text = '*'.repeat(Math.min(params.text.length, 64)) + ` (${params.text.length} chars)`
581
+ }
582
+ // Execute scripts may embed form tokens / credentials; mask script,
583
+ // args, and result for both direct execute and replay-of-execute.
584
+ const isExecute = e.action === 'execute' || (e.action === 'replay' && params.of === 'execute')
585
+ if (isExecute) {
586
+ if (typeof params.script === 'string') {
587
+ params.script = `/* ${params.script.length} chars redacted */`
588
+ }
589
+ if (Array.isArray(params.args)) {
590
+ params.args = params.args.map(() => '***')
591
+ }
592
+ }
593
+ const row: { seq: number; action: string; ok: boolean; params: unknown; result?: string; error?: string } = {
594
+ seq: e.seq,
595
+ action: e.action,
596
+ ok: e.ok,
597
+ params,
598
+ }
599
+ if (isExecute && typeof e.result === 'string') {
600
+ row.result = `[${e.result.length} chars redacted]`
601
+ } else if (e.result !== undefined) {
602
+ row.result = e.result
603
+ }
604
+ if (e.error !== undefined) row.error = e.error
605
+ return row
606
+ })
607
+ return { entries: rendered as never }
608
+ },
609
+ }))
610
+
611
+ tools.push(defineTool({
612
+ name: 'dsh_browser_visited',
613
+ description: 'List pages the shared browser has visited, newest first, from the PERSISTENT browsing history: it survives closing the browser and restarting DSH, so it is how you (or the human) find a page again afterwards. Reopen one by passing its url to dsh_browser_open. Not to be confused with dsh_browser_history, which is only the current session\'s operation log (navigate/click/type) and disappears with the session.',
614
+ parameters: {
615
+ limit: { type: 'number', description: 'Maximum entries to return (default 30, capped at 200).' },
616
+ domain: { type: 'string', description: 'Only visits whose hostname contains this text (case-insensitive).' },
617
+ query: { type: 'string', description: 'Only visits whose URL or title contains this text (case-insensitive).' },
618
+ session: { type: 'string', description: 'Only visits recorded by this task/session label — use it to separate your own pages from another session\'s or the human\'s.' },
619
+ },
620
+ output: {
621
+ schema: {
622
+ type: 'object',
623
+ additionalProperties: false,
624
+ properties: {
625
+ count: { type: 'number', required: true },
626
+ entries: {
627
+ type: 'array',
628
+ required: true,
629
+ items: {
630
+ type: 'object',
631
+ additionalProperties: false,
632
+ properties: {
633
+ at: { type: 'number', required: true },
634
+ url: { type: 'string', required: true },
635
+ title: { type: 'string' },
636
+ session: { type: 'string' },
637
+ },
638
+ },
639
+ },
640
+ },
641
+ },
642
+ render: (_args, value) => {
643
+ const entries = value.entries as Array<{ at: number; url: string; title?: string; session?: string }>
644
+ let lastSession: string | undefined
645
+ if (entries.length === 0) {
646
+ return [{ type: 'text', text: '(no recorded visits — nothing has been browsed yet, or history recording is turned off in settings)' }]
647
+ }
648
+ return [{
649
+ type: 'text',
650
+ text: entries.map(entry => {
651
+ const when = new Date(entry.at).toISOString().replace('T', ' ').slice(0, 16)
652
+ const title = entry.title !== undefined ? `${entry.title} — ` : ''
653
+ const tag = entry.session !== undefined && entry.session !== lastSession
654
+ ? ` [session ${entry.session.slice(0, 8)}]`
655
+ : ''
656
+ lastSession = entry.session
657
+ return `${when} ${title}${entry.url}${tag}`
658
+ }).join('\n'),
659
+ }]
660
+ },
661
+ },
662
+ timeoutMs,
663
+ isConcurrencySafe: () => true,
664
+ async execute(args, _exec) {
665
+ const browser = ctx.get('browser')
666
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
667
+ const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? args.limit : 30
668
+ const limit = Math.max(1, Math.min(200, Math.floor(rawLimit)))
669
+ const domain = typeof args.domain === 'string' && args.domain.trim() !== '' ? args.domain.trim() : undefined
670
+ const query = typeof args.query === 'string' && args.query.trim() !== '' ? args.query.trim() : undefined
671
+ const session = typeof args.session === 'string' && args.session.trim() !== '' ? args.session.trim() : undefined
672
+ const entries = browser.visited({
673
+ limit,
674
+ ...domain !== undefined ? { domain } : {},
675
+ ...query !== undefined ? { query } : {},
676
+ ...session !== undefined ? { session } : {},
677
+ })
678
+ return {
679
+ count: entries.length,
680
+ entries: entries.map(entry => ({
681
+ at: entry.at,
682
+ url: entry.url,
683
+ ...entry.title !== undefined ? { title: entry.title } : {},
684
+ ...entry.session !== undefined ? { session: entry.session } : {},
685
+ })),
686
+ }
687
+ },
688
+ }))
689
+
690
+ tools.push(defineTool({
691
+ name: 'dsh_browser_replay',
692
+ description: 'Replay one recorded browser operation by its history sequence number (from dsh_browser_history). Navigate/click/type are re-issued against the current page; execute re-runs its script. The replayed step is appended to history as a new entry.',
693
+ parameters: {
694
+ seq: { type: 'number', required: true, description: 'The history entry sequence number to replay.' },
695
+ },
696
+ output: {
697
+ schema: { type: 'object', additionalProperties: false, properties: { replayed: { type: 'boolean', required: true } } },
698
+ render: (_args, value) => [{ type: 'text', text: value.replayed ? 'Replayed.' : 'Replay failed.' }],
699
+ },
700
+ timeoutMs,
701
+ isConcurrencySafe: () => false,
702
+ async execute(args, exec) {
703
+ assertAllowed(state, 'dsh_browser_replay', taskKey(exec))
704
+ const browser = ctx.get('browser')
705
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
706
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
707
+ await browser.replay(session, args.seq)
708
+ return { replayed: true }
709
+ },
710
+ }))
711
+
712
+ tools.push(defineTool({
713
+ name: 'dsh_browser_session',
714
+ description: 'Show THIS task\'s browser session: its id and open tabs. Each task (DSH session) has its own browser session, so this reflects what your task drives. The window is shared with the human and other tasks, but tab sets and history are isolated per task.',
715
+ parameters: {},
716
+ output: {
717
+ schema: {
718
+ type: 'object',
719
+ additionalProperties: false,
720
+ properties: {
721
+ session: { type: 'string', required: true },
722
+ tabs: {
723
+ type: 'array',
724
+ required: true,
725
+ items: {
726
+ type: 'object',
727
+ additionalProperties: false,
728
+ properties: {
729
+ id: { type: 'string', required: true },
730
+ url: { type: 'string', required: true },
731
+ active: { type: 'boolean', required: true },
732
+ },
733
+ },
734
+ },
735
+ },
736
+ },
737
+ render: (_args, value) => [{
738
+ type: 'text',
739
+ text: `Session ${value.session}\n${(value.tabs as { id: string; url: string; active: boolean }[]).map(t => `${t.active ? '*' : ' '} ${t.id} ${t.url}`).join('\n')}`,
740
+ }],
741
+ },
742
+ timeoutMs,
743
+ isConcurrencySafe: () => true,
744
+ async execute(_args, exec) {
745
+ const browser = ctx.get('browser')
746
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
747
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
748
+ const tabs = await browser.listTabs(session)
749
+ const scope = browserSessionHandle(taskKey(exec), session)
750
+ return { session: sessionWireId(scope), tabs: scopedTabs(scope, tabs).map(t => ({ id: t.id, url: t.url, active: t.active })) }
751
+ },
752
+ }))
753
+
754
+ tools.push(defineTool({
755
+ name: 'dsh_browser_reset_session',
756
+ description: 'Reset THIS task\'s browser session: close it entirely so the next dsh_browser_* call starts a fresh session with one blank tab. Other tasks\' sessions are untouched. Use when a session is in a bad state or you want a clean slate.',
757
+ parameters: {},
758
+ output: {
759
+ schema: { type: 'object', additionalProperties: false, properties: { reset: { type: 'boolean', required: true } } },
760
+ render: (_args, value) => [{ type: 'text', text: value.reset ? 'This task\'s browser session was closed; the next call starts fresh.' : 'Failed.' }],
761
+ },
762
+ timeoutMs,
763
+ isConcurrencySafe: () => false, // closes the whole session; exclusive within a task
764
+ async execute(_args, exec) {
765
+ assertAllowed(state, 'dsh_browser_reset_session', taskKey(exec))
766
+ const browser = ctx.get('browser')
767
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
768
+ const key = taskKey(exec)
769
+ await state.pendingPanelOpens.get(key)
770
+ state.panelUrlByTask.delete(key)
771
+ const session = state.sessionsByTask.get(key)
772
+ if (session !== undefined) {
773
+ try {
774
+ await browser.close(session)
775
+ } finally {
776
+ // Always forget the mapping so the next call opens a fresh session,
777
+ // even if the provider close threw (the session is half-closed).
778
+ state.sessionsByTask.delete(key)
779
+ }
780
+ }
781
+ return { reset: true }
782
+ },
783
+ }))
784
+
785
+ return tools
786
+ }