dsh-builtin-browser 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/README.en.md +89 -0
  2. package/browser-extension/constants.mjs +20 -0
  3. package/browser-extension/controller.mjs +293 -0
  4. package/browser-extension/locales.mjs +15 -0
  5. package/browser-extension/manifest.json +12 -0
  6. package/browser-extension/options.html +14 -0
  7. package/browser-extension/options.mjs +9 -0
  8. package/browser-extension/permission-guard.mjs +13 -0
  9. package/browser-extension/worker.mjs +74 -0
  10. package/package.json +20 -2
  11. package/scripts/build-client.mjs +305 -0
  12. package/scripts/build.mjs +69 -0
  13. package/scripts/bundle-host.mjs +28 -0
  14. package/scripts/fix-exports.mjs +40 -0
  15. package/scripts/install-electron.mjs +101 -0
  16. package/scripts/pack.mjs +99 -0
  17. package/scripts/publish-manifest.mjs +56 -0
  18. package/scripts/verify-exports.mjs +58 -0
  19. package/scripts/verify-preview-sdk.mjs +93 -0
  20. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  21. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  22. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  23. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  24. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  25. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  26. package/skills/dsh-debug-host/SKILL.md +56 -0
  27. package/skills/dsh-debug-self/SKILL.md +50 -0
  28. package/src/bridge-compatibility.ts +39 -0
  29. package/src/browser/anti-bot.ts +251 -0
  30. package/src/browser/deep-dom.ts +40 -0
  31. package/src/browser/handles.ts +89 -0
  32. package/src/browser/runtime.ts +578 -0
  33. package/src/browser/takeover-target.ts +45 -0
  34. package/src/browser/types.ts +870 -0
  35. package/src/browser-electron/authenticated-route.ts +109 -0
  36. package/src/browser-electron/automatic-maintenance.ts +736 -0
  37. package/src/browser-electron/bridge-auto.ts +159 -0
  38. package/src/browser-electron/bridge-connection.ts +386 -0
  39. package/src/browser-electron/bridge-endpoint.ts +129 -0
  40. package/src/browser-electron/bridge-install.ts +290 -0
  41. package/src/browser-electron/bridge-maintenance.ts +189 -0
  42. package/src/browser-electron/bridge-status.ts +386 -0
  43. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  44. package/src/browser-electron/desktop-identity.ts +353 -0
  45. package/src/browser-electron/desktop-shell.ts +100 -0
  46. package/src/browser-electron/document-readiness.ts +45 -0
  47. package/src/browser-electron/electron-provision.ts +347 -0
  48. package/src/browser-electron/entry.ts +1378 -0
  49. package/src/browser-electron/ephemeral-profile.ts +189 -0
  50. package/src/browser-electron/extension-browser.ts +230 -0
  51. package/src/browser-electron/extension-setup.ts +67 -0
  52. package/src/browser-electron/file-write.ts +31 -0
  53. package/src/browser-electron/foreground-watch.ts +142 -0
  54. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  55. package/src/browser-electron/guest-cookie-store.ts +59 -0
  56. package/src/browser-electron/guest-css-runtime.ts +76 -0
  57. package/src/browser-electron/guest-css.ts +68 -0
  58. package/src/browser-electron/guest-route.ts +716 -0
  59. package/src/browser-electron/guest-runtime.ts +408 -0
  60. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  61. package/src/browser-electron/guest-storage.ts +120 -0
  62. package/src/browser-electron/history-store.ts +224 -0
  63. package/src/browser-electron/host-main.ts +1385 -0
  64. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  65. package/src/browser-electron/http-body.ts +65 -0
  66. package/src/browser-electron/json-reply.ts +47 -0
  67. package/src/browser-electron/maintenance-broker.ts +166 -0
  68. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  69. package/src/browser-electron/maintenance-route.ts +68 -0
  70. package/src/browser-electron/missing-system-browser.ts +114 -0
  71. package/src/browser-electron/open-slot.ts +49 -0
  72. package/src/browser-electron/paths.ts +25 -0
  73. package/src/browser-electron/preferred-browser.ts +130 -0
  74. package/src/browser-electron/preview-route.ts +215 -0
  75. package/src/browser-electron/process-ownership.ts +174 -0
  76. package/src/browser-electron/process.ts +23 -0
  77. package/src/browser-electron/profile-checkpoint.ts +187 -0
  78. package/src/browser-electron/profile-command.ts +47 -0
  79. package/src/browser-electron/profile-extension.ts +129 -0
  80. package/src/browser-electron/profile-lease.ts +211 -0
  81. package/src/browser-electron/profile-residue.ts +49 -0
  82. package/src/browser-electron/provider-core.ts +1107 -0
  83. package/src/browser-electron/provider-interaction.ts +1034 -0
  84. package/src/browser-electron/provider-media.ts +589 -0
  85. package/src/browser-electron/provider-navigation.ts +323 -0
  86. package/src/browser-electron/provider-observation.ts +664 -0
  87. package/src/browser-electron/provider-tabs.ts +372 -0
  88. package/src/browser-electron/provider.ts +666 -0
  89. package/src/browser-electron/reference-route.ts +598 -0
  90. package/src/browser-electron/remote-host.ts +1538 -0
  91. package/src/browser-electron/rpc-input.ts +13 -0
  92. package/src/browser-electron/rpc-ops.ts +41 -0
  93. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  94. package/src/browser-electron/runtime-route.ts +105 -0
  95. package/src/browser-electron/runtime-status.ts +309 -0
  96. package/src/browser-electron/settings-route.ts +64 -0
  97. package/src/browser-electron/settings-store.ts +593 -0
  98. package/src/browser-electron/shortcuts-route.ts +112 -0
  99. package/src/browser-electron/sidebar-only-host.ts +300 -0
  100. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  101. package/src/browser-electron/system-browser.ts +1850 -0
  102. package/src/browser-electron/tauri-host.ts +194 -0
  103. package/src/browser-electron/timing.ts +16 -0
  104. package/src/browser-electron/virtual-cursor.ts +162 -0
  105. package/src/browser-electron/windows-system.ts +24 -0
  106. package/src/browser-reference/delivery.ts +384 -0
  107. package/src/browser-reference/entry.ts +631 -0
  108. package/src/browser-reference/export.ts +339 -0
  109. package/src/browser-reference/import.ts +303 -0
  110. package/src/browser-reference/page-script.ts +1537 -0
  111. package/src/browser-reference/service.ts +1346 -0
  112. package/src/browser-reference/store.ts +172 -0
  113. package/src/browser-reference/text-quote.ts +219 -0
  114. package/src/browser-reference/types.ts +195 -0
  115. package/src/browser-reference/visible.ts +367 -0
  116. package/src/browser-reference/web-sources.ts +106 -0
  117. package/src/client/apply-guard.ts +22 -0
  118. package/src/client/browser/BrowserController.ts +693 -0
  119. package/src/client/browser/BrowserFrame.ts +78 -0
  120. package/src/client/browser/BrowserNavigation.ts +169 -0
  121. package/src/client/browser/BrowserPage.ts +23 -0
  122. package/src/client/browser/BrowserPersistence.ts +44 -0
  123. package/src/client/browser/IframeImpl.ts +182 -0
  124. package/src/client/browser/child-tabs.ts +14 -0
  125. package/src/client/browser/frame-history.ts +125 -0
  126. package/src/client/browser/frame-state.ts +27 -0
  127. package/src/client/browser/iframe-reference.ts +67 -0
  128. package/src/client/browser/initialization.ts +262 -0
  129. package/src/client/browser/omnibox.ts +243 -0
  130. package/src/client/browser/store.ts +38 -0
  131. package/src/client/browser/takeover-channel.ts +72 -0
  132. package/src/client/browser/url.ts +46 -0
  133. package/src/client/browser/web-reference-source.ts +56 -0
  134. package/src/client/css-modules.d.ts +4 -0
  135. package/src/client/definition.tsx +36 -0
  136. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  137. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  138. package/src/client/electron/NativeChildPresentation.ts +53 -0
  139. package/src/client/electron/NativeViewPage.ts +265 -0
  140. package/src/client/electron/pages.ts +23 -0
  141. package/src/client/electron/reference-overlay.ts +53 -0
  142. package/src/client/electron/workspace.ts +33 -0
  143. package/src/client/index.ts +333 -0
  144. package/src/client/locales.ts +860 -0
  145. package/src/client/pages.ts +28 -0
  146. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  147. package/src/client/reference/client/draft-reference.ts +167 -0
  148. package/src/client/reference/client/index.ts +7 -0
  149. package/src/client/reference/client/ordered-submission.ts +108 -0
  150. package/src/client/reference/client/pending-delivery.ts +216 -0
  151. package/src/client/reference/client/plugin.ts +208 -0
  152. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  153. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  154. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  155. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  156. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  157. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  158. package/src/client/reference/client/production/assembly.ts +447 -0
  159. package/src/client/reference/client/production/asset-store.ts +144 -0
  160. package/src/client/reference/client/production/availability.ts +72 -0
  161. package/src/client/reference/client/production/bytes.ts +36 -0
  162. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  163. package/src/client/reference/client/production/delivery-client.ts +211 -0
  164. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  165. package/src/client/reference/client/production/http-transport.ts +212 -0
  166. package/src/client/reference/client/production/production-submission.ts +70 -0
  167. package/src/client/reference/client/production/protocol.ts +234 -0
  168. package/src/client/reference/client/production/reference-card.ts +240 -0
  169. package/src/client/reference/client/production/reference-labels.ts +29 -0
  170. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  171. package/src/client/reference/client/production/reveal.ts +215 -0
  172. package/src/client/reference/client/production/runtime.ts +1056 -0
  173. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  174. package/src/client/reference/client/production/source-marker.ts +99 -0
  175. package/src/client/reference/client/production/source-opener.ts +55 -0
  176. package/src/client/reference/client/production/styles.ts +104 -0
  177. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  178. package/src/client/reference/client/reveal.ts +109 -0
  179. package/src/client/reference/client/scheme.ts +114 -0
  180. package/src/client/reference/client/session-schedule.ts +36 -0
  181. package/src/client/reference/client/types.ts +168 -0
  182. package/src/client/reference/css-modules.d.ts +4 -0
  183. package/src/client/reference/index.ts +11 -0
  184. package/src/client/reference-capture-owner.ts +162 -0
  185. package/src/client/reference-intents.ts +36 -0
  186. package/src/client/settings/index.ts +42 -0
  187. package/src/client/settings/mount-guard.ts +31 -0
  188. package/src/client/settings/panel.ts +2768 -0
  189. package/src/client/shortcut-open.ts +30 -0
  190. package/src/client/startpage/binding.ts +99 -0
  191. package/src/client/startpage/controller.ts +300 -0
  192. package/src/client/startpage/model.ts +279 -0
  193. package/src/client/view/Browser.module.css +751 -0
  194. package/src/client/view/BrowserBody.tsx +315 -0
  195. package/src/client/view/BrowserPresentation.ts +9 -0
  196. package/src/client/view/BrowserTitle.tsx +17 -0
  197. package/src/client/view/IframePresentation.ts +365 -0
  198. package/src/client/view/StartPage.tsx +598 -0
  199. package/src/client/view/TakeoverBanner.tsx +21 -0
  200. package/src/compat/host-features.ts +92 -0
  201. package/src/index.ts +110 -0
  202. package/src/reference-owner.ts +5 -0
  203. package/src/reference-page.ts +9 -0
  204. package/src/reference-source.ts +3 -0
  205. package/src/reference-text.ts +219 -0
  206. package/src/startpage-settings.ts +103 -0
  207. package/src/startpage.ts +71 -0
  208. package/src/takeover-protocol.ts +28 -0
  209. package/src/tool-browser/block-recovery.ts +85 -0
  210. package/src/tool-browser/code-tool.ts +555 -0
  211. package/src/tool-browser/code-worker.ts +725 -0
  212. package/src/tool-browser/element-fields.ts +167 -0
  213. package/src/tool-browser/errors.ts +40 -0
  214. package/src/tool-browser/index.ts +265 -0
  215. package/src/tool-browser/page-probe.ts +675 -0
  216. package/src/tool-browser/panel-page.ts +126 -0
  217. package/src/tool-browser/probe-client.ts +183 -0
  218. package/src/tool-browser/screenshot-annotations.ts +131 -0
  219. package/src/tool-browser/screenshot-image.ts +49 -0
  220. package/src/tool-browser/state.ts +375 -0
  221. package/src/tool-browser/takeover.ts +199 -0
  222. package/src/tool-browser/tools-debug.ts +806 -0
  223. package/src/tool-browser/tools-interaction.ts +956 -0
  224. package/src/tool-browser/tools-navigation.ts +786 -0
  225. package/src/tool-browser/tools-observation.ts +474 -0
  226. package/src/tool-browser/tools-reference.ts +294 -0
  227. package/src/types/electron-shim.d.ts +144 -0
  228. package/src/types.ts +85 -0
  229. package/src/web-guest.ts +35 -0
  230. package/tools/accept-desktop.mjs +148 -0
  231. package/dist/client.d.cts +0 -516
  232. package/dist/client.d.mts +0 -516
  233. package/dist/index.cjs +0 -92
  234. package/dist/index.d.mts +0 -2960
  235. package/dist/index.mjs +0 -24
  236. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  237. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  238. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  239. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  240. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  241. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  242. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  243. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  244. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  245. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  246. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  247. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  248. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  249. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  250. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  256. package/dsh-host-patch/sources/manifest.json +0 -218
  257. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  258. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  259. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  260. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  261. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  262. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  263. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  264. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  265. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  266. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  267. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  268. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  269. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  293. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,593 @@
