dsh-builtin-browser 1.0.1 → 1.0.3

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 (360) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  22. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  23. package/dsh-host-patch/README.md +4 -0
  24. package/dsh-host-patch/apply.mjs +61 -13
  25. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  26. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  27. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  28. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  29. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  30. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  31. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  32. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  33. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  34. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  35. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  36. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  37. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  38. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  39. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  40. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  41. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  42. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  43. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  44. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  45. package/dsh-host-patch/sources/manifest.json +218 -0
  46. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  47. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  48. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  49. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  50. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  51. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  52. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  53. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  54. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  55. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  56. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  57. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  58. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  59. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  60. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  61. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  62. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  63. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  64. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  65. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  66. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  67. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  68. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  69. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  70. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  71. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  72. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  73. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  74. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  75. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  76. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  77. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  78. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  79. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  80. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  81. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  82. package/dsh-host-patch/sources/series.json +260 -0
  83. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  84. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  85. package/dsh-host-patch/tauri-revision1.json +39 -0
  86. package/dsh-host-patch/tauri.json +43 -0
  87. package/dsh-host-patch/v023-alpha2.json +153 -0
  88. package/lib/browser/anti-bot.js +215 -0
  89. package/lib/browser/deep-dom.js +39 -0
  90. package/lib/browser/runtime.js +15 -0
  91. package/lib/browser/takeover-target.js +13 -6
  92. package/lib/browser/types.js +30 -1
  93. package/lib/browser-electron/authenticated-route.js +16 -2
  94. package/lib/browser-electron/automatic-maintenance.js +16 -10
  95. package/lib/browser-electron/bridge-connection.js +3 -8
  96. package/lib/browser-electron/bridge-install.js +2 -1
  97. package/lib/browser-electron/bridge-status.js +55 -26
  98. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  99. package/lib/browser-electron/desktop-identity.js +28 -5
  100. package/lib/browser-electron/desktop-shell.js +64 -0
  101. package/lib/browser-electron/electron-provision.js +105 -18
  102. package/lib/browser-electron/entry.js +129 -44
  103. package/lib/browser-electron/extension-browser.js +4 -4
  104. package/lib/browser-electron/foreground-watch.js +134 -0
  105. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  106. package/lib/browser-electron/guest-route.js +181 -32
  107. package/lib/browser-electron/guest-runtime.js +61 -10
  108. package/lib/browser-electron/guest-storage.js +2 -2
  109. package/lib/browser-electron/history-store.js +1 -5
  110. package/lib/browser-electron/host-main.js +8 -4
  111. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  112. package/lib/browser-electron/maintenance-route.js +2 -1
  113. package/lib/browser-electron/missing-system-browser.js +5 -9
  114. package/lib/browser-electron/preferred-browser.js +7 -3
  115. package/lib/browser-electron/preview-route.js +9 -13
  116. package/lib/browser-electron/process-ownership.js +1 -1
  117. package/lib/browser-electron/profile-command.js +2 -1
  118. package/lib/browser-electron/profile-extension.js +5 -0
  119. package/lib/browser-electron/profile-lease.js +152 -47
  120. package/lib/browser-electron/provider-core.js +527 -0
  121. package/lib/browser-electron/provider-interaction.js +963 -0
  122. package/lib/browser-electron/provider-media.js +518 -0
  123. package/lib/browser-electron/provider-navigation.js +301 -0
  124. package/lib/browser-electron/provider-observation.js +623 -0
  125. package/lib/browser-electron/provider-tabs.js +372 -0
  126. package/lib/browser-electron/provider.js +150 -3301
  127. package/lib/browser-electron/reference-route.js +9 -18
  128. package/lib/browser-electron/remote-host.js +79 -34
  129. package/lib/browser-electron/runtime-status.js +56 -6
  130. package/lib/browser-electron/settings-store.js +3 -6
  131. package/lib/browser-electron/sidebar-only-host.js +1 -1
  132. package/lib/browser-electron/system-browser.js +539 -172
  133. package/lib/browser-electron/tauri-host.js +208 -0
  134. package/lib/browser-electron/virtual-cursor.js +23 -13
  135. package/lib/browser-reference/service.js +22 -4
  136. package/lib/browser-reference/web-sources.js +1 -1
  137. package/lib/client.js +43409 -0
  138. package/lib/compat/host-features.js +75 -0
  139. package/lib/reference-source.js +1 -1
  140. package/lib/reference-text.js +23 -1
  141. package/lib/takeover-protocol.js +1 -1
  142. package/lib/tool-browser/block-recovery.js +69 -0
  143. package/lib/tool-browser/code-tool.js +170 -19
  144. package/lib/tool-browser/code-worker.js +115 -20
  145. package/lib/tool-browser/errors.js +34 -0
  146. package/lib/tool-browser/index.js +66 -3593
  147. package/lib/tool-browser/page-probe.js +227 -28
  148. package/lib/tool-browser/panel-page.js +2 -1
  149. package/lib/tool-browser/probe-client.js +157 -0
  150. package/lib/tool-browser/screenshot-annotations.js +108 -0
  151. package/lib/tool-browser/state.js +337 -0
  152. package/lib/tool-browser/takeover.js +1 -1
  153. package/lib/tool-browser/tools-debug.js +862 -0
  154. package/lib/tool-browser/tools-interaction.js +993 -0
  155. package/lib/tool-browser/tools-navigation.js +807 -0
  156. package/lib/tool-browser/tools-observation.js +461 -0
  157. package/lib/tool-browser/tools-reference.js +293 -0
  158. package/lib/web-guest.js +1 -0
  159. package/package.json +15 -53
  160. package/README.en.md +0 -89
  161. package/browser-extension/constants.mjs +0 -20
  162. package/browser-extension/controller.mjs +0 -293
  163. package/browser-extension/locales.mjs +0 -15
  164. package/browser-extension/manifest.json +0 -12
  165. package/browser-extension/options.html +0 -14
  166. package/browser-extension/options.mjs +0 -9
  167. package/browser-extension/permission-guard.mjs +0 -13
  168. package/browser-extension/worker.mjs +0 -74
  169. package/dist/client.cjs +0 -43167
  170. package/lib/browser-reference/submission-receipts.js +0 -139
  171. package/scripts/build.mjs +0 -66
  172. package/scripts/bundle-host.mjs +0 -28
  173. package/scripts/fix-exports.mjs +0 -50
  174. package/scripts/install-electron.mjs +0 -51
  175. package/scripts/verify-exports.mjs +0 -47
  176. package/scripts/verify-preview-sdk.mjs +0 -93
  177. package/skills/dsh-builtin-browser/SKILL.md +0 -73
  178. package/skills/dsh-builtin-browser/references/batch.md +0 -53
  179. package/skills/dsh-builtin-browser/references/deliver.md +0 -31
  180. package/skills/dsh-builtin-browser/references/locate.md +0 -11
  181. package/skills/dsh-builtin-browser/references/recover.md +0 -11
  182. package/skills/dsh-builtin-browser/references/verify.md +0 -13
  183. package/skills/dsh-debug-host/SKILL.md +0 -56
  184. package/skills/dsh-debug-self/SKILL.md +0 -50
  185. package/src/bridge-compatibility.ts +0 -39
  186. package/src/browser/handles.ts +0 -89
  187. package/src/browser/runtime.ts +0 -560
  188. package/src/browser/takeover-target.ts +0 -36
  189. package/src/browser/types.ts +0 -817
  190. package/src/browser-electron/authenticated-route.ts +0 -84
  191. package/src/browser-electron/automatic-maintenance.ts +0 -726
  192. package/src/browser-electron/bridge-auto.ts +0 -159
  193. package/src/browser-electron/bridge-connection.ts +0 -385
  194. package/src/browser-electron/bridge-endpoint.ts +0 -129
  195. package/src/browser-electron/bridge-install.ts +0 -289
  196. package/src/browser-electron/bridge-maintenance.ts +0 -189
  197. package/src/browser-electron/bridge-status.ts +0 -347
  198. package/src/browser-electron/desktop-bridge-host.ts +0 -251
  199. package/src/browser-electron/desktop-identity.ts +0 -320
  200. package/src/browser-electron/document-readiness.ts +0 -45
  201. package/src/browser-electron/electron-provision.ts +0 -261
  202. package/src/browser-electron/entry.ts +0 -1299
  203. package/src/browser-electron/ephemeral-profile.ts +0 -189
  204. package/src/browser-electron/extension-browser.ts +0 -223
  205. package/src/browser-electron/extension-setup.ts +0 -67
  206. package/src/browser-electron/file-write.ts +0 -31
  207. package/src/browser-electron/guest-cookie-jar.ts +0 -176
  208. package/src/browser-electron/guest-cookie-store.ts +0 -59
  209. package/src/browser-electron/guest-css-runtime.ts +0 -76
  210. package/src/browser-electron/guest-css.ts +0 -68
  211. package/src/browser-electron/guest-route.ts +0 -568
  212. package/src/browser-electron/guest-runtime.ts +0 -357
  213. package/src/browser-electron/guest-storage-runtime.ts +0 -54
  214. package/src/browser-electron/guest-storage.ts +0 -117
  215. package/src/browser-electron/history-store.ts +0 -227
  216. package/src/browser-electron/host-main.ts +0 -1381
  217. package/src/browser-electron/host-patch-maintenance.ts +0 -112
  218. package/src/browser-electron/http-body.ts +0 -65
  219. package/src/browser-electron/json-reply.ts +0 -47
  220. package/src/browser-electron/maintenance-broker.ts +0 -166
  221. package/src/browser-electron/maintenance-lifecycle.ts +0 -91
  222. package/src/browser-electron/maintenance-route.ts +0 -67
  223. package/src/browser-electron/missing-system-browser.ts +0 -113
  224. package/src/browser-electron/open-slot.ts +0 -49
  225. package/src/browser-electron/paths.ts +0 -25
  226. package/src/browser-electron/preferred-browser.ts +0 -120
  227. package/src/browser-electron/preview-route.ts +0 -218
  228. package/src/browser-electron/process-ownership.ts +0 -168
  229. package/src/browser-electron/process.ts +0 -23
  230. package/src/browser-electron/profile-checkpoint.ts +0 -187
  231. package/src/browser-electron/profile-command.ts +0 -46
  232. package/src/browser-electron/profile-extension.ts +0 -124
  233. package/src/browser-electron/profile-lease.ts +0 -115
  234. package/src/browser-electron/profile-residue.ts +0 -49
  235. package/src/browser-electron/provider.ts +0 -4571
  236. package/src/browser-electron/reference-route.ts +0 -608
  237. package/src/browser-electron/remote-host.ts +0 -1462
  238. package/src/browser-electron/rpc-input.ts +0 -13
  239. package/src/browser-electron/rpc-ops.ts +0 -41
  240. package/src/browser-electron/runtime-diagnostics.ts +0 -38
  241. package/src/browser-electron/runtime-route.ts +0 -105
  242. package/src/browser-electron/runtime-status.ts +0 -242
  243. package/src/browser-electron/settings-route.ts +0 -64
  244. package/src/browser-electron/settings-store.ts +0 -589
  245. package/src/browser-electron/shortcuts-route.ts +0 -112
  246. package/src/browser-electron/sidebar-only-host.ts +0 -298
  247. package/src/browser-electron/startpage-shortcuts.ts +0 -213
  248. package/src/browser-electron/system-browser.ts +0 -1497
  249. package/src/browser-electron/timing.ts +0 -16
  250. package/src/browser-electron/virtual-cursor.ts +0 -152
  251. package/src/browser-electron/windows-system.ts +0 -24
  252. package/src/browser-reference/delivery.ts +0 -384
  253. package/src/browser-reference/entry.ts +0 -631
  254. package/src/browser-reference/export.ts +0 -339
  255. package/src/browser-reference/import.ts +0 -303
  256. package/src/browser-reference/page-script.ts +0 -1537
  257. package/src/browser-reference/service.ts +0 -1315
  258. package/src/browser-reference/store.ts +0 -172
  259. package/src/browser-reference/submission-receipts.ts +0 -122
  260. package/src/browser-reference/text-quote.ts +0 -219
  261. package/src/browser-reference/types.ts +0 -195
  262. package/src/browser-reference/visible.ts +0 -367
  263. package/src/browser-reference/web-sources.ts +0 -103
  264. package/src/client/browser/BrowserController.ts +0 -693
  265. package/src/client/browser/BrowserFrame.ts +0 -78
  266. package/src/client/browser/BrowserNavigation.ts +0 -169
  267. package/src/client/browser/BrowserPage.ts +0 -23
  268. package/src/client/browser/BrowserPersistence.ts +0 -44
  269. package/src/client/browser/IframeImpl.ts +0 -176
  270. package/src/client/browser/child-tabs.ts +0 -14
  271. package/src/client/browser/iframe-reference.ts +0 -67
  272. package/src/client/browser/initialization.ts +0 -262
  273. package/src/client/browser/omnibox.ts +0 -243
  274. package/src/client/browser/store.ts +0 -38
  275. package/src/client/browser/takeover-channel.ts +0 -72
  276. package/src/client/browser/url.ts +0 -46
  277. package/src/client/browser/web-reference-source.ts +0 -52
  278. package/src/client/css-modules.d.ts +0 -4
  279. package/src/client/definition.tsx +0 -30
  280. package/src/client/electron/ElectronWebViewImpl.ts +0 -364
  281. package/src/client/electron/ElectronWebviewPresentation.ts +0 -138
  282. package/src/client/electron/NativeChildPresentation.ts +0 -45
  283. package/src/client/electron/NativeViewPage.ts +0 -251
  284. package/src/client/electron/pages.ts +0 -23
  285. package/src/client/electron/reference-overlay.ts +0 -53
  286. package/src/client/electron/workspace.ts +0 -33
  287. package/src/client/index.ts +0 -293
  288. package/src/client/locales.ts +0 -857
  289. package/src/client/pages.ts +0 -28
  290. package/src/client/reference/client/BrowserRefLink.tsx +0 -142
  291. package/src/client/reference/client/draft-reference.ts +0 -167
  292. package/src/client/reference/client/index.ts +0 -7
  293. package/src/client/reference/client/ordered-submission.ts +0 -108
  294. package/src/client/reference/client/pending-delivery.ts +0 -216
  295. package/src/client/reference/client/plugin.ts +0 -189
  296. package/src/client/reference/client/production/ReferenceCapsules.tsx +0 -345
  297. package/src/client/reference/client/production/ReferenceDock.module.css +0 -193
  298. package/src/client/reference/client/production/ReferenceDock.tsx +0 -6
  299. package/src/client/reference/client/production/ReferenceFeedback.tsx +0 -15
  300. package/src/client/reference/client/production/ReferenceMath.tsx +0 -44
  301. package/src/client/reference/client/production/ReferenceText.tsx +0 -36
  302. package/src/client/reference/client/production/assembly.ts +0 -471
  303. package/src/client/reference/client/production/asset-store.ts +0 -144
  304. package/src/client/reference/client/production/availability.ts +0 -74
  305. package/src/client/reference/client/production/bytes.ts +0 -36
  306. package/src/client/reference/client/production/delivery-client.ts +0 -211
  307. package/src/client/reference/client/production/draft-adapter.ts +0 -508
  308. package/src/client/reference/client/production/http-transport.ts +0 -217
  309. package/src/client/reference/client/production/production-submission.ts +0 -310
  310. package/src/client/reference/client/production/protocol.ts +0 -231
  311. package/src/client/reference/client/production/reference-card.ts +0 -240
  312. package/src/client/reference/client/production/reference-labels.ts +0 -29
  313. package/src/client/reference/client/production/reply-link-bridge.ts +0 -222
  314. package/src/client/reference/client/production/reveal.ts +0 -215
  315. package/src/client/reference/client/production/runtime.ts +0 -1101
  316. package/src/client/reference/client/production/snapshot-adapter.ts +0 -154
  317. package/src/client/reference/client/production/source-marker.ts +0 -63
  318. package/src/client/reference/client/production/source-opener.ts +0 -55
  319. package/src/client/reference/client/production/styles.ts +0 -104
  320. package/src/client/reference/client/production/user-text-rule.ts +0 -58
  321. package/src/client/reference/client/reveal.ts +0 -107
  322. package/src/client/reference/client/scheme.ts +0 -114
  323. package/src/client/reference/client/types.ts +0 -168
  324. package/src/client/reference/css-modules.d.ts +0 -4
  325. package/src/client/reference/index.ts +0 -11
  326. package/src/client/reference-capture-owner.ts +0 -162
  327. package/src/client/reference-intents.ts +0 -36
  328. package/src/client/settings/index.ts +0 -34
  329. package/src/client/settings/panel.ts +0 -2657
  330. package/src/client/shortcut-open.ts +0 -30
  331. package/src/client/startpage/binding.ts +0 -99
  332. package/src/client/startpage/controller.ts +0 -303
  333. package/src/client/startpage/model.ts +0 -279
  334. package/src/client/view/Browser.module.css +0 -751
  335. package/src/client/view/BrowserBody.tsx +0 -314
  336. package/src/client/view/BrowserPresentation.ts +0 -9
  337. package/src/client/view/BrowserTitle.tsx +0 -17
  338. package/src/client/view/IframePresentation.ts +0 -344
  339. package/src/client/view/StartPage.tsx +0 -597
  340. package/src/client/view/TakeoverBanner.tsx +0 -21
  341. package/src/index.ts +0 -110
  342. package/src/reference-owner.ts +0 -5
  343. package/src/reference-page.ts +0 -9
  344. package/src/reference-source.ts +0 -3
  345. package/src/reference-text.ts +0 -197
  346. package/src/startpage-settings.ts +0 -103
  347. package/src/startpage.ts +0 -71
  348. package/src/takeover-protocol.ts +0 -19
  349. package/src/tool-browser/code-tool.ts +0 -401
  350. package/src/tool-browser/code-worker.ts +0 -639
  351. package/src/tool-browser/element-fields.ts +0 -167
  352. package/src/tool-browser/index.ts +0 -3733
  353. package/src/tool-browser/page-probe.ts +0 -474
  354. package/src/tool-browser/panel-page.ts +0 -124
  355. package/src/tool-browser/screenshot-image.ts +0 -49
  356. package/src/tool-browser/takeover.ts +0 -198
  357. package/src/types/electron-shim.d.ts +0 -144
  358. package/src/types.ts +0 -85
  359. package/src/web-guest.ts +0 -34
  360. package/tools/accept-desktop.mjs +0 -148
