dsh-builtin-browser 0.5.8 → 1.0.1

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 (401) hide show
  1. package/CHANGELOG.md +410 -1
  2. package/README.en.md +16 -64
  3. package/README.md +33 -64
  4. package/assets/browser-carriers.svg +20 -0
  5. package/assets/browser-extension-identity.d.mts +2 -0
  6. package/assets/browser-extension-identity.mjs +2 -0
  7. package/assets/browser-messages.d.mts +5 -0
  8. package/assets/browser-messages.mjs +64 -0
  9. package/assets/browser-panel-locales.d.mts +2 -0
  10. package/assets/browser-panel-locales.mjs +380 -0
  11. package/assets/browser-policy.d.mts +37 -0
  12. package/assets/browser-policy.mjs +37 -0
  13. package/assets/browser-products.d.mts +6 -0
  14. package/assets/browser-products.mjs +76 -0
  15. package/assets/screenshots/1-main.png +0 -0
  16. package/assets/screenshots/2-form-fill.png +0 -0
  17. package/assets/screenshots/3-challenge.png +0 -0
  18. package/browser-extension/constants.mjs +20 -0
  19. package/browser-extension/controller.mjs +293 -0
  20. package/browser-extension/locales.mjs +15 -0
  21. package/browser-extension/manifest.json +12 -0
  22. package/browser-extension/options.html +14 -0
  23. package/browser-extension/options.mjs +9 -0
  24. package/browser-extension/permission-guard.mjs +13 -0
  25. package/browser-extension/worker.mjs +74 -0
  26. package/cordis.patch.yml +23 -48
  27. package/desktop-bridge/desktop-discovery.d.mts +2 -0
  28. package/desktop-bridge/desktop-discovery.mjs +36 -0
  29. package/desktop-bridge/desktop-identity.json +17 -1
  30. package/desktop-bridge/desktop-processes.d.mts +1 -0
  31. package/desktop-bridge/desktop-processes.mjs +15 -0
  32. package/desktop-bridge/guest-proxy.mjs +109 -0
  33. package/desktop-bridge/install.mjs +197 -74
  34. package/desktop-bridge/main.mjs +11 -0
  35. package/desktop-bridge/maintenance-files.d.mts +8 -0
  36. package/desktop-bridge/maintenance-files.mjs +28 -0
  37. package/desktop-bridge/maintenance-progress.ps1 +2 -2
  38. package/desktop-bridge/native-guests.mjs +41 -0
  39. package/desktop-bridge/plugin-browser-bridge.js +618 -370
  40. package/desktop-bridge/profile-loader.mjs +26 -0
  41. package/dist/client.cjs +43167 -0
  42. package/dist/client.d.cts +516 -0
  43. package/dist/client.d.mts +516 -0
  44. package/dist/index.cjs +92 -0
  45. package/dist/index.d.mts +2960 -0
  46. package/dist/index.mjs +24 -0
  47. package/docs/HANDOVER-2026-11-15.md +178 -0
  48. package/docs/README.md +10 -19
  49. package/docs/architecture.md +17 -145
  50. package/docs/child-tabs.md +13 -0
  51. package/docs/desktop-acceptance.md +9 -0
  52. package/docs/development.md +88 -18
  53. package/docs/extension-browser.md +44 -0
  54. package/docs/hardcoding-audit.md +64 -0
  55. package/docs/limitations.md +23 -73
  56. package/docs/pr64-extension-status.md +46 -0
  57. package/docs/pr64-maintenance.md +25 -0
  58. package/docs/pr64-native-children.md +52 -0
  59. package/docs/pr64-native-views.md +60 -0
  60. package/docs/tool-reference.md +87 -11
  61. package/docs/user-guide.md +47 -255
  62. package/docs/why-browser.md +6 -39
  63. package/dsh-host-patch/README.md +60 -0
  64. package/dsh-host-patch/apply.mjs +194 -0
  65. package/dsh-host-patch/legacy-bridge.mjs +53 -0
  66. package/dsh-host-patch/rc3-revision1.json +90 -0
  67. package/dsh-host-patch/rc3-revision2.json +112 -0
  68. package/dsh-host-patch/rc3-revision3.json.gz +0 -0
  69. package/dsh-host-patch/rc3-revision4.json.gz +0 -0
  70. package/dsh-host-patch/rc3-revision5.json.gz +0 -0
  71. package/dsh-host-patch/rc3-revision6.json.gz +0 -0
  72. package/dsh-host-patch/rc3-revision7.json.gz +0 -0
  73. package/dsh-host-patch/rc3-revision8.json.gz +0 -0
  74. package/dsh-host-patch/rc3.json +148 -0
  75. package/dsh-host-patch/rc5-revision1.json +90 -0
  76. package/dsh-host-patch/rc5-revision2.json +112 -0
  77. package/dsh-host-patch/rc5-revision3.json.gz +0 -0
  78. package/dsh-host-patch/rc5-revision4.json.gz +0 -0
  79. package/dsh-host-patch/rc5-revision5.json.gz +0 -0
  80. package/dsh-host-patch/rc5-revision6.json.gz +0 -0
  81. package/dsh-host-patch/rc5-revision7.json.gz +0 -0
  82. package/dsh-host-patch/rc5-revision8.json.gz +0 -0
  83. package/dsh-host-patch/rc5.json +148 -0
  84. package/lib/bridge-compatibility.js +38 -0
  85. package/lib/browser/handles.js +78 -0
  86. package/lib/browser/runtime.js +155 -43
  87. package/lib/browser/takeover-target.js +24 -0
  88. package/lib/browser-electron/authenticated-route.js +23 -0
  89. package/lib/browser-electron/automatic-maintenance.js +394 -51
  90. package/lib/browser-electron/bridge-auto.js +2 -1
  91. package/lib/browser-electron/bridge-connection.js +8 -1
  92. package/lib/browser-electron/bridge-install.js +27 -2
  93. package/lib/browser-electron/bridge-maintenance.js +35 -10
  94. package/lib/browser-electron/bridge-status.js +98 -27
  95. package/lib/browser-electron/desktop-bridge-host.js +193 -560
  96. package/lib/browser-electron/desktop-identity.js +40 -2
  97. package/lib/browser-electron/document-readiness.js +34 -0
  98. package/lib/browser-electron/electron-provision.js +14 -44
  99. package/lib/browser-electron/entry.js +659 -252
  100. package/lib/browser-electron/extension-browser.js +234 -0
  101. package/lib/browser-electron/extension-setup.js +69 -0
  102. package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
  103. package/lib/browser-electron/guest-cookie-jar.js +10559 -0
  104. package/lib/browser-electron/guest-cookie-store.js +74 -0
  105. package/lib/browser-electron/guest-css-runtime.js +75 -0
  106. package/lib/browser-electron/guest-css.js +106 -0
  107. package/lib/browser-electron/guest-route.js +603 -0
  108. package/lib/browser-electron/guest-runtime.js +356 -0
  109. package/lib/browser-electron/guest-storage-runtime.js +52 -0
  110. package/lib/browser-electron/guest-storage.js +163 -0
  111. package/lib/browser-electron/history-store.js +2 -1
  112. package/lib/browser-electron/host-main.js +162 -7
  113. package/lib/browser-electron/host-patch-maintenance.js +141 -0
  114. package/lib/browser-electron/http-body.js +22 -0
  115. package/lib/browser-electron/maintenance-broker.js +35 -5
  116. package/lib/browser-electron/maintenance-lifecycle.js +7 -5
  117. package/lib/browser-electron/maintenance-route.js +9 -6
  118. package/lib/browser-electron/open-slot.js +47 -0
  119. package/lib/browser-electron/paths.js +4 -1
  120. package/lib/browser-electron/preferred-browser.js +144 -0
  121. package/lib/browser-electron/preview-route.js +11 -8
  122. package/lib/browser-electron/process-ownership.js +198 -0
  123. package/lib/browser-electron/profile-checkpoint.js +222 -0
  124. package/lib/browser-electron/profile-command.js +60 -0
  125. package/lib/browser-electron/profile-extension.js +126 -0
  126. package/lib/browser-electron/profile-lease.js +157 -0
  127. package/lib/browser-electron/profile-residue.js +61 -0
  128. package/lib/browser-electron/provider.js +719 -262
  129. package/lib/browser-electron/reference-route.js +635 -0
  130. package/lib/browser-electron/remote-host.js +12 -13
  131. package/lib/browser-electron/runtime-route.js +6 -5
  132. package/lib/browser-electron/runtime-status.js +30 -29
  133. package/lib/browser-electron/settings-store.js +10 -5
  134. package/lib/browser-electron/shortcuts-route.js +108 -0
  135. package/lib/browser-electron/sidebar-only-host.js +119 -18
  136. package/lib/browser-electron/startpage-shortcuts.js +172 -0
  137. package/lib/browser-electron/system-browser.js +352 -371
  138. package/lib/browser-electron/windows-system.js +2 -1
  139. package/lib/browser-reference/delivery.js +326 -0
  140. package/lib/browser-reference/entry.js +597 -0
  141. package/lib/browser-reference/export.js +298 -0
  142. package/lib/browser-reference/import.js +295 -0
  143. package/lib/browser-reference/page-script.js +1406 -0
  144. package/lib/browser-reference/service.js +1062 -0
  145. package/lib/browser-reference/store.js +177 -0
  146. package/lib/browser-reference/submission-receipts.js +139 -0
  147. package/lib/browser-reference/text-quote.js +167 -0
  148. package/lib/browser-reference/types.js +11 -0
  149. package/lib/browser-reference/visible.js +311 -0
  150. package/lib/browser-reference/web-sources.js +97 -0
  151. package/lib/index.js +10 -3
  152. package/lib/reference-owner.js +5 -0
  153. package/lib/reference-page.js +12 -0
  154. package/lib/reference-source.js +2 -0
  155. package/lib/reference-text.js +188 -0
  156. package/lib/startpage-settings.js +63 -0
  157. package/lib/startpage.js +44 -0
  158. package/lib/takeover-protocol.js +2 -0
  159. package/lib/tool-browser/code-tool.js +416 -0
  160. package/lib/tool-browser/code-worker.js +872 -0
  161. package/lib/tool-browser/index.js +940 -76
  162. package/lib/tool-browser/page-probe.js +3 -3
  163. package/lib/tool-browser/panel-page.js +95 -0
  164. package/lib/tool-browser/screenshot-image.js +51 -0
  165. package/lib/tool-browser/takeover.js +205 -0
  166. package/lib/types.js +1 -0
  167. package/lib/web-guest.js +26 -0
  168. package/native-host/client.d.mts +17 -0
  169. package/native-host/client.mjs +100 -0
  170. package/native-host/host.mjs +150 -0
  171. package/native-host/identity.d.mts +2 -0
  172. package/native-host/identity.mjs +1 -0
  173. package/native-host/install.mjs +168 -0
  174. package/native-host/protocol.mjs +75 -0
  175. package/package.json +80 -92
  176. package/scripts/build.mjs +66 -0
  177. package/scripts/bundle-host.mjs +28 -0
  178. package/scripts/fix-exports.mjs +50 -0
  179. package/scripts/install-electron.mjs +11 -26
  180. package/scripts/verify-exports.mjs +47 -0
  181. package/scripts/verify-preview-sdk.mjs +93 -0
  182. package/skills/dsh-builtin-browser/SKILL.md +56 -47
  183. package/skills/dsh-builtin-browser/references/batch.md +31 -1
  184. package/skills/dsh-debug-host/SKILL.md +56 -0
  185. package/skills/dsh-debug-self/SKILL.md +50 -0
  186. package/src/bridge-compatibility.ts +39 -0
  187. package/src/browser/handles.ts +89 -0
  188. package/src/browser/runtime.ts +146 -50
  189. package/src/browser/takeover-target.ts +36 -0
  190. package/src/browser/types.ts +19 -7
  191. package/src/browser-electron/authenticated-route.ts +29 -1
  192. package/src/browser-electron/automatic-maintenance.ts +368 -56
  193. package/src/browser-electron/bridge-auto.ts +5 -4
  194. package/src/browser-electron/bridge-connection.ts +20 -2
  195. package/src/browser-electron/bridge-endpoint.ts +3 -3
  196. package/src/browser-electron/bridge-install.ts +40 -4
  197. package/src/browser-electron/bridge-maintenance.ts +42 -14
  198. package/src/browser-electron/bridge-status.ts +94 -23
  199. package/src/browser-electron/desktop-bridge-host.ts +185 -585
  200. package/src/browser-electron/desktop-identity.ts +53 -2
  201. package/src/browser-electron/document-readiness.ts +45 -0
  202. package/src/browser-electron/electron-provision.ts +12 -45
  203. package/src/browser-electron/entry.ts +1299 -882
  204. package/src/browser-electron/ephemeral-profile.ts +1 -1
  205. package/src/browser-electron/extension-browser.ts +223 -0
  206. package/src/browser-electron/extension-setup.ts +67 -0
  207. package/src/browser-electron/guest-cookie-jar.ts +176 -0
  208. package/src/browser-electron/guest-cookie-store.ts +59 -0
  209. package/src/browser-electron/guest-css-runtime.ts +76 -0
  210. package/src/browser-electron/guest-css.ts +68 -0
  211. package/src/browser-electron/guest-route.ts +568 -0
  212. package/src/browser-electron/guest-runtime.ts +357 -0
  213. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  214. package/src/browser-electron/guest-storage.ts +117 -0
  215. package/src/browser-electron/history-store.ts +5 -4
  216. package/src/browser-electron/host-main.ts +156 -11
  217. package/src/browser-electron/host-patch-maintenance.ts +112 -0
  218. package/src/browser-electron/http-body.ts +23 -0
  219. package/src/browser-electron/maintenance-broker.ts +29 -5
  220. package/src/browser-electron/maintenance-lifecycle.ts +14 -9
  221. package/src/browser-electron/maintenance-route.ts +17 -14
  222. package/src/browser-electron/missing-system-browser.ts +2 -2
  223. package/src/browser-electron/open-slot.ts +49 -0
  224. package/src/browser-electron/paths.ts +5 -1
  225. package/src/browser-electron/preferred-browser.ts +120 -0
  226. package/src/browser-electron/preview-route.ts +18 -11
  227. package/src/browser-electron/process-ownership.ts +168 -0
  228. package/src/browser-electron/profile-checkpoint.ts +187 -0
  229. package/src/browser-electron/profile-command.ts +46 -0
  230. package/src/browser-electron/profile-extension.ts +124 -0
  231. package/src/browser-electron/profile-lease.ts +115 -0
  232. package/src/browser-electron/profile-residue.ts +49 -0
  233. package/src/browser-electron/provider.ts +771 -289
  234. package/src/browser-electron/reference-route.ts +608 -0
  235. package/src/browser-electron/remote-host.ts +15 -15
  236. package/src/browser-electron/runtime-route.ts +11 -10
  237. package/src/browser-electron/runtime-status.ts +51 -32
  238. package/src/browser-electron/settings-store.ts +27 -7
  239. package/src/browser-electron/shortcuts-route.ts +112 -0
  240. package/src/browser-electron/sidebar-only-host.ts +118 -19
  241. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  242. package/src/browser-electron/system-browser.ts +309 -338
  243. package/src/browser-electron/windows-system.ts +2 -1
  244. package/src/browser-reference/delivery.ts +384 -0
  245. package/src/browser-reference/entry.ts +631 -0
  246. package/src/browser-reference/export.ts +339 -0
  247. package/src/browser-reference/import.ts +303 -0
  248. package/src/browser-reference/page-script.ts +1537 -0
  249. package/src/browser-reference/service.ts +1315 -0
  250. package/src/browser-reference/store.ts +172 -0
  251. package/src/browser-reference/submission-receipts.ts +122 -0
  252. package/src/browser-reference/text-quote.ts +219 -0
  253. package/src/browser-reference/types.ts +195 -0
  254. package/src/browser-reference/visible.ts +367 -0
  255. package/src/browser-reference/web-sources.ts +103 -0
  256. package/src/client/browser/BrowserController.ts +693 -0
  257. package/src/client/browser/BrowserFrame.ts +78 -0
  258. package/src/client/browser/BrowserNavigation.ts +169 -0
  259. package/src/client/browser/BrowserPage.ts +23 -0
  260. package/src/client/browser/BrowserPersistence.ts +44 -0
  261. package/src/client/browser/IframeImpl.ts +176 -0
  262. package/src/client/browser/child-tabs.ts +14 -0
  263. package/src/client/browser/iframe-reference.ts +67 -0
  264. package/src/client/browser/initialization.ts +262 -0
  265. package/src/client/browser/omnibox.ts +243 -0
  266. package/src/client/browser/store.ts +38 -0
  267. package/src/client/browser/takeover-channel.ts +72 -0
  268. package/src/client/browser/url.ts +46 -0
  269. package/src/client/browser/web-reference-source.ts +52 -0
  270. package/src/client/css-modules.d.ts +4 -0
  271. package/src/client/definition.tsx +30 -0
  272. package/src/client/electron/ElectronWebViewImpl.ts +364 -0
  273. package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
  274. package/src/client/electron/NativeChildPresentation.ts +45 -0
  275. package/src/client/electron/NativeViewPage.ts +251 -0
  276. package/src/client/electron/pages.ts +23 -0
  277. package/src/client/electron/reference-overlay.ts +53 -0
  278. package/src/client/electron/workspace.ts +33 -0
  279. package/src/client/index.ts +293 -0
  280. package/src/client/locales.ts +857 -0
  281. package/src/client/pages.ts +28 -0
  282. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  283. package/src/client/reference/client/draft-reference.ts +167 -0
  284. package/src/client/reference/client/index.ts +7 -0
  285. package/src/client/reference/client/ordered-submission.ts +108 -0
  286. package/src/client/reference/client/pending-delivery.ts +216 -0
  287. package/src/client/reference/client/plugin.ts +189 -0
  288. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  289. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  290. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  291. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  292. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  293. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  294. package/src/client/reference/client/production/assembly.ts +471 -0
  295. package/src/client/reference/client/production/asset-store.ts +144 -0
  296. package/src/client/reference/client/production/availability.ts +74 -0
  297. package/src/client/reference/client/production/bytes.ts +36 -0
  298. package/src/client/reference/client/production/delivery-client.ts +211 -0
  299. package/src/client/reference/client/production/draft-adapter.ts +508 -0
  300. package/src/client/reference/client/production/http-transport.ts +217 -0
  301. package/src/client/reference/client/production/production-submission.ts +310 -0
  302. package/src/client/reference/client/production/protocol.ts +231 -0
  303. package/src/client/reference/client/production/reference-card.ts +240 -0
  304. package/src/client/reference/client/production/reference-labels.ts +29 -0
  305. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  306. package/src/client/reference/client/production/reveal.ts +215 -0
  307. package/src/client/reference/client/production/runtime.ts +1101 -0
  308. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  309. package/src/client/reference/client/production/source-marker.ts +63 -0
  310. package/src/client/reference/client/production/source-opener.ts +55 -0
  311. package/src/client/reference/client/production/styles.ts +104 -0
  312. package/src/client/reference/client/production/user-text-rule.ts +58 -0
  313. package/src/client/reference/client/reveal.ts +107 -0
  314. package/src/client/reference/client/scheme.ts +114 -0
  315. package/src/client/reference/client/types.ts +168 -0
  316. package/src/client/reference/css-modules.d.ts +4 -0
  317. package/src/client/reference/index.ts +11 -0
  318. package/src/client/reference-capture-owner.ts +162 -0
  319. package/src/client/reference-intents.ts +36 -0
  320. package/src/client/settings/index.ts +34 -0
  321. package/{client.js → src/client/settings/panel.ts} +2657 -2231
  322. package/src/client/shortcut-open.ts +30 -0
  323. package/src/client/startpage/binding.ts +99 -0
  324. package/src/client/startpage/controller.ts +303 -0
  325. package/src/client/startpage/model.ts +279 -0
  326. package/src/client/view/Browser.module.css +751 -0
  327. package/src/client/view/BrowserBody.tsx +314 -0
  328. package/src/client/view/BrowserPresentation.ts +9 -0
  329. package/src/client/view/BrowserTitle.tsx +17 -0
  330. package/src/client/view/IframePresentation.ts +344 -0
  331. package/src/client/view/StartPage.tsx +597 -0
  332. package/src/client/view/TakeoverBanner.tsx +21 -0
  333. package/src/index.ts +110 -73
  334. package/src/reference-owner.ts +5 -0
  335. package/src/reference-page.ts +9 -0
  336. package/src/reference-source.ts +3 -0
  337. package/src/reference-text.ts +197 -0
  338. package/src/startpage-settings.ts +103 -0
  339. package/src/startpage.ts +71 -0
  340. package/src/takeover-protocol.ts +19 -0
  341. package/src/tool-browser/code-tool.ts +401 -0
  342. package/src/tool-browser/code-worker.ts +639 -0
  343. package/src/tool-browser/index.ts +908 -77
  344. package/src/tool-browser/page-probe.ts +4 -4
  345. package/src/tool-browser/panel-page.ts +124 -0
  346. package/src/tool-browser/screenshot-image.ts +49 -0
  347. package/src/tool-browser/takeover.ts +198 -0
  348. package/src/types/electron-shim.d.ts +20 -0
  349. package/src/types.ts +85 -0
  350. package/src/web-guest.ts +34 -0
  351. package/tools/accept-desktop.mjs +148 -0
  352. package/lib/browser/runtime.d.ts +0 -175
  353. package/lib/browser/types.d.ts +0 -797
  354. package/lib/browser-electron/authenticated-route.d.ts +0 -27
  355. package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
  356. package/lib/browser-electron/bridge-auto.d.ts +0 -93
  357. package/lib/browser-electron/bridge-connection.d.ts +0 -93
  358. package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
  359. package/lib/browser-electron/bridge-install.d.ts +0 -85
  360. package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
  361. package/lib/browser-electron/bridge-status.d.ts +0 -50
  362. package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
  363. package/lib/browser-electron/desktop-identity.d.ts +0 -58
  364. package/lib/browser-electron/electron-provision.d.ts +0 -92
  365. package/lib/browser-electron/entry.d.ts +0 -64
  366. package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
  367. package/lib/browser-electron/file-write.d.ts +0 -2
  368. package/lib/browser-electron/history-store.d.ts +0 -98
  369. package/lib/browser-electron/host-main.d.ts +0 -26
  370. package/lib/browser-electron/http-body.d.ts +0 -24
  371. package/lib/browser-electron/json-reply.d.ts +0 -33
  372. package/lib/browser-electron/maintenance-broker.d.ts +0 -35
  373. package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
  374. package/lib/browser-electron/maintenance-route.d.ts +0 -18
  375. package/lib/browser-electron/missing-system-browser.d.ts +0 -54
  376. package/lib/browser-electron/paths.d.ts +0 -4
  377. package/lib/browser-electron/preview-route.d.ts +0 -89
  378. package/lib/browser-electron/process.d.ts +0 -14
  379. package/lib/browser-electron/provider.d.ts +0 -959
  380. package/lib/browser-electron/remote-host.d.ts +0 -256
  381. package/lib/browser-electron/rpc-input.d.ts +0 -4
  382. package/lib/browser-electron/rpc-ops.d.ts +0 -18
  383. package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
  384. package/lib/browser-electron/runtime-route.d.ts +0 -55
  385. package/lib/browser-electron/runtime-status.d.ts +0 -116
  386. package/lib/browser-electron/settings-route.d.ts +0 -15
  387. package/lib/browser-electron/settings-store.d.ts +0 -224
  388. package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
  389. package/lib/browser-electron/system-browser.d.ts +0 -367
  390. package/lib/browser-electron/timing.d.ts +0 -8
  391. package/lib/browser-electron/virtual-cursor.d.ts +0 -67
  392. package/lib/browser-electron/windows-system.d.ts +0 -3
  393. package/lib/index.d.ts +0 -30
  394. package/lib/tool-browser/element-fields.d.ts +0 -145
  395. package/lib/tool-browser/index.d.ts +0 -53
  396. package/lib/tool-browser/page-probe.d.ts +0 -86
  397. package/scripts/consumer-install-check.mjs +0 -72
  398. package/scripts/run-tests.mjs +0 -32
  399. package/scripts/verify-host-compat.mjs +0 -195
  400. package/scripts/verify-preview-route.mjs +0 -168
  401. package/scripts/verify-runtime-status.mjs +0 -179