1
+ import { BROWSER_PROFILE_DIR } from '../../assets/browser-policy.mjs'
2
+ /**
3
+ * Plugin-owned settings document — the switches the browser settings panel
4
+ * exposes, stored next to the browsing history so both follow the same rules:
5
+ * they survive the browser process and DSH restarts.
6
+ *
7
+ * Every field is optional on disk and falls back to a default, so a hand-edited
8
+ * or older file never breaks startup; an unreadable document refuses capability
9
+ * gates while retaining the defaults for presentation and other conveniences.
10
+ * @module dsh-browser/browser-electron/settings-store
11
+ */
12
+
13
+ import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
14
+ import { dirname, join } from 'node:path'
15
+ import { dshHome } from './paths.ts'
16
+ import type { BrowserChannel } from './system-browser.ts'
17
+
18
+ /** Vision/operation strategy the provider prefers when the model can see. */
19
+ export type VisionStrategy = 'auto' | 'nonVisual'
20
+
21
+ /**
22
+ * Whether a launched browser gets a window.
23
+ *
24
+ * Split from {@link VisionStrategy} because these answer different questions: that one is how the
25
+ * agent examines a page, this one is whether the browser has anywhere to draw.
26
+ */
27
+ export type HeadlessMode = 'auto' | 'headless' | 'windowed'
28
+
29
+ /** Every value {@link HeadlessMode} accepts, for validation and the settings UI. */
30
+ export const HEADLESS_MODES = ['auto', 'headless', 'windowed'] as const
31
+
32
+ /**
33
+ * Which profile the browser runs on.
34
+ *
35
+ * `plugin` 是插件自己的目录(默认):不碰用户的窗口、书签与登录态,也不会因为用户开着浏览器而启动失败。
36
+ * `user` 复用用户自己的 profile,登录态天然可用,但要求用户的浏览器先关掉——否则 Chromium 以
37
+ * exit 21(`PROFILE_IN_USE`)退出。
38
+ */
39
+ export type SystemProfile = 'user' | 'plugin'
40
+
41
+ /** Every value {@link SystemProfile} accepts, for validation and the settings UI. */
42
+ export const SYSTEM_PROFILES = ['user', 'plugin'] as const
43
+
44
+ /** The full settings document, with every field resolved. */
45
+ export interface BrowserSettings {
46
+ /** Persistent browsing history (visited pages). */
47
+ readonly history: {
48
+ readonly enabled: boolean
49
+ readonly maxEntries: number
50
+ readonly maxAgeDays: number
51
+ }
52
+ /** Login-state retention: cookies and the browser profile. */
53
+ readonly cookies: {
54
+ readonly persist: boolean
55
+ }
56
+ /** Presentation behaviour. */
57
+ readonly ui: {
58
+ /** Auto-expand the side panel once per task, then leave the user alone. */
59
+ readonly autoExpandOnce: boolean
60
+ /** Release the browser when its session ends, instead of waiting for a close. */
61
+ readonly closeWithSession: boolean
62
+ /** Show the synthetic cursor/click feedback while the agent operates. */
63
+ readonly virtualCursor: boolean
64
+ /**
65
+ * Quiet mode: drive the page without taking over the screen.
66
+ *
67
+ * Off (the default) keeps the contract this plugin is built on — human and agent share one
68
+ * window, so an operation raises it and the user can see what is being driven. On, the
69
+ * carrier never activates the application and never steals keyboard focus:
70
+ * - screenshots of a minimized or hidden window go through CDP `Page.captureScreenshot`
71
+ * instead of `capturePage()`, so grabbing an image stops being a reason to show a window;
72
+ * - navigation and tab switching only change which view is visible INSIDE the window; a
73
+ * minimized window stays minimized;
74
+ * - Installed Chrome / Edge opens its first window off-screen in the normal state (a minimized
75
+ * window would stop rAF); agent navigation and tab switches never move it; the user selecting
76
+ * its tab, or a takeover, moves it onto the primary display once without activating it;
77
+ * - synthesized input still needs a display surface (Chromium drops `Input.*` for a view
78
+ * without one), so that one barrier may restore a minimized window — with
79
+ * `showInactive()`, which shows it without becoming the key window, and without
80
+ * `moveTop()`.
81
+ *
82
+ * Reported as issue #35: a minimized browser window was restored and focused by the next
83
+ * screenshot or click, pulling the user out of whatever they were typing in.
84
+ */
85
+ readonly quiet: boolean
86
+ }
87
+ /** Visual vs non-visual operation strategy. */
88
+ readonly vision: {
89
+ readonly strategy: VisionStrategy
90
+ }
91
+ /** Which browser binary carries the agent's pages. */
92
+ readonly browser: {
93
+ readonly channel: BrowserChannel
94
+ /**
95
+ * Whether the browser gets a window.
96
+ *
97
+ * `auto` (the default) launches headless when the process has no display — no `DISPLAY` and no
98
+ * `WAYLAND_DISPLAY` — and with a window otherwise. That combination is what makes the plugin
99
+ * work under systemd, in a container, or on an SSH-only server while leaving desktop users
100
+ * with the visible window they expect. `true` forces headless (CI, screenshot-only servers);
101
+ * `false` forces a window, so a misconfigured display fails loudly instead of silently
102
+ * degrading into a browser nobody can see.
103
+ *
104
+ * Reported as issue #32: as a systemd service there is no display, Chromium exits with
105
+ * "could not connect to display", and every `dsh_browser_*` call failed with "exited
106
+ * immediately after launch".
107
+ */
108
+ readonly headless: HeadlessMode
109
+ /**
110
+ * `plugin` (default) launches a separate DSH-owned persistent profile.
111
+ * Explicit `user` attaches to the running, paired extension profile; never launches it.
112
+ */
113
+ readonly systemProfile: SystemProfile
114
+ }
115
+ /** Whether the agent may read cookies / export login state. */
116
+ readonly credentials: {
117
+ readonly allowRead: boolean
118
+ }
119
+ /**
120
+ * Live view of the browser for a remote operator (issue #34).
121
+ *
122
+ * OFF by default, and that default is the feature's main safety property: a live browser frame can
123
+ * contain a CAPTCHA, an account name, or logged-in content, so nobody should be able to watch
124
+ * without the host having said yes first. The remote side also cannot turn it on: this file is
125
+ * written through the plugin's own settings route, which admits only same-origin requests from the
126
+ * host's own UI, and the frame endpoint refuses everything when this is false.
127
+ */
128
+ readonly remoteView: {
129
+ /** Serve browser frames to a remote viewer. */
130
+ readonly enabled: boolean
131
+ }
132
+ /**
133
+ * What the agent is allowed to DO, as opposed to what it may look at.
134
+ *
135
+ * These are OPERATOR switches: the settings panel is not reachable from the model, so a
136
+ * value here refuses whatever the model asks for, and no tool can lift it. That is what
137
+ * separates them from `dsh_browser_restrict`, which is the model's own soft guardrail. All
138
+ * three default to on, which is the documented out-of-the-box behaviour.
139
+ */
140
+ readonly actions: {
141
+ /** Run arbitrary page scripts in the active tab (`dsh_browser_execute`). */
142
+ readonly allowExecute: boolean
143
+ /** Download a URL to disk (`dsh_browser_download`). */
144
+ readonly allowDownload: boolean
145
+ /** Write cookies — importing login state (`dsh_browser_auth` restore). */
146
+ readonly allowCredentialWrite: boolean
147
+ }
148
+ /**
149
+ * Where a downloaded file goes after it lands on disk.
150
+ *
151
+ * An ATTRIBUTE of a download, not a new concept: an empty `tool` means the behaviour is exactly
152
+ * what it was before this existed. The user owns the field, can point it at any MCP tool that
153
+ * takes a path (Feishu drive, Baidu Netdisk), and can empty it again at any time.
154
+ */
155
+ /**
156
+ * Desktop bridge handled without asking.
157
+ *
158
+ * Historical automatic-install preference retained when reading existing settings documents.
159
+ * Runtime automatic installation is disabled; bridge maintenance is an explicit action after
160
+ * DSH Desktop is closed, even when an older document contains autoInstall=true.
161
+ */
162
+ readonly bridge: {
163
+ /** Legacy preference; it does not trigger installation at runtime. Default false. */
164
+ readonly autoInstall: boolean
165
+ }
166
+ readonly delivery: {
167
+ /** MCP tool that receives the saved file. Empty = save locally and stop there. */
168
+ readonly tool: string
169
+ /** Flat argument template; {path}, {name} and {size} are substituted into string values. */
170
+ readonly args: Readonly<Record<string, string>>
171
+ /** `keep-local` reports both outcomes; `stop` reports the handoff failure as the result. */
172
+ readonly onFail: 'keep-local' | 'stop'
173
+ /** Per-site override: page host → tool name. */
174
+ readonly sites: Readonly<Record<string, string>>
175
+ }
176
+ }
177
+
178
+ /** Defaults for every switch: the documented out-of-the-box behaviour. */
179
+ export const DEFAULT_SETTINGS: BrowserSettings = {
180
+ history: { enabled: true, maxEntries: 5_000, maxAgeDays: 90 },
181
+ cookies: { persist: true },
182
+ ui: { autoExpandOnce: true, closeWithSession: false, virtualCursor: true, quiet: false },
183
+ vision: { strategy: 'auto' },
184
+ // External browsers require an explicit choice; automatic modes never open native windows.
185
+ browser: { channel: 'sidebar', headless: 'auto', systemProfile: 'plugin' },
186
+ credentials: { allowRead: true },
187
+ // Off unless the host turns it on. A frame can show a CAPTCHA, an account name, or logged-in
188
+ // content, so watching is an explicit decision rather than something a remote client can arrange.
189
+ remoteView: { enabled: false },
190
+ bridge: { autoInstall: false },
191
+ actions: { allowExecute: true, allowDownload: true, allowCredentialWrite: true },
192
+ // Local by default: the file lands in downloadDir and nothing leaves the machine until the user
193
+ // names a tool here. {file_path} is the argument name both Feishu's and Netdisk's upload tools use.
194
+ delivery: { tool: '', args: { file_path: '{path}' }, onFail: 'keep-local', sites: {} },
195
+ }
196
+
197
+ /**
198
+ * Absolute path of the settings file, beside the browser profile and the
199
+ * browsing history.
200
+ * @returns the settings file path.
201
+ */
202
+ export function settingsPath(): string {
203
+ const home = dshHome()
204
+ return join(home, BROWSER_PROFILE_DIR, 'settings.json')
205
+ }
206
+
207
+ /** Coerce one boolean field, keeping the default when absent or mistyped. */
208
+ function bool(value: unknown, fallback: boolean): boolean {
209
+ return typeof value === 'boolean' ? value : fallback
210
+ }
211
+
212
+ /**
213
+ * Coerce one boolean field that GATES A CAPABILITY.
214
+ *
215
+ * The difference from {@link bool} is what a mistyped value means. Absent still takes the
216
+ * default — a document written before the switch existed is the documented behaviour. But
217
+ * present-and-not-a-boolean is a document this code cannot read, and for a switch that gates
218
+ * something the operator chose to limit, unreadable resolves to OFF. `bool`'s fallback made
219
+ * `"false"` (a string), `null` (a truncated write) and `1` all mean the same as `true`, so a
220
+ * single dropped byte reopened every capability that had been turned off.
221
+ * @param value - the raw value from the settings document.
222
+ * @param fallback - the default, used only when the field is absent.
223
+ * @returns the value when it is a boolean, `false` when it is anything else.
224
+ */
225
+ function gate(value: unknown, fallback: boolean): boolean {
226
+ if (value === undefined) return fallback
227
+ return value === true
228
+ }
229
+
230
+ /**
231
+ * What an unreadable document resolves to.
232
+ *
233
+ * Only the capability gates are refused; everything else keeps its default. The distinction is
234
+ * deliberate: refusing history, presentation or browser choice would punish the user for a
235
+ * corrupt file without protecting anything, while refusing the gates is the whole point —
236
+ * "the operator's intent cannot be read" must not resolve to "the operator permits".
237
+ */
238
+ const SETTINGS_WHEN_UNREADABLE: BrowserSettings = {
239
+ ...DEFAULT_SETTINGS,
240
+ credentials: { allowRead: false },
241
+ actions: { allowExecute: false, allowDownload: false, allowCredentialWrite: false },
242
+ }
243
+
244
+ /**
245
+ * The channels a settings document may name.
246
+ *
247
+ * Exported so the log line and the error message can quote the same set the parser accepts: a
248
+ * message that lists a value the code rejects (or omits one it takes) is worse than no message.
249
+ */
250
+ export const BROWSER_CHANNELS = ['chrome', 'edge', 'electron', 'auto', 'bundled', 'sidebar'] as const
251
+
252
+ /**
253
+ * Coerce the headless mode, keeping `auto` when the value is not one of the known choices.
254
+ *
255
+ * Booleans are accepted as a convenience because "headless: true" is what anyone writing this by
256
+ * hand would try first, and rejecting it over a type difference would be pedantry: `true` maps to
257
+ * `headless`, `false` to `windowed`. Anything else is reported rather than silently defaulted,
258
+ * for the same reason as {@link resolveChannel}: a discarded value and an honoured one must not
259
+ * look alike.
260
+ * @param value - the raw value from the settings document.
261
+ * @param warn - where to report a discarded value.
262
+ * @returns a valid mode.
263
+ */
264
+ function resolveHeadless(value: unknown, warn?: (message: string) => void): HeadlessMode {
265
+ if (value === undefined) return DEFAULT_SETTINGS.browser.headless
266
+ if (value === true) return 'headless'
267
+ if (value === false) return 'windowed'
268
+ if (typeof value === 'string' && (HEADLESS_MODES as readonly string[]).includes(value)) {
269
+ return value as HeadlessMode
270
+ }
271
+ warn?.(
272
+ `dsh-builtin-browser: browser.headless ${JSON.stringify(value)} is not a known mode, so the `
273
+ + `default "${DEFAULT_SETTINGS.browser.headless}" was used instead. Expected one of: `
274
+ + `${HEADLESS_MODES.join(', ')} (or a boolean).`,
275
+ )
276
+ return DEFAULT_SETTINGS.browser.headless
277
+ }
278
+
279
+ /**
280
+ * Coerce the browser channel, keeping the default when it is not one of the
281
+ * known choices. A hand-edited typo must not silently select a different browser.
282
+ *
283
+ * Coercing is right; coercing QUIETLY is not. A typo and "the setting did nothing" look exactly
284
+ * the same to whoever typed it, which is why every discarded value is reported.
285
+ * @param value - the raw value from the settings document.
286
+ * @param warn - where to report a discarded value, when the caller has somewhere to put it.
287
+ * @returns a valid channel.
288
+ */
289
+ function resolveChannel(value: unknown, warn?: (message: string) => void): BrowserChannel {
290
+ // Absent is the ordinary case, not a mistake: a document that never mentioned the channel gets
291
+ // the default without a word.
292
+ if (value === undefined) return DEFAULT_SETTINGS.browser.channel
293
+ if ((BROWSER_CHANNELS as readonly unknown[]).includes(value)) return value as BrowserChannel
294
+ warn?.(
295
+ `dsh-builtin-browser: browser.channel ${JSON.stringify(value)} is not a known channel, so the `
296
+ + `default "${DEFAULT_SETTINGS.browser.channel}" was used instead. Expected one of: `
297
+ + `${BROWSER_CHANNELS.join(', ')}.`,
298
+ )
299
+ return DEFAULT_SETTINGS.browser.channel
300
+ }
301
+
302
+ /** Coerce one positive-integer field, keeping the default when invalid. */
303
+ function count(value: unknown, fallback: number): number {
304
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
305
+ const floored = Math.floor(value)
306
+ // A fractional value below 1 floors to 0, and 0 is not "very few" in either place these are
307
+ // used: as a history entry cap it means `slice(len - 0)`, i.e. keep nothing, so a hand-typed
308
+ // `0.5` silently wiped the history file on the next rewrite. Anything that survives the
309
+ // floor has to still be a usable limit.
310
+ return floored > 0 ? floored : fallback
311
+ }
312
+
313
+ /** Read one nested section of an unknown document, or an empty object. */
314
+ /**
315
+ * Read one section of the document, distinguishing ABSENT from UNREADABLE.
316
+ *
317
+ * Absent (the key is not there at all) is a document written before the section existed, and
318
+ * the defaults apply — that is the documented behaviour. Present-but-not-an-object
319
+ * (`"actions": false`, `null` from a truncated write, a stray string) is a document this code
320
+ * cannot read, and returning `{}` for it made every gate inside look absent, so each one took
321
+ * its permissive default. A whole section mistyped is exactly the shape a careless hand edit
322
+ * produces, and it opened every capability the section was there to bound.
323
+ * @param source - the parsed document.
324
+ * @param key - the section name.
325
+ * @returns the section, or undefined when it is present but not an object.
326
+ */
327
+ function section(source: Record<string, unknown>, key: string): Record<string, unknown> | undefined {
328
+ const value = source[key]
329
+ if (value === undefined) return {}
330
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
331
+ ? value as Record<string, unknown>
332
+ : undefined
333
+ }
334
+
335
+ /**
336
+ * Resolve a raw settings document (already parsed, shape unknown) into the full
337
+ * document, field by field. Unknown keys are dropped: the file is not a place to
338
+ * smuggle configuration.
339
+ * @param raw - the parsed file contents.
340
+ * @returns the resolved settings.
341
+ */
342
+ export function resolveSettings(raw: unknown, warn?: (message: string) => void): BrowserSettings {
343
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return SETTINGS_WHEN_UNREADABLE
344
+ const source = raw as Record<string, unknown>
345
+ const history = section(source, 'history')
346
+ const cookies = section(source, 'cookies')
347
+ const ui = section(source, 'ui')
348
+ const vision = section(source, 'vision')
349
+ const credentials = section(source, 'credentials')
350
+ const browser = section(source, 'browser')
351
+ const actions = section(source, 'actions')
352
+ const remoteView = section(source, 'remoteView')
353
+ // Read defensively: this section is hand-editable, and a bad value must fall back to "local only"
354
+ // rather than fail the whole document.
355
+ const deliverySection = (section(source, 'delivery') ?? {}) as { tool?: unknown; args?: unknown; onFail?: unknown; sites?: unknown }
356
+ const strings = (value: unknown, fallback: Record<string, string>): Record<string, string> => {
357
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return { ...fallback }
358
+ const out: Record<string, string> = {}
359
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
360
+ if (typeof entry === 'string') out[key] = entry
361
+ }
362
+ return Object.keys(out).length === 0 ? { ...fallback } : out
363
+ }
364
+ // A section that is present but unreadable refuses its gates rather than defaulting them
365
+ // open. The rest of a broken section keeps its defaults: refusing history or presentation
366
+ // would punish the user for a bad file without protecting anything.
367
+ const credentialsUsable = credentials ?? {}
368
+ const actionsUsable = actions ?? {}
369
+ return {
370
+ history: {
371
+ enabled: bool(history?.enabled, DEFAULT_SETTINGS.history.enabled),
372
+ maxEntries: count(history?.maxEntries, DEFAULT_SETTINGS.history.maxEntries),
373
+ maxAgeDays: count(history?.maxAgeDays, DEFAULT_SETTINGS.history.maxAgeDays),
374
+ },
375
+ cookies: { persist: bool(cookies?.persist, DEFAULT_SETTINGS.cookies.persist) },
376
+ ui: {
377
+ autoExpandOnce: bool(ui?.autoExpandOnce, DEFAULT_SETTINGS.ui.autoExpandOnce),
378
+ closeWithSession: bool(ui?.closeWithSession, DEFAULT_SETTINGS.ui.closeWithSession),
379
+ virtualCursor: bool(ui?.virtualCursor, DEFAULT_SETTINGS.ui.virtualCursor),
380
+ // Presentation preference, not a capability gate: a mistyped value keeps the documented
381
+ // default (off) instead of being read as "on", because quiet mode changes how every
382
+ // operation presents itself and should never be the accidental result of a bad edit.
383
+ quiet: bool(ui?.quiet, DEFAULT_SETTINGS.ui.quiet),
384
+ },
385
+ vision: { strategy: vision?.strategy === 'nonVisual' ? 'nonVisual' : DEFAULT_SETTINGS.vision.strategy },
386
+ browser: {
387
+ channel: resolveChannel(browser?.channel, warn),
388
+ headless: resolveHeadless(browser?.headless, warn),
389
+ // 不认识的值退回 `plugin`:这一侧不会与用户正在运行的浏览器抢 profile,是"装好即用"的前提。
390
+ // 之前这一层不产出该字段,`entry.ts` 的 `systemProfile !== 'plugin'` 恒成立,浏览器总是跑在用户
391
+ // profile 上——用户开着 Edge 时 Chromium 以 exit 21 退出,插件报"引擎起不来"。
392
+ systemProfile: (browser as { systemProfile?: unknown } | undefined)?.systemProfile === 'user' ? 'user' : 'plugin',
393
+ },
394
+ credentials: {
395
+ // `gate` returns false for anything present-and-not-a-boolean, so an unreadable section
396
+ // is refused here for free: the section itself is the "present but wrong" value.
397
+ allowRead: credentials === undefined
398
+ ? false
399
+ : gate(credentialsUsable.allowRead, DEFAULT_SETTINGS.credentials.allowRead),
400
+ },
401
+ actions: {
402
+ allowExecute: actions === undefined
403
+ ? false
404
+ : gate(actionsUsable.allowExecute, DEFAULT_SETTINGS.actions.allowExecute),
405
+ allowDownload: actions === undefined
406
+ ? false
407
+ : gate(actionsUsable.allowDownload, DEFAULT_SETTINGS.actions.allowDownload),
408
+ allowCredentialWrite: actions === undefined
409
+ ? false
410
+ : gate(actionsUsable.allowCredentialWrite, DEFAULT_SETTINGS.actions.allowCredentialWrite),
411
+ },
412
+ // Fail-closed, and stated separately from `gate`'s fallback so the intent is visible: an
413
+ // unreadable or absent section means nobody watches. Unlike the other switches, whose defaults
414
+ // are "on", this one has no safe default other than off.
415
+ bridge: {
416
+ autoInstall: section(source, 'bridge') === undefined
417
+ ? DEFAULT_SETTINGS.bridge.autoInstall
418
+ : gate((section(source, 'bridge') as { autoInstall?: unknown }).autoInstall, DEFAULT_SETTINGS.bridge.autoInstall),
419
+ },
420
+ remoteView: {
421
+ enabled: remoteView === undefined
422
+ ? false
423
+ : gate((remoteView as { enabled?: unknown }).enabled, false),
424
+ },
425
+ delivery: {
426
+ tool: typeof deliverySection.tool === 'string' && /^[A-Za-z0-9_.-]+$/.test(deliverySection.tool)
427
+ ? deliverySection.tool
428
+ : '',
429
+ args: strings(deliverySection.args, DEFAULT_SETTINGS.delivery.args),
430
+ onFail: deliverySection.onFail === 'stop' ? 'stop' : 'keep-local',
431
+ sites: strings(deliverySection.sites, {}),
432
+ },
433
+ }
434
+ }
435
+
436
+ /**
437
+ * File-backed settings with an in-memory snapshot. Reads re-stat the file so an
438
+ * edit from another process (or the settings panel writing through a second
439
+ * code path) is picked up without a restart; writes are atomic enough for a
440
+ * single-writer plugin and never throw at the caller.
441
+ */
442
+ export class SettingsStore {
443
+ private cached: BrowserSettings | undefined
444
+ /** Last observed mtime, used to invalidate the cache on external edits. */
445
+ private cachedMtimeMs = -1
446
+ private readonly file: string
447
+ private readonly log?: (message: string) => void
448
+ constructor(file: string = settingsPath(), log?: (message: string) => void) {
449
+ this.file = file
450
+ this.log = log
451
+ }
452
+
453
+ /** Path this store reads and writes. */
454
+ path(): string {
455
+ return this.file
456
+ }
457
+
458
+ /**
459
+ * Current settings, re-read when the file changed on disk.
460
+ * @returns the resolved settings document.
461
+ */
462
+ get(): BrowserSettings {
463
+ let mtimeMs = -1
464
+ try {
465
+ // stat directly: existsSync costs about thirteen times what the stat does, and the
466
+ // stat already throws when the file is missing — which the catch below handles.
467
+ mtimeMs = statSync(this.file).mtimeMs
468
+ } catch (error) {
469
+ // Only an absent document means first-run defaults. Access/storage errors do not
470
+ // erase the operator's decisions, even when an earlier read was cached.
471
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
472
+ this.cached = undefined
473
+ this.cachedMtimeMs = -1
474
+ return SETTINGS_WHEN_UNREADABLE
475
+ }
476
+ mtimeMs = -1
477
+ }
478
+ // Return the cache BEFORE reading. The read used to happen first "just in case", which
479
+ // made the cache pointless: every call paid for a synchronous read of the whole file and
480
+ // then discarded it. This is on the path of every tool call that consults a setting, so
481
+ // it was a stat plus a read per call where a single stat will do.
482
+ if (this.cached !== undefined && mtimeMs === this.cachedMtimeMs) return this.cached
483
+
484
+ let text: string | undefined
485
+ if (mtimeMs !== -1) {
486
+ try {
487
+ text = readFileSync(this.file, 'utf8')
488
+ } catch {
489
+ // It was there a moment ago (the stat above) and cannot be read now: permissions, a
490
+ // lock, a directory in the way. That is not "no document" — the file is not absent, so
491
+ // what it said is unknown, and unknown resolves to the refusing document.
492
+ this.cached = SETTINGS_WHEN_UNREADABLE
493
+ this.cachedMtimeMs = mtimeMs
494
+ return this.cached
495
+ }
496
+ }
497
+ try {
498
+ // A leading BOM is what ordinary Windows editors (Notepad, PowerShell's
499
+ // `Set-Content -Encoding utf8`) leave behind, and `JSON.parse` rejects it.
500
+ // Without this strip, hand-editing the settings file silently discarded every
501
+ // value in it: the document looked correct, and the plugin quietly ran on
502
+ // defaults — including switches the user had just turned off.
503
+ const body = text?.replace(/^\uFEFF/, '')
504
+ this.cached = body === undefined ? DEFAULT_SETTINGS : resolveSettings(JSON.parse(body), m => this.log?.(m))
505
+ } catch {
506
+ // A document that EXISTS but cannot be parsed is not the same as no document at all: the
507
+ // first is a corrupted or half-written file whose contents were the operator's decisions,
508
+ // the second is a first run. Resolving both to the defaults meant a kill during the write,
509
+ // or one stray character, silently reopened the capabilities that had been switched off —
510
+ // so this side refuses them instead (see SETTINGS_WHEN_UNREADABLE).
511
+ this.cached = SETTINGS_WHEN_UNREADABLE
512
+ }
513
+ this.cachedMtimeMs = mtimeMs
514
+ return this.cached
515
+ }
516
+
517
+ /**
518
+ * Merge a partial patch into the stored document and persist it.
519
+ * @param patch - the fields to change (unknown keys are ignored).
520
+ * @returns the settings after the merge.
521
+ */
522
+ update(patch: unknown): BrowserSettings {
523
+ const current = this.get()
524
+ const merged = resolveSettings(deepMerge(current as unknown as Record<string, unknown>, patch), m => this.log?.(m))
525
+ try {
526
+ mkdirSync(dirname(this.file), { recursive: true })
527
+ writeFileAtomic(this.file, `${JSON.stringify(merged, null, 2)}\n`)
528
+ } catch (error) {
529
+ // Do NOT publish the new value as cached, and do not pretend the file changed: a
530
+ // reader compares the file's mtime against this stamp, so stamping "now" on a failed
531
+ // write made the next get() re-read the file and silently revert the user's change.
532
+ // Clear the cache before failing: the value on disk is still the old one, so leaving
533
+ // the merged document cached would hand the next reader something that does not exist —
534
+ // and the stamp would make it look fresh until the mtime comparison rolled it back.
535
+ this.cached = undefined
536
+ this.cachedMtimeMs = -1
537
+ throw new Error(`dsh-builtin-browser: settings could not be saved: ${error instanceof Error ? error.message : String(error)}`)
538
+
539
+ }
540
+ return merged
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Replace a file's contents atomically: write a sibling temporary file, then rename it over
546
+ * the target.
547
+ *
548
+ * `writeFileSync(target, …)` truncates and rewrites in place, so a crash, a full disk or an
549
+ * antivirus lock in the middle leaves HALF a JSON document. That used to be silent: the reader
550
+ * resolved an unparseable file to the defaults, so a torn write flipped `credentials.allowRead`
551
+ * and the action switches back ON, and the next successful update wrote those defaults to disk
552
+ * for good. The read side no longer does that (see {@link SETTINGS_WHEN_UNREADABLE}) — but the
553
+ * write side still has to stop producing torn files at all, because half a document is not
554
+ * something this plugin should ever leave behind.
555
+ *
556
+ * The rename is the commit point: a reader sees either the old document or the new one,
557
+ * never a partial one. It stays in the same directory so the rename is atomic on Windows
558
+ * as well as POSIX (`renameSync` maps to MoveFileEx there: same-volume replaces are
559
+ * atomic, cross-volume ones are not supported at all).
560
+ *
561
+ * The temporary is written with a unique suffix rather than a fixed `.tmp`, so two writers
562
+ * (the settings panel and a second DSH process) cannot rename each other's half-written
563
+ * file into place. Shared with the history store, which had the same hole.
564
+ * @param file - the target path.
565
+ * @param contents - the complete new document.
566
+ */
567
+ export function writeFileAtomic(file: string, contents: string): void {
568
+ const temporary = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`
569
+ try {
570
+ writeFileSync(temporary, contents)
571
+ renameSync(temporary, file)
572
+ } catch (error) {
573
+ // The rename is the commit point, so a failure before it leaves the target untouched —
574
+ // only the temporary has to go, and it must not be left behind as garbage.
575
+ try { rmSync(temporary, { force: true }) } catch { /* the temp is already the least of it */ }
576
+ throw error
577
+ }
578
+ }
579
+
580
+ /** One-level-deep merge over the settings sections (patch wins). */
581
+ function deepMerge(base: Record<string, unknown>, patch: unknown): Record<string, unknown> {
582
+ if (typeof patch !== 'object' || patch === null) return base
583
+ const result: Record<string, unknown> = { ...base }
584
+ for (const [key, value] of Object.entries(patch as Record<string, unknown>)) {
585
+ const existing = result[key]
586
+ if (typeof value === 'object' && value !== null && typeof existing === 'object' && existing !== null) {
587
+ result[key] = { ...existing as Record<string, unknown>, ...value as Record<string, unknown> }
588
+ } else {
589
+ result[key] = value
590
+ }
591
+ }
592
+ return result
593
+ }