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,375 @@
1
+ /**
2
+ * Per-apply browser tool state: task sessions, the allow-list restriction, and surface rules.
3
+ * @module dsh-browser/tool-browser/state
4
+ */
5
+
6
+ import type { Context } from '@deepseek-ai/cordis'
7
+ import { BrowserTakeovers } from './takeover.ts'
8
+ import { readFileSync } from 'node:fs'
9
+ import type { defineTool } from '@deepseek-ai/dsh-tools'
10
+ import { SettingsStore, settingsPath } from '../browser-electron/settings-store.ts'
11
+ import { assertCapability, CDP_CARRIER_CAPABILITIES, WEB_PANEL_CAPABILITIES, type BrowserSessionId, type CarrierCapabilities } from '../browser/types.ts'
12
+ import { MAX_FILL_FIELDS, TOOL_WAIT_MIN_MS, TOOL_WAIT_RESERVE_MS } from '../../assets/browser-policy.mjs'
13
+ import type { Config } from './index.ts'
14
+
15
+ /**
16
+ * Register a cleanup that runs once when the process exits.
17
+ *
18
+ * A single hook per process, holding a list of callbacks, rather than one listener per
19
+ * session: sessions come and go, listeners do not, and Node warns when a listener count
20
+ * passes ten.
21
+ */
22
+ export const exitCleanups = new Set<() => void>()
23
+ let exitHookInstalled = false
24
+ export function registerExitCleanup(cleanup: () => void): void {
25
+ exitCleanups.add(cleanup)
26
+ if (exitHookInstalled) return
27
+ exitHookInstalled = true
28
+ process.on('exit', () => {
29
+ for (const run of exitCleanups) {
30
+ try { run() } catch { /* exiting; nothing useful to do */ }
31
+ }
32
+ })
33
+ }
34
+
35
+ /**
36
+ * Which surface an open should use.
37
+ *
38
+ * "panel" - place the page in the DSH sidebar and open nothing else (the normal Web behaviour).
39
+ * "builtin"- drive the plugin's own Electron browser or the explicitly selected installed Chrome/Edge.
40
+ * @returns the configured surface, defaulting to "panel".
41
+ */
42
+ export function readSurface(): 'panel' | 'builtin' {
43
+ // A host that already resolved the surface declares it; otherwise the plugin's own settings file under
44
+ // the live DSH_HOME decides. No machine-specific path is consulted.
45
+ const declared = (globalThis as unknown as Record<string, unknown>).__dshBrowserSurface
46
+ if (declared === 'builtin') return 'builtin'
47
+ try {
48
+ const raw = readFileSync(settingsPath(), 'utf8').replace(/^\uFEFF/u, '')
49
+ const parsed = JSON.parse(raw) as { browser?: { surface?: unknown; channel?: unknown } }
50
+ const surface = parsed.browser?.surface
51
+ if (surface === 'builtin' || surface === 'panel') return surface
52
+ // Issue #106 & Scheme C: an explicit installed browser channel (chrome / edge) or standalone
53
+ // Electron channel (electron) must drive that browser carrier rather than falling into the
54
+ // Web iframe / Desktop sidebar panel by default.
55
+ const channel = parsed.browser?.channel
56
+ if (channel === 'chrome' || channel === 'edge' || channel === 'electron') return 'builtin'
57
+ } catch { /* no settings yet */ }
58
+ if (declared === 'panel') return 'panel'
59
+ return 'panel'
60
+ }
61
+
62
+ /**
63
+ * Keep the built-in browser for DSH itself.
64
+ *
65
+ * "builtin" exists to debug DSH: a client bundle, the settings panel, the sidebar UI. Using it for an
66
+ * ordinary site opens a window the reader did not ask for — measured as "why did you open the built-in
67
+ * browser again". A non-loopback target therefore degrades to "panel" silently; the caller's intent does
68
+ * not override the rule.
69
+ * @param surface - the requested surface.
70
+ * @param url - the page being opened.
71
+ * @returns the surface that will actually be used.
72
+ */
73
+ export function enforceSurface(surface: 'panel' | 'builtin', _url: string): 'panel' | 'builtin' {
74
+ // The caller decides the surface. An earlier version degraded "builtin" to "panel" for anything but a
75
+ // loopback URL, which also blocked the agent from driving the human's OWN browser — the opposite of what
76
+ // the setting is for. Which window appears is decided by the carrier (bundled Electron vs. the human's
77
+ // Edge), not by the URL. Keeping ordinary tests on the sidebar is a working rule, not a code constraint.
78
+ return surface
79
+ }
80
+
81
+ /**
82
+ * Refuse a request that cannot work BEFORE anything is opened.
83
+ *
84
+ * The sidebar renders pages through a same-origin proxy, so asking it to load this machine answers with a
85
+ * network-level failure that reads like a bug in the page. Reporting that afterwards is useless — the call
86
+ * already happened. The rule is therefore enforced up front: a loopback target on the panel surface is
87
+ * refused, and the message names the surface that does work.
88
+ * @param surface - the surface this call would use.
89
+ * @param url - the page being opened.
90
+ */
91
+ export function assertSurfaceCanHost(surface: 'panel' | 'builtin', url: string): void {
92
+ if (surface !== 'panel') return
93
+ let host: string
94
+ try { host = new URL(url).hostname.toLowerCase() } catch { return }
95
+ const local = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]' || /^127\./u.test(host)
96
+ if (!local) return
97
+ throw new Error('dsh-builtin-browser: the sidebar cannot host this machine (' + host
98
+ + '). It proxies pages through itself, so loading DSH there is the proxy fetching its own server. '
99
+ + '调试 DSH 请用 surface: "builtin"(内置浏览器),普通网页才走侧栏。')
100
+ }
101
+
102
+ /** Per-apply (per-context) tool state: sessions, in-flight opens, restriction. */
103
+ export interface ToolBrowserState {
104
+ /** Per-task browser sessions, keyed by the calling DSH session id. */
105
+ readonly sessionsByTask: Map<string, BrowserSessionId>
106
+ /** In-flight first-open per task key, so concurrent first calls share one session. */
107
+ readonly pendingOpens: Map<string, Promise<BrowserSessionId>>
108
+ /**
109
+ * Action restriction per task, plus one from the plugin's own configuration.
110
+ *
111
+ * Two different things share this policy. A restriction from `cordis.patch.yml` is an
112
+ * operator decision about the whole plugin, so it applies to everyone and lives in
113
+ * `configRestrictedTo`. One set by `dsh_browser_restrict` is a decision by one task about
114
+ * its own work, so it is keyed by task — a single shared value let one task lock the
115
+ * browser tools of every other task, which is not what any caller asks for. Sessions
116
+ * beside it were already keyed this way; this was not.
117
+ */
118
+ configRestrictedTo: readonly string[] | undefined
119
+ restrictedByTask: Map<string, readonly string[]>
120
+ /** Active panel opens, including Web iframes that cannot be driven over CDP. */
121
+ panelUrlByTask: Map<string, string>
122
+ pendingPanelOpens: Map<string, Promise<void>>
123
+ }
124
+
125
+ export function createState(): ToolBrowserState {
126
+ return {
127
+ sessionsByTask: new Map(), pendingOpens: new Map(), configRestrictedTo: undefined,
128
+ restrictedByTask: new Map(), panelUrlByTask: new Map(), pendingPanelOpens: new Map(),
129
+ }
130
+ }
131
+
132
+ /** Every live state, for the test hook (introspection only, never shared). */
133
+ export const liveStates = new Set<ToolBrowserState>()
134
+
135
+ /**
136
+ * Tools that only observe, plus the ones that undo a restriction.
137
+ *
138
+ * Never subject to an allow-list: restricting what the agent may *do* must not also
139
+ * blind it or trap it, and the tool descriptions promise as much. dsh_browser_restrict
140
+ * is in here so a task that restricted everything can still lift it.
141
+ */
142
+ export const READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
143
+ // Tools that only observe.
144
+ 'dsh_browser_snapshot', 'dsh_browser_a11y', 'dsh_browser_content', 'dsh_browser_scrape',
145
+ 'dsh_browser_screenshot', 'dsh_browser_get_value', 'dsh_browser_wait', 'dsh_browser_challenge',
146
+ 'dsh_browser_list_tabs', 'dsh_browser_session', 'dsh_browser_history', 'dsh_browser_visited',
147
+ // Observation added in 0.5.7: console lines, network responses, an assertion, a self-check and the
148
+ // help index. All five only read (the probe's buffers belong to the page, not to the task), so an
149
+ // allow-list must not blind a task that restricted itself.
150
+ 'dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response',
151
+ 'dsh_browser_assert', 'dsh_browser_doctor', 'dsh_browser_help',
152
+ // Reading the page's own digest and searching its text: observation like the rest.
153
+ 'dsh_browser_find', 'dsh_browser_state',
154
+ // Where the page keeps its data: shapes of what the page already holds, never a request.
155
+ 'dsh_browser_data_sources',
156
+ // References read the page the human already has open and write only this plugin's own store;
157
+ // restricting an agent's actions must not stop it from recording what it was told to read.
158
+ 'dsh_browser_reference_capture', 'dsh_browser_reference_reveal', 'dsh_browser_reference_list',
159
+ // dsh_browser_auth reads cookies out of the browser: an observation, and one the
160
+ // credentials switch gates on its own (see credentials.allowRead in the settings).
161
+ // dsh_browser_auth is deliberately NOT here. It reads cookies on "flush" but WRITES them on
162
+ // "restore", to arbitrary domains, which is an action like any other — exempting the tool
163
+ // would let a task that restricted its own actions rewrite the shared browser's logins.
164
+ //
165
+ // Getting out of a bad state, or lifting the restriction itself. Without these a task
166
+ // that restricted everything could neither recover nor be released.
167
+ 'dsh_browser_restrict', 'dsh_browser_reset_session', 'dsh_browser_reset',
168
+ ])
169
+
170
+ /**
171
+ * Guard one browser tool call against the active restriction. Refuses calls
172
+ * not on the allow-list when a restriction is in effect.
173
+ * @param state - the calling context's tool state.
174
+ * @param toolName - the browser tool about to run.
175
+ */
176
+ export function assertAllowed(state: ToolBrowserState, toolName: string, task: string): void {
177
+ // dsh_browser_restrict must stay usable, or a task that restricted everything
178
+ // could never lift it again.
179
+ // An allow-list is a statement about ACTIONS, so it must not take away the ability to
180
+ // look, or to get out of a bad state. The tool description and both READMEs promise
181
+ // that read-only tools are never blocked; before this they were, because only
182
+ // dsh_browser_restrict itself was exempt — a narrow list then locked dsh_browser_history,
183
+ // dsh_browser_reset_session and dsh_browser_auth away with no way back.
184
+ if (READ_ONLY_TOOLS.has(toolName) || toolName === 'dsh_browser_restrict') return
185
+ const config = state.configRestrictedTo
186
+ if (config !== undefined && !config.includes(toolName)) {
187
+ throw new Error(`browser action "${toolName}" is restricted by the plugin configuration (allow-list: ${config.join(', ')})`)
188
+ }
189
+ const allowed = state.restrictedByTask.get(task)
190
+ if (allowed === undefined || allowed.includes(toolName)) return
191
+ throw new Error(`browser action "${toolName}" is restricted (allow-list: ${allowed.join(', ')})`)
192
+ }
193
+
194
+ /** The agent view a tool execution carries (id + agent-scoped context). */
195
+ export interface ExecAgent {
196
+ readonly id?: string
197
+ /** Agent-scoped Cordis context; its effects unwind on agent disposal. */
198
+ readonly ctx?: Context
199
+ }
200
+
201
+ /** Extract the agent from a tool-execution context, when one exists. */
202
+ export function agentOf(exec: unknown): ExecAgent | undefined {
203
+ return (exec as { agent?: ExecAgent } | undefined)?.agent
204
+ }
205
+
206
+ /**
207
+ * The task key for a tool call: the calling DSH session id, or the shared
208
+ * default key when the call carries no agent context (CLI probes, tests).
209
+ * @param exec - the tool-execution context; only its optional agent id is read.
210
+ */
211
+ export function taskKey(exec: { agent?: { id?: string } } | undefined): string {
212
+ return exec?.agent?.id ?? 'default'
213
+ }
214
+
215
+ /** Whether this task's page was placed in the DSH sidebar panel rather than a plugin-owned window. */
216
+ export function panelBound(state: ToolBrowserState, key: string): boolean {
217
+ return state.panelUrlByTask.has(key)
218
+ }
219
+
220
+ /**
221
+ * What the task's current carrier can do. A panel placement without a live CDP session is the Web
222
+ * iframe panel: it can only be navigated. Everything else is a CDP-backed page.
223
+ */
224
+ export function carrierCapabilities(browser: NonNullable<Context['browser']>, state: ToolBrowserState, key: string): CarrierCapabilities {
225
+ const session = state.sessionsByTask.get(key)
226
+ return panelBound(state, key) && (session === undefined || !browser.exists(session)) ? WEB_PANEL_CAPABILITIES : CDP_CARRIER_CAPABILITIES
227
+ }
228
+
229
+ export function rememberSession(browser: NonNullable<Context['browser']>, state: ToolBrowserState, key: string, agent: ExecAgent | undefined, session: BrowserSessionId | undefined, panelUrl?: string): void {
230
+ const previous = state.sessionsByTask.get(key)
231
+ const previousPanelUrl = state.panelUrlByTask.get(key)
232
+ if (session === undefined) state.sessionsByTask.delete(key)
233
+ else state.sessionsByTask.set(key, session)
234
+ if (panelUrl === undefined) state.panelUrlByTask.delete(key)
235
+ else state.panelUrlByTask.set(key, panelUrl)
236
+ if (previous === session && (previousPanelUrl !== undefined) === (panelUrl !== undefined)) return
237
+ const cleanup = (): void => {
238
+ if (state.sessionsByTask.get(key) !== session || state.panelUrlByTask.has(key) !== (panelUrl !== undefined)) return
239
+ state.sessionsByTask.delete(key)
240
+ state.panelUrlByTask.delete(key)
241
+ if (session !== undefined) void browser.close(session).catch(() => {})
242
+ }
243
+ try {
244
+ if (agent?.ctx !== undefined) agent.ctx.effect(() => cleanup)
245
+ else if (key === 'default' && session !== undefined) registerExitCleanup(() => browser.close(session).catch(() => {}))
246
+ } catch (error) {
247
+ cleanup()
248
+ if (previous !== undefined) state.sessionsByTask.set(key, previous)
249
+ if (previousPanelUrl !== undefined) state.panelUrlByTask.set(key, previousPanelUrl)
250
+ throw error
251
+ }
252
+ if (previous !== undefined && previous !== session) void browser.close(previous).catch(() => {})
253
+ }
254
+
255
+ /**
256
+ * Resolve the calling task's browser session, opening one on first use.
257
+ * Concurrent first calls for the same key share a single open. When the call
258
+ * carries an agent, the session's lifetime is tied to the agent's scoped
259
+ * context: it closes automatically when the agent (DSH session) is disposed,
260
+ * so sessions and their windows never leak after a task ends.
261
+ * @param browser - the seam service.
262
+ * @param state - the calling context's tool state.
263
+ * @param key - the task key (see {@link taskKey}).
264
+ * @param agent - the calling agent, when any (its ctx owns the session).
265
+ * @returns the task's session id.
266
+ */
267
+ export async function ensureSession(browser: NonNullable<Context['browser']>, state: ToolBrowserState, key: string, agent?: ExecAgent, create = false): Promise<BrowserSessionId> {
268
+ await state.pendingPanelOpens.get(key)
269
+ const existing = state.sessionsByTask.get(key)
270
+ if (existing !== undefined) {
271
+ // The human closing a browser window ends that session, so a cached id can
272
+ // be stale: never hand a dead session back to a tool call.
273
+ if (browser.exists(existing)) return existing
274
+ state.sessionsByTask.delete(key)
275
+ }
276
+ const pending = state.pendingOpens.get(key)
277
+ if (pending !== undefined) return pending
278
+ assertCapability(carrierCapabilities(browser, state, key), 'cdp',
279
+ 'dsh-builtin-browser: the panel surface has no live CDP session for this operation. '
280
+ + 'Use the CDP-backed DSH desktop sidebar with a connected desktop bridge and call dsh_browser_open again. '
281
+ + 'The Web iframe panel cannot provide live snapshots, a11y, content, scrape, screenshots, interactions, '
282
+ + 'uploads, downloads, or reference capture. Reading tools never start a separate browser.')
283
+ // Starting a browser is `dsh_browser_open`'s job and nobody else's. A read tool asking "what is on
284
+ // screen" used to start one — which, with the human's own Edge already running, handed the command over
285
+ // and opened yet another window, reported as "one look, two Edge windows". A reader with nothing open
286
+ // reports that instead of launching anything.
287
+ if (!create) {
288
+ throw new Error('dsh-builtin-browser: nothing is open in this task yet — call dsh_browser_open first. '
289
+ + 'Reading tools never start a browser.')
290
+ }
291
+ // The task key rides along as the session label so the window title shows
292
+ // which task's page is currently visible to the human.
293
+ const opening = browser.open(key).then(
294
+ session => {
295
+ state.pendingOpens.delete(key)
296
+ rememberSession(browser, state, key, agent, session)
297
+ return session
298
+ },
299
+ error => { state.pendingOpens.delete(key); throw error },
300
+ )
301
+ state.pendingOpens.set(key, opening)
302
+ return opening
303
+ }
304
+
305
+ /** What every tool module closes over: the apply's context, settings and per-apply state. */
306
+ export interface ToolScope {
307
+ readonly ctx: Context
308
+ readonly config: Config
309
+ readonly state: ToolBrowserState
310
+ readonly takeovers: BrowserTakeovers
311
+ readonly settingsStore: SettingsStore
312
+ readonly timeoutMs: number
313
+ readonly maxWaitMs: number
314
+ readonly maxFillFields: number
315
+ readonly surface: NonNullable<Config['surface']>
316
+ }
317
+
318
+ /** One tool definition, as `defineTool` returns it. */
319
+ export type ToolDefinition = ReturnType<typeof defineTool>
320
+
321
+ /**
322
+ * Longest wait `dsh_browser_wait` may poll for, leaving room for the tool call itself to
323
+ * finish and report.
324
+ *
325
+ * `dsh_browser_wait` promises a VERDICT — `{ready:false, reason}` — and the enclosing tool
326
+ * call aborts at `timeoutMs`. A caller-supplied budget longer than that aborted the call
327
+ * instead, so the documented verdict never arrived. Clamping to just inside the budget is
328
+ * what keeps the promise: the polling stops, the reason is returned.
329
+ */
330
+ export function maxWaitFor(timeoutMs: number): number {
331
+ return Math.max(TOOL_WAIT_MIN_MS, timeoutMs - TOOL_WAIT_RESERVE_MS)
332
+ }
333
+
334
+ /**
335
+ * Most fields `dsh_browser_fill` accepts in one batch.
336
+ *
337
+ * The batch runs as ONE page evaluation, so hundreds of fields do not produce hundreds of
338
+ * per-field verdicts — they produce a single evaluate that exceeds the tool budget and
339
+ * throws, which is the opposite of the documented "per-field failures are reported instead
340
+ * of throwing". Real forms are far smaller than this; anything larger should be split.
341
+ */
342
+ export { MAX_FILL_FIELDS }
343
+
344
+ /** Every tool, in the order the entry registers it (and the code tool's catalog lists it). */
345
+ export const REGISTRATION_ORDER: readonly string[] = [
346
+ 'dsh_browser_request_takeover', 'dsh_browser_shortcuts', 'dsh_browser_open', 'dsh_browser_snapshot',
347
+ 'dsh_browser_a11y', 'dsh_browser_challenge', 'dsh_browser_wait', 'dsh_browser_execute',
348
+ 'dsh_browser_content', 'dsh_browser_scrape', 'dsh_browser_click', 'dsh_browser_click_sequence',
349
+ 'dsh_browser_type', 'dsh_browser_scroll', 'dsh_browser_back', 'dsh_browser_forward', 'dsh_browser_refresh',
350
+ 'dsh_browser_key', 'dsh_browser_fill', 'dsh_browser_set_value', 'dsh_browser_check', 'dsh_browser_select',
351
+ 'dsh_browser_clear', 'dsh_browser_get_value', 'dsh_browser_screenshot', 'dsh_browser_list_tabs',
352
+ 'dsh_browser_switch_tab', 'dsh_browser_close_tab', 'dsh_browser_reset', 'dsh_browser_history',
353
+ 'dsh_browser_visited', 'dsh_browser_replay', 'dsh_browser_download', 'dsh_browser_session',
354
+ 'dsh_browser_reset_session', 'dsh_browser_restrict', 'dsh_browser_auth', 'dsh_browser_console',
355
+ 'dsh_browser_network', 'dsh_browser_dialog', 'dsh_browser_wait_for_response', 'dsh_browser_assert',
356
+ 'dsh_browser_drag', 'dsh_browser_doctor', 'dsh_browser_help', 'dsh_browser_do', 'dsh_browser_upload',
357
+ 'dsh_browser_hover', 'dsh_browser_find', 'dsh_browser_state', 'dsh_browser_reference_capture',
358
+ 'dsh_browser_reference_reveal', 'dsh_browser_reference_list', 'dsh_browser_data_sources', 'dsh_browser_fetch_json',
359
+ ]
360
+
361
+ /** Test hook: inspect and reset session mappings across every live plugin apply. */
362
+ export const internals = {
363
+ /** A copy of every live apply's per-task session map (task key -> provider session id). */
364
+ get sessions(): ReadonlyMap<string, BrowserSessionId> {
365
+ const merged = new Map<string, BrowserSessionId>()
366
+ for (const state of liveStates) {
367
+ for (const [key, session] of state.sessionsByTask) merged.set(key, session)
368
+ }
369
+ return merged
370
+ },
371
+ /** Drop one task's mapping (across live applies) without closing the provider session. */
372
+ clearSession(key = 'default'): void {
373
+ for (const state of liveStates) state.sessionsByTask.delete(key)
374
+ },
375
+ }
@@ -0,0 +1,199 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { carrierTakeoverTarget, hasCarrierTakeover } from '../browser/takeover-target.ts'
3
+ import type { IncomingMessage, ServerResponse } from 'node:http'
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+ import { pairedRoute, type BrowserHttpHandler, type BrowserPairingConnection } from '../browser-electron/authenticated-route.ts'
6
+ import { readJsonBody } from '../browser-electron/http-body.ts'
7
+ import { replyJson } from '../browser-electron/json-reply.ts'
8
+ import { sameOrigin } from '../browser-electron/settings-route.ts'
9
+ import { referenceOwnerKey } from '../reference-owner.ts'
10
+ import { TAKEOVER_ROUTE, TAKEOVER_TOOL, type TakeoverDecision, type TakeoverNotice, type TakeoverSummary } from '../takeover-protocol.ts'
11
+
12
+ interface Page {
13
+ readonly connected?: () => boolean
14
+ readonly reveal?: (until?: AbortSignal) => Promise<boolean>
15
+ readonly owner: string
16
+ readonly tabId: string
17
+ readonly pageId: string
18
+ readonly lease: string
19
+ url: string
20
+ active: boolean
21
+ seen: number
22
+ navigationUrl?: string
23
+ }
24
+
25
+ interface Pending {
26
+ readonly id: string
27
+ readonly page: Page
28
+ readonly reason: string
29
+ readonly instructions?: string
30
+ readonly controller: AbortController
31
+ readonly signal?: AbortSignal
32
+ readonly button: Promise<TakeoverDecision>
33
+ readonly answer: (decision: TakeoverDecision) => void
34
+ readonly summary: Promise<TakeoverSummary>
35
+ readonly report: (summary: TakeoverSummary) => void
36
+ phase: 'waiting' | 'summary'
37
+ }
38
+
39
+ function text(value: unknown, max: number): string {
40
+ if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error('invalid takeover field')
41
+ return value
42
+ }
43
+
44
+ function summary(value: unknown): TakeoverSummary {
45
+ const data = value as Partial<TakeoverSummary> | undefined
46
+ if (!data || typeof data.title !== 'string' || data.title.length > 1000 || typeof data.snapshotHint !== 'string'
47
+ || data.snapshotHint.length > 2000 || typeof data.fresh !== 'boolean') throw new Error('invalid takeover summary')
48
+ const url = new URL(text(data.url, 8192))
49
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) throw new Error('invalid takeover URL')
50
+ return { url: url.href, title: data.title, snapshotHint: data.snapshotHint, fresh: data.fresh }
51
+ }
52
+
53
+ export class BrowserTakeovers {
54
+ private browser?: object
55
+ attachBrowser(browser: object | undefined): void { this.browser = browser }
56
+ private readonly pages = new Map<string, Page>()
57
+ private readonly pending = new Map<string, Pending>()
58
+ private readonly results = new Map<string, Promise<unknown>>()
59
+ private readonly changed = new Set<() => void>()
60
+ private disposed = false
61
+
62
+ private key(page: Pick<Page, 'owner' | 'tabId'>): string { return JSON.stringify([page.owner, page.tabId]) }
63
+
64
+ target(owner: string): Page {
65
+ const candidates = [...this.pages.values()].filter(page => page.owner === referenceOwnerKey(owner) && page.active && Date.now() - page.seen < 3000)
66
+ if (candidates.length !== 1) throw new Error('Browser takeover requires one active, connected sidebar tab. Select the browser tab and retry.')
67
+ return candidates[0]!
68
+ }
69
+
70
+ async adopt(owner: string, signal: AbortSignal, navigationUrl?: string, timeoutMs = 15000): Promise<Page> {
71
+ signal.throwIfAborted()
72
+ const carrier = carrierTakeoverTarget(this.browser, owner)
73
+ if (carrier) return { ...carrier, owner: referenceOwnerKey(owner), lease: randomUUID(), active: true, seen: Date.now() }
74
+ if (hasCarrierTakeover(this.browser)) throw new Error('The selected personal browser has no connected tab in this conversation. Reconnect the extension or open a tab; no sidebar fallback.')
75
+ return new Promise<Page>((resolve, reject) => {
76
+ const finish = (page?: Page, error?: unknown): void => {
77
+ clearTimeout(timer)
78
+ signal.removeEventListener('abort', abort)
79
+ this.changed.delete(check)
80
+ if (error !== undefined) reject(error); else resolve(page!)
81
+ }
82
+ const abort = (): void => { finish(undefined, signal.reason) }
83
+ const check = (): void => {
84
+ if (this.disposed) { finish(undefined, new Error('Browser takeover service was disposed.')); return }
85
+ const candidates = [...this.pages.values()].filter(page => page.owner === referenceOwnerKey(owner) && page.active && Date.now() - page.seen < 3000)
86
+ if (candidates.length > 1) finish(undefined, new Error('Browser takeover requires one selected, visible sidebar tab. Close or hide the other browser panes and retry.'))
87
+ else if (candidates[0] && (navigationUrl === undefined || candidates[0].url === navigationUrl || candidates[0].navigationUrl === navigationUrl)) finish(candidates[0])
88
+ }
89
+ const timer = setTimeout(() => finish(undefined, new Error('Browser takeover requires one active, connected sidebar tab in this conversation. Select the browser tab, wait for it to load, and retry.')), timeoutMs)
90
+ this.changed.add(check)
91
+ signal.addEventListener('abort', abort, { once: true })
92
+ check()
93
+ })
94
+ }
95
+
96
+ blocks(owner: string, tabId?: string): boolean {
97
+ return [...this.pending.values()].some(pending => pending.page.owner === referenceOwnerKey(owner)
98
+ && !pending.signal?.aborted && (tabId === undefined || pending.page.pageId === tabId.replace(/^page:/u, '') || pending.page.tabId === tabId))
99
+ }
100
+
101
+ run<T>(page: Page, reason: string, instructions: string | undefined, signal: AbortSignal | undefined,
102
+ operation: (pending: Pending) => Promise<T>): Promise<T> {
103
+ const key = this.key(page)
104
+ const existing = this.results.get(key)
105
+ if (existing) return existing as Promise<T>
106
+ const controller = new AbortController()
107
+ const abort = (): void => { controller.abort(signal?.reason) }
108
+ signal?.addEventListener('abort', abort, { once: true })
109
+ if (signal?.aborted) abort()
110
+ let answer!: Pending['answer'], report!: Pending['report']
111
+ const pending: Pending = { id: randomUUID(), page, reason, ...instructions === undefined ? {} : { instructions }, controller, ...signal === undefined ? {} : { signal },
112
+ button: new Promise(resolve => { answer = resolve }), answer: decision => { answer(decision) },
113
+ summary: new Promise(resolve => { report = resolve }), report: value => { report(value) }, phase: 'waiting' }
114
+ this.pending.set(key, pending)
115
+ const expiry = setInterval(() => { if (page.connected ? !page.connected() : Date.now() - page.seen > 15000) controller.abort() }, 1000)
116
+ expiry.unref()
117
+ const result = Promise.resolve().then(() => operation(pending)).finally(() => {
118
+ clearInterval(expiry)
119
+ controller.abort()
120
+ signal?.removeEventListener('abort', abort)
121
+ this.pending.delete(key)
122
+ this.results.delete(key)
123
+ })
124
+ this.results.set(key, result)
125
+ return result
126
+ }
127
+
128
+ async listen(request: { readonly toolName: string; readonly signal?: AbortSignal }, next: () => Promise<TakeoverDecision>): Promise<TakeoverDecision> {
129
+ const pending = request.toolName === TAKEOVER_TOOL && [...this.pending.values()].find(item => item.controller.signal === request.signal)
130
+ return pending ? Promise.race([pending.button, next()]) : next()
131
+ }
132
+
133
+ dispose(): void {
134
+ this.disposed = true
135
+ for (const pending of this.pending.values()) pending.controller.abort()
136
+ this.pages.clear()
137
+ for (const changed of this.changed) changed()
138
+ }
139
+
140
+ exchange(data: Record<string, unknown>): object {
141
+ for (const [lease, page] of this.pages) if (Date.now() - page.seen > 15000) {
142
+ this.pages.delete(lease)
143
+ this.pending.get(this.key(page))?.controller.abort()
144
+ }
145
+ if (data.operation === 'register') {
146
+ if (this.pages.size >= 1024) throw new Error('browser takeover page capacity exceeded')
147
+ const owner = referenceOwnerKey(text(data.owner, 300)), tabId = text(data.tabId, 300), pageId = text(data.pageId, 300)
148
+ const url = new URL(text(data.url, 8192))
149
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('invalid takeover URL')
150
+ const lease = randomUUID()
151
+ for (const [old, page] of this.pages) if (page.owner === owner && page.pageId === pageId) this.pages.delete(old)
152
+ const navigationUrl = data.navigationUrl === undefined ? undefined : new URL(text(data.navigationUrl, 8192)).href
153
+ if (navigationUrl !== undefined && !/^https?:\/\//u.test(navigationUrl)) throw new Error('invalid takeover navigation URL')
154
+ this.pages.set(lease, { lease, owner, tabId, pageId, url: url.href, active: data.active === true, seen: Date.now(), ...navigationUrl === undefined ? {} : { navigationUrl } })
155
+ for (const changed of this.changed) changed()
156
+ return { lease }
157
+ }
158
+ const page = this.pages.get(text(data.lease, 100))
159
+ if (!page) throw new Error('browser takeover page lease expired')
160
+ if (data.operation === 'remove') { this.pages.delete(page.lease); this.pending.get(this.key(page))?.controller.abort(); return {} }
161
+ const pending = this.pending.get(this.key(page))
162
+ if (data.operation === 'poll') {
163
+ const url = new URL(text(data.url, 8192))
164
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('invalid takeover URL')
165
+ page.url = url.href; page.active = data.active === true; page.seen = Date.now()
166
+ const navigationUrl = data.navigationUrl === undefined ? undefined : new URL(text(data.navigationUrl, 8192)).href
167
+ if (navigationUrl !== undefined && !/^https?:\/\//u.test(navigationUrl)) throw new Error('invalid takeover navigation URL')
168
+ page.navigationUrl = navigationUrl
169
+ for (const changed of this.changed) changed()
170
+ const notice: TakeoverNotice | undefined = pending && !pending.signal?.aborted && (pending.phase === 'summary' || !pending.controller.signal.aborted)
171
+ ? { id: pending.id, reason: pending.reason, ...pending.instructions === undefined ? {} : { instructions: pending.instructions }, phase: pending.phase } : undefined
172
+ return { notice }
173
+ }
174
+ if (!pending || pending.id !== data.id || pending.signal?.aborted || (pending.phase === 'waiting' && pending.controller.signal.aborted)) throw new Error('browser takeover request is no longer pending')
175
+ if (data.operation === 'answer' && pending.phase === 'waiting' && (data.outcome === 'done' || data.outcome === 'skipped')) {
176
+ pending.answer(data.outcome === 'done' ? 'allowed-once' : 'rejected')
177
+ } else if (data.operation === 'summary' && pending.phase === 'summary') pending.report(summary(data.summary))
178
+ else throw new Error('invalid browser takeover operation')
179
+ return {}
180
+ }
181
+
182
+ handler = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {
183
+ if (request.method !== 'POST') { replyJson(response, 405, { error: 'method-not-allowed' }); return }
184
+ if (!sameOrigin(request, true)) { replyJson(response, 403, { error: 'not-same-origin' }); return }
185
+ try { replyJson(response, 200, this.exchange(await readJsonBody<Record<string, unknown>>(request, 16384))) }
186
+ catch (error) { replyJson(response, 400, { error: String(error) }) }
187
+ }
188
+ }
189
+
190
+ export function installTakeovers(ctx: Context, takeovers: BrowserTakeovers): void {
191
+ takeovers.attachBrowser(ctx.get('browser'))
192
+ ctx.on?.('approval/request' as never, ((request: { toolName: string; signal?: AbortSignal }, next: () => Promise<TakeoverDecision>) => takeovers.listen(request, next)) as never, { prepend: true })
193
+ ctx.effect(() => () => { takeovers.dispose() })
194
+ ctx.inject?.(['webServer'] as never, (host: Context) => {
195
+ const server = host.get('webServer' as never) as unknown as { register(spec: { kind: 'exact'; path: string; auth?: 'anonymous' | 'required' | 'deny'; handler: BrowserHttpHandler }): () => void }
196
+ host.effect(() => server.register({ kind: 'exact', path: TAKEOVER_ROUTE, auth: 'required', handler: pairedRoute(
197
+ () => ctx.get('connection' as never) as unknown as BrowserPairingConnection | undefined, takeovers.handler) }))
198
+ })
199
+ }