@@ -1,3 +1,5 @@
1
+ import { PATH_NAMES, INSTALL_LOCATIONS } from '../../assets/browser-products.mjs';
2
+ import { cdpVersionUrl, CDP_DEFAULT_ATTACH_PORT, CDP_ATTACH_PROBE_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
1
3
  /**
2
4
  * Drive the browser the user already has (Chrome / Edge / any Chromium) instead of
3
5
  * the Electron we ship — the same approach Codex Browser Use takes.
@@ -27,6 +29,8 @@
27
29
  import { readFileSync, rmSync, statSync } from 'node:fs';
28
30
  import { existsSync } from 'node:fs';
29
31
  import { join } from 'node:path';
32
+ import { acquireProfileLease } from './profile-lease.js';
33
+ import { BrowserProcessOwnership } from './process-ownership.js';
30
34
  /**
31
35
  * How long a killed browser is given to actually exit before the launch proceeds.
32
36
  *
@@ -61,115 +65,18 @@ const CLOSE_GRACE_MS = 6_000;
61
65
  * interval, so a worst-case iteration costs 500 ms and the budget still affords ~60 attempts.
62
66
  */
63
67
  const PORT_PROBE_MS = 250;
64
- /**
65
- * How long to keep trying to adopt a browser after a launcher reported a clean exit.
66
- *
67
- * Exit code 0 means the launcher handed the request to an instance already holding this profile —
68
- * but on Windows that stub exits BEFORE the real browser writes `DevToolsActivePort`. Measured on
69
- * Chrome 156: stub gone at 300 ms, port file present at 441 ms (issue #33). A single attempt read
70
- * too early and reported a launch failure for a browser that was starting normally, so this is a
71
- * retry rather than one shot.
72
- *
73
- * 8 s is the reporter's measured-working bound and is generous against that ~150 ms gap: an honest
74
- * hand-off resolves in well under a second, and a launch that genuinely failed still reaches the
75
- * error within the same budget the CDP loop already allows.
76
- */
77
- const HANDOFF_ADOPT_MS = 8_000;
78
- /** The real launcher: spawn a detached-free child with pipes closed. */
79
- const defaultLauncher = (path, args) => spawn(path, [...args], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false });
68
+ function diagnosticTail(value) {
69
+ return value.replace(/\b(?:https?|wss?):\/\/[^\s]+/giu, '[URL redacted]')
70
+ .replace(/\b(authorization|cookie|password|token|secret)(\s*[:=]\s*)[^\r\n]+/giu, '$1$2[redacted]')
71
+ .replace(/\bBearer\s+[^\s]+/giu, 'Bearer [redacted]')
72
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/gu, '')
73
+ .split('\n').slice(-12).join('\n').slice(-2048);
74
+ }
75
+ /** The real launcher: retain stderr for bounded launch diagnostics. */
76
+ const defaultLauncher = (path, args) => spawn(path, [...args], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: false });
80
77
  import { spawn } from 'node:child_process';