@@ -1,1315 +0,0 @@
1
- /**
2
- * Browser reference service: capture a page's selection into an immutable
3
- * snapshot, and reveal that snapshot later in the same page.
4
- *
5
- * WHAT CROSSES THE BOUNDARY
6
- * The page half is external content. Everything it returns is treated as
7
- * untrusted input: shapes are validated field by field, strings are capped, ids
8
- * are assigned here rather than taken from the page, and the manifest hash is
9
- * recomputed over the validated snapshot. A page that returns a fabricated
10
- * part cannot make the store hold something the page could never prove.
11
- *
12
- * The browser itself is reached through one injected function, so the whole
13
- * capture/reveal flow is testable without a browser and the carrier does not
14
- * matter: the same script runs through the only path every carrier has.
15
- * @module dsh-browser/browser-reference/service
16
- */
17
-
18
- import { createHash, randomUUID } from 'node:crypto'
19
- import { referenceOwnerKey } from '../reference-owner.ts'
20
- import { webReferenceSources, type WebReferenceSources } from './web-sources.ts'
21
- import { sameReferenceDocument as samePage } from '../reference-page.ts'
22
- import { isReferenceText, normalizeReferenceText, MAX_REFERENCE_TEXT, referenceTextContent, renderReferenceText } from '../reference-text.ts'
23
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
24
- import { dirname, join } from 'node:path'
25
- import { manifestHashOf, ReferenceStore, referenceStorePath } from './store.ts'
26
- import { MAX_REFERENCE_COMMENT } from './entry.ts'
27
- import {
28
- collectAssetKeys, encodeReferenceExport,
29
- } from './export.ts'
30
- import type { ExportAsset, ReferenceExportFormat } from './export.ts'
31
- import { findTextQuote } from './text-quote.ts'
32
- import {
33
- captureScript,
34
- highlightScript,
35
- noticeScript,
36
- pageFactsScript,
37
- pageTextScript,
38
- rasterizeScript,
39
- revealElementScript,
40
- } from './page-script.ts'
41
- import { frameCaptureScript, validateFrameCapture, validateFrameSelector } from './entry.ts'
42
- import {
43
- clipFromFacts,
44
- compareImageVersion,
45
- maskScript,
46
- unmaskScript,
47
- validateVisibleFacts,
48
- versionProbeScript,
49
- visibleFactsScript,
50
- } from './visible.ts'
51
- import type {
52
- ScreenshotFacts,
53
- VersionStatus,
54
- VisibleCaptureMeta,
55
- VisibleCaptureResult,
56
- VisibleClip,
57
- } from './visible.ts'
58
- import type {
59
- BrowserReference,
60
- BrowserReferenceCarrier,
61
- BrowserReferenceEntry,
62
- BrowserReferenceOrigin,
63
- BrowserReferencePart,
64
- ImageReferencePart,
65
- TableAnchor,
66
- TableCellRun,
67
- TableCellSnapshot,
68
- TableReferencePart,
69
- TextReferencePart,
70
- BrowserReferenceTarget,
71
- } from './types.ts'
72
- import type {
73
- RawCaptureEvent,
74
- RawCaptureResult,
75
- RawCell,
76
- RawCellRun,
77
- RawElementRevealResult,
78
- RawHighlightResult,
79
- RawPageTextResult,
80
- RawRasterResult,
81
- RawTable,
82
- } from './page-script.ts'
83
-
84
- /** One call into the page; the host supplies this from its carrier. */
85
- export interface ReferenceEvaluateRequest {
86
- readonly script: string
87
- readonly args?: readonly unknown[]
88
- readonly timeoutMs?: number
89
- }
90
-
91
- /** The browser capabilities the service needs, and nothing else. */
92
- export interface ReferenceHost {
93
- /** Evaluate a page script; the value may be the script's JSON string. */
94
- evaluate(sessionId: string, request: ReferenceEvaluateRequest, signal?: AbortSignal): Promise<unknown>
95
- /** Whether the owning browser session is still alive. */
96
- exists(sessionId: string): boolean
97
- /** Save one URL to a local file with the session's cookies, when the carrier can. */
98
- download?(sessionId: string, url: string, savePath: string, signal?: AbortSignal): Promise<void>
99
- /**
100
- * Capture a clipped, read-only visible-region screenshot. Optional: a host
101
- * without this capability keeps the source-image / rasterised-image paths.
102
- */
103
- captureVisible?(sessionId: string, clip: VisibleClip, signal?: AbortSignal): Promise<VisibleCaptureResult>
104
- now?(): Date
105
- newId?(): string
106
- }
107
-
108
- type MaterializedAsset = {
109
- assetKey: string
110
- representation: 'source-image' | 'rasterized-image' | 'visible-snapshot'
111
- versionStatus?: VersionStatus
112
- visible?: VisibleCaptureMeta
113
- }
114
-
115
- export interface ReferenceCaptureAction {
116
- readonly windowId: string
117
- readonly entry: 'native-menu' | 'page-overlay'
118
- readonly frameSelector?: string
119
- /** The image/table this action named, even if the selection collapsed. */
120
- readonly target?: BrowserReferenceTarget
121
- /** Optional note the human typed in the selection bar (three-state §3). */
122
- readonly comment?: string
123
- /**
124
- * Selection text frozen by the page bar before its comment field took focus.
125
- * When the live selection is already collapsed, this is what the capture
126
- * locates (and what keeps the reference from silently capturing nothing).
127
- */
128
- readonly selectionText?: string
129
- /**
130
- * The COMPLETE ordered capture the bar froze at that same moment: text runs,
131
- * assets and table ranges with their anchors. Preferred over `selectionText`,
132
- * which can only re-locate wording and therefore loses images/tables and can
133
- * pick a different occurrence of the same paragraph.
134
- */
135
- readonly capture?: RawCaptureResult
136
- }
137
-
138
- let referenceCaptureActionHandler: ((action: ReferenceCaptureAction) => Promise<void>) | undefined
139
-
140
- /** Register the handler for a human right-click / floating-button intent. */
141
- export function setReferenceCaptureActionHandler(
142
- handler: (action: ReferenceCaptureAction) => Promise<void>,
143
- ): () => void {
144
- referenceCaptureActionHandler = handler
145
- return () => { if (referenceCaptureActionHandler === handler) referenceCaptureActionHandler = undefined }
146
- }
147
-
148
- /** Called by the provider when the host reports a human reference action. */
149
- export async function dispatchReferenceCaptureAction(action: ReferenceCaptureAction): Promise<void> {
150
- if (referenceCaptureActionHandler === undefined) throw new Error('reference capture handler is unavailable')
151
- await referenceCaptureActionHandler(action)
152
- }
153
-
154
- /** One piece of a capture that could not be committed. */
155
- export interface CaptureFailure {
156
- readonly kind: 'text' | 'image' | 'table' | 'reference'
157
- readonly reason: string
158
- /** Anything a caller can show without reading the page again. */
159
- readonly detail?: Readonly<Record<string, unknown>>
160
- }
161
-
162
- /** Result of a capture attempt. `reference` is absent when the group was refused. */
163
- export interface CaptureOutcome {
164
- readonly reference?: BrowserReference
165
- readonly failures: readonly CaptureFailure[]
166
- }
167
-
168
- /** What the caller wants captured. */
169
- export interface CaptureRequest {
170
- readonly sourcePageId?: string
171
- /** The DSH session that owns the reference. */
172
- readonly sessionId: string
173
- /** The browser session holding the page; defaults to `sessionId`. */
174
- readonly browserSessionId?: string
175
- readonly origin?: BrowserReferenceOrigin
176
- readonly entry?: BrowserReferenceEntry
177
- readonly carrier?: BrowserReferenceCarrier
178
- /**
179
- * Commit the parts that succeeded even when some failed. The default is the
180
- * design's rule: a reference is an ordered whole, so a broken image does not
181
- * silently become a missing one.
182
- */
183
- readonly allowPartial?: boolean
184
- /** Capture this table even when the selection does not touch it. */
185
- readonly tableSelector?: string
186
- /** With no live selection, register this text as an agent excerpt. */
187
- readonly excerptText?: string
188
- /**
189
- * A complete capture the page bar froze while the selection still existed.
190
- * Used verbatim; the page is only re-read to confirm it is still the same
191
- * document, so a changed page is reported instead of capturing other text.
192
- */
193
- readonly frozenCapture?: RawCaptureResult
194
- /** Capture a same-origin iframe's selection instead of the top document. */
195
- readonly frameSelector?: string
196
- /** Capture THIS image/table/text even when the selection has collapsed. */
197
- readonly target?: BrowserReferenceTarget
198
- /** The user's own note, stored with the reference and never hashed. */
199
- readonly comment?: string
200
- /**
201
- * Prove that a downloaded image is the version the page had loaded. Default
202
- * true; a page that cannot be probed is reported as unverifiable, not as a
203
- * verified match, but does not by itself invalidate the capture.
204
- */
205
- readonly verifyImageVersion?: boolean
206
- /** Allow a masked visible-region snapshot when no trustworthy source bytes exist. */
207
- readonly allowVisibleSnapshot?: boolean
208
- }
209
-
210
- /** Per-part reveal result. */
211
- export interface RevealPartResult {
212
- readonly partId: string
213
- readonly type: 'text' | 'image' | 'table'
214
- readonly status: 'revealed' | 'ambiguous' | 'missing'
215
- readonly matches?: number
216
- /** True when the literal text missed and whitespace-collapsed matching found it. */
217
- readonly collapsed?: boolean
218
- readonly note?: string
219
- }
220
-
221
- /** How a reveal call ended. */
222
- export interface RevealOutcome {
223
- readonly referenceId: string
224
- readonly status: 'revealed' | 'partial' | 'ambiguous' | 'missing' | 'not-found' | 'page-mismatch' | 'session-unavailable' | 'unavailable'
225
- readonly pageUrl: string
226
- /** Where the browser is now, when it could be read. */
227
- readonly currentUrl?: string
228
- readonly parts: readonly RevealPartResult[]
229
- readonly note?: string
230
- }
231
-
232
- /**
233
- * The reserved seam for putting a reference into a DSH draft.
234
- *
235
- * The host has no plugin-facing draft API today (the composer is package
236
- * internal), so this plugin captures and stores references and leaves delivery
237
- * to whoever implements this interface. When a host adapter is registered the
238
- * same service can deliver; until then `insertIntoDraft` answers honestly that
239
- * no adapter exists.
240
- */
241
- export interface BrowserReferenceDraftAdapter {
242
- insertReference(reference: BrowserReference, options: { readonly sessionId: string; readonly focus?: boolean }): Promise<{ readonly applied: boolean; readonly reason?: string }>
243
- }
244
-
245
- /** Tunables; every default is a cap the caller can only tighten. */
246
- export interface BrowserReferenceServiceOptions {
247
- readonly webSources?: WebReferenceSources
248
- /** Characters of context on each side of a text anchor. Default 32. */
249
- readonly context?: number
250
- /** Longest single text part. Default 20000 characters. */
251
- readonly maxTextPartLength?: number
252
- /** Most parts in one reference. Default 64. */
253
- readonly maxParts?: number
254
- /** Most cells captured per table. Default 2000. */
255
- readonly maxTableCells?: number
256
- /** Page text budget for capture/reveal. Default 2 000 000 characters. */
257
- readonly maxPageText?: number
258
- /** Largest image kept. Default 20 MiB. */
259
- readonly maxImageBytes?: number
260
- /** Where image bytes live. Default `reference-assets` beside the store. */
261
- readonly assetDir?: string
262
- /** Page evaluation budget. Default 20 s. */
263
- readonly timeoutMs?: number
264
- readonly sourceSession?: (owner: string, pageId: string) => Promise<string>
265
- readonly sourceReady?: (owner: string) => Promise<void>
266
- }
267
-
268
- /** Every limit after clamping; the caller's values only ever tighten these. */
269
- interface ResolvedOptions {
270
- context: number
271
- maxTextPartLength: number
272
- maxParts: number
273
- maxTableCells: number
274
- maxPageText: number
275
- maxImageBytes: number
276
- timeoutMs: number
277
- }
278
-
279
-
280
- const DEFAULTS: ResolvedOptions = {
281
- context: 32,
282
- maxTextPartLength: MAX_REFERENCE_TEXT,
283
- maxParts: 64,
284
- maxTableCells: 2_000,
285
- maxPageText: 2_000_000,
286
- maxImageBytes: 20 * 1024 * 1024,
287
- timeoutMs: 20_000,
288
- }
289
-
290
- function isRecord(value: unknown): value is Record<string, unknown> {
291
- return typeof value === 'object' && value !== null && !Array.isArray(value)
292
- }
293
-
294
- function textOf(value: unknown, limit: number): string {
295
- return typeof value === 'string' ? value.slice(0, limit) : ''
296
- }
297
-
298
- function integerOf(value: unknown, fallback: number, min: number, max: number): number {
299
- const number = typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : fallback
300
- return Math.min(Math.max(number, min), max)
301
- }
302
-
303
- function booleanOf(value: unknown): boolean {
304
- return value === true
305
- }
306
-
307
- function numberPathOf(value: unknown): readonly number[] | undefined {
308
- if (!Array.isArray(value) || value.length === 0 || value.length > 64) return undefined
309
- const path: number[] = []
310
- for (const entry of value) {
311
- if (typeof entry !== 'number' || !Number.isInteger(entry) || entry < 0 || entry > 1_000_000) return undefined
312
- path.push(entry)
313
- }
314
- return path
315
- }
316
-
317
- /** Decode a data URL into bytes and its declared MIME type. */
318
- function decodeDataUrl(url: string): { bytes: Buffer; mime: string } | undefined {
319
- const match = /^data:([^;,]+)((?:;[^,]*)?),([\s\S]*)$/i.exec(url)
320
- if (match === null) return undefined
321
- const mime = match[1].toLowerCase()
322
- const parameters = match[2].toLowerCase()
323
- const payload = match[3]
324
- try {
325
- const bytes = parameters.includes(';base64')
326
- ? Buffer.from(payload, 'base64')
327
- : Buffer.from(decodeURIComponent(payload), 'utf8')
328
- return bytes.length > 0 ? { bytes, mime } : undefined
329
- } catch {
330
- return undefined
331
- }
332
- }
333
-
334
- /** Recognise the bytes rather than trusting a page-declared MIME type. */
335
- export function sniffImageMime(bytes: Buffer): string | undefined {
336
- if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'
337
- if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'
338
- if (bytes.length >= 6 && bytes.toString('ascii', 0, 3) === 'GIF') return 'image/gif'
339
- if (bytes.length >= 12 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'
340
- if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d) return 'image/bmp'
341
- if (bytes.length >= 12 && bytes.toString('ascii', 4, 8) === 'ftyp') {
342
- const brand = bytes.toString('ascii', 8, 12)
343
- if (brand === 'avif' || brand === 'avis') return 'image/avif'
344
- }
345
- const head = bytes.toString('utf8', 0, Math.min(bytes.length, 512)).trimStart().toLowerCase()
346
- if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg'))) return 'image/svg+xml'
347
- if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0) return 'image/x-icon'
348
- return undefined
349
- }
350
-
351
- /** What a stored asset file is, beside the bytes. */
352
- export interface ReferenceAssetMeta {
353
- readonly assetKey: string
354
- readonly mime: string
355
- readonly bytes: number
356
- readonly sourceUrl: string
357
- readonly representation: 'source-image' | 'rasterized-image' | 'visible-snapshot'
358
- readonly savedAt: string
359
- /** Present when the bytes came from a URL that could be version-checked. */
360
- readonly versionStatus?: VersionStatus
361
- /** Present for a visible-region snapshot. */
362
- readonly visible?: VisibleCaptureMeta
363
- }
364
-
365
- /**
366
- * Capture and reveal browser references for one host.
367
- *
368
- * Instances share immutable storage and the browser's owned Web source channel.
369
- */
370
- export class BrowserReferenceService {
371
- readonly webSources: WebReferenceSources | undefined
372
- private adapter: BrowserReferenceDraftAdapter | undefined
373
- private readonly assetDir: string
374
- private readonly host: ReferenceHost
375
- private readonly options: ResolvedOptions
376
- private readonly store: ReferenceStore
377
- private readonly sourceSession: BrowserReferenceServiceOptions['sourceSession']
378
- private readonly sourceReady: BrowserReferenceServiceOptions['sourceReady']
379
-
380
- constructor(host: ReferenceHost, store: ReferenceStore = new ReferenceStore(), options: BrowserReferenceServiceOptions = {}) {
381
- this.host = host
382
- this.store = store
383
- this.sourceSession = options.sourceSession
384
- this.sourceReady = options.sourceReady
385
- this.webSources = options.webSources
386
- this.options = {
387
- context: integerOf(options.context, DEFAULTS.context, 0, 512),
388
- maxTextPartLength: integerOf(options.maxTextPartLength, DEFAULTS.maxTextPartLength, 1, MAX_REFERENCE_TEXT),
389
- maxParts: integerOf(options.maxParts, DEFAULTS.maxParts, 1, 1_000),
390
- maxTableCells: integerOf(options.maxTableCells, DEFAULTS.maxTableCells, 1, 20_000),
391
- maxPageText: integerOf(options.maxPageText, DEFAULTS.maxPageText, 1_000, 50_000_000),
392
- maxImageBytes: integerOf(options.maxImageBytes, DEFAULTS.maxImageBytes, 1_024, 200 * 1024 * 1024),
393
- timeoutMs: integerOf(options.timeoutMs, DEFAULTS.timeoutMs, 1_000, 300_000),
394
- }
395
- this.assetDir = options.assetDir ?? join(dirname(referenceStorePath()), 'reference-assets')
396
- }
397
-
398
- /** Register the host's draft adapter; `undefined` removes it. */
399
- setDraftAdapter(adapter: BrowserReferenceDraftAdapter | undefined): void {
400
- this.adapter = adapter
401
- }
402
-
403
- /** The store, for listings. */
404
- get references(): ReferenceStore {
405
- return this.store
406
- }
407
-
408
- /** Read one reference. */
409
- get(referenceId: string): BrowserReference | undefined {
410
- return this.store.get(referenceId)
411
- }
412
-
413
- /** List references, newest last. */
414
- list(filter: { readonly sessionId?: string; readonly pageUrl?: string; readonly limit?: number } = {}): BrowserReference[] {
415
- return this.store.list(filter)
416
- }
417
-
418
- /** Absolute path of one stored asset, or undefined when it is absent. */
419
- assetPath(assetKey: string): string | undefined {
420
- if (!/^[0-9a-f]{64}$/.test(assetKey)) return undefined
421
- const file = join(this.assetDir, `${assetKey}.bin`)
422
- return existsSync(file) ? file : undefined
423
- }
424
-
425
- /**
426
- * Export stored records and the image bytes they bind.
427
- * @param options - output shape and an optional owning-session filter.
428
- * @returns the encoded file.
429
- */
430
- exportBundle(options: { readonly format: ReferenceExportFormat; readonly sessionId?: string }):
431
- { readonly fileName: string; readonly mime: string; readonly body: Buffer } {
432
- const references = this.store.list(options.sessionId === undefined ? {} : { sessionId: options.sessionId })
433
- const assets: ExportAsset[] = []
434
- for (const assetKey of collectAssetKeys(references)) {
435
- const file = this.assetPath(assetKey)
436
- if (file === undefined) continue
437
- let bytes: Buffer
438
- try { bytes = readFileSync(file) } catch { continue }
439
- let meta: { readonly mime?: unknown; readonly sourceUrl?: unknown } = {}
440
- try { meta = JSON.parse(readFileSync(file.replace(/\.bin$/u, '.json'), 'utf8')) as typeof meta } catch { /* legacy asset without a sidecar */ }
441
- const mime = typeof meta.mime === 'string' && meta.mime !== '' ? meta.mime : sniffImageMime(bytes)
442
- if (mime === undefined) continue
443
- assets.push({
444
- assetKey,
445
- mime,
446
- bytes,
447
- ...typeof meta.sourceUrl === 'string' && meta.sourceUrl !== '' ? { sourceUrl: meta.sourceUrl } : {},
448
- })
449
- }
450
- return encodeReferenceExport({
451
- references,
452
- assets,
453
- exportedAt: (this.host.now?.() ?? new Date()).toISOString(),
454
- }, options.format)
455
- }
456
-
457
- /**
458
- * Deliver one stored reference into a draft through the registered adapter.
459
- * @param referenceId - the stored reference.
460
- * @returns `ok: false` with a reason when no adapter exists or it refused.
461
- */
462
- async insertIntoDraft(referenceId: string): Promise<{ readonly ok: boolean; readonly reason?: string }> {
463
- const reference = this.store.get(referenceId)
464
- if (reference === undefined) return { ok: false, reason: 'reference-not-found' }
465
- if (this.adapter === undefined) return { ok: false, reason: 'draft-adapter-unavailable' }
466
- const sessionId = reference.owner.sessionId
467
- if (sessionId === undefined || sessionId === '') return { ok: false, reason: 'reference-has-no-session' }
468
- try {
469
- const result = await this.adapter.insertReference(reference, { sessionId, focus: false })
470
- return result.applied ? { ok: true } : { ok: false, reason: result.reason ?? 'draft-adapter-refused' }
471
- } catch (error) {
472
- return { ok: false, reason: String(error instanceof Error ? error.message : error) }
473
- }
474
- }
475
-
476
- /**
477
- * Capture the page's current selection (or one table / one excerpt).
478
- * @param request - what to capture and which session owns it.
479
- * @param signal - cancels the page evaluations.
480
- * @returns the stored reference, or the failures that prevented one.
481
- */
482
- async capture(request: CaptureRequest, signal?: AbortSignal): Promise<CaptureOutcome> {
483
- const sessionId = referenceOwnerKey(request.sessionId)
484
- if (sessionId === '') return { failures: [{ kind: 'reference', reason: 'session-id-required' }] }
485
- const browserSessionId = (request.browserSessionId ?? request.sessionId).trim()
486
- if (browserSessionId === '') return { failures: [{ kind: 'reference', reason: 'browser-session-id-required' }] }
487
- // A frozen capture needs no browser session: the page already handed over the complete snapshot, so
488
- // nothing has to be read from a tab. The Web sidebar is exactly that case — its guest is an iframe
489
- // the plugin does not own, so it has no browser:<uuid> at all, and requiring one refused every
490
- // quote with "session-unavailable" (measured 422 on every attempt, in every conversation).
491
- const fromFrozen = request.frozenCapture !== undefined && request.browserSessionId === undefined
492
- if (request.sourcePageId !== undefined && (!fromFrozen || !this.webSources?.owns(sessionId, request.sourcePageId))) {
493
- return { failures: [{ kind: 'reference', reason: 'web-source-not-owned' }] }
494
- }
495
- if (!fromFrozen && !this.host.exists(browserSessionId)) {
496
- return { failures: [{ kind: 'reference', reason: 'session-unavailable' }] }
497
- }
498
-
499
- const frameSelector = request.frameSelector === undefined ? undefined : validateFrameSelector(request.frameSelector)
500
- if (request.frameSelector !== undefined && frameSelector === undefined) {
501
- return { failures: [{ kind: 'reference', reason: 'invalid-frame-selector' }] }
502
- }
503
- let raw: RawCaptureResult
504
- try {
505
- const frozen = request.frozenCapture
506
- if (frozen !== undefined) {
507
- // The bar froze this while the real range still existed. Confirm the page
508
- // is still the same document before trusting it: a capture from a page
509
- // the user navigated away from must fail loudly, not silently become a
510
- // quote of whatever is on screen now.
511
- const frozenUrl = typeof frozen.url === 'string' ? frozen.url : ''
512
- if (request.sourcePageId !== undefined && !this.webSources?.owns(sessionId, request.sourcePageId, frozenUrl)) {
513
- return { failures: [{ kind: 'reference', reason: 'page-changed' }] }
514
- }
515
- if (!fromFrozen && frozenUrl !== '' && this.host.exists(browserSessionId)) {
516
- const facts = await this.run<{ url?: unknown }>(browserSessionId, pageFactsScript(), [], signal)
517
- const currentUrl = typeof facts === 'object' && facts !== null && typeof (facts as { url?: unknown }).url === 'string'
518
- ? String((facts as { url: string }).url)
519
- : ''
520
- // Same rule as reveal: a fragment-only change is the same document.
521
- if (currentUrl !== '' && !samePage(currentUrl, frozenUrl)) {
522
- return { failures: [{ kind: 'reference', reason: 'page-changed' }] }
523
- }
524
- }
525
- raw = frozen
526
- } else if (frameSelector !== undefined) {
527
- const framed = validateFrameCapture(
528
- await this.run<unknown>(browserSessionId, frameCaptureScript(), [{
529
- frameSelector, context: this.options.context,
530
- maxChars: this.options.maxPageText, maxCells: this.options.maxTableCells,
531
- ...request.tableSelector !== undefined ? { tableSelector: request.tableSelector } : {},
532
- ...request.excerptText !== undefined && request.excerptText !== '' ? { excerptText: request.excerptText } : {},
533
- ...request.target !== undefined ? { target: request.target } : {},
534
- }], signal),
535
- frameSelector,
536
- )
537
- if (framed === undefined) return { failures: [{ kind: 'reference', reason: 'frame-capture-invalid' }] }
538
- if (framed.ok !== true) {
539
- return { failures: [{ kind: 'reference', reason: `frame-capture-refused: ${framed.reason ?? 'unavailable'}` }] }
540
- }
541
- raw = {
542
- ok: true,
543
- url: framed.url,
544
- frameUrl: framed.frameUrl,
545
- title: framed.title,
546
- events: (framed.events ?? []) as readonly RawCaptureEvent[],
547
- }
548
- } else {
549
- raw = await this.run<RawCaptureResult>(browserSessionId, captureScript(), [{
550
- context: this.options.context,
551
- maxChars: this.options.maxPageText,
552
- maxCells: this.options.maxTableCells,
553
- ...request.tableSelector !== undefined ? { tableSelector: request.tableSelector } : {},
554
- ...request.excerptText !== undefined && request.excerptText !== '' ? { excerptText: request.excerptText } : {},
555
- ...request.target !== undefined ? { target: request.target } : {},
556
- }], signal)
557
- }
558
- } catch (error) {
559
- return { failures: [{ kind: 'reference', reason: `capture-failed: ${messageOf(error)}` }] }
560
- }
561
- if (raw.ok !== true) {
562
- return { failures: [{ kind: 'reference', reason: textOf(raw.reason, 200) || 'capture-refused' }] }
563
- }
564
-
565
- const failures: CaptureFailure[] = []
566
- const parts: BrowserReferencePart[] = []
567
- const pageUrl = textOf(raw.url, 4000)
568
- // Without a page address the reference can never be revealed or checked for
569
- // "still the same page", so it is not a usable snapshot.
570
- if (pageUrl === '') return { failures: [{ kind: 'reference', reason: 'page-url-missing' }] }
571
- const events = Array.isArray(raw.events) ? raw.events : []
572
- let counter = 0
573
- const nextPartId = (): string => `p${++counter}`
574
-
575
- if (events.length > this.options.maxParts) {
576
- failures.push({ kind: 'reference', reason: 'too-many-parts', detail: { parts: events.length, limit: this.options.maxParts } })
577
- }
578
-
579
- for (const event of events.slice(0, this.options.maxParts)) {
580
- if (!isRecord(event)) continue
581
- const kind = textOf((event as RawCaptureEvent).kind, 20)
582
- if (kind === 'text') {
583
- const textPart = this.textPart(event as RawCaptureEvent, nextPartId)
584
- if ('reason' in textPart) failures.push(textPart)
585
- else parts.push(textPart)
586
- } else if (kind === 'image') {
587
- const imagePart = await this.imagePart(browserSessionId, event as RawCaptureEvent, nextPartId, signal, {
588
- verifyImageVersion: request.verifyImageVersion !== false,
589
- allowVisibleSnapshot: request.allowVisibleSnapshot !== false,
590
- })
591
- if ('reason' in imagePart) failures.push(imagePart)
592
- else parts.push(imagePart)
593
- } else if (kind === 'table') {
594
- const tablePart = await this.tablePart(browserSessionId, event as RawCaptureEvent, nextPartId, signal, {
595
- // A cell image is one image, not "whatever region is selected"; a
596
- // masked visible snapshot of the table would misreport it.
597
- verifyImageVersion: request.verifyImageVersion !== false,
598
- allowVisibleSnapshot: false,
599
- })
600
- if ('reason' in tablePart) failures.push(tablePart)
601
- else {
602
- parts.push(tablePart.part)
603
- parts.push(...tablePart.cellImages)
604
- failures.push(...tablePart.failures)
605
- }
606
- } else {
607
- failures.push({ kind: 'reference', reason: 'unsupported-part', detail: { kind } })
608
- }
609
- }
610
-
611
- if (parts.length === 0) {
612
- failures.push({ kind: 'reference', reason: 'nothing-captured' })
613
- return { failures }
614
- }
615
- if (failures.length > 0 && request.allowPartial !== true) return { failures }
616
-
617
- const carrier = request.carrier ?? 'bundled'
618
- // The comment is the human's own note; bound it so a hostile page cannot
619
- // turn it into an unbounded record, and trim rather than reject.
620
- const comment = textOf(request.comment, MAX_REFERENCE_COMMENT).trim()
621
- const origin = request.origin ?? 'user-selection'
622
- const entry = request.entry ?? 'agent-tool'
623
- const referenceId = this.host.newId?.() ?? randomUUID()
624
- const frameUrl = textOf(raw.frameUrl, 4000) || pageUrl
625
- const withoutHash = {
626
- version: 1 as const,
627
- provider: 'dsh-browser' as const,
628
- referenceId,
629
- owner: { sessionId, ...fromFrozen ? {} : { browserSessionId }, ...request.sourcePageId === undefined ? {} : { sourcePageId: request.sourcePageId } },
630
- provenance: { origin, entry },
631
- source: {
632
- pageUrl,
633
- title: textOf(raw.title, 500),
634
- capturedAt: (this.host.now?.() ?? new Date()).toISOString(),
635
- ...frameUrl !== '' ? {
636
- frameUrl,
637
- frameRoute: frameSelector !== undefined ? 'frame' as const : 'main' as const,
638
- ...frameSelector !== undefined ? { frameSelector } : {},
639
- } : {},
640
- carrier,
641
- },
642
- parts,
643
- ...comment !== '' ? { comment } : {},
644
- }
645
- const reference: BrowserReference = { ...withoutHash, manifestHash: manifestHashOf(withoutHash) }
646
- try {
647
- this.store.append(reference)
648
- } catch (error) {
649
- return { failures: [...failures, { kind: 'reference', reason: `store-refused: ${messageOf(error)}` }] }
650
- }
651
- return { reference, failures }
652
- }
653
-
654
- /**
655
- * Tell the page that its capture did not become a reference.
656
- *
657
- * A refused capture used to be stderr-only: the bar closed and the reader had
658
- * no idea why nothing appeared. This is best-effort — a page that navigated
659
- * away or a carrier without an evaluate path must not fail the capture.
660
- *
661
- * @param sessionId - the browser view the bar lives in.
662
- * @param text - one sentence for the reader.
663
- */
664
- async notify(sessionId: string, text: string): Promise<void> {
665
- try {
666
- await this.run<unknown>(sessionId, noticeScript(text), [])
667
- } catch {
668
- // Deliberately ignored: the delivery path already reported the failure.
669
- }
670
- }
671
-
672
- /**
673
- * Locate one stored reference in its page. Without a `partId` the group's
674
- * first part is located, which is the group's reading position.
675
- * @param referenceId - the stored reference.
676
- * @param request - optional specific part.
677
- * @param signal - cancels the page evaluations.
678
- */
679
- async reveal(referenceId: string, request: { readonly partId?: string; readonly navigate?: boolean; readonly sourcePageId?: string; readonly ownerSessionId?: string } = {}, signal?: AbortSignal): Promise<RevealOutcome> {
680
- const reference = this.store.get(referenceId)
681
- if (reference === undefined) return { referenceId, status: 'not-found', pageUrl: '', parts: [], note: 'no such reference is stored' }
682
- const owner = referenceOwnerKey(reference.owner.sessionId ?? '')
683
- if (request.ownerSessionId !== undefined && referenceOwnerKey(request.ownerSessionId) !== owner) {
684
- return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: 'reference belongs to another conversation' }
685
- }
686
- const sourcePageId = request.sourcePageId ?? reference.owner.sourcePageId
687
- const webPage = sourcePageId?.startsWith('iframe:') ? sourcePageId : undefined
688
- if (webPage !== undefined) {
689
- const target = request.partId === undefined ? reference.parts.slice(0, 1) : reference.parts.filter(part => part.partId === request.partId)
690
- if (target.length === 0) return { referenceId, status: 'not-found', pageUrl: reference.source.pageUrl, parts: [] }
691
- const status = await this.webSources?.reveal(reference, webPage, request.partId, signal) ?? 'unavailable'
692
- return { referenceId, status, pageUrl: reference.source.pageUrl, parts: target.map(part => ({ partId: part.partId, type: part.type, status: status === 'revealed' ? 'revealed' : status === 'ambiguous' ? 'ambiguous' : 'missing' })), ...status === 'unavailable' ? { note: 'owned web source is unavailable or did not acknowledge reveal' } : {} }
693
- }
694
- const captured = reference.owner.browserSessionId
695
- const live = captured !== undefined && captured !== '' && this.host.exists(captured) ? captured : undefined
696
- let sessionId = live
697
- if (sourcePageId !== undefined) {
698
- const owner = referenceOwnerKey(reference.owner.sessionId ?? '')
699
- if (!owner || this.sourceSession === undefined) return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: 'sidebar source binding unsupported' }
700
- try { sessionId = await this.sourceSession(owner, sourcePageId) }
701
- catch (error) { return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) } }
702
- }
703
- if (sessionId === undefined) {
704
- if (reference.source.carrier === 'sidebar') {
705
- try { await this.sourceReady?.(owner) }
706
- catch (error) { return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) } }
707
- }
708
- return {
709
- referenceId,
710
- status: captured === undefined ? 'unavailable' : 'session-unavailable',
711
- pageUrl: reference.source.pageUrl,
712
- parts: [],
713
- note: captured === undefined ? 'reference has no live source binding' : 'the browser session that captured this reference is gone',
714
- }
715
- }
716
-
717
- let facts: { readonly url?: unknown }
718
- try {
719
- facts = await this.run<{ url?: unknown }>(sessionId, pageFactsScript(), [], signal)
720
- } catch (error) {
721
- return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) }
722
- }
723
- const currentUrl = textOf(facts.url, 4000)
724
- if (!samePage(currentUrl, reference.source.pageUrl)) {
725
- return {
726
- referenceId,
727
- status: 'page-mismatch',
728
- pageUrl: reference.source.pageUrl,
729
- currentUrl,
730
- parts: [],
731
- note: 'the session is showing another page; open the stored URL before revealing',
732
- }
733
- }
734
-
735
- const target = request.partId === undefined
736
- ? reference.parts.slice(0, 1)
737
- : reference.parts.filter(part => part.partId === request.partId)
738
- if (target.length === 0) {
739
- return { referenceId, status: 'not-found', pageUrl: reference.source.pageUrl, currentUrl, parts: [], note: 'no such part in this reference' }
740
- }
741
-
742
- const results: RevealPartResult[] = []
743
- let pageText: string | undefined
744
- for (const part of target) {
745
- if (part.type === 'text') {
746
- try {
747
- if (pageText === undefined) {
748
- const read = await this.run<RawPageTextResult>(sessionId, pageTextScript(), [{ maxChars: this.options.maxPageText, legacy: part.content === undefined }], signal)
749
- pageText = textOf(read.text, this.options.maxPageText)
750
- }
751
- const locate = findTextQuote(pageText, part.anchor)
752
- if (locate.status === 'found' && locate.range !== undefined) {
753
- const highlight = await this.run<RawHighlightResult>(sessionId, highlightScript(), [{
754
- start: locate.range.start,
755
- end: locate.range.end,
756
- maxChars: this.options.maxPageText,
757
- legacy: part.content === undefined,
758
- }], signal)
759
- results.push({
760
- partId: part.partId,
761
- type: 'text',
762
- status: highlight.ok === true ? 'revealed' : 'missing',
763
- matches: locate.matches.length,
764
- collapsed: locate.collapsed,
765
- ...highlight.ok === true ? {} : { note: textOf(highlight.reason, 200) || 'highlight-failed' },
766
- })
767
- } else {
768
- results.push({
769
- partId: part.partId,
770
- type: 'text',
771
- status: locate.status === 'ambiguous' ? 'ambiguous' : 'missing',
772
- matches: locate.matches.length,
773
- collapsed: locate.collapsed,
774
- })
775
- }
776
- } catch (error) {
777
- results.push({ partId: part.partId, type: 'text', status: 'missing', note: messageOf(error) })
778
- }
779
- } else if (part.type === 'image') {
780
- const result = await this.revealElement(sessionId, 'image', {
781
- ...part.anchor,
782
- ...part.alt !== undefined ? { alt: part.alt } : {},
783
- }, signal)
784
- results.push({ partId: part.partId, type: 'image', status: result.status, matches: result.matches })
785
- } else {
786
- const cells = part.table.cells.filter(cell => cell.includedAs === 'selection')
787
- .map(({ row, column }) => ({ row, column }))
788
- const result = await this.revealElement(sessionId, 'table', part.anchor, signal, cells)
789
- results.push({ partId: part.partId, type: 'table', status: result.status, matches: result.matches })
790
- }
791
- }
792
-
793
- const revealed = results.filter(result => result.status === 'revealed').length
794
- const status: RevealOutcome['status'] = revealed === results.length
795
- ? 'revealed'
796
- : revealed > 0 ? 'partial' : results.some(result => result.status === 'ambiguous') ? 'ambiguous' : 'missing'
797
- return { referenceId, status, pageUrl: reference.source.pageUrl, currentUrl, parts: results }
798
- }
799
-
800
- private async revealElement(
801
- sessionId: string,
802
- kind: 'image' | 'table',
803
- anchor: object,
804
- signal?: AbortSignal,
805
- cells?: readonly { readonly row: number; readonly column: number }[],
806
- ): Promise<{ status: 'revealed' | 'ambiguous' | 'missing'; matches?: number }> {
807
- try {
808
- const result = await this.run<RawElementRevealResult>(sessionId, revealElementScript(), [{
809
- kind,
810
- anchor,
811
- ...cells === undefined ? {} : { cells },
812
- }], signal)
813
- const status = result.status === 'found' ? 'revealed' : result.status === 'ambiguous' ? 'ambiguous' : 'missing'
814
- return { status, ...typeof result.matches === 'number' ? { matches: result.matches } : {} }
815
- } catch {
816
- return { status: 'missing' }
817
- }
818
- }
819
-
820
- /** Validate one text event into a part, or a failure. */
821
- private textPart(event: RawCaptureEvent, nextPartId: () => string): TextReferencePart | CaptureFailure {
822
- const exact = textOf(event.exact, this.options.maxTextPartLength + 1)
823
- if (exact.trim() === '') return { kind: 'text', reason: 'empty-text' }
824
- if (event.content === undefined && exact.length > this.options.maxTextPartLength) {
825
- return { kind: 'text', reason: 'text-too-long', detail: { characters: exact.length, limit: this.options.maxTextPartLength } }
826
- }
827
- const content = event.content === undefined ? undefined : normalizeReferenceText(event.content, Infinity)
828
- if (event.content !== undefined && (content === undefined
829
- || referenceTextContent(content).replace(/\s/gu, '') !== exact.replace(/\s/gu, ''))) {
830
- return { kind: 'text', reason: 'invalid-text-content' }
831
- }
832
- if (content !== undefined && !isReferenceText(content, this.options.maxTextPartLength)) {
833
- return { kind: 'text', reason: 'text-too-long', detail: { characters: renderReferenceText(content).length, limit: this.options.maxTextPartLength } }
834
- }
835
- return {
836
- partId: nextPartId(),
837
- type: 'text',
838
- text: exact,
839
- ...(content === undefined ? {} : { content }),
840
- anchor: {
841
- exact,
842
- prefix: textOf(event.prefix, 512),
843
- suffix: textOf(event.suffix, 512),
844
- },
845
- }
846
- }
847
-
848
- /** Validate one image event, materialise its bytes, or fail it. */
849
- private async imagePart(
850
- sessionId: string,
851
- event: RawCaptureEvent,
852
- nextPartId: () => string,
853
- signal?: AbortSignal,
854
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
855
- verifyImageVersion: true, allowVisibleSnapshot: true,
856
- },
857
- ): Promise<ImageReferencePart | CaptureFailure> {
858
- const currentSrc = textOf(event.currentSrc, 4000)
859
- const src = textOf(event.src, 4000)
860
- const attributeSrc = textOf(event.attributeSrc, 4000)
861
- const dataUrl = textOf(event.dataUrl, Math.ceil(this.options.maxImageBytes * 4 / 3) + 4096)
862
- const alt = textOf(event.alt, 500)
863
- const selector = textOf(event.selector, 1000)
864
- const path = numberPathOf(event.path)
865
- if (currentSrc === '' && src === '' && attributeSrc === '' && dataUrl === '' && selector === '' && path === undefined) {
866
- return { kind: 'image', reason: 'image-has-no-source' }
867
- }
868
- const saved = await this.materializeImage(sessionId, {
869
- urls: [...new Set([dataUrl, currentSrc, src, attributeSrc].filter(url => url !== ''))],
870
- ...path !== undefined ? { path } : {},
871
- ...selector !== '' ? { selector } : {},
872
- }, signal, policy)
873
- if ('reason' in saved) return { kind: 'image', reason: saved.reason, ...saved.detail !== undefined ? { detail: saved.detail } : {} }
874
- const partId = nextPartId()
875
- const anchorSrc = /^data:/i.test(src) ? '' : src
876
- const anchorCurrent = /^data:/i.test(currentSrc) ? '' : currentSrc
877
- return {
878
- partId,
879
- type: 'image',
880
- assetKey: saved.assetKey,
881
- representation: saved.representation,
882
- ...alt !== '' ? { alt } : {},
883
- ...textOf(event.caption, 500) !== '' ? { caption: textOf(event.caption, 500) } : {},
884
- anchor: {
885
- ...anchorSrc !== '' ? { src: anchorSrc } : {},
886
- ...anchorCurrent !== '' ? { currentSrc: anchorCurrent } : {},
887
- ...alt !== '' ? { alt } : {},
888
- ...selector !== '' ? { selector } : {},
889
- ...isRecord(event.geometry) ? { geometry: {
890
- x: integerOf(event.geometry.x, 0, -1_000_000, 1_000_000),
891
- y: integerOf(event.geometry.y, 0, -1_000_000, 1_000_000),
892
- w: integerOf(event.geometry.w, 0, 0, 1_000_000),
893
- h: integerOf(event.geometry.h, 0, 0, 1_000_000),
894
- } } : {},
895
- ...saved.versionStatus !== undefined ? { versionStatus: saved.versionStatus } : {},
896
- ...saved.visible !== undefined ? { visible: {
897
- rects: saved.visible.rects,
898
- partiallyVisible: saved.visible.partiallyVisible,
899
- clip: {
900
- x: saved.visible.clip.x, y: saved.visible.clip.y,
901
- width: saved.visible.clip.width, height: saved.visible.clip.height,
902
- },
903
- dpr: saved.visible.dpr,
904
- visualScale: saved.visible.visualScale,
905
- viewport: saved.visible.viewport,
906
- scroll: saved.visible.scroll,
907
- } } : {},
908
- },
909
- }
910
- }
911
-
912
- /**
913
- * Try the page's real bytes first, then a page-side raster, then — only when
914
- * the host can take a read-only clipped screenshot — a masked visible-region
915
- * snapshot. Remember which one the stored asset actually is.
916
- *
917
- * B33/B57: a URL may serve a newer asset between selection and download.
918
- * When the page session can still be probed and its digest disagrees with the
919
- * downloaded bytes, those bytes are NEVER advertised as 'source-image'.
920
- * An unprobeable page is reported as unverifiable, not as a verified match.
921
- */
922
- private async materializeImage(
923
- sessionId: string,
924
- image: { readonly urls: readonly string[]; readonly path?: readonly number[]; readonly selector?: string },
925
- signal?: AbortSignal,
926
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
927
- verifyImageVersion: true, allowVisibleSnapshot: true,
928
- },
929
- ): Promise<MaterializedAsset | { reason: string; detail?: Record<string, unknown> }> {
930
- let versionChangedUrl = ''
931
- for (const url of image.urls) {
932
- if (/^data:image\//i.test(url)) {
933
- const decoded = decodeDataUrl(url)
934
- if (decoded !== undefined && decoded.bytes.length <= this.options.maxImageBytes) {
935
- const saved = this.saveAsset(decoded.bytes, '', 'source-image')
936
- if (saved !== undefined) return saved
937
- }
938
- continue
939
- }
940
- if (/^https?:/i.test(url) && this.host.download !== undefined) {
941
- const temp = join(this.assetDir, '.tmp', `${randomUUID()}.bin`)
942
- mkdirSync(dirname(temp), { recursive: true })
943
- try {
944
- await this.host.download(sessionId, url, temp, signal)
945
- const bytes = readFileSync(temp)
946
- if (bytes.length > 0 && bytes.length <= this.options.maxImageBytes) {
947
- let status: VersionStatus = 'unverifiable'
948
- if (policy.verifyImageVersion) {
949
- try {
950
- const probe = await this.run<unknown>(sessionId, versionProbeScript(), [{ url }], signal)
951
- status = compareImageVersion(probe, bytes)
952
- } catch {
953
- // A blocked page fetch, a dead session or a timed-out evaluate
954
- // is not evidence either way. Keep the old honest behaviour and
955
- // record the uncertainty in the asset sidecar.
956
- status = 'unverifiable'
957
- }
958
- }
959
- if (status === 'changed') {
960
- versionChangedUrl = url
961
- continue
962
- }
963
- const saved = this.saveAsset(bytes, url, 'source-image', { versionStatus: status })
964
- if (saved !== undefined) return { ...saved, versionStatus: status }
965
- }
966
- } catch { /* the page-side raster below is the next honest attempt */ } finally {
967
- try { rmSync(temp, { force: true }) } catch { /* temp file already gone */ }
968
- }
969
- }
970
- }
971
-
972
- let rasterReason: string | undefined
973
- try {
974
- const raster = await this.run<RawRasterResult>(sessionId, rasterizeScript(), [{
975
- path: image.path,
976
- selector: image.selector,
977
- maxDimension: 1600,
978
- }], signal)
979
- if (raster.ok === true && typeof raster.dataUrl === 'string') {
980
- const decoded = decodeDataUrl(raster.dataUrl)
981
- if (decoded !== undefined && decoded.bytes.length <= this.options.maxImageBytes) {
982
- const sourceUrl = image.urls.find(url => !/^data:/i.test(url)) ?? ''
983
- const saved = this.saveAsset(decoded.bytes, sourceUrl, 'rasterized-image')
984
- if (saved !== undefined) return saved
985
- }
986
- } else {
987
- rasterReason = textOf(raster.reason, 100) || 'raster-failed'
988
- }
989
- } catch (error) {
990
- rasterReason = messageOf(error)
991
- }
992
-
993
- if (policy.allowVisibleSnapshot) {
994
- const visible = await this.tryVisibleSnapshot(sessionId, signal)
995
- if (visible !== undefined) return visible
996
- }
997
- if (versionChangedUrl !== '') {
998
- return {
999
- reason: 'image-version-changed',
1000
- detail: { url: versionChangedUrl.slice(0, 300), status: 'changed' },
1001
- }
1002
- }
1003
- if (rasterReason !== undefined) return { reason: 'image-unavailable', detail: { page: rasterReason } }
1004
- return { reason: 'image-not-an-image' }
1005
- }
1006
-
1007
- /**
1008
- * B58/B12/B10: mask every rectangle outside the selection, capture only the
1009
- * visible intersection, then remove the mask even when the capture fails.
1010
- * The mask (not an oversized clip) is what keeps a multi-column selection
1011
- * free of the neighbouring column's content.
1012
- */
1013
- private async tryVisibleSnapshot(sessionId: string, signal?: AbortSignal): Promise<MaterializedAsset | undefined> {
1014
- if (this.host.captureVisible === undefined) return undefined
1015
- let facts: ScreenshotFacts | undefined
1016
- try {
1017
- facts = validateVisibleFacts(await this.run<unknown>(sessionId, visibleFactsScript(), [], signal))
1018
- } catch { return undefined }
1019
- if (facts === undefined) return undefined
1020
- const planned = clipFromFacts(facts)
1021
- if (planned === undefined) return undefined
1022
- // The mask is applied BEFORE the screenshot and removed in `finally`. The
1023
- // flag is set before the page call, not after it returns: a timed-out call
1024
- // may still have run, and leaving the shade over the human's page would be a
1025
- // visible, permanent side effect of a failed capture.
1026
- let maskAttempted = false
1027
- try {
1028
- maskAttempted = true
1029
- await this.run<unknown>(sessionId, maskScript(), [{
1030
- rects: facts.rects,
1031
- viewportWidth: facts.viewportWidth,
1032
- viewportHeight: facts.viewportHeight,
1033
- }], signal)
1034
- const shot = await this.host.captureVisible(sessionId, planned.clip, signal)
1035
- const decoded = decodeDataUrl(shot.dataUrl)
1036
- if (decoded === undefined || decoded.bytes.length === 0 || decoded.bytes.length > this.options.maxImageBytes) return undefined
1037
- const saved = this.saveAsset(decoded.bytes, '', 'visible-snapshot', { visible: planned.meta })
1038
- if (saved === undefined) return undefined
1039
- return { ...saved, visible: planned.meta }
1040
- } catch {
1041
- return undefined
1042
- } finally {
1043
- if (maskAttempted) {
1044
- // No signal on purpose: an aborted or timed-out capture is exactly when
1045
- // the page most needs its shade removed, so cleanup must not be cancelled.
1046
- try { await this.run<unknown>(sessionId, unmaskScript(), []) } catch { /* best effort cleanup */ }
1047
- }
1048
- }
1049
- }
1050
-
1051
- /** Write content-addressed bytes plus a metadata sidecar. */
1052
- private saveAsset(
1053
- bytes: Buffer,
1054
- sourceUrl: string,
1055
- representation: 'source-image' | 'rasterized-image' | 'visible-snapshot',
1056
- extra: { readonly versionStatus?: VersionStatus; readonly visible?: VisibleCaptureMeta } = {},
1057
- ): MaterializedAsset | undefined {
1058
- const mime = sniffImageMime(bytes)
1059
- if (mime === undefined) return undefined
1060
- const assetKey = createHash('sha256').update(bytes).digest('hex')
1061
- mkdirSync(this.assetDir, { recursive: true })
1062
- const file = join(this.assetDir, `${assetKey}.bin`)
1063
- if (!existsSync(file)) {
1064
- const temp = `${file}.${process.pid}-${randomUUID()}.tmp`
1065
- writeFileSync(temp, bytes)
1066
- renameSync(temp, file)
1067
- }
1068
- const meta: ReferenceAssetMeta = {
1069
- assetKey,
1070
- mime,
1071
- bytes: bytes.length,
1072
- sourceUrl,
1073
- representation,
1074
- savedAt: (this.host.now?.() ?? new Date()).toISOString(),
1075
- ...extra.versionStatus !== undefined ? { versionStatus: extra.versionStatus } : {},
1076
- ...extra.visible !== undefined ? { visible: extra.visible } : {},
1077
- }
1078
- const metaFile = join(this.assetDir, `${assetKey}.json`)
1079
- if (!existsSync(metaFile)) {
1080
- // Same atomic temp + rename as the .bin above: two processes (or a crash
1081
- // mid-write) must never leave a half-written sidecar that /asset would
1082
- // silently serve as application/octet-stream.
1083
- const temp = `${metaFile}.${process.pid}-${randomUUID()}.tmp`
1084
- writeFileSync(temp, JSON.stringify(meta))
1085
- renameSync(temp, metaFile)
1086
- }
1087
- return { assetKey, representation }
1088
- }
1089
-
1090
- /** Validate one table event into a part plus the image parts its cells carry. */
1091
- private async tablePart(
1092
- sessionId: string,
1093
- event: RawCaptureEvent,
1094
- nextPartId: () => string,
1095
- signal?: AbortSignal,
1096
- policy: { readonly verifyImageVersion: boolean; readonly allowVisibleSnapshot: boolean } = {
1097
- verifyImageVersion: true, allowVisibleSnapshot: false,
1098
- },
1099
- ): Promise<{ part: TableReferencePart; cellImages: ImageReferencePart[]; failures: CaptureFailure[] } | CaptureFailure> {
1100
- const raw = event.table
1101
- if (!isRecord(raw)) return { kind: 'table', reason: 'table-missing' }
1102
- const table = raw as RawTable
1103
- const rawCells = Array.isArray(table.cells) ? table.cells.map(cell => isRecord(cell) && cell.content !== undefined
1104
- ? { ...cell, content: normalizeReferenceText(cell.content) ?? null } : cell) : []
1105
- if (rawCells.length === 0) return { kind: 'table', reason: 'table-empty' }
1106
- if (booleanOf(table.truncated) || rawCells.length > this.options.maxTableCells) {
1107
- return {
1108
- kind: 'table',
1109
- reason: 'table-too-large',
1110
- detail: { cells: rawCells.length, limit: this.options.maxTableCells },
1111
- }
1112
- }
1113
-
1114
- if (rawCells.some(cell => isRecord(cell) && cell.content !== undefined && (!isReferenceText(cell.content)
1115
- || referenceTextContent(cell.content).replace(/\s/gu, '') !== textOf(cell.text, 2000).replace(/\s/gu, '')))) {
1116
- return { kind: 'table', reason: 'invalid-text-content' }
1117
- }
1118
- const failures: CaptureFailure[] = []
1119
- const cellImages: ImageReferencePart[] = []
1120
- const cells: TableCellSnapshot[] = []
1121
- // The table comes first in `parts`, so it takes its id before the cell images it carries:
1122
- // ids must read in part order or a caller citing `p1` would mean the image, not the table.
1123
- const tablePartId = nextPartId()
1124
- let firstSelectedCell: { row: number; column: number } | undefined
1125
-
1126
- for (const candidate of rawCells) {
1127
- if (!isRecord(candidate)) continue
1128
- const cell = candidate as RawCell
1129
- const row = integerOf(cell.row, -1, 0, 100_000)
1130
- const column = integerOf(cell.column, -1, 0, 10_000)
1131
- if (row < 0 || column < 0) continue
1132
- const role = cell.role === 'header' ? 'header' : 'data'
1133
- const includedAs = cell.includedAs === 'header-context' ? 'header-context' : 'selection'
1134
- const runs: TableCellRun[] = []
1135
- for (const rawRun of Array.isArray(cell.inlineContent) ? cell.inlineContent.slice(0, 50) : []) {
1136
- if (!isRecord(rawRun)) continue
1137
- const run = rawRun as RawCellRun
1138
- if (run.type === 'text') {
1139
- const text = textOf(run.text, 2000)
1140
- if (text !== '') runs.push({ type: 'text', text })
1141
- } else if (run.type === 'image') {
1142
- const saved = await this.materializeImage(sessionId, {
1143
- urls: [...new Set([textOf(run.currentSrc, 4000), textOf(run.src, 4000)].filter(url => url !== ''))],
1144
- }, signal, policy)
1145
- if ('reason' in saved) {
1146
- failures.push({ kind: 'image', reason: `cell-image: ${saved.reason}`, detail: { row, column } })
1147
- continue
1148
- }
1149
- const partId = nextPartId()
1150
- runs.push({ type: 'image', partId, assetKey: saved.assetKey })
1151
- cellImages.push({
1152
- partId,
1153
- type: 'image',
1154
- assetKey: saved.assetKey,
1155
- representation: saved.representation,
1156
- anchor: {
1157
- ...textOf(run.currentSrc, 4000) !== '' ? { currentSrc: textOf(run.currentSrc, 4000) } : {},
1158
- ...textOf(run.src, 4000) !== '' ? { src: textOf(run.src, 4000) } : {},
1159
- ...textOf(run.alt, 500) !== '' ? { alt: textOf(run.alt, 500) } : {},
1160
- },
1161
- })
1162
- }
1163
- }
1164
- const snapshot: TableCellSnapshot = {
1165
- row,
1166
- column,
1167
- rowSpan: integerOf(cell.rowSpan, 1, 1, 1000),
1168
- columnSpan: integerOf(cell.columnSpan, 1, 1, 200),
1169
- role,
1170
- text: textOf(cell.text, 2000),
1171
- ...(cell.content === undefined ? {} : { content: cell.content }),
1172
- includedAs,
1173
- partialText: booleanOf(cell.partialText),
1174
- ...runs.length > 0 ? { inlineContent: runs } : {},
1175
- }
1176
- if (firstSelectedCell === undefined && includedAs === 'selection') firstSelectedCell = { row, column }
1177
- cells.push(snapshot)
1178
- }
1179
- if (cells.length === 0) return { kind: 'table', reason: 'table-empty' }
1180
-
1181
- const headers: string[] = []
1182
- const firstCells: string[] = []
1183
- for (const cell of cells) {
1184
- // Every header the page captured is a locate hint: one selected header and one kept as
1185
- // context are equally good at recognising the same table after a re-render.
1186
- if (cell.role === 'header' && headers.length < 8 && cell.text !== '' && !headers.includes(cell.text)) headers.push(cell.text)
1187
- if (cell.row === 0 && firstCells.length < 8) firstCells.push(cell.text)
1188
- }
1189
- const completeness = table.completeness === 'visible-rows' || table.completeness === 'dom-table' || table.completeness === 'aria-grid'
1190
- ? table.completeness
1191
- : 'selected-cells'
1192
- const anchor: TableAnchor = {
1193
- ...textOf(event.selector, 1000) !== '' ? { selector: textOf(event.selector, 1000) } : {},
1194
- ...textOf(table.caption, 500) !== '' ? { caption: textOf(table.caption, 500) } : {},
1195
- headers,
1196
- firstCells,
1197
- ...firstSelectedCell !== undefined ? { cell: firstSelectedCell } : {},
1198
- }
1199
- return {
1200
- part: {
1201
- partId: tablePartId,
1202
- type: 'table',
1203
- table: {
1204
- rowCount: integerOf(table.rowCount, 0, 0, 100_000),
1205
- columnCount: integerOf(table.columnCount, 0, 0, 10_000),
1206
- cells,
1207
- ...textOf(table.caption, 500) !== '' ? { caption: textOf(table.caption, 500) } : {},
1208
- completeness,
1209
- normalizationVersion: '1',
1210
- },
1211
- anchor,
1212
- },
1213
- cellImages,
1214
- failures,
1215
- }
1216
- }
1217
-
1218
- private async run<T>(sessionId: string, script: string, args: readonly unknown[], signal?: AbortSignal): Promise<T> {
1219
- const value = await this.host.evaluate(sessionId, {
1220
- script,
1221
- args,
1222
- timeoutMs: this.options.timeoutMs,
1223
- }, signal)
1224
- const parsed = typeof value === 'string' ? JSON.parse(value) as unknown : value
1225
- if (!isRecord(parsed)) throw new Error('browser reference: the page returned no usable result')
1226
- return parsed as T
1227
- }
1228
- }
1229
-
1230
- function messageOf(error: unknown): string {
1231
- return error instanceof Error ? error.message : String(error)
1232
- }
1233
-
1234
- /** What a list row or tool answer carries; the full parts stay in the store. */
1235
- export interface ReferenceSummary {
1236
- readonly referenceId: string
1237
- readonly title: string
1238
- readonly pageUrl: string
1239
- readonly capturedAt: string
1240
- readonly carrier: BrowserReferenceCarrier
1241
- readonly origin: BrowserReferenceOrigin
1242
- readonly entry: BrowserReferenceEntry
1243
- readonly partCount: number
1244
- readonly parts: readonly { readonly partId: string; readonly type: string; readonly preview: string }[]
1245
- }
1246
-
1247
- /**
1248
- * Project one reference into the compact shape a list or a tool answer shows.
1249
- * @param reference - the stored snapshot.
1250
- */
1251
- export function summarizeReference(reference: BrowserReference): ReferenceSummary {
1252
- return {
1253
- referenceId: reference.referenceId,
1254
- title: reference.source.title,
1255
- pageUrl: reference.source.pageUrl,
1256
- capturedAt: reference.source.capturedAt,
1257
- carrier: reference.source.carrier,
1258
- origin: reference.provenance.origin,
1259
- entry: reference.provenance.entry,
1260
- partCount: reference.parts.length,
1261
- parts: reference.parts.map(part => {
1262
- if (part.type === 'text') {
1263
- return { partId: part.partId, type: 'text', preview: part.text.replace(/\s+/g, ' ').slice(0, 160) }
1264
- }
1265
- if (part.type === 'image') {
1266
- return { partId: part.partId, type: 'image', preview: part.alt ?? part.caption ?? part.anchor.src ?? '' }
1267
- }
1268
- const shape = `${part.table.rowCount}x${part.table.columnCount}`
1269
- return { partId: part.partId, type: 'table', preview: part.table.caption !== undefined ? `${part.table.caption} (${shape})` : shape }
1270
- }),
1271
- }
1272
- }
1273
-
1274
- /** The browser surface the service needs; `BrowserRuntime` satisfies it structurally. */
1275
- export interface BrowserRuntimeLike {
1276
- execute(
1277
- session: string,
1278
- request: { readonly script: string; readonly args?: readonly unknown[]; readonly timeoutMs?: number },
1279
- signal?: AbortSignal,
1280
- ): Promise<{ readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly exception: string }>
1281
- exists(session: string): boolean
1282
- download(session: string, request: { readonly url: string; readonly savePath: string }, signal?: AbortSignal): Promise<{ readonly path: string }>
1283
- }
1284
-
1285
- /**
1286
- * Build the service against the plugin's browser runtime.
1287
- * @param browser - the `ctx.browser` runtime.
1288
- * @param options - optional caps and store overrides.
1289
- */
1290
- export function createReferenceService(
1291
- browser: BrowserRuntimeLike,
1292
- options: BrowserReferenceServiceOptions & {
1293
- readonly store?: ReferenceStore
1294
- /** Optional: a read-only clipped screenshot for masked visible snapshots. */
1295
- readonly visibleCapture?: (sessionId: string, clip: VisibleClip, signal?: AbortSignal) => Promise<VisibleCaptureResult>
1296
- } = {},
1297
- ): BrowserReferenceService {
1298
- const { store, visibleCapture, ...rest } = options
1299
- return new BrowserReferenceService({
1300
- evaluate: async (sessionId, request, signal) => {
1301
- const result = await browser.execute(sessionId, {
1302
- script: request.script,
1303
- ...request.args !== undefined ? { args: request.args } : {},
1304
- ...request.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {},
1305
- }, signal)
1306
- if (!result.ok) throw new Error(result.exception)
1307
- return result.value
1308
- },
1309
- exists: sessionId => browser.exists(sessionId),
1310
- download: async (sessionId, url, savePath, signal) => {
1311
- await browser.download(sessionId, { url, savePath }, signal)
1312
- },
1313
- ...visibleCapture !== undefined ? { captureVisible: visibleCapture } : {},
1314
- }, store ?? new ReferenceStore(), { webSources: webReferenceSources(browser), ...rest })
1315
- }