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,174 @@
1
+ import { PERSONAL_PROFILE_DIRS } from '../../assets/browser-products.mjs'
2
+ import { windowsPowerShellPath } from './windows-system.ts'
3
+ import { execFile } from 'node:child_process'
4
+ import { readFile, readlink } from 'node:fs/promises'
5
+ import { realpathSync } from 'node:fs'
6
+ import { homedir } from 'node:os'
7
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
8
+ import { promisify } from 'node:util'
9
+ import type { ChildProcess } from 'node:child_process'
10
+
11
+ export interface ProcessIdentity {
12
+ readonly pid: number
13
+ readonly created: string
14
+ readonly executable: string
15
+ readonly argv: readonly string[]
16
+ }
17
+
18
+ export type ProcessInspector = (pid: number) => Promise<ProcessIdentity | undefined>
19
+ export interface ProcessOwnershipOptions {
20
+ readonly managed: boolean
21
+ readonly inspect?: ProcessInspector
22
+ }
23
+
24
+ const execute = promisify(execFile)
25
+ const windowsInspection = String.raw`
26
+ $ErrorActionPreference='Stop'
27
+ try {
28
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
29
+ $p=Get-CimInstance Win32_Process -Filter ('ProcessId='+$env:DSH_INSPECT_PID)
30
+ if($null -eq $p -or !$p.ExecutablePath -or !$p.CommandLine -or !$p.CreationDate) { throw 'Process identity is unavailable' }
31
+ @{pid=[int]$p.ProcessId;created=$p.CreationDate.ToUniversalTime().Ticks.ToString();
32
+ executable=$p.ExecutablePath;commandLine=$p.CommandLine} | ConvertTo-Json -Compress
33
+ } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 2 }
34
+ `
35
+
36
+ export function parseWindowsCommandLine(command: string): string[] {
37
+ const argv: string[] = []
38
+ let value = '', quoted = false, started = false
39
+ for (let i = 0; i < command.length; i++) {
40
+ const char = command[i]!
41
+ if ((char === ' ' || char === '\t') && !quoted) {
42
+ if (started) argv.push(value)
43
+ value = ''; started = false
44
+ continue
45
+ }
46
+ started = true
47
+ if (char === '\\') {
48
+ let count = 1
49
+ while (command[i + 1] === '\\') { count++; i++ }
50
+ if (command[i + 1] !== '"') { value += '\\'.repeat(count); continue }
51
+ value += '\\'.repeat(Math.floor(count / 2))
52
+ if (count % 2) { value += '"'; i++; continue }
53
+ i++
54
+ } else if (char !== '"') { value += char; continue }
55
+ if (quoted && command[i + 1] === '"') { value += '"'; i++ }
56
+ else quoted = !quoted
57
+ }
58
+ if (started) argv.push(value)
59
+ return argv
60
+ }
61
+
62
+ export async function inspectProcess(pid: number, diagnose?: (reason: string) => void): Promise<ProcessIdentity | undefined> {
63
+ if (!Number.isSafeInteger(pid) || pid <= 0) return undefined
64
+ try {
65
+ if (process.platform === 'win32') {
66
+ const { stdout } = await execute(windowsPowerShellPath(),
67
+ ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(windowsInspection, 'utf16le').toString('base64')],
68
+ { windowsHide: true, timeout: 15000, maxBuffer: 128 * 1024, env: { ...process.env, DSH_INSPECT_PID: String(pid) } })
69
+ const result = JSON.parse(stdout.replace(/^\uFEFF/u, ''))
70
+ if (result.pid !== pid || typeof result.created !== 'string' || !result.created
71
+ || typeof result.executable !== 'string' || !result.executable
72
+ || typeof result.commandLine !== 'string' || !result.commandLine) throw new Error('Windows returned an incomplete or mismatched process identity')
73
+ return { pid, created: result.created, executable: result.executable, argv: parseWindowsCommandLine(result.commandLine) }
74
+ }
75
+ if (process.platform === 'linux') {
76
+ const root = `/proc/${pid}`
77
+ const before = await readFile(`${root}/stat`, 'utf8')
78
+ const executable = await readlink(`${root}/exe`)
79
+ const command = await readFile(`${root}/cmdline`, 'utf8')
80
+ const after = await readFile(`${root}/stat`, 'utf8')
81
+ const start = (stat: string): string | undefined => stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]
82
+ const created = start(before)
83
+ if (!created || created !== start(after) || !command.endsWith('\0')) return undefined
84
+ return { pid, created, executable, argv: command.slice(0, -1).split('\0') }
85
+ }
86
+ } catch (error) { diagnose?.(String(error).slice(-2000)) }
87
+ return undefined
88
+ }
89
+
90
+ function canonical(path: string): string {
91
+ const actual = realpathSync(path)
92
+ return process.platform === 'win32' ? actual.toLowerCase() : actual
93
+ }
94
+
95
+ function personalProfile(path: string): boolean {
96
+ const roots = process.platform === 'win32'
97
+ ? PERSONAL_PROFILE_DIRS.win32
98
+ .map(name => join(process.env.LOCALAPPDATA || homedir(), name))
99
+ : process.platform === 'darwin'
100
+ ? PERSONAL_PROFILE_DIRS.darwin.map(name => join(homedir(), 'Library', 'Application Support', name))
101
+ : PERSONAL_PROFILE_DIRS.linux.map(name => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), name))
102
+ return roots.some(root => {
103
+ let actual: string
104
+ try { actual = canonical(root) } catch { actual = resolve(root); if (process.platform === 'win32') actual = actual.toLowerCase() }
105
+ const child = relative(actual, path)
106
+ return child === '' || (child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child))
107
+ })
108
+ }
109
+
110
+ function dataDirectory(argv: readonly string[]): string | undefined {
111
+ const values: string[] = []
112
+ for (let i = 1; i < argv.length; i++) {
113
+ const arg = argv[i]!
114
+ if (arg === '--user-data-dir') values.push(argv[++i] ?? '')
115
+ else if (arg.startsWith('--user-data-dir=')) values.push(arg.slice('--user-data-dir='.length))
116
+ }
117
+ return values.length === 1 && values[0] !== '' ? values[0] : undefined
118
+ }
119
+
120
+ export class BrowserProcessOwnership {
121
+ private readonly records = new WeakMap<ChildProcess, { identity: ProcessIdentity; executable: string; directory: string }>()
122
+ private readonly executable: string
123
+ private readonly directory: string
124
+ private readonly options: ProcessOwnershipOptions
125
+ constructor(executable: string, directory: string,
126
+ options: ProcessOwnershipOptions) {
127
+ this.executable = executable
128
+ this.directory = directory
129
+ this.options = options
130
+ }
131
+
132
+ private live(child: ChildProcess): boolean {
133
+ return Number.isSafeInteger(child.pid) && child.exitCode === null && child.signalCode === null
134
+ }
135
+
136
+ async capture(child: ChildProcess): Promise<void> {
137
+ if (!this.options.managed || !this.live(child)) return
138
+ try {
139
+ const record = await (this.options.inspect ?? inspectProcess)(child.pid!)
140
+ if (!record || !this.live(child) || record.pid !== child.pid || !record.created) return
141
+ const directory = canonical(this.directory), argument = dataDirectory(record.argv)
142
+ if (!argument || personalProfile(directory) || canonical(argument) !== directory
143
+ || canonical(record.executable) !== canonical(this.executable)) return
144
+ this.records.set(child, { identity: record, executable: canonical(record.executable), directory })
145
+ } catch { /* Fail closed. */ }
146
+ }
147
+
148
+ async verify(child: ChildProcess): Promise<boolean> {
149
+ const captured = this.records.get(child)
150
+ if (!captured || !this.live(child)) return false
151
+ const record = captured.identity
152
+ try {
153
+ const current = await (this.options.inspect ?? inspectProcess)(record.pid)
154
+ return this.live(child) && current !== undefined && current.pid === record.pid
155
+ && current.created === record.created && current.executable === record.executable
156
+ && JSON.stringify(current.argv) === JSON.stringify(record.argv)
157
+ && canonical(current.executable) === captured.executable && canonical(this.executable) === captured.executable
158
+ && canonical(dataDirectory(current.argv) ?? '') === captured.directory && this.ownsDirectory(child)
159
+ } catch { return false }
160
+ }
161
+
162
+ ownsDirectory(child: ChildProcess, path = this.directory): boolean {
163
+ const captured = this.records.get(child)
164
+ try {
165
+ return captured !== undefined && canonical(path) === captured.directory
166
+ && canonical(this.directory) === captured.directory && !personalProfile(captured.directory)
167
+ } catch { return false }
168
+ }
169
+
170
+ async terminate(child: ChildProcess): Promise<boolean> {
171
+ if (!await this.verify(child) || !this.live(child)) return false
172
+ try { return child.kill() } catch { return false }
173
+ }
174
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * One shared definition of process liveness.
3
+ *
4
+ * Signal 0 performs the permission and existence checks and delivers nothing, so it is safe to
5
+ * call on a pid we only read from a file. `EPERM` means the process exists and belongs to
6
+ * someone else, which is still "alive" for the endpoint reader and the profile sweeper alike.
7
+ * @module dsh-browser/browser-electron/process
8
+ */
9
+
10
+ /**
11
+ * Whether a process with this pid exists, without signalling it.
12
+ * @param pid - the process id to test; a non-integer or non-positive value is never alive.
13
+ * @returns whether that process exists.
14
+ */
15
+ export function pidAlive(pid: number): boolean {
16
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
17
+ try {
18
+ process.kill(pid, 0)
19
+ return true
20
+ } catch (error) {
21
+ return (error as NodeJS.ErrnoException)?.code === 'EPERM'
22
+ }
23
+ }
@@ -0,0 +1,187 @@
1
+ import { copyFile, lstat, mkdir, readdir, readFile, readlink, rename, rm, rmdir, stat, symlink, writeFile } from 'node:fs/promises'
2
+ import { dirname, join, resolve } from 'node:path'
3
+ import { installedProfileExtension, MAIN_EXTENSION_NAME } from './profile-extension.ts'
4
+ import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
5
+ import { runProfileCommand } from './profile-command.ts'
6
+
7
+ type Entry = { path: string } & (
8
+ | { kind: 'missing' | 'directory' | 'file' }
9
+ | { kind: 'link'; target: string; type: 'directory' | 'file' }
10
+ )
11
+ interface CheckpointIO {
12
+ readonly copyFile: typeof copyFile
13
+ readonly symlink: typeof symlink
14
+ readonly readdir: typeof readdir
15
+ readonly reconcile: () => Promise<void>
16
+ }
17
+ const pluginPath = join('node_modules', MAIN_EXTENSION_NAME)
18
+ const manifestPaths = ['package.json', 'pnpm-lock.yaml', join('node_modules', '.modules.yaml')]
19
+
20
+ async function describe(profile: string, path: string, packageEntry = false): Promise<Entry> {
21
+ const source = join(profile, path)
22
+ let info
23
+ try { info = await lstat(source) } catch (error) {
24
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { path, kind: 'missing' }
25
+ throw error
26
+ }
27
+ if (info.isSymbolicLink()) {
28
+ const target = await readlink(source)
29
+ let type: 'directory' | 'file' = 'directory'
30
+ if (!packageEntry) {
31
+ try { type = (await stat(source)).isDirectory() ? 'directory' : 'file' } catch (error) {
32
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
33
+ }
34
+ }
35
+ return { path, kind: 'link', target, type }
36
+ }
37
+ return { path, kind: info.isDirectory() ? 'directory' : 'file' }
38
+ }
39
+
40
+ async function inventory(profile: string, io: CheckpointIO): Promise<Entry[]> {
41
+ const entries: Entry[] = []
42
+ for (const name of (await io.readdir(join(profile, 'node_modules'))).sort()) {
43
+ const path = join('node_modules', name), entry = await describe(profile, path, true)
44
+ entries.push(entry)
45
+ if (name.startsWith('@') && entry.kind === 'directory') {
46
+ for (const child of (await io.readdir(join(profile, path))).sort()) entries.push(await describe(profile, join(path, child), true))
47
+ }
48
+ }
49
+ return entries
50
+ }
51
+
52
+ async function saveProfile(profile: string, before: string, io: CheckpointIO): Promise<{ entries: Entry[]; modules: Entry[] }> {
53
+ const entries: Entry[] = []
54
+ const visit = async (path: string, packageEntry = false): Promise<void> => {
55
+ const entry = await describe(profile, path, packageEntry)
56
+ entries.push(entry)
57
+ const destination = join(before, 'files', path)
58
+ if (entry.kind === 'directory') {
59
+ await mkdir(destination, { recursive: true })
60
+ for (const name of (await io.readdir(join(profile, path))).sort()) await visit(join(path, name))
61
+ } else if (entry.kind === 'file') {
62
+ await mkdir(dirname(destination), { recursive: true })
63
+ await io.copyFile(join(profile, path), destination)
64
+ }
65
+ }
66
+ if ((await lstat(join(profile, 'node_modules'))).isSymbolicLink()) throw new Error('REINSTALL_CHECKPOINT_LINKED_MODULES: node_modules must be a real directory')
67
+ const modules = await inventory(profile, io)
68
+ for (const path of manifestPaths) await visit(path)
69
+ await visit(pluginPath, true)
70
+ await writeFile(join(before, 'metadata.json'), JSON.stringify({ version: 2, entries, modules }))
71
+ return { entries, modules }
72
+ }
73
+
74
+ async function restoreLink(profile: string, entry: Extract<Entry, { kind: 'link' }>, io: CheckpointIO): Promise<void> {
75
+ const destination = join(profile, entry.path)
76
+ await mkdir(dirname(destination), { recursive: true })
77
+ try {
78
+ await io.symlink(entry.type === 'directory' && process.platform === 'win32' ? resolve(dirname(destination), entry.target) : entry.target,
79
+ destination, entry.type === 'directory' ? 'junction' : 'file')
80
+ } catch (error) { throw new Error(`REINSTALL_LINK_RESTORE_FAILED: ${entry.type} link ${entry.path}: ${String(error)}`) }
81
+ }
82
+
83
+ async function restoreFiles(profile: string, before: string, entries: readonly Entry[], io: CheckpointIO): Promise<void> {
84
+ const errors: string[] = []
85
+ for (const path of [...manifestPaths, pluginPath]) {
86
+ try { await rm(join(profile, path), { recursive: true, force: true }) } catch (error) { errors.push(`${path}: ${String(error)}`) }
87
+ }
88
+ for (const entry of entries) {
89
+ try {
90
+ const destination = join(profile, entry.path)
91
+ if (entry.kind === 'directory') await mkdir(destination, { recursive: true })
92
+ else if (entry.kind === 'file') {
93
+ await mkdir(dirname(destination), { recursive: true })
94
+ await io.copyFile(join(before, 'files', entry.path), destination)
95
+ } else if (entry.kind === 'link') await restoreLink(profile, entry, io)
96
+ } catch (error) { errors.push(`${entry.path}: ${String(error)}`) }
97
+ }
98
+ if (errors.length > 0) throw new Error(errors.join('; '))
99
+ }
100
+
101
+ function unrelated(entries: readonly Entry[]): string {
102
+ return JSON.stringify(entries.filter(entry => entry.path !== pluginPath && !manifestPaths.includes(entry.path) && entry.path !== join('node_modules', '.ignored')))
103
+ }
104
+
105
+ async function recoverModules(profile: string, modules: readonly Entry[], io: CheckpointIO): Promise<void> {
106
+ const ignored = join('node_modules', '.ignored')
107
+ const recover = async (entry: Entry): Promise<void> => {
108
+ if (entry.path === pluginPath || manifestPaths.includes(entry.path) || entry.path === ignored) return
109
+ const current = await describe(profile, entry.path, true)
110
+ if (JSON.stringify(current) === JSON.stringify(entry)) return
111
+ if (current.kind !== 'missing') throw new Error(`REINSTALL_UNRELATED_PACKAGE_CHANGED: ${entry.path}`)
112
+ if (entry.kind === 'link') await restoreLink(profile, entry, io)
113
+ else {
114
+ const relative = entry.path.slice('node_modules'.length + 1), parts = relative.split(/[\\/]/)
115
+ for (let i = 0; i < parts.length; i++) {
116
+ const parent = await describe(profile, join(ignored, ...parts.slice(0, i)), true)
117
+ if (parent.kind !== 'directory') throw new Error(`REINSTALL_ORPHAN_RECOVERY_FAILED: unsafe or missing .ignored path for ${entry.path}`)
118
+ }
119
+ await mkdir(dirname(join(profile, entry.path)), { recursive: true })
120
+ await rename(join(profile, ignored, relative), join(profile, entry.path))
121
+ for (let i = parts.length - 1; i >= 0; i--) {
122
+ if (i === 0 && modules.some(entry => entry.path === ignored)) break
123
+ try { await rmdir(join(profile, ignored, ...parts.slice(0, i))) } catch (error) {
124
+ if (!['ENOENT', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error
125
+ }
126
+ }
127
+ }
128
+ }
129
+ const errors: string[] = []
130
+ for (const entry of modules) {
131
+ try { await recover(entry) } catch (error) { errors.push(String(error)) }
132
+ }
133
+ if (errors.length > 0) throw new Error(errors.join('; '))
134
+ }
135
+
136
+ async function verifyProfile(home: string): Promise<void> {
137
+ await installedProfileExtension(home)
138
+ const script = `const {createRequire} = await import('node:module'); const {readFile} = await import('node:fs/promises'); await readFile(createRequire(process.argv[1]).resolve(${JSON.stringify(MAIN_EXTENSION_NAME)}));`
139
+ const isElectron = process.versions.electron !== undefined
140
+ const argv = [...(isElectron ? ['--expose-internals'] : []), '--input-type=module', '--eval', script, '--', join(home, 'profiles', 'desktop', 'package.json')]
141
+ const env: NodeJS.ProcessEnv = { ...process.env, ...(isElectron ? { ELECTRON_RUN_AS_NODE: '1', ELECTRON_NO_ASAR: '1' } : {}) }
142
+ const result = await runProfileCommand(process.execPath, argv, env, 10_000)
143
+ if (result.code !== 0) throw new Error(`REINSTALL_PROFILE_RESOLUTION_FAILED: ${result.output}`)
144
+ }
145
+
146
+ /** The checkpoint lives beside the staged worker, never inside the removable profile. */
147
+ export async function withProfileCheckpoint<T>(home: string, directory: string, operation: () => Promise<T>, options: Pick<CheckpointIO, 'reconcile'> & Partial<CheckpointIO>): Promise<T> {
148
+ const profile = join(home, 'profiles', 'desktop'), before = join(directory, 'profile-before')
149
+ const io = { copyFile, symlink, readdir, ...options }
150
+ let saved: { entries: Entry[]; modules: Entry[] }
151
+ let created = false
152
+ try {
153
+ await verifyProfile(home)
154
+ await mkdir(before)
155
+ created = true
156
+ saved = await saveProfile(profile, before, io)
157
+ } catch (error) {
158
+ if (created) await rm(before, { recursive: true, force: true })
159
+ throw new Error(`REINSTALL_CHECKPOINT_FAILED: profile unchanged: ${String(error)}`)
160
+ }
161
+ try {
162
+ const result = await operation()
163
+ if (unrelated(await inventory(profile, io)) !== unrelated(saved.modules)) throw new Error('REINSTALL_UNRELATED_PACKAGES_CHANGED: package manager changed unrelated entries; restoring the profile')
164
+ await verifyProfile(home)
165
+ return result
166
+ } catch (failure) {
167
+ const attempt = async (restore: () => Promise<void>): Promise<string | undefined> => {
168
+ try { await restore(); return undefined } catch (error) { return String(error) }
169
+ }
170
+ let filesError = await attempt(() => restoreFiles(profile, before, saved.entries, io))
171
+ let modulesError = await attempt(() => recoverModules(profile, saved.modules, io))
172
+ let resolutionError = await attempt(() => verifyProfile(home))
173
+ let reconcileError: string | undefined
174
+ if (filesError === undefined && (modulesError !== undefined || resolutionError !== undefined)) {
175
+ reconcileError = await attempt(() => io.reconcile())
176
+ filesError = await attempt(() => restoreFiles(profile, before, saved.entries, io))
177
+ modulesError = await attempt(() => recoverModules(profile, saved.modules, io))
178
+ resolutionError = await attempt(() => verifyProfile(home))
179
+ }
180
+ const restored = filesError === undefined && resolutionError === undefined
181
+ ? 'REINSTALL_PROFILE_RESTORED: profile manifests and plugin restored directly and plugin resolution verified'
182
+ : 'Profile restoration could not be fully verified'
183
+ const errors = [filesError, modulesError, resolutionError, reconcileError].filter(error => error !== undefined)
184
+ if (errors.length > 0) throw new MaintenanceRecoveryError(`REINSTALL_ROLLBACK_FAILED: ${errors.join('; ')}; ${restored}; original failure: ${String(failure)}; checkpoint: ${before}`)
185
+ throw new Error(`${String(failure)}; ${restored}`)
186
+ }
187
+ }
@@ -0,0 +1,47 @@
1
+ import { PROFILE_COMMAND_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
2
+ import { execFile, spawn } from 'node:child_process'
3
+ import { dirname, join } from 'node:path'
4
+ import { windowsPowerShellPath } from './windows-system.ts'
5
+ import { MaintenanceRecoveryError } from './maintenance-lifecycle.ts'
6
+
7
+ /** Terminate the complete package-manager tree before allowing a profile rollback. */
8
+ export async function runProfileCommand(command: string, args: readonly string[], environment: NodeJS.ProcessEnv, timeoutMs = PROFILE_COMMAND_TIMEOUT_MS): Promise<{ code: number; output: string }> {
9
+ const taskkill = process.platform === 'win32' ? join(dirname(dirname(dirname(windowsPowerShellPath(environment)))), 'taskkill.exe') : undefined
10
+ return await new Promise((resolve, reject) => {
11
+ const child = spawn(command, [...args], { env: environment, windowsHide: true, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] })
12
+ let output = '', timedOut = false
13
+ let termination: Promise<void> | undefined
14
+ const append = (data: Buffer): void => { output = (output + data.toString()).slice(-1_048_576) }
15
+ child.stdout.on('data', append)
16
+ child.stderr.on('data', append)
17
+ const timer = setTimeout(() => {
18
+ timedOut = true
19
+ if (child.pid === undefined) return
20
+ const pid = child.pid
21
+ termination = new Promise((done, reject) => {
22
+ if (taskkill !== undefined) {
23
+ execFile(taskkill, ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 10_000 }, error => { if (error) reject(error); else done() })
24
+ } else {
25
+ try { process.kill(-pid, 'SIGKILL'); done() } catch (error) {
26
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') done()
27
+ else reject(error)
28
+ }
29
+ }
30
+ })
31
+ void termination.catch(error => {
32
+ child.unref()
33
+ child.stdout.destroy()
34
+ child.stderr.destroy()
35
+ reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`))
36
+ })
37
+ }, timeoutMs)
38
+ child.once('error', error => { clearTimeout(timer); resolve({ code: 1, output: `REINSTALL_COMMAND_START_FAILED: ${error.message}` }) })
39
+ child.once('close', async (code, signal) => {
40
+ clearTimeout(timer)
41
+ try { await termination } catch (error) {
42
+ reject(new MaintenanceRecoveryError(`${output}\nREINSTALL_ROLLBACK_FAILED: cannot confirm package-manager termination: ${String(error)}`)); return
43
+ }
44
+ resolve({ code: timedOut ? 1 : code ?? 1, output: `${output}${timedOut ? `\nREINSTALL_COMMAND_TIMEOUT: exceeded ${timeoutMs}ms; package-manager tree terminated` : signal === null ? '' : `\nREINSTALL_COMMAND_SIGNAL: ${signal}`}`.trim() })
45
+ })
46
+ })
47
+ }
@@ -0,0 +1,129 @@
1
+ /** Profile-only extension maintenance through the installation's supported dsh plugin command. */
2
+ import { createHash } from 'node:crypto'
3
+ import { constants } from 'node:fs'
4
+ import { readFile, access, stat } from 'node:fs/promises'
5
+ import { join, resolve, isAbsolute } from 'node:path'
6
+ import type { BridgeAction, BridgeActionResult } from './bridge-install.ts'
7
+ import { BridgeConnection } from './bridge-connection.ts'
8
+ import { desktopPaths, readAsarFile } from './desktop-identity.ts'
9
+ import { runProfileCommand } from './profile-command.ts'
10
+
11
+ export const MAIN_EXTENSION_UNSUPPORTED = 'DESKTOP_MAIN_EXTENSION_UNSUPPORTED'
12
+ export const MAIN_EXTENSION_NAME = 'dsh-builtin-browser'
13
+ export interface MainExtensionStatus {
14
+ readonly state: 'not-installed' | 'pending-restart' | 'loaded' | 'failed'
15
+ readonly version?: string
16
+ readonly loadedAt?: string
17
+ readonly code?: string
18
+ }
19
+ export interface InstalledExtension { readonly version: string; readonly build: string }
20
+
21
+ export async function readHostExtensionStatus(home: string): Promise<MainExtensionStatus | undefined> {
22
+ let connection: BridgeConnection | undefined
23
+ try {
24
+ const endpoint = JSON.parse(await readFile(join(home, 'dsh-builtin-browser-bridge.json'), 'utf8')) as { port: number; token: string; pid: number }
25
+ if (!Number.isSafeInteger(endpoint.pid) || endpoint.pid <= 0 || !Number.isInteger(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535
26
+ || typeof endpoint.token !== 'string' || endpoint.token === '') return undefined
27
+ process.kill(endpoint.pid, 0)
28
+ connection = new BridgeConnection(endpoint)
29
+ const answer = await connection.call({ op: 'version' }, 1_000)
30
+ const status = answer.mainExtension as MainExtensionStatus | undefined
31
+ if (answer.ok !== true || answer.homeId !== extensionHomeId(home) || status === null || typeof status !== 'object'
32
+ || !['not-installed', 'pending-restart', 'loaded', 'failed'].includes(status.state)) return undefined
33
+ return { state: status.state, ...typeof status.version === 'string' ? { version: status.version } : {},
34
+ ...typeof status.loadedAt === 'string' ? { loadedAt: status.loadedAt } : {}, ...typeof status.code === 'string' ? { code: status.code } : {} }
35
+ } catch { return undefined } finally { connection?.close() }
36
+ }
37
+
38
+ export function extensionHomeId(home: string): string {
39
+ const path = resolve(home)
40
+ return createHash('sha256').update(process.platform === 'win32' ? path.toLowerCase() : path).digest('hex')
41
+ }
42
+
43
+ export async function installedProfileExtension(home: string): Promise<InstalledExtension> {
44
+ const directory = join(home, 'profiles', 'desktop', 'node_modules', MAIN_EXTENSION_NAME)
45
+ const pkg = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')) as { name?: unknown; version?: unknown; dsh?: { desktop?: { main?: unknown } } }
46
+ if (pkg.name !== MAIN_EXTENSION_NAME || typeof pkg.version !== 'string' || pkg.dsh?.desktop?.main !== './desktop-bridge/main.mjs') {
47
+ throw new Error('EXTENSION_ENTRY_INVALID')
48
+ }
49
+ const build = createHash('sha256').update(await readFile(join(directory, 'desktop-bridge/plugin-browser-bridge.js'))).digest('hex')
50
+ return { version: pkg.version, build }
51
+ }
52
+
53
+ export async function profileDependencySpec(home: string): Promise<string> {
54
+ const manifest = JSON.parse(await readFile(join(home, 'profiles', 'desktop', 'package.json'), 'utf8')) as { dependencies?: Record<string, unknown> }
55
+ const dependency = manifest.dependencies?.[MAIN_EXTENSION_NAME]
56
+ if (typeof dependency !== 'string' || dependency.trim() === '') throw Object.assign(new Error('The Desktop profile has no dsh-builtin-browser dependency to reinstall.'), { code: 'REINSTALL_DEPENDENCY_MISSING' })
57
+ return dependency
58
+ }
59
+
60
+ export async function profileRuntimeDirectory(root: string): Promise<string> {
61
+ const directory = join(desktopPaths(root).resources, 'runtime')
62
+ const pnpm = join(directory, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs')
63
+ try {
64
+ await access(pnpm, constants.R_OK)
65
+ if (!(await stat(pnpm)).isFile()) throw new Error('Not a regular file')
66
+ } catch {
67
+ throw Object.assign(new Error(`The Desktop bundled package manager is missing or unreadable: ${pnpm}`), { code: 'REINSTALL_RUNTIME_MISSING' })
68
+ }
69
+ return directory
70
+ }
71
+
72
+ export async function profileExtensionCommand(action: BridgeAction, root: string, home: string, capturedSpec?: string): Promise<readonly string[]> {
73
+ if (!isAbsolute(root) || !isAbsolute(home)) throw new Error('invalid Desktop profile location')
74
+ const profile = join(home, 'profiles', 'desktop')
75
+ const dependency = action === 'install' ? capturedSpec ?? await profileDependencySpec(home) : undefined
76
+ if (action === 'install' && (typeof dependency !== 'string' || dependency.trim() === '')) throw new Error('REINSTALL_DEPENDENCY_MISSING')
77
+ const resources = desktopPaths(root).resources
78
+ const entry = 'dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/cli.js'
79
+ const archive = join(resources, 'app.asar')
80
+ let cli = join(archive, entry)
81
+ if (readAsarFile(archive, entry) === undefined) {
82
+ try { await access(cli) } catch { cli = join(resources, 'app', entry); await access(cli) }
83
+ }
84
+ const args = [cli, 'plugin', '--profile', 'desktop']
85
+ if (action === 'uninstall') return [...args, 'remove', MAIN_EXTENSION_NAME]
86
+ let spec = String(dependency)
87
+ if (/^(?:file|link):/.test(spec)) {
88
+ const colon = spec.indexOf(':')
89
+ spec = spec.slice(0, colon + 1) + resolve(profile, spec.slice(colon + 1))
90
+ }
91
+ return [...args, 'add', /^(?:file|link):/.test(spec) ? spec : `${MAIN_EXTENSION_NAME}@${spec}`]
92
+ }
93
+
94
+ export async function repairProfileExtension(action: BridgeAction, root: string, home: string, run: (
95
+ command: string, argv: readonly string[], environment: NodeJS.ProcessEnv, timeout?: number,
96
+ ) => Promise<{ code: number; output: string }>, capturedSpec?: string): Promise<BridgeActionResult> {
97
+ const support = await profileRuntimeDirectory(root)
98
+ const invocation = await profileExtensionCommand(action, root, home, capturedSpec)
99
+ const packedCli = invocation[0].replaceAll('\\', '/').includes('/app.asar/')
100
+ const script = `process.env.ELECTRON_NO_ASAR = '1'; import { dirname, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; const { runDesktopCli } = await import(pathToFileURL(process.argv[1]).href); const support = ${JSON.stringify(support)}; await (runDesktopCli.length >= 2 ? runDesktopCli(resolve(dirname(process.argv[1]), '../../../..'), support) : runDesktopCli(support));`
101
+ const argv = ['--expose-internals', '--input-type=module', '--eval', script, '--', ...invocation]
102
+ const command = desktopPaths(root).executable
103
+ const environment = profileEnvironment(home, packedCli)
104
+ const result = await run(command, argv, environment, 300_000)
105
+ return { ok: result.code === 0, code: result.code, output: result.output.slice(-20_000), command: [command, ...argv].map(value => JSON.stringify(value)).join(' '), restarted: false }
106
+ }
107
+
108
+ function profileEnvironment(home: string, packedCli = false): NodeJS.ProcessEnv {
109
+ const env: NodeJS.ProcessEnv = { ...process.env }
110
+ for (const key of Object.keys(env)) {
111
+ if (key.toUpperCase() === 'ELECTRON_NO_ASAR') delete env[key]
112
+ }
113
+ // `CI` makes pnpm non-interactive. Without it a reconcile answered a supply-chain prompt with
114
+ // "?" and exited non-zero, the maintenance transaction rolled back, and the bridge stayed
115
+ // "已失效" — a repair path that could not repair. The reporter is pinned for the same reason:
116
+ // an unattended command must produce a log, not a question.
117
+ return { ...env, DSH_HOME: home, ELECTRON_RUN_AS_NODE: '1', ...(packedCli ? {} : { ELECTRON_NO_ASAR: '1' }),
118
+ CI: 'true', npm_config_reporter: 'append-only', PNPM_CONFIG_REPORTER: 'append-only',
119
+ npm_config_ignore_scripts: 'true', npm_config_auto_install_peers: 'false',
120
+ PNPM_CONFIG_IGNORE_SCRIPTS: 'true', PNPM_CONFIG_AUTO_INSTALL_PEERS: 'false' }
121
+ }
122
+
123
+ /** Best-effort reconciliation after the checkpoint has restored the profile files and plugin. */
124
+ export async function reconcileProfile(root: string, home: string, run: typeof runProfileCommand = runProfileCommand): Promise<void> {
125
+ const runtime = await profileRuntimeDirectory(root)
126
+ const result = await run(desktopPaths(root).executable, ['--expose-internals', join(runtime, 'primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.mjs'),
127
+ '--dir', join(home, 'profiles', 'desktop'), 'install', '--frozen-lockfile', '--ignore-scripts', '--config.auto-install-peers=false'], profileEnvironment(home), 300_000)
128
+ if (result.code !== 0) throw new Error(`REINSTALL_RECONCILE_FAILED: ${result.output}`)
129
+ }