81
78
  import { randomUUID } from 'node:crypto';
82
- /**
83
- * Launcher names to look for on PATH, per product and per platform.
84
- *
85
- * The names genuinely differ: Linux distributions package the launcher under a
86
- * versioned name (`microsoft-edge-stable`, `google-chrome-stable`), Windows puts
87
- * `chrome.exe` in an Application directory that may or may not be on PATH, and macOS
88
- * ships the executable inside the .app bundle. PATH is still consulted first on every
89
- * platform — it is what reflects how the user actually installed the browser.
90
- */
91
- const PATH_NAMES = {
92
- chrome: {
93
- win32: ['chrome'],
94
- darwin: ['Google Chrome', 'Chromium'],
95
- linux: ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser'],
96
- },
97
- edge: {
98
- win32: ['msedge'],
99
- darwin: ['Microsoft Edge'],
100
- linux: ['microsoft-edge-stable', 'microsoft-edge', 'microsoft-edge-dev'],
101
- },
102
- brave: {
103
- win32: ['brave'],
104
- darwin: ['Brave Browser'],
105
- linux: ['brave-browser', 'brave'],
106
- },
107
- };
108
- /**
109
- * Where each product installs when its launcher is not on PATH.
110
- *
111
- * Windows keeps the executable inside a version-less Application directory; macOS
112
- * keeps it inside the .app bundle; Linux distributions that do not use a launcher
113
- * put it under /usr/bin or /opt. All are checked, and anything missed can be named
114
- * explicitly with DSH_BROWSER_<KIND>_PATH.
115
- */
116
- const INSTALL_LOCATIONS = {
117
- chrome: {
118
- win32: [
119
- String.raw `%ProgramFiles%\Google\Chrome\Application\chrome.exe`,
120
- String.raw `%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe`,
121
- // Where a per-user install lands, which is what Chrome's own installer chooses when it
122
- // cannot (or should not) write to Program Files. Missing this meant the plugin reported
123
- // "no browser found" on machines that plainly had one.
124
- String.raw `%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe`,
125
- String.raw `%LOCALAPPDATA%\Chromium\Application\chrome.exe`,
126
- ],
127
- darwin: [
128
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
129
- '/Applications/Chromium.app/Contents/MacOS/Chromium',
130
- ],
131
- linux: [
132
- '/usr/bin/google-chrome-stable',
133
- '/usr/bin/google-chrome',
134
- '/usr/bin/chromium',
135
- '/opt/google/chrome/chrome',
136
- '/snap/bin/chromium',
137
- ],
138
- },
139
- edge: {
140
- win32: [
141
- String.raw `%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe`,
142
- String.raw `%ProgramFiles%\Microsoft\Edge\Application\msedge.exe`,
143
- String.raw `%LOCALAPPDATA%\Microsoft\Edge\Application\msedge.exe`,
144
- ],
145
- darwin: ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'],
146
- linux: [
147
- '/usr/bin/microsoft-edge-stable',
148
- '/usr/bin/microsoft-edge',
149
- '/usr/bin/microsoft-edge-dev',
150
- ],
151
- },
152
- brave: {
153
- win32: [
154
- String.raw `%ProgramFiles%\BraveSoftware\Brave-Browser\Application\brave.exe`,
155
- String.raw `%ProgramFiles(x86)%\BraveSoftware\Brave-Browser\Application\brave.exe`,
156
- String.raw `%LOCALAPPDATA%\BraveSoftware\Brave-Browser\Application\brave.exe`,
157
- ],
158
- darwin: ['/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'],
159
- linux: ['/usr/bin/brave-browser', '/usr/bin/brave', '/snap/bin/brave'],
160
- },
161
- };
162
- /**
163
- * Resolve the environment references in one install location.
164
- *
165
- * The list is static strings, but a per-user install lands under %LOCALAPPDATA%, so the entry
166
- * has to be resolved against the environment detection was HANDED rather than process.env — a
167
- * caller that supplies a platform and an environment (which is what makes detection testable)
168
- * must not end up reading the developer's real machine.
169
- * @param location - one entry from the install-location table.
170
- * @param env - the environment to resolve against.
171
- * @returns the path with %NAME% references replaced, or the entry unchanged when unknown.
172
- */
79
+ import { readTabHandle, resolveSessionHandle, resolveTabHandle, sessionWireId, tabWireId } from '../browser/handles.js';
173
80
  /**
174
81
  * Whether a browser's self-reported product name is one this carrier could have launched.
175
82
  *
@@ -198,37 +105,6 @@ function hasDisplay(env = process.env) {
198
105
  return true;
199
106
  return (env.DISPLAY ?? '') !== '' || (env.WAYLAND_DISPLAY ?? '') !== '';
200
107
  }
201
- /**
202
- * Whether Chromium's own sandbox cannot start here.
203
- *
204
- * Two cases, both of which make the browser exit at once rather than degrade: running as root
205
- * (the sandbox refuses), and running inside a container that lacks the namespaces it needs. The
206
- * check is deliberately conservative — when it is unsure it answers false, so the default is the
207
- * sandboxed launch and the weaker mode only happens where it is required.
208
- * @param env - the environment to inspect; defaults to the current process.
209
- * @returns true when `--no-sandbox` is required for the browser to start at all.
210
- */
211
- function needsNoSandbox(env = process.env) {
212
- if (process.platform === 'win32')
213
- return false;
214
- try {
215
- if (typeof process.getuid === 'function' && process.getuid() === 0)
216
- return true;
217
- }
218
- catch {
219
- // No getuid: not a POSIX process; the container checks below still apply.
220
- }
221
- if ((env.container ?? '') !== '')
222
- return true;
223
- try {
224
- if (existsSync('/.dockerenv'))
225
- return true;
226
- }
227
- catch {
228
- // An unreadable root is not evidence of a container.
229
- }
230
- return false;
231
- }
232
108
  /**
233
109
  * Resolve `auto` into a concrete decision, and say why.
234
110
  *
@@ -399,8 +275,8 @@ class CdpClient {
399
275
  isAlive() {
400
276
  return this.socket.readyState === WebSocket.OPEN;
401
277
  }
402
- async whenReady() {
403
- const timeoutMs = 30_000;
278
+ async whenReady(deadline = Date.now() + 30_000) {
279
+ const timeoutMs = Math.max(1, deadline - Date.now());
404
280
  let timer;
405
281
  try {
406
282
  await Promise.race([
@@ -415,6 +291,11 @@ class CdpClient {
415
291
  clearTimeout(timer);
416
292
  }
417
293
  }
294
+ async whenClosed() {
295
+ if (this.socket.readyState === WebSocket.CLOSED)
296
+ return;
297
+ await new Promise(resolve => this.socket.addEventListener('close', () => resolve(), { once: true }));
298
+ }
418
299
  /**
419
300
  * Send one CDP command, optionally on an attached session.
420
301
  * @param method - the CDP method.
@@ -422,7 +303,7 @@ class CdpClient {
422
303
  * @param sessionId - the flattened session to target, when this is a page command.
423
304
  * @returns the CDP result.
424
305
  */
425
- async send(method, params, sessionId) {
306
+ async send(method, params, sessionId, timeoutMs = 30_000) {
426
307
  // Fail fast and say why. Waiting out the timeout on a closed socket produced
427
308
  // only "timed out", which reads as a slow page and hides the real cause.
428
309
  if (!this.isAlive()) {
@@ -437,7 +318,7 @@ class CdpClient {
437
318
  setTimeout(() => {
438
319
  if (this.pending.delete(id))
439
320
  reject(new Error(`dsh-builtin-browser: ${method} timed out`));
440
- }, 30_000).unref?.();
321
+ }, timeoutMs).unref?.();
441
322
  });
442
323
  }
443
324
  /** Close the socket. */
@@ -484,6 +365,7 @@ export class SystemBrowserViewHost {
484
365
  launcher;
485
366
  headlessMode;
486
367
  isQuiet;
368
+ profileError;
487
369
  /**
488
370
  * viewId -> the session that view rides, and the client that issued it.
489
371
  *
@@ -517,9 +399,10 @@ export class SystemBrowserViewHost {
517
399
  */
518
400
  clientSuspect = false;
519
401
  child;
520
- /** Whether this connection's surplus blank pages have been collapsed already. */
521
- blanksNormalized = false;
402
+ profileLease;
522
403
  starting;
404
+ lastLaunchError;
405
+ launchDiagnostic;
523
406
  /**
524
407
  * Browsers that ignored a kill.
525
408
  *
@@ -528,6 +411,10 @@ export class SystemBrowserViewHost {
528
411
  * stop. Forgetting them is what allowed a launch this host could not undo.
529
412
  */
530
413
  stubborn = [];
414
+ ownership;
415
+ ownedClients = new WeakMap();
416
+ ownedChildren = new WeakSet();
417
+ createdTargets = new WeakMap();
531
418
  /**
532
419
  * @param browser - the detected installation to launch on first use.
533
420
  * @param profileDir - a plugin-owned directory; the user's own profile is never touched.
@@ -547,7 +434,7 @@ export class SystemBrowserViewHost {
547
434
  * Whether this launch should get a window. See {@link resolveLaunchMode} for how `auto` decides
548
435
  * and why a display-less host needs headless at all (issue #32).
549
436
  */
550
- headlessMode = 'auto', isQuiet = () => false) {
437
+ headlessMode = 'auto', isQuiet = () => false, profileError, ownership = { managed: false }) {
551
438
  this.browser = browser;
552
439
  this.profileDir = profileDir;
553
440
  this.extraArgs = extraArgs;
@@ -555,6 +442,41 @@ export class SystemBrowserViewHost {
555
442
  this.launcher = launcher;
556
443
  this.headlessMode = headlessMode;
557
444
  this.isQuiet = isQuiet;
445
+ this.profileError = profileError;
446
+ this.ownership = new BrowserProcessOwnership(browser.path, profileDir, ownership);
447
+ }
448
+ async stopChild(child) {
449
+ if (child.exitCode !== null || child.signalCode !== null)
450
+ return true;
451
+ if (await this.ownership.terminate(child))
452
+ return true;
453
+ this.lastLaunchError = 'Cleanup refused: process ownership could not be verified; browser left running.';
454
+ if (this.launchDiagnostic)
455
+ this.launchDiagnostic.cleanup = 'ownership-unverified';
456
+ return false;
457
+ }
458
+ async prepare() {
459
+ try {
460
+ await this.ensureClient();
461
+ }
462
+ catch (error) {
463
+ const launch = this.connectionStatus().launch;
464
+ if (!(error instanceof Error) || launch === undefined)
465
+ throw error;
466
+ throw Object.assign(new Error(`${error.message} Launch diagnostic: ${JSON.stringify(launch)}`, { cause: error }), 'code' in error ? { code: error.code } : {});
467
+ }
468
+ }
469
+ connectionStatus() {
470
+ const connected = !this.disposed && this.client?.isAlive() === true && !this.clientSuspect;
471
+ return { connected, detail: connected ? 'Browser launched and connected over CDP.'
472
+ : this.profileError ?? this.lastLaunchError ?? (this.disposed ? 'Browser carrier was released.'
473
+ : this.starting ? 'Browser launch is in progress; no live CDP connection yet.'
474
+ : this.client ? 'Browser CDP connection was lost or is awaiting verification.'
475
+ : 'Browser has not launched; run a browser command to establish CDP. No live CDP connection.'),
476
+ ...this.launchDiagnostic === undefined ? {} : { launch: {
477
+ ...this.launchDiagnostic, devToolsActivePortPresent: existsSync(join(this.profileDir, 'DevToolsActivePort')),
478
+ } },
479
+ };
558
480
  }
559
481
  /** Which product this host would drive (for diagnostics). */
560
482
  get kind() {
@@ -609,16 +531,14 @@ export class SystemBrowserViewHost {
609
531
  forgetBrowserState() {
610
532
  this.views.clear();
611
533
  this.sessions.clear();
612
- // A new browser comes with its own surplus pages, so the tidy-up runs again for it. Without
613
- // this, a restart would inherit the previous connection's "already handled" and leave the new
614
- // browser's extra blank page in place for the rest of the session.
615
- this.blanksNormalized = false;
616
534
  }
617
535
  async ensureClient() {
618
536
  // A disposed host must never start a browser: doing so would spawn a process
619
537
  // nobody owns and nobody will kill.
620
538
  if (this.disposed)
621
539
  throw new Error('dsh-builtin-browser: this browser host was released');
540
+ if (this.profileError !== undefined)
541
+ throw new Error(this.profileError);
622
542
  // The exit listener clears this, but a socket can also die without the process doing so
623
543
  // (the browser closing its debugging endpoint, a dropped connection). Checking the
624
544
  // socket's own state costs nothing and turns a 30s hang into a restart.
@@ -645,15 +565,14 @@ export class SystemBrowserViewHost {
645
565
  this.forgetBrowserState();
646
566
  }
647
567
  // Concurrent first calls share one startup rather than racing two browsers.
648
- this.starting ??= this.start().finally(() => { this.starting = undefined; });
649
- const client = await this.starting;
650
- // Once per connection. A browser opens more than one page when it starts, and the surplus is
651
- // invisible to the plugin's tab model — see normalizeBlankPages for why that matters.
652
- if (!this.blanksNormalized) {
653
- this.blanksNormalized = true;
654
- await this.normalizeBlankPages(client);
655
- }
656
- return client;
568
+ this.starting ??= this.start().then(client => {
569
+ this.lastLaunchError = undefined;
570
+ return client;
571
+ }).catch(error => {
572
+ this.lastLaunchError = error instanceof Error ? error.message : String(error);
573
+ throw error;
574
+ }).finally(() => { this.starting = undefined; });
575
+ return await this.starting;
657
576
  }
658
577
  /**
659
578
  * Take over a browser already serving this profile, instead of racing it.
@@ -673,23 +592,29 @@ export class SystemBrowserViewHost {
673
592
  * @param _why - a short phrase for the log, naming which attempt this is.
674
593
  * @returns a connected client for the running browser, or undefined when there is none.
675
594
  */
676
- async adoptRunningBrowser(_why) {
595
+ async adoptRunningBrowser(_why, explicitPort, deadline = Date.now() + 30_000) {
677
596
  const portFile = join(this.profileDir, 'DevToolsActivePort');
678
597
  let port;
679
- try {
680
- if (!existsSync(portFile))
681
- return undefined;
682
- const value = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '');
683
- if (!Number.isInteger(value) || value <= 0)
684
- return undefined;
685
- port = value;
686
- }
687
- catch {
688
- return undefined;
598
+ if (typeof explicitPort === 'number' && explicitPort > 0) {
599
+ port = explicitPort;
689
600
  }
601
+ else
602
+ try {
603
+ if (!existsSync(portFile))
604
+ return undefined;
605
+ const value = Number(readFileSync(portFile, 'utf8').split('\n')[0]?.trim() ?? '');
606
+ if (!Number.isInteger(value) || value <= 0)
607
+ return undefined;
608
+ port = value;
609
+ }
610
+ catch {
611
+ return undefined;
612
+ }
613
+ let client;
614
+ let identified = false;
690
615
  try {
691
- const version = await (await fetch(`http://127.0.0.1:${port}/json/version`, {
692
- signal: AbortSignal.timeout(PORT_PROBE_MS),
616
+ const version = await (await fetch(cdpVersionUrl(port), {
617
+ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),
693
618
  })).json();
694
619
  if (typeof version.webSocketDebuggerUrl !== 'string')
695
620
  return undefined;
@@ -697,23 +622,33 @@ export class SystemBrowserViewHost {
697
622
  // exits. The endpoint's own answer is the evidence, and it has to name a browser.
698
623
  if (!isBrowserProduct(version.Browser))
699
624
  return undefined;
700
- const client = new CdpClient(version.webSocketDebuggerUrl);
701
- await client.whenReady();
625
+ identified = true;
626
+ client = new CdpClient(version.webSocketDebuggerUrl);
627
+ await client.whenReady(deadline);
702
628
  // Asked through the protocol too, so a websocket that merely accepts connections is not
703
629
  // mistaken for a browser that answers.
704
- const info = await client.send('Browser.getVersion', {});
705
- if (!isBrowserProduct(info?.product)) {
630
+ const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now()));
631
+ if (!isBrowserProduct(info?.product) || info.product !== version.Browser)
632
+ throw new Error('browser did not acknowledge its identity');
633
+ if (this.disposed) {
706
634
  client.close();
707
635
  return undefined;
708
636
  }
709
- if (this.disposed) {
637
+ await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()));
638
+ if (this.disposed || Date.now() >= deadline) {
710
639
  client.close();
711
640
  return undefined;
712
641
  }
713
642
  this.client = client;
714
643
  return client;
715
644
  }
716
- catch {
645
+ catch (error) {
646
+ client?.close();
647
+ if (identified)
648
+ throw error;
649
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
650
+ throw new Error('browser did not acknowledge its discovery endpoint before the launch deadline', { cause: error });
651
+ }
717
652
  // No endpoint, nothing listening, or not a browser: all of them mean "launch one".
718
653
  return undefined;
719
654
  }
@@ -727,10 +662,23 @@ export class SystemBrowserViewHost {
727
662
  * @returns the connected client.
728
663
  */
729
664
  async start() {
665
+ const deadline = Date.now() + 30_000;
666
+ this.profileLease ??= acquireProfileLease(this.profileDir);
730
667
  // Before spawning anything: is a browser for THIS profile already running? A DSH restart
731
668
  // leaves one behind, and launching into it is the failure reported as "exited immediately
732
669
  // after launch (exit code 0)" that required killing seven processes by hand.
733
- const adopted = await this.adoptRunningBrowser('before launch');
670
+ // A browser the human started with an explicit debugging port. Port 0 makes Chromium write the chosen
671
+ // port into the profile, which the probe below already finds; an explicit port leaves no file, so this
672
+ // is the only way to reach it. Attaching means driving the window they already have open.
673
+ const explicitPort = Number(process.env.DSH_BROWSER_ATTACH_PORT ?? '');
674
+ const attached = Number.isSafeInteger(explicitPort) && explicitPort > 0
675
+ ? await this.adoptRunningBrowser('explicit attach port', explicitPort, deadline) : undefined;
676
+ if (attached !== undefined) {
677
+ ;
678
+ globalThis.__dshBrowserCarrier = 'attached';
679
+ return attached;
680
+ }
681
+ const adopted = await this.adoptRunningBrowser('before launch', undefined, deadline);
734
682
  if (adopted !== undefined)
735
683
  return adopted;
736
684
  // Whether a window exists is decided by `browser.headless` ALONE (plus the operator's
@@ -769,19 +717,9 @@ export class SystemBrowserViewHost {
769
717
  // `--no-startup-window` keeps the browser alive with no window and no initial page; measured
770
718
  // by the reporter on Chrome 156 as writing DevToolsActivePort in 599 ms, answering
771
719
  // `/json/version`, listing two extension targets and no page, and then creating windows
772
- // normally through `Target.createTarget`. A browser that does start a blank despite this is
773
- // still handled: `normalizeBlankPages` closes the surplus and `buildSession` adopts the rest.
720
+ // normally through `Target.createTarget`.
774
721
  '--no-startup-window',
775
722
  ];
776
- // Chromium's own sandbox cannot start in some of these environments — running as root, or
777
- // inside a container without the namespaces it needs — and it exits rather than degrading.
778
- // Only then is the sandbox dropped, and never silently: a setting that weakens process
779
- // isolation must be visible in the log, because whoever reads it has to be able to disagree.
780
- if (launch.headless && needsNoSandbox()) {
781
- args.splice(args.length - 2, 0, '--no-sandbox');
782
- process.stderr.write('[dsh-browser] launching with --no-sandbox: '
783
- + 'this process runs as root or in a container, where the Chromium sandbox cannot start\n');
784
- }
785
723
  if (launch.headless) {
786
724
  process.stderr.write(`[dsh-browser] launching headless (${launch.why}); `
787
725
  + 'the browser has no window but every tool works the same\n');
@@ -791,10 +729,8 @@ export class SystemBrowserViewHost {
791
729
  // exit would then be treated as the launch failing.
792
730
  if (this.child !== undefined) {
793
731
  const dying = this.child;
794
- try {
795
- dying.kill();
796
- }
797
- catch { /* already gone */ }
732
+ if (!await this.stopChild(dying))
733
+ throw new Error(this.lastLaunchError);
798
734
  this.child = undefined;
799
735
  // Whatever the old browser issued is worthless now, and its exit listener cannot clean
800
736
  // up after itself: this.child is reassigned below, so the old child's exit event returns
@@ -829,6 +765,8 @@ export class SystemBrowserViewHost {
829
765
  this.stubborn.splice(at2, 1);
830
766
  });
831
767
  });
768
+ if (dying.exitCode === null && dying.signalCode === null)
769
+ throw new Error('dsh-builtin-browser: the previous browser still holds this profile; refusing another launch');
832
770
  }
833
771
  // The port file is deliberately NOT deleted here, and that is a reversal.
834
772
  //
@@ -865,6 +803,12 @@ export class SystemBrowserViewHost {
865
803
  }
866
804
  })();
867
805
  let child;
806
+ if (this.disposed || Date.now() >= deadline)
807
+ throw new Error('dsh-builtin-browser: launch was cancelled or its deadline expired');
808
+ const launchDiagnostic = {
809
+ stderrTail: '', exitCode: null, signal: null, devToolsActivePortPresent: existsSync(portFile),
810
+ };
811
+ this.launchDiagnostic = launchDiagnostic;
868
812
  try {
869
813
  child = this.launcher(this.browser.path, args);
870
814
  }
@@ -875,6 +819,12 @@ export class SystemBrowserViewHost {
875
819
  throw new Error(`dsh-builtin-browser: could not launch ${this.browser.path}: ${error instanceof Error ? error.message : String(error)}`);
876
820
  }
877
821
  this.child = child;
822
+ launchDiagnostic.exitCode = child.exitCode;
823
+ launchDiagnostic.signal = child.signalCode;
824
+ child.on('exit', (code, signal) => {
825
+ launchDiagnostic.exitCode = code ?? child.exitCode;
826
+ launchDiagnostic.signal = signal ?? child.signalCode;
827
+ });
878
828
  /**
879
829
  * A launch that fails (ENOENT, no permission, a broken binary) is reported by an
880
830
  * asynchronous 'error' event on the child, NOT by a throw here and NOT by exitCode.
@@ -882,7 +832,19 @@ export class SystemBrowserViewHost {
882
832
  * down — one bad browser path would kill DSH, not just fail a tool call.
883
833
  */
884
834
  let launchError;
885
- child.on('error', error => { launchError = error; });
835
+ let diagnostic = '';
836
+ child.stderr?.on('data', chunk => {
837
+ diagnostic = (diagnostic + String(chunk)).slice(-4096);
838
+ launchDiagnostic.stderrTail = diagnosticTail(diagnostic);
839
+ if (/remote debugging requires a non-default data directory/iu.test(diagnostic)) {
840
+ launchError = new Error('The browser refused remote debugging on its default user profile. A live CDP connection is required; no alternative profile was substituted.');
841
+ }
842
+ });
843
+ child.on('error', error => {
844
+ launchError = error;
845
+ launchDiagnostic.exitCode = child.exitCode;
846
+ launchDiagnostic.signal = child.signalCode;
847
+ });
886
848
  // A browser that exits later is as unusable as one that never started, and the failure
887
849
  // has to reach the NEXT call rather than being swallowed: clearing the client here is
888
850
  // what makes ensureClient() start a fresh browser instead of returning a socket to a
@@ -893,11 +855,13 @@ export class SystemBrowserViewHost {
893
855
  this.client?.close();
894
856
  this.client = undefined;
895
857
  this.child = undefined;
858
+ this.lastLaunchError = 'Browser exited; the CDP connection is no longer live.';
896
859
  // The pages this client opened belong to the process that just died; keeping their
897
860
  // session ids means every later command is sent to a browser that never issued them.
898
861
  // Clearing these is what makes the restart usable rather than merely alive.
899
862
  this.forgetBrowserState();
900
863
  });
864
+ await this.ownership.capture(child);
901
865
  /**
902
866
  * The port this launch wrote, or undefined while it has not written one yet.
903
867
  *
@@ -917,7 +881,7 @@ export class SystemBrowserViewHost {
917
881
  // keeps this correct on a filesystem whose timestamps are coarser than a millisecond.
918
882
  if (portFileBefore !== undefined
919
883
  && after.mtimeMs <= portFileBefore.mtimeMs
920
- && contents === portFileBefore.contents)
884
+ && contents === portFileBefore.contents && child.exitCode !== 0)
921
885
  return undefined;
922
886
  const value = Number(contents.split('\n')[0]?.trim() ?? '');
923
887
  return Number.isInteger(value) && value > 0 ? value : undefined;
@@ -926,7 +890,6 @@ export class SystemBrowserViewHost {
926
890
  return undefined;
927
891
  }
928
892
  };
929
- const deadline = Date.now() + 30_000;
930
893
  /**
931
894
  * Why the loop stopped, so the failure can say what actually happened. Reporting
932
895
  * every ending as "did not expose CDP within 30s" was wrong three ways: the cause,
@@ -940,7 +903,7 @@ export class SystemBrowserViewHost {
940
903
  // to a dead process behind. The child is killed here too — dispose() may have
941
904
  // run before this child was recorded, leaving nobody else to do it.
942
905
  if (this.disposed) {
943
- child.kill();
906
+ await this.stopChild(child);
944
907
  if (this.child === child)
945
908
  this.child = undefined;
946
909
  stopped = 'released';
@@ -953,9 +916,7 @@ export class SystemBrowserViewHost {
953
916
  break;
954
917
  }
955
918
  if (Date.now() > deadline) {
956
- child.kill();
957
- if (this.child === child)
958
- this.child = undefined;
919
+ await this.stopChild(child);
959
920
  stopped = 'timeout';
960
921
  break;
961
922
  }
@@ -963,7 +924,7 @@ export class SystemBrowserViewHost {
963
924
  // alone made a killed browser look alive and the launch run out its full 30s deadline
964
925
  // before reporting "did not expose CDP" — a timeout for something that died at once.
965
926
  // The sibling check on the release path already looked at both.
966
- if (child.exitCode !== null || child.signalCode !== null) {
927
+ if (child.signalCode !== null || (child.exitCode !== null && child.exitCode !== 0)) {
967
928
  if (this.child === child)
968
929
  this.child = undefined;
969
930
  stopped = 'exited';
@@ -974,12 +935,12 @@ export class SystemBrowserViewHost {
974
935
  const port = freshPort();
975
936
  if (port !== undefined) {
976
937
  try {
977
- const version = await (await fetch(`http://127.0.0.1:${port}/json/version`, {
938
+ const version = await (await fetch(cdpVersionUrl(port), {
978
939
  // Bounded: an unanswered loopback request would otherwise park inside this
979
940
  // iteration for the rest of the budget, and the deadline above is only re-checked
980
941
  // between iterations. Deliberately no larger than the 250 ms sleep — see
981
942
  // PORT_PROBE_MS.
982
- signal: AbortSignal.timeout(PORT_PROBE_MS),
943
+ signal: AbortSignal.timeout(Math.max(1, Math.min(PORT_PROBE_MS, deadline - Date.now()))),
983
944
  })).json();
984
945
  if (typeof version.webSocketDebuggerUrl === 'string') {
985
946
  const client = new CdpClient(version.webSocketDebuggerUrl);
@@ -987,9 +948,34 @@ export class SystemBrowserViewHost {
987
948
  // answered above — so the browser is listening and this is a handshake, not a
988
949
  // discovery. A handshake that outlives the launch is reported as the timeout it
989
950
  // is, by the same deadline that governs everything else here.
990
- await client.whenReady();
951
+ try {
952
+ await client.whenReady(deadline);
953
+ const info = await client.send('Browser.getVersion', {}, undefined, Math.max(1, deadline - Date.now()));
954
+ if (typeof info.product !== 'string' || info.product === '' || info.product !== version.Browser)
955
+ throw Object.assign(new Error('browser did not acknowledge its identity'), { code: 'BROWSER_LAUNCH_UNACKNOWLEDGED' });
956
+ await client.send('Target.setDiscoverTargets', { discover: true }, undefined, Math.max(1, deadline - Date.now()));
957
+ }
958
+ catch (error) {
959
+ client.close();
960
+ throw error;
961
+ }
991
962
  // Still wanted? A dispose() during the handshake has already killed the
992
963
  // process, so publishing the client would leave a dangling connection.
964
+ if (this.disposed || Date.now() >= deadline) {
965
+ client.close();
966
+ break;
967
+ }
968
+ if (await this.ownership.verify(child)) {
969
+ try {
970
+ const processes = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000);
971
+ if (processes.processInfo?.some(entry => entry.type === 'browser' && entry.id === child.pid)
972
+ && await this.ownership.verify(child)) {
973
+ this.ownedClients.set(client, child);
974
+ this.ownedChildren.add(child);
975
+ }
976
+ }
977
+ catch { /* An unidentified endpoint is borrowed, never owned. */ }
978
+ }
993
979
  if (this.disposed) {
994
980
  client.close();
995
981
  break;
@@ -998,7 +984,9 @@ export class SystemBrowserViewHost {
998
984
  return client;
999
985
  }
1000
986
  }
1001
- catch {
987
+ catch (error) {
988
+ if (error?.code === 'BROWSER_LAUNCH_UNACKNOWLEDGED')
989
+ throw error;
1002
990
  // The file can exist a moment before the port answers; poll again.
1003
991
  }
1004
992
  }
@@ -1018,42 +1006,20 @@ export class SystemBrowserViewHost {
1018
1006
  // which is the same mistake this message was written to correct, pointing the other way.
1019
1007
  const code = child.exitCode;
1020
1008
  const signal = child.signalCode;
1021
- const clean = code === 0 && signal === null;
1022
- // Exit code 0 IS the hand-off: the request went to an instance already holding this profile,
1023
- // so that instance is our browser and it is running right now. Adopting it turns the
1024
- // reported "kill the leftovers by hand, on every restart" into a call that just works.
1025
- //
1026
- // Adopted with a bounded RETRY, because on Windows the launcher stub exits before the browser
1027
- // has written its port file: measured 300 ms to exit against 441 ms for DevToolsActivePort.
1028
- // One attempt therefore read too early and reported "exited immediately after launch" for a
1029
- // browser that was starting normally — reported as issue #33, where the reporter's own
1030
- // retry loop fixed it. 8 s at 250 ms is their measured-working bound and is generous against
1031
- // the ~150 ms gap, without turning a genuinely failed launch into a slow failure.
1032
- if (clean) {
1033
- const deadline = Date.now() + HANDOFF_ADOPT_MS;
1034
- for (;;) {
1035
- const recovered = await this.adoptRunningBrowser('after a hand-off');
1036
- if (recovered !== undefined)
1037
- return recovered;
1038
- if (this.disposed || Date.now() >= deadline)
1039
- break;
1040
- await new Promise(resolve => setTimeout(resolve, PORT_PROBE_MS));
1041
- }
1042
- }
1043
- throw new Error(clean
1044
- ? `dsh-builtin-browser: ${target} exited immediately after launch (exit code 0). `
1045
- + 'That means it handed the request to an instance already using this profile '
1046
- + 'directory and quit — look for a leftover browser process from an earlier run, then retry.'
1047
- : `dsh-builtin-browser: ${target} exited immediately after launch `
1048
- + `(${signal !== null ? `killed by ${signal}` : `exit code ${String(code)}`}), so it did not `
1049
- + 'hand the request anywhere — the browser failed to start rather than deferring to another '
1050
- + 'instance. Check that it can run at all: run it by hand, and look for a crash or a missing '
1051
- + 'dependency rather than a leftover process.');
1009
+ throw new Error(`dsh-builtin-browser: ${target} exited immediately after launch `
1010
+ + `(${signal !== null ? `killed by ${signal}` : `exit code ${String(code)}`}), so it did not `
1011
+ + 'hand the request anywhere — the browser failed to start rather than deferring to another '
1012
+ + 'instance. Check that it can run at all: run it by hand, and look for a crash or a missing '
1013
+ + 'dependency rather than a leftover process.');
1052
1014
  }
1053
1015
  if (stopped === 'released') {
1054
1016
  throw new Error(`dsh-builtin-browser: ${target} was released while it was starting`);
1055
1017
  }
1056
- throw new Error(`dsh-builtin-browser: ${target} did not expose CDP within 30s`);
1018
+ throw new Error(`dsh-builtin-browser: ${target} did not expose CDP within 30s. `
1019
+ + (child.exitCode === 0 && !existsSync(portFile)
1020
+ ? 'The launcher exited successfully without DevToolsActivePort; it may have handed off to an already-running browser without debugging enabled. '
1021
+ : 'The selected profile did not provide a live debugging endpoint. ')
1022
+ + 'No alternative browser profile was substituted.');
1057
1023
  }
1058
1024
  /**
1059
1025
  * Whether this host can back views.
@@ -1073,7 +1039,7 @@ export class SystemBrowserViewHost {
1073
1039
  * Those pages are real: they hold memory and stay until something closes them. Measured on a real
1074
1040
  * window: four pages present while `dsh_browser_list_tabs` reported one.
1075
1041
  *
1076
- * Discovery is already on at connection time (see the blank-page normalisation), so
1042
+ * Discovery is enabled before the connection is published, so
1077
1043
  * `Target.getTargets` also lists pages that existed before this client connected.
1078
1044
  * @returns the browser's pages, or an empty list when it cannot answer.
1079
1045
  */
@@ -1090,11 +1056,20 @@ export class SystemBrowserViewHost {
1090
1056
  * CDP target id, and the two never match. The first version returned everything and relied on the
1091
1057
  * caller to filter, which reported the same page twice.
1092
1058
  *
1093
- * Discovery is already on at connection time (see the blank-page normalisation), so
1059
+ * Discovery is enabled before the connection is published, so
1094
1060
  * `Target.getTargets` also lists pages that existed before this client connected.
1095
1061
  * @returns the browser's pages that are not ours, or an empty list when it cannot answer.
1096
1062
  */
1097
- async listPages() {
1063
+ async listPages(
1064
+ // The installed browser is one shared instance, not a per-conversation
1065
+ // panel, so ownership does not scope its listing.
1066
+ scope, options = {}) {
1067
+ // Looking for a page must never START the human's browser. Before this
1068
+ // check the reference-bar pump called listPages on every tick, whose
1069
+ // ensureClient() launched Edge on its own within seconds of the plugin
1070
+ // loading — measured with no open/navigate call at all.
1071
+ if (options.requireRunning === true && !this.started)
1072
+ return [];
1098
1073
  try {
1099
1074
  const client = await this.ensureClient();
1100
1075
  const listed = await client.send('Target.getTargets', {});
@@ -1104,7 +1079,7 @@ export class SystemBrowserViewHost {
1104
1079
  .filter(entry => !/^edge:\/\/sync-confirmation-dialog(?:\/|$)/.test(entry.url ?? ''))
1105
1080
  .filter(entry => !ours.has(entry.targetId))
1106
1081
  .map(entry => ({
1107
- id: entry.targetId,
1082
+ id: tabWireId({ ...resolveSessionHandle(scope), tab: `page:${entry.targetId}` }),
1108
1083
  url: typeof entry.url === 'string' ? entry.url : '',
1109
1084
  ...typeof entry.title === 'string' && entry.title !== '' ? { title: entry.title } : {},
1110
1085
  }));
@@ -1117,23 +1092,39 @@ export class SystemBrowserViewHost {
1117
1092
  /**
1118
1093
  * Close one page by the target id {@link listPages} reported.
1119
1094
  *
1120
- * `Target.closeTarget` is the browser's own close, so it works for pages this plugin never
1121
- * created. The page may already be gone if the human closed it in the meantime — the caller
1122
- * asked for it to be closed and it is, so that is not an error.
1095
+ * Only targets created by this owner/session on this connection may be closed.
1123
1096
  * @param id - the CDP target id.
1124
1097
  */
1125
- async closePage(id) {
1098
+ async closePage(id, scope = sessionWireId(readTabHandle(id))) {
1099
+ const identity = resolveTabHandle(resolveSessionHandle(scope), id);
1100
+ const view = this.views.get(id);
1101
+ if (view === undefined && !identity.tab.startsWith('page:'))
1102
+ return;
1126
1103
  const client = await this.ensureClient();
1127
- await client.send('Target.closeTarget', { targetId: id }).catch(() => undefined);
1104
+ const targetId = view === undefined ? identity.tab.replace(/^page:/, '') : this.sessions.get(view.session);
1105
+ if (targetId === undefined)
1106
+ throw new Error('dsh-builtin-browser: browser page is stale');
1107
+ const creator = this.createdTargets.get(client)?.get(targetId);
1108
+ if (creator === undefined)
1109
+ throw new Error('dsh-builtin-browser: personal or adopted tabs are detach-only; close the tab in the browser');
1110
+ resolveTabHandle(resolveSessionHandle(scope), creator);
1111
+ const answer = await client.send('Target.closeTarget', { targetId });
1112
+ if (answer.success !== true)
1113
+ throw new Error('dsh-builtin-browser: browser close was not acknowledged');
1114
+ this.createdTargets.get(client)?.delete(targetId);
1128
1115
  }
1129
- createView() {
1130
- const viewId = randomUUID();
1116
+ createView(identity) {
1117
+ const viewId = identity ?? tabWireId({ owner: 'standalone', session: randomUUID(), tab: randomUUID() });
1118
+ readTabHandle(viewId);
1131
1119
  return {
1132
1120
  id: viewId,
1133
1121
  // This is the real browser, not Electron: CDP's JPEG encoder works here, so the
1134
1122
  // provider may pass format and quality through instead of falling back to PNG.
1135
1123
  supportsCdpJpeg: true,
1136
1124
  sendCommand: async (method, params) => {
1125
+ if (method === 'Browser.close' || method === 'Target.closeTarget' || method === 'Page.close') {
1126
+ throw new Error('dsh-builtin-browser: use explicit tab close; browser-wide and unowned-tab closes are not allowed');
1127
+ }
1137
1128
  // A command that never answered is the only signal that a client has wedged — the
1138
1129
  // socket can stay OPEN while nothing comes back, which is the form the reporter saw with
1139
1130
  // a live, healthy-looking Edge. Dropping the client here means the next call starts a new
@@ -1225,20 +1216,17 @@ export class SystemBrowserViewHost {
1225
1216
  },
1226
1217
  };
1227
1218
  }
1228
- destroyView(handle) {
1219
+ destroyView(handle, _options) {
1229
1220
  const cachedView = this.views.get(handle.id);
1230
1221
  this.views.delete(handle.id);
1231
1222
  if (cachedView === undefined)
1232
1223
  return;
1233
1224
  const session = cachedView.session;
1234
- // A session id is not a target id: closing the page needs the target the session
1235
- // was attached to, which is why they are tracked separately.
1236
1225
  const targetId = this.sessions.get(session);
1237
1226
  this.sessions.delete(session);
1238
1227
  // Nothing to close if the browser was never started.
1239
1228
  if (targetId !== undefined && this.client !== undefined) {
1240
- // Best-effort: a page that is already gone is not an error.
1241
- void this.client.send('Target.closeTarget', { targetId }).catch(() => undefined);
1229
+ void cachedView.client.send('Target.detachFromTarget', { sessionId: session }).catch(() => undefined);
1242
1230
  }
1243
1231
  }
1244
1232
  /** Nothing to show: the browser owns its own windows. */
@@ -1283,10 +1271,12 @@ export class SystemBrowserViewHost {
1283
1271
  * view-level concern and not available to the host.
1284
1272
  */
1285
1273
  async focus() {
1286
- try {
1287
- this.child?.kill('SIGCONT');
1274
+ if (this.child && await this.ownership.verify(this.child)) {
1275
+ try {
1276
+ this.child.kill('SIGCONT');
1277
+ }
1278
+ catch { /* Windows has no SIGCONT. */ }
1288
1279
  }
1289
- catch { /* Windows has no SIGCONT; nothing to do */ }
1290
1280
  }
1291
1281
  /**
1292
1282
  * Close the browser we launched, if we ever launched one.
@@ -1302,16 +1292,24 @@ export class SystemBrowserViewHost {
1302
1292
  const client = this.client;
1303
1293
  this.forgetBrowserState();
1304
1294
  this.client = undefined;
1305
- // Ask before killing. `kill()` on Windows is TerminateProcess, which gives the browser no
1306
- // chance to flush its profile — and Chrome records how it ended in that profile, so a
1307
- // hard kill leaves it marked as a crash and the NEXT launch offers to restore a session.
1308
- // That is a visible symptom (an extra window) traced all the way back to this line.
1309
- if (client !== undefined) {
1295
+ const disconnect = async () => {
1296
+ if (!client)
1297
+ return;
1298
+ const owner = this.ownedClients.get(client);
1310
1299
  try {
1311
- void client.send('Browser.close', {}).catch(() => { });
1300
+ if (owner && await this.ownership.verify(owner)) {
1301
+ const result = await client.send('SystemInfo.getProcessInfo', {}, undefined, 1000);
1302
+ if (result.processInfo?.some(entry => entry.type === 'browser' && entry.id === owner.pid)
1303
+ && await this.ownership.verify(owner))
1304
+ await client.send('Browser.close', {}, undefined, 1000);
1305
+ }
1312
1306
  }
1313
- catch { /* already gone */ }
1314
- }
1307
+ catch { /* An unverified endpoint is detach-only. */ }
1308
+ finally {
1309
+ client.close();
1310
+ }
1311
+ };
1312
+ void disconnect();
1315
1313
  // Both the browser we launched and anything that ignored an earlier kill. They hold this
1316
1314
  // profile, so leaving them running means the next launch contends with a browser nobody owns.
1317
1315
  const doomed = [this.child, ...this.stubborn.splice(0)].filter((entry) => entry !== undefined);
@@ -1324,45 +1322,42 @@ export class SystemBrowserViewHost {
1324
1322
  * ending does not wait for this, and the browser — having been asked to close — generally
1325
1323
  * gets there on its own. If it does not, the kill still lands while the process lives.
1326
1324
  */
1327
- const force = () => { try {
1328
- dying.kill();
1329
- }
1330
- catch { /* already gone */ } };
1325
+ const force = () => { void this.stopChild(dying); };
1331
1326
  const timer = setTimeout(force, CLOSE_GRACE_MS);
1332
1327
  timer.unref?.();
1333
1328
  dying.once('exit', () => { clearTimeout(timer); });
1334
1329
  }
1335
1330
  const ephemeral = this.ephemeralDir;
1336
- if (ephemeral !== undefined) {
1337
- const removeEphemeral = () => {
1338
- try {
1339
- rmSync(ephemeral, { recursive: true, force: true });
1340
- }
1341
- catch { /* best effort */ }
1342
- };
1343
- // `this.child` was cleared above; the saved processes still own the profile until
1344
- // their exit events arrive. Deleting it now races Chromium's final cookie flush.
1345
- const live = doomed.filter(child => child.exitCode === null && child.signalCode === null);
1346
- if (live.length > 0) {
1347
- const remaining = new Set(live);
1348
- for (const child of live)
1349
- child.once('exit', () => {
1350
- remaining.delete(child);
1351
- if (remaining.size === 0)
1352
- removeEphemeral();
1353
- });
1354
- }
1355
- else if (client !== undefined) {
1356
- // A handed-off browser has no process handle. Give its graceful close time to
1357
- // finish; abandoned profiles remain eligible for the next startup's safe sweep.
1358
- setTimeout(() => {
1359
- if (!client.isAlive())
1360
- removeEphemeral();
1361
- }, CLOSE_GRACE_MS).unref?.();
1362
- }
1363
- else {
1364
- removeEphemeral();
1365
- }
1331
+ const cleanup = () => {
1332
+ void (async () => {
1333
+ const removeProfile = () => {
1334
+ if (ephemeral !== undefined && doomed.length > 0 && doomed.every(child => this.ownership.ownsDirectory(child, ephemeral) && this.ownedChildren.has(child)
1335
+ && (child.exitCode !== null || child.signalCode !== null)))
1336
+ rmSync(ephemeral, { recursive: true, force: true });
1337
+ };
1338
+ if (this.profileLease !== undefined)
1339
+ await this.profileLease.release(removeProfile);
1340
+ else
1341
+ removeProfile();
1342
+ this.profileLease = undefined;
1343
+ })().catch(error => process.stderr.write(`[dsh-browser] profile release failed: ${String(error)}\n`));
1344
+ };
1345
+ // Saved processes retain the profile until their exit events arrive.
1346
+ const live = doomed.filter(child => child.exitCode === null && child.signalCode === null);
1347
+ if (live.length > 0) {
1348
+ const remaining = new Set(live);
1349
+ for (const child of live)
1350
+ child.once('exit', () => {
1351
+ remaining.delete(child);
1352
+ if (remaining.size === 0)
1353
+ cleanup();
1354
+ });
1355
+ }
1356
+ else if (client !== undefined) {
1357
+ void client.whenClosed().then(cleanup);
1358
+ }
1359
+ else {
1360
+ cleanup();
1366
1361
  }
1367
1362
  }
1368
1363
  /**
@@ -1405,11 +1400,13 @@ export class SystemBrowserViewHost {
1405
1400
  // through the tools. Taking the blank instead makes the page the browser already opened the
1406
1401
  // one the caller gets.
1407
1402
  const adopted = await this.adoptBlankTarget(client);
1408
- const targetId = adopted ?? await this.createTarget(client);
1403
+ const targetId = adopted ?? await this.createTarget(client, viewId);
1409
1404
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
1410
1405
  const sessionId = attached?.sessionId;
1411
1406
  if (typeof sessionId !== 'string')
1412
1407
  throw new Error('dsh-builtin-browser: the browser did not attach to the new page');
1408
+ if (adopted !== undefined)
1409
+ this.rememberTarget(client, targetId, viewId);
1413
1410
  // The session id is what page commands ride; the target id is what closes it.
1414
1411
  this.sessions.set(sessionId, targetId);
1415
1412
  this.views.set(viewId, { session: sessionId, client });
@@ -1436,8 +1433,12 @@ export class SystemBrowserViewHost {
1436
1433
  * @param targetId - the carrier's page id, which for this carrier IS the CDP target id.
1437
1434
  * @returns a handle for that page, in the same shape {@link createView} returns.
1438
1435
  */
1439
- async adoptPage(targetId) {
1440
- const handle = this.createView();
1436
+ async adoptPage(identity, scope = sessionWireId(readTabHandle(identity))) {
1437
+ const tab = resolveTabHandle(resolveSessionHandle(scope), identity).tab;
1438
+ if (!tab.startsWith('page:'))
1439
+ throw new Error('dsh-builtin-browser: invalid carrier page handle');
1440
+ const targetId = tab.slice('page:'.length);
1441
+ const handle = this.createView(identity);
1441
1442
  const client = await this.ensureClient();
1442
1443
  const attached = await client.send('Target.attachToTarget', { targetId, flatten: true });
1443
1444
  const sessionId = attached?.sessionId;
@@ -1454,92 +1455,45 @@ export class SystemBrowserViewHost {
1454
1455
  * Take an unclaimed blank page, if the browser has one to spare.
1455
1456
  *
1456
1457
  * "Unclaimed" is what matters: a blank page the plugin is already driving belongs to a view, and
1457
- * handing the same target to a second view would make two views share one page. The page kept by
1458
- * {@link normalizeBlankPages} is exactly the unclaimed one this is looking for.
1458
+ * handing the same target to a second view would make two views share one page.
1459
1459
  * @param client - the connected browser.
1460
1460
  * @returns the target id to reuse, or undefined when a new page has to be created.
1461
1461
  */
1462
1462
  async adoptBlankTarget(client) {
1463
- try {
1464
- const listed = await client.send('Target.getTargets', {});
1465
- const claimed = new Set(this.sessions.values());
1466
- for (const entry of listed?.targetInfos ?? []) {
1467
- if (entry.type !== 'page' || typeof entry.targetId !== 'string')
1468
- continue;
1469
- if (!isBlankUrl(entry.url))
1470
- continue;
1471
- if (claimed.has(entry.targetId))
1472
- continue;
1473
- return entry.targetId;
1474
- }
1475
- return undefined;
1476
- }
1477
- catch {
1478
- // Discovery is best-effort; creating a page is the behaviour this replaced.
1479
- return undefined;
1463
+ const listed = await client.send('Target.getTargets', {});
1464
+ if (!Array.isArray(listed?.targetInfos))
1465
+ throw new Error('dsh-builtin-browser: the browser did not acknowledge its target inventory');
1466
+ const claimed = new Set(this.sessions.values());
1467
+ for (const entry of listed.targetInfos) {
1468
+ if (entry.type !== 'page' || typeof entry.targetId !== 'string')
1469
+ continue;
1470
+ if (!isBlankUrl(entry.url))
1471
+ continue;
1472
+ if (claimed.has(entry.targetId))
1473
+ continue;
1474
+ return entry.targetId;
1480
1475
  }
1476
+ return undefined;
1481
1477
  }
1482
1478
  /** Create one page, refusing to go on without an id. */
1483
- async createTarget(client) {
1479
+ async createTarget(client, viewId) {
1484
1480
  const created = await client.send('Target.createTarget', {
1485
1481
  url: 'about:blank',
1486
1482
  ...this.isQuiet() ? { background: true } : {},
1487
1483
  });
1488
1484
  const targetId = created?.targetId;
1489
- if (typeof targetId !== 'string')
1485
+ if (typeof targetId !== 'string' || targetId === '')
1490
1486
  throw new Error('dsh-builtin-browser: the browser did not create a page');
1487
+ this.rememberTarget(client, targetId, viewId);
1491
1488
  return targetId;
1492
1489
  }
1493
- /**
1494
- * Collapse the blank pages a freshly started browser comes with down to one.
1495
- *
1496
- * Chrome opens more than one page when it is given a URL on top of its own start page, and this
1497
- * is the browser's behaviour rather than a session restore: measured on a cleanly exited profile
1498
- * as well as a crashed one, both pages appear within a second of launch. There is nothing to
1499
- * configure away — by the time a client can talk to the browser, both already exist.
1500
- *
1501
- * Left alone the surplus page is invisible to the plugin's tab model and therefore unclosable
1502
- * through the tools, so it survives every navigation and accumulates for as long as the window
1503
- * lives. One is kept deliberately: {@link buildSession} adopts it instead of creating a third.
1504
- *
1505
- * `Target.setDiscoverTargets` has to come first. Without it the browser may omit pages that
1506
- * existed before this client connected — which is precisely the page that needs closing, and the
1507
- * reason the first attempt at this fix failed silently.
1508
- * @param client - the connected browser.
1509
- * @returns how many surplus blank pages were closed.
1510
- */
1511
- async normalizeBlankPages(client) {
1512
- try {
1513
- await client.send('Target.setDiscoverTargets', { discover: true });
1514
- const listed = await client.send('Target.getTargets', {});
1515
- const blanks = (listed?.targetInfos ?? []).filter(entry => entry.type === 'page' && typeof entry.targetId === 'string' && isBlankUrl(entry.url));
1516
- const claimed = new Set(this.sessions.values());
1517
- let closed = 0;
1518
- // Keep the first unclaimed blank (that is the one buildSession will adopt) and close the rest.
1519
- let kept = false;
1520
- for (const entry of blanks) {
1521
- const targetId = entry.targetId;
1522
- if (claimed.has(targetId))
1523
- continue;
1524
- if (!kept) {
1525
- kept = true;
1526
- continue;
1527
- }
1528
- try {
1529
- await client.send('Target.closeTarget', { targetId });
1530
- closed += 1;
1531
- }
1532
- catch {
1533
- // It may already be gone; one failure must not stop the rest.
1534
- }
1535
- }
1536
- return closed;
1537
- }
1538
- catch {
1539
- // A browser that will not answer Target commands has a real problem, and the next command
1540
- // will report it. Turning a tidy-up into a functional error here would hide that.
1541
- return 0;
1490
+ rememberTarget(client, targetId, viewId) {
1491
+ let targets = this.createdTargets.get(client);
1492
+ if (!targets) {
1493
+ targets = new Map();
1494
+ this.createdTargets.set(client, targets);
1542
1495
  }
1496
+ targets.set(targetId, viewId);
1543
1497
  }
1544
1498
  /** Views whose session is being created right now, so a second caller waits for the first. */
1545
1499
  sessionBuilding = new Map();
@@ -1548,3 +1502,30 @@ export class SystemBrowserViewHost {
1548
1502
  /** sessionId -> targetId, so a destroyed view can close the right page. */
1549
1503
  sessions = new Map();
1550
1504
  }
1505
+ /**
1506
+ * Probe for a browser the human already has open with a debugging port.
1507
+ *
1508
+ * Chromium exposes CDP only when it was STARTED with --remote-debugging-port, so an already-running Edge
1509
+ * cannot be attached unless it was launched that way. Attaching is therefore opt-in: this probe answers
1510
+ * "is there something to attach to right now", and the caller decides whether to use it.
1511
+ * @param port - the debugging port to try (default 9222).
1512
+ * @param timeoutMs - how long to wait for the endpoint.
1513
+ * @returns the browser banner when an endpoint answers, undefined otherwise.
1514
+ */
1515
+ export async function probeAttach(port = CDP_DEFAULT_ATTACH_PORT, timeoutMs = CDP_ATTACH_PROBE_TIMEOUT_MS) {
1516
+ const controller = new AbortController();
1517
+ const timer = setTimeout(() => { controller.abort(); }, timeoutMs);
1518
+ try {
1519
+ const response = await fetch(cdpVersionUrl(port), { signal: controller.signal });
1520
+ if (!response.ok)
1521
+ return undefined;
1522
+ const body = await response.json();
1523
+ return typeof body.Browser === 'string' ? body.Browser : 'unknown';
1524
+ }
1525
+ catch {
1526
+ return undefined;
1527
+ }
1528
+ finally {
1529
+ clearTimeout(timer);
1530
+ }
1531
+ }