dsh-builtin-browser 0.5.8 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +410 -1
- package/README.en.md +16 -64
- package/README.md +33 -64
- package/assets/browser-carriers.svg +20 -0
- package/assets/browser-extension-identity.d.mts +2 -0
- package/assets/browser-extension-identity.mjs +2 -0
- package/assets/browser-messages.d.mts +5 -0
- package/assets/browser-messages.mjs +64 -0
- package/assets/browser-panel-locales.d.mts +2 -0
- package/assets/browser-panel-locales.mjs +380 -0
- package/assets/browser-policy.d.mts +37 -0
- package/assets/browser-policy.mjs +37 -0
- package/assets/browser-products.d.mts +6 -0
- package/assets/browser-products.mjs +76 -0
- package/assets/screenshots/1-main.png +0 -0
- package/assets/screenshots/2-form-fill.png +0 -0
- package/assets/screenshots/3-challenge.png +0 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/cordis.patch.yml +23 -48
- package/desktop-bridge/desktop-discovery.d.mts +2 -0
- package/desktop-bridge/desktop-discovery.mjs +36 -0
- package/desktop-bridge/desktop-identity.json +17 -1
- package/desktop-bridge/desktop-processes.d.mts +1 -0
- package/desktop-bridge/desktop-processes.mjs +15 -0
- package/desktop-bridge/guest-proxy.mjs +109 -0
- package/desktop-bridge/install.mjs +197 -74
- package/desktop-bridge/main.mjs +11 -0
- package/desktop-bridge/maintenance-files.d.mts +8 -0
- package/desktop-bridge/maintenance-files.mjs +28 -0
- package/desktop-bridge/maintenance-progress.ps1 +2 -2
- package/desktop-bridge/native-guests.mjs +41 -0
- package/desktop-bridge/plugin-browser-bridge.js +618 -370
- package/desktop-bridge/profile-loader.mjs +26 -0
- package/dist/client.cjs +43167 -0
- package/dist/client.d.cts +516 -0
- package/dist/client.d.mts +516 -0
- package/dist/index.cjs +92 -0
- package/dist/index.d.mts +2960 -0
- package/dist/index.mjs +24 -0
- package/docs/HANDOVER-2026-11-15.md +178 -0
- package/docs/README.md +10 -19
- package/docs/architecture.md +17 -145
- package/docs/child-tabs.md +13 -0
- package/docs/desktop-acceptance.md +9 -0
- package/docs/development.md +88 -18
- package/docs/extension-browser.md +44 -0
- package/docs/hardcoding-audit.md +64 -0
- package/docs/limitations.md +23 -73
- package/docs/pr64-extension-status.md +46 -0
- package/docs/pr64-maintenance.md +25 -0
- package/docs/pr64-native-children.md +52 -0
- package/docs/pr64-native-views.md +60 -0
- package/docs/tool-reference.md +87 -11
- package/docs/user-guide.md +47 -255
- package/docs/why-browser.md +6 -39
- package/dsh-host-patch/README.md +60 -0
- package/dsh-host-patch/apply.mjs +194 -0
- package/dsh-host-patch/legacy-bridge.mjs +53 -0
- package/dsh-host-patch/rc3-revision1.json +90 -0
- package/dsh-host-patch/rc3-revision2.json +112 -0
- package/dsh-host-patch/rc3-revision3.json.gz +0 -0
- package/dsh-host-patch/rc3-revision4.json.gz +0 -0
- package/dsh-host-patch/rc3-revision5.json.gz +0 -0
- package/dsh-host-patch/rc3-revision6.json.gz +0 -0
- package/dsh-host-patch/rc3-revision7.json.gz +0 -0
- package/dsh-host-patch/rc3-revision8.json.gz +0 -0
- package/dsh-host-patch/rc3.json +148 -0
- package/dsh-host-patch/rc5-revision1.json +90 -0
- package/dsh-host-patch/rc5-revision2.json +112 -0
- package/dsh-host-patch/rc5-revision3.json.gz +0 -0
- package/dsh-host-patch/rc5-revision4.json.gz +0 -0
- package/dsh-host-patch/rc5-revision5.json.gz +0 -0
- package/dsh-host-patch/rc5-revision6.json.gz +0 -0
- package/dsh-host-patch/rc5-revision7.json.gz +0 -0
- package/dsh-host-patch/rc5-revision8.json.gz +0 -0
- package/dsh-host-patch/rc5.json +148 -0
- package/lib/bridge-compatibility.js +38 -0
- package/lib/browser/handles.js +78 -0
- package/lib/browser/runtime.js +155 -43
- package/lib/browser/takeover-target.js +24 -0
- package/lib/browser-electron/authenticated-route.js +23 -0
- package/lib/browser-electron/automatic-maintenance.js +394 -51
- package/lib/browser-electron/bridge-auto.js +2 -1
- package/lib/browser-electron/bridge-connection.js +8 -1
- package/lib/browser-electron/bridge-install.js +27 -2
- package/lib/browser-electron/bridge-maintenance.js +35 -10
- package/lib/browser-electron/bridge-status.js +98 -27
- package/lib/browser-electron/desktop-bridge-host.js +193 -560
- package/lib/browser-electron/desktop-identity.js +40 -2
- package/lib/browser-electron/document-readiness.js +34 -0
- package/lib/browser-electron/electron-provision.js +14 -44
- package/lib/browser-electron/entry.js +659 -252
- package/lib/browser-electron/extension-browser.js +234 -0
- package/lib/browser-electron/extension-setup.js +69 -0
- package/lib/browser-electron/guest-cookie-jar.LICENSE.txt +32 -0
- package/lib/browser-electron/guest-cookie-jar.js +10559 -0
- package/lib/browser-electron/guest-cookie-store.js +74 -0
- package/lib/browser-electron/guest-css-runtime.js +75 -0
- package/lib/browser-electron/guest-css.js +106 -0
- package/lib/browser-electron/guest-route.js +603 -0
- package/lib/browser-electron/guest-runtime.js +356 -0
- package/lib/browser-electron/guest-storage-runtime.js +52 -0
- package/lib/browser-electron/guest-storage.js +163 -0
- package/lib/browser-electron/history-store.js +2 -1
- package/lib/browser-electron/host-main.js +162 -7
- package/lib/browser-electron/host-patch-maintenance.js +141 -0
- package/lib/browser-electron/http-body.js +22 -0
- package/lib/browser-electron/maintenance-broker.js +35 -5
- package/lib/browser-electron/maintenance-lifecycle.js +7 -5
- package/lib/browser-electron/maintenance-route.js +9 -6
- package/lib/browser-electron/open-slot.js +47 -0
- package/lib/browser-electron/paths.js +4 -1
- package/lib/browser-electron/preferred-browser.js +144 -0
- package/lib/browser-electron/preview-route.js +11 -8
- package/lib/browser-electron/process-ownership.js +198 -0
- package/lib/browser-electron/profile-checkpoint.js +222 -0
- package/lib/browser-electron/profile-command.js +60 -0
- package/lib/browser-electron/profile-extension.js +126 -0
- package/lib/browser-electron/profile-lease.js +157 -0
- package/lib/browser-electron/profile-residue.js +61 -0
- package/lib/browser-electron/provider.js +719 -262
- package/lib/browser-electron/reference-route.js +635 -0
- package/lib/browser-electron/remote-host.js +12 -13
- package/lib/browser-electron/runtime-route.js +6 -5
- package/lib/browser-electron/runtime-status.js +30 -29
- package/lib/browser-electron/settings-store.js +10 -5
- package/lib/browser-electron/shortcuts-route.js +108 -0
- package/lib/browser-electron/sidebar-only-host.js +119 -18
- package/lib/browser-electron/startpage-shortcuts.js +172 -0
- package/lib/browser-electron/system-browser.js +352 -371
- package/lib/browser-electron/windows-system.js +2 -1
- package/lib/browser-reference/delivery.js +326 -0
- package/lib/browser-reference/entry.js +597 -0
- package/lib/browser-reference/export.js +298 -0
- package/lib/browser-reference/import.js +295 -0
- package/lib/browser-reference/page-script.js +1406 -0
- package/lib/browser-reference/service.js +1062 -0
- package/lib/browser-reference/store.js +177 -0
- package/lib/browser-reference/submission-receipts.js +139 -0
- package/lib/browser-reference/text-quote.js +167 -0
- package/lib/browser-reference/types.js +11 -0
- package/lib/browser-reference/visible.js +311 -0
- package/lib/browser-reference/web-sources.js +97 -0
- package/lib/index.js +10 -3
- package/lib/reference-owner.js +5 -0
- package/lib/reference-page.js +12 -0
- package/lib/reference-source.js +2 -0
- package/lib/reference-text.js +188 -0
- package/lib/startpage-settings.js +63 -0
- package/lib/startpage.js +44 -0
- package/lib/takeover-protocol.js +2 -0
- package/lib/tool-browser/code-tool.js +416 -0
- package/lib/tool-browser/code-worker.js +872 -0
- package/lib/tool-browser/index.js +940 -76
- package/lib/tool-browser/page-probe.js +3 -3
- package/lib/tool-browser/panel-page.js +95 -0
- package/lib/tool-browser/screenshot-image.js +51 -0
- package/lib/tool-browser/takeover.js +205 -0
- package/lib/types.js +1 -0
- package/lib/web-guest.js +26 -0
- package/native-host/client.d.mts +17 -0
- package/native-host/client.mjs +100 -0
- package/native-host/host.mjs +150 -0
- package/native-host/identity.d.mts +2 -0
- package/native-host/identity.mjs +1 -0
- package/native-host/install.mjs +168 -0
- package/native-host/protocol.mjs +75 -0
- package/package.json +80 -92
- package/scripts/build.mjs +66 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +50 -0
- package/scripts/install-electron.mjs +11 -26
- package/scripts/verify-exports.mjs +47 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +56 -47
- package/skills/dsh-builtin-browser/references/batch.md +31 -1
- package/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +146 -50
- package/src/browser/takeover-target.ts +36 -0
- package/src/browser/types.ts +19 -7
- package/src/browser-electron/authenticated-route.ts +29 -1
- package/src/browser-electron/automatic-maintenance.ts +368 -56
- package/src/browser-electron/bridge-auto.ts +5 -4
- package/src/browser-electron/bridge-connection.ts +20 -2
- package/src/browser-electron/bridge-endpoint.ts +3 -3
- package/src/browser-electron/bridge-install.ts +40 -4
- package/src/browser-electron/bridge-maintenance.ts +42 -14
- package/src/browser-electron/bridge-status.ts +94 -23
- package/src/browser-electron/desktop-bridge-host.ts +185 -585
- package/src/browser-electron/desktop-identity.ts +53 -2
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +12 -45
- package/src/browser-electron/entry.ts +1299 -882
- package/src/browser-electron/ephemeral-profile.ts +1 -1
- package/src/browser-electron/extension-browser.ts +223 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/guest-cookie-jar.ts +176 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +568 -0
- package/src/browser-electron/guest-runtime.ts +357 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +117 -0
- package/src/browser-electron/history-store.ts +5 -4
- package/src/browser-electron/host-main.ts +156 -11
- package/src/browser-electron/host-patch-maintenance.ts +112 -0
- package/src/browser-electron/http-body.ts +23 -0
- package/src/browser-electron/maintenance-broker.ts +29 -5
- package/src/browser-electron/maintenance-lifecycle.ts +14 -9
- package/src/browser-electron/maintenance-route.ts +17 -14
- package/src/browser-electron/missing-system-browser.ts +2 -2
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +5 -1
- package/src/browser-electron/preferred-browser.ts +120 -0
- package/src/browser-electron/preview-route.ts +18 -11
- package/src/browser-electron/process-ownership.ts +168 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +46 -0
- package/src/browser-electron/profile-extension.ts +124 -0
- package/src/browser-electron/profile-lease.ts +115 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider.ts +771 -289
- package/src/browser-electron/reference-route.ts +608 -0
- package/src/browser-electron/remote-host.ts +15 -15
- package/src/browser-electron/runtime-route.ts +11 -10
- package/src/browser-electron/runtime-status.ts +51 -32
- package/src/browser-electron/settings-store.ts +27 -7
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +118 -19
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +309 -338
- package/src/browser-electron/windows-system.ts +2 -1
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1315 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/submission-receipts.ts +122 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +103 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +176 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +52 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +30 -0
- package/src/client/electron/ElectronWebViewImpl.ts +364 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +138 -0
- package/src/client/electron/NativeChildPresentation.ts +45 -0
- package/src/client/electron/NativeViewPage.ts +251 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +293 -0
- package/src/client/locales.ts +857 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +189 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +471 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +74 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +508 -0
- package/src/client/reference/client/production/http-transport.ts +217 -0
- package/src/client/reference/client/production/production-submission.ts +310 -0
- package/src/client/reference/client/production/protocol.ts +231 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1101 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +63 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +58 -0
- package/src/client/reference/client/reveal.ts +107 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +34 -0
- package/{client.js → src/client/settings/panel.ts} +2657 -2231
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +303 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +314 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +344 -0
- package/src/client/view/StartPage.tsx +597 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/index.ts +110 -73
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +197 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +19 -0
- package/src/tool-browser/code-tool.ts +401 -0
- package/src/tool-browser/code-worker.ts +639 -0
- package/src/tool-browser/index.ts +908 -77
- package/src/tool-browser/page-probe.ts +4 -4
- package/src/tool-browser/panel-page.ts +124 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/takeover.ts +198 -0
- package/src/types/electron-shim.d.ts +20 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +34 -0
- package/tools/accept-desktop.mjs +148 -0
- package/lib/browser/runtime.d.ts +0 -175
- package/lib/browser/types.d.ts +0 -797
- package/lib/browser-electron/authenticated-route.d.ts +0 -27
- package/lib/browser-electron/automatic-maintenance.d.ts +0 -41
- package/lib/browser-electron/bridge-auto.d.ts +0 -93
- package/lib/browser-electron/bridge-connection.d.ts +0 -93
- package/lib/browser-electron/bridge-endpoint.d.ts +0 -30
- package/lib/browser-electron/bridge-install.d.ts +0 -85
- package/lib/browser-electron/bridge-maintenance.d.ts +0 -24
- package/lib/browser-electron/bridge-status.d.ts +0 -50
- package/lib/browser-electron/desktop-bridge-host.d.ts +0 -248
- package/lib/browser-electron/desktop-identity.d.ts +0 -58
- package/lib/browser-electron/electron-provision.d.ts +0 -92
- package/lib/browser-electron/entry.d.ts +0 -64
- package/lib/browser-electron/ephemeral-profile.d.ts +0 -37
- package/lib/browser-electron/file-write.d.ts +0 -2
- package/lib/browser-electron/history-store.d.ts +0 -98
- package/lib/browser-electron/host-main.d.ts +0 -26
- package/lib/browser-electron/http-body.d.ts +0 -24
- package/lib/browser-electron/json-reply.d.ts +0 -33
- package/lib/browser-electron/maintenance-broker.d.ts +0 -35
- package/lib/browser-electron/maintenance-lifecycle.d.ts +0 -32
- package/lib/browser-electron/maintenance-route.d.ts +0 -18
- package/lib/browser-electron/missing-system-browser.d.ts +0 -54
- package/lib/browser-electron/paths.d.ts +0 -4
- package/lib/browser-electron/preview-route.d.ts +0 -89
- package/lib/browser-electron/process.d.ts +0 -14
- package/lib/browser-electron/provider.d.ts +0 -959
- package/lib/browser-electron/remote-host.d.ts +0 -256
- package/lib/browser-electron/rpc-input.d.ts +0 -4
- package/lib/browser-electron/rpc-ops.d.ts +0 -18
- package/lib/browser-electron/runtime-diagnostics.d.ts +0 -12
- package/lib/browser-electron/runtime-route.d.ts +0 -55
- package/lib/browser-electron/runtime-status.d.ts +0 -116
- package/lib/browser-electron/settings-route.d.ts +0 -15
- package/lib/browser-electron/settings-store.d.ts +0 -224
- package/lib/browser-electron/sidebar-only-host.d.ts +0 -36
- package/lib/browser-electron/system-browser.d.ts +0 -367
- package/lib/browser-electron/timing.d.ts +0 -8
- package/lib/browser-electron/virtual-cursor.d.ts +0 -67
- package/lib/browser-electron/windows-system.d.ts +0 -3
- package/lib/index.d.ts +0 -30
- package/lib/tool-browser/element-fields.d.ts +0 -145
- package/lib/tool-browser/index.d.ts +0 -53
- package/lib/tool-browser/page-probe.d.ts +0 -86
- package/scripts/consumer-install-check.mjs +0 -72
- package/scripts/run-tests.mjs +0 -32
- package/scripts/verify-host-compat.mjs +0 -195
- package/scripts/verify-preview-route.mjs +0 -168
- package/scripts/verify-runtime-status.mjs +0 -179
|
@@ -0,0 +1,1062 @@
|
|
|
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
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
18
|
+
import { referenceOwnerKey } from '../reference-owner.js';
|
|
19
|
+
import { webReferenceSources } from './web-sources.js';
|
|
20
|
+
import { sameReferenceDocument as samePage } from '../reference-page.js';
|
|
21
|
+
import { isReferenceText, normalizeReferenceText, MAX_REFERENCE_TEXT, referenceTextContent, renderReferenceText } from '../reference-text.js';
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
23
|
+
import { dirname, join } from 'node:path';
|
|
24
|
+
import { manifestHashOf, ReferenceStore, referenceStorePath } from './store.js';
|
|
25
|
+
import { MAX_REFERENCE_COMMENT } from './entry.js';
|
|
26
|
+
import { collectAssetKeys, encodeReferenceExport, } from './export.js';
|
|
27
|
+
import { findTextQuote } from './text-quote.js';
|
|
28
|
+
import { captureScript, highlightScript, noticeScript, pageFactsScript, pageTextScript, rasterizeScript, revealElementScript, } from './page-script.js';
|
|
29
|
+
import { frameCaptureScript, validateFrameCapture, validateFrameSelector } from './entry.js';
|
|
30
|
+
import { clipFromFacts, compareImageVersion, maskScript, unmaskScript, validateVisibleFacts, versionProbeScript, visibleFactsScript, } from './visible.js';
|
|
31
|
+
let referenceCaptureActionHandler;
|
|
32
|
+
/** Register the handler for a human right-click / floating-button intent. */
|
|
33
|
+
export function setReferenceCaptureActionHandler(handler) {
|
|
34
|
+
referenceCaptureActionHandler = handler;
|
|
35
|
+
return () => { if (referenceCaptureActionHandler === handler)
|
|
36
|
+
referenceCaptureActionHandler = undefined; };
|
|
37
|
+
}
|
|
38
|
+
/** Called by the provider when the host reports a human reference action. */
|
|
39
|
+
export async function dispatchReferenceCaptureAction(action) {
|
|
40
|
+
if (referenceCaptureActionHandler === undefined)
|
|
41
|
+
throw new Error('reference capture handler is unavailable');
|
|
42
|
+
await referenceCaptureActionHandler(action);
|
|
43
|
+
}
|
|
44
|
+
const DEFAULTS = {
|
|
45
|
+
context: 32,
|
|
46
|
+
maxTextPartLength: MAX_REFERENCE_TEXT,
|
|
47
|
+
maxParts: 64,
|
|
48
|
+
maxTableCells: 2_000,
|
|
49
|
+
maxPageText: 2_000_000,
|
|
50
|
+
maxImageBytes: 20 * 1024 * 1024,
|
|
51
|
+
timeoutMs: 20_000,
|
|
52
|
+
};
|
|
53
|
+
function isRecord(value) {
|
|
54
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
55
|
+
}
|
|
56
|
+
function textOf(value, limit) {
|
|
57
|
+
return typeof value === 'string' ? value.slice(0, limit) : '';
|
|
58
|
+
}
|
|
59
|
+
function integerOf(value, fallback, min, max) {
|
|
60
|
+
const number = typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : fallback;
|
|
61
|
+
return Math.min(Math.max(number, min), max);
|
|
62
|
+
}
|
|
63
|
+
function booleanOf(value) {
|
|
64
|
+
return value === true;
|
|
65
|
+
}
|
|
66
|
+
function numberPathOf(value) {
|
|
67
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > 64)
|
|
68
|
+
return undefined;
|
|
69
|
+
const path = [];
|
|
70
|
+
for (const entry of value) {
|
|
71
|
+
if (typeof entry !== 'number' || !Number.isInteger(entry) || entry < 0 || entry > 1_000_000)
|
|
72
|
+
return undefined;
|
|
73
|
+
path.push(entry);
|
|
74
|
+
}
|
|
75
|
+
return path;
|
|
76
|
+
}
|
|
77
|
+
/** Decode a data URL into bytes and its declared MIME type. */
|
|
78
|
+
function decodeDataUrl(url) {
|
|
79
|
+
const match = /^data:([^;,]+)((?:;[^,]*)?),([\s\S]*)$/i.exec(url);
|
|
80
|
+
if (match === null)
|
|
81
|
+
return undefined;
|
|
82
|
+
const mime = match[1].toLowerCase();
|
|
83
|
+
const parameters = match[2].toLowerCase();
|
|
84
|
+
const payload = match[3];
|
|
85
|
+
try {
|
|
86
|
+
const bytes = parameters.includes(';base64')
|
|
87
|
+
? Buffer.from(payload, 'base64')
|
|
88
|
+
: Buffer.from(decodeURIComponent(payload), 'utf8');
|
|
89
|
+
return bytes.length > 0 ? { bytes, mime } : undefined;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Recognise the bytes rather than trusting a page-declared MIME type. */
|
|
96
|
+
export function sniffImageMime(bytes) {
|
|
97
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
|
|
98
|
+
return 'image/png';
|
|
99
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
|
|
100
|
+
return 'image/jpeg';
|
|
101
|
+
if (bytes.length >= 6 && bytes.toString('ascii', 0, 3) === 'GIF')
|
|
102
|
+
return 'image/gif';
|
|
103
|
+
if (bytes.length >= 12 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP')
|
|
104
|
+
return 'image/webp';
|
|
105
|
+
if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d)
|
|
106
|
+
return 'image/bmp';
|
|
107
|
+
if (bytes.length >= 12 && bytes.toString('ascii', 4, 8) === 'ftyp') {
|
|
108
|
+
const brand = bytes.toString('ascii', 8, 12);
|
|
109
|
+
if (brand === 'avif' || brand === 'avis')
|
|
110
|
+
return 'image/avif';
|
|
111
|
+
}
|
|
112
|
+
const head = bytes.toString('utf8', 0, Math.min(bytes.length, 512)).trimStart().toLowerCase();
|
|
113
|
+
if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg')))
|
|
114
|
+
return 'image/svg+xml';
|
|
115
|
+
if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0)
|
|
116
|
+
return 'image/x-icon';
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Capture and reveal browser references for one host.
|
|
121
|
+
*
|
|
122
|
+
* Instances share immutable storage and the browser's owned Web source channel.
|
|
123
|
+
*/
|
|
124
|
+
export class BrowserReferenceService {
|
|
125
|
+
webSources;
|
|
126
|
+
adapter;
|
|
127
|
+
assetDir;
|
|
128
|
+
host;
|
|
129
|
+
options;
|
|
130
|
+
store;
|
|
131
|
+
sourceSession;
|
|
132
|
+
sourceReady;
|
|
133
|
+
constructor(host, store = new ReferenceStore(), options = {}) {
|
|
134
|
+
this.host = host;
|
|
135
|
+
this.store = store;
|
|
136
|
+
this.sourceSession = options.sourceSession;
|
|
137
|
+
this.sourceReady = options.sourceReady;
|
|
138
|
+
this.webSources = options.webSources;
|
|
139
|
+
this.options = {
|
|
140
|
+
context: integerOf(options.context, DEFAULTS.context, 0, 512),
|
|
141
|
+
maxTextPartLength: integerOf(options.maxTextPartLength, DEFAULTS.maxTextPartLength, 1, MAX_REFERENCE_TEXT),
|
|
142
|
+
maxParts: integerOf(options.maxParts, DEFAULTS.maxParts, 1, 1_000),
|
|
143
|
+
maxTableCells: integerOf(options.maxTableCells, DEFAULTS.maxTableCells, 1, 20_000),
|
|
144
|
+
maxPageText: integerOf(options.maxPageText, DEFAULTS.maxPageText, 1_000, 50_000_000),
|
|
145
|
+
maxImageBytes: integerOf(options.maxImageBytes, DEFAULTS.maxImageBytes, 1_024, 200 * 1024 * 1024),
|
|
146
|
+
timeoutMs: integerOf(options.timeoutMs, DEFAULTS.timeoutMs, 1_000, 300_000),
|
|
147
|
+
};
|
|
148
|
+
this.assetDir = options.assetDir ?? join(dirname(referenceStorePath()), 'reference-assets');
|
|
149
|
+
}
|
|
150
|
+
/** Register the host's draft adapter; `undefined` removes it. */
|
|
151
|
+
setDraftAdapter(adapter) {
|
|
152
|
+
this.adapter = adapter;
|
|
153
|
+
}
|
|
154
|
+
/** The store, for listings. */
|
|
155
|
+
get references() {
|
|
156
|
+
return this.store;
|
|
157
|
+
}
|
|
158
|
+
/** Read one reference. */
|
|
159
|
+
get(referenceId) {
|
|
160
|
+
return this.store.get(referenceId);
|
|
161
|
+
}
|
|
162
|
+
/** List references, newest last. */
|
|
163
|
+
list(filter = {}) {
|
|
164
|
+
return this.store.list(filter);
|
|
165
|
+
}
|
|
166
|
+
/** Absolute path of one stored asset, or undefined when it is absent. */
|
|
167
|
+
assetPath(assetKey) {
|
|
168
|
+
if (!/^[0-9a-f]{64}$/.test(assetKey))
|
|
169
|
+
return undefined;
|
|
170
|
+
const file = join(this.assetDir, `${assetKey}.bin`);
|
|
171
|
+
return existsSync(file) ? file : undefined;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Export stored records and the image bytes they bind.
|
|
175
|
+
* @param options - output shape and an optional owning-session filter.
|
|
176
|
+
* @returns the encoded file.
|
|
177
|
+
*/
|
|
178
|
+
exportBundle(options) {
|
|
179
|
+
const references = this.store.list(options.sessionId === undefined ? {} : { sessionId: options.sessionId });
|
|
180
|
+
const assets = [];
|
|
181
|
+
for (const assetKey of collectAssetKeys(references)) {
|
|
182
|
+
const file = this.assetPath(assetKey);
|
|
183
|
+
if (file === undefined)
|
|
184
|
+
continue;
|
|
185
|
+
let bytes;
|
|
186
|
+
try {
|
|
187
|
+
bytes = readFileSync(file);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
let meta = {};
|
|
193
|
+
try {
|
|
194
|
+
meta = JSON.parse(readFileSync(file.replace(/\.bin$/u, '.json'), 'utf8'));
|
|
195
|
+
}
|
|
196
|
+
catch { /* legacy asset without a sidecar */ }
|
|
197
|
+
const mime = typeof meta.mime === 'string' && meta.mime !== '' ? meta.mime : sniffImageMime(bytes);
|
|
198
|
+
if (mime === undefined)
|
|
199
|
+
continue;
|
|
200
|
+
assets.push({
|
|
201
|
+
assetKey,
|
|
202
|
+
mime,
|
|
203
|
+
bytes,
|
|
204
|
+
...typeof meta.sourceUrl === 'string' && meta.sourceUrl !== '' ? { sourceUrl: meta.sourceUrl } : {},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return encodeReferenceExport({
|
|
208
|
+
references,
|
|
209
|
+
assets,
|
|
210
|
+
exportedAt: (this.host.now?.() ?? new Date()).toISOString(),
|
|
211
|
+
}, options.format);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Deliver one stored reference into a draft through the registered adapter.
|
|
215
|
+
* @param referenceId - the stored reference.
|
|
216
|
+
* @returns `ok: false` with a reason when no adapter exists or it refused.
|
|
217
|
+
*/
|
|
218
|
+
async insertIntoDraft(referenceId) {
|
|
219
|
+
const reference = this.store.get(referenceId);
|
|
220
|
+
if (reference === undefined)
|
|
221
|
+
return { ok: false, reason: 'reference-not-found' };
|
|
222
|
+
if (this.adapter === undefined)
|
|
223
|
+
return { ok: false, reason: 'draft-adapter-unavailable' };
|
|
224
|
+
const sessionId = reference.owner.sessionId;
|
|
225
|
+
if (sessionId === undefined || sessionId === '')
|
|
226
|
+
return { ok: false, reason: 'reference-has-no-session' };
|
|
227
|
+
try {
|
|
228
|
+
const result = await this.adapter.insertReference(reference, { sessionId, focus: false });
|
|
229
|
+
return result.applied ? { ok: true } : { ok: false, reason: result.reason ?? 'draft-adapter-refused' };
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
return { ok: false, reason: String(error instanceof Error ? error.message : error) };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Capture the page's current selection (or one table / one excerpt).
|
|
237
|
+
* @param request - what to capture and which session owns it.
|
|
238
|
+
* @param signal - cancels the page evaluations.
|
|
239
|
+
* @returns the stored reference, or the failures that prevented one.
|
|
240
|
+
*/
|
|
241
|
+
async capture(request, signal) {
|
|
242
|
+
const sessionId = referenceOwnerKey(request.sessionId);
|
|
243
|
+
if (sessionId === '')
|
|
244
|
+
return { failures: [{ kind: 'reference', reason: 'session-id-required' }] };
|
|
245
|
+
const browserSessionId = (request.browserSessionId ?? request.sessionId).trim();
|
|
246
|
+
if (browserSessionId === '')
|
|
247
|
+
return { failures: [{ kind: 'reference', reason: 'browser-session-id-required' }] };
|
|
248
|
+
// A frozen capture needs no browser session: the page already handed over the complete snapshot, so
|
|
249
|
+
// nothing has to be read from a tab. The Web sidebar is exactly that case — its guest is an iframe
|
|
250
|
+
// the plugin does not own, so it has no browser:<uuid> at all, and requiring one refused every
|
|
251
|
+
// quote with "session-unavailable" (measured 422 on every attempt, in every conversation).
|
|
252
|
+
const fromFrozen = request.frozenCapture !== undefined && request.browserSessionId === undefined;
|
|
253
|
+
if (request.sourcePageId !== undefined && (!fromFrozen || !this.webSources?.owns(sessionId, request.sourcePageId))) {
|
|
254
|
+
return { failures: [{ kind: 'reference', reason: 'web-source-not-owned' }] };
|
|
255
|
+
}
|
|
256
|
+
if (!fromFrozen && !this.host.exists(browserSessionId)) {
|
|
257
|
+
return { failures: [{ kind: 'reference', reason: 'session-unavailable' }] };
|
|
258
|
+
}
|
|
259
|
+
const frameSelector = request.frameSelector === undefined ? undefined : validateFrameSelector(request.frameSelector);
|
|
260
|
+
if (request.frameSelector !== undefined && frameSelector === undefined) {
|
|
261
|
+
return { failures: [{ kind: 'reference', reason: 'invalid-frame-selector' }] };
|
|
262
|
+
}
|
|
263
|
+
let raw;
|
|
264
|
+
try {
|
|
265
|
+
const frozen = request.frozenCapture;
|
|
266
|
+
if (frozen !== undefined) {
|
|
267
|
+
// The bar froze this while the real range still existed. Confirm the page
|
|
268
|
+
// is still the same document before trusting it: a capture from a page
|
|
269
|
+
// the user navigated away from must fail loudly, not silently become a
|
|
270
|
+
// quote of whatever is on screen now.
|
|
271
|
+
const frozenUrl = typeof frozen.url === 'string' ? frozen.url : '';
|
|
272
|
+
if (request.sourcePageId !== undefined && !this.webSources?.owns(sessionId, request.sourcePageId, frozenUrl)) {
|
|
273
|
+
return { failures: [{ kind: 'reference', reason: 'page-changed' }] };
|
|
274
|
+
}
|
|
275
|
+
if (!fromFrozen && frozenUrl !== '' && this.host.exists(browserSessionId)) {
|
|
276
|
+
const facts = await this.run(browserSessionId, pageFactsScript(), [], signal);
|
|
277
|
+
const currentUrl = typeof facts === 'object' && facts !== null && typeof facts.url === 'string'
|
|
278
|
+
? String(facts.url)
|
|
279
|
+
: '';
|
|
280
|
+
// Same rule as reveal: a fragment-only change is the same document.
|
|
281
|
+
if (currentUrl !== '' && !samePage(currentUrl, frozenUrl)) {
|
|
282
|
+
return { failures: [{ kind: 'reference', reason: 'page-changed' }] };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
raw = frozen;
|
|
286
|
+
}
|
|
287
|
+
else if (frameSelector !== undefined) {
|
|
288
|
+
const framed = validateFrameCapture(await this.run(browserSessionId, frameCaptureScript(), [{
|
|
289
|
+
frameSelector, context: this.options.context,
|
|
290
|
+
maxChars: this.options.maxPageText, maxCells: this.options.maxTableCells,
|
|
291
|
+
...request.tableSelector !== undefined ? { tableSelector: request.tableSelector } : {},
|
|
292
|
+
...request.excerptText !== undefined && request.excerptText !== '' ? { excerptText: request.excerptText } : {},
|
|
293
|
+
...request.target !== undefined ? { target: request.target } : {},
|
|
294
|
+
}], signal), frameSelector);
|
|
295
|
+
if (framed === undefined)
|
|
296
|
+
return { failures: [{ kind: 'reference', reason: 'frame-capture-invalid' }] };
|
|
297
|
+
if (framed.ok !== true) {
|
|
298
|
+
return { failures: [{ kind: 'reference', reason: `frame-capture-refused: ${framed.reason ?? 'unavailable'}` }] };
|
|
299
|
+
}
|
|
300
|
+
raw = {
|
|
301
|
+
ok: true,
|
|
302
|
+
url: framed.url,
|
|
303
|
+
frameUrl: framed.frameUrl,
|
|
304
|
+
title: framed.title,
|
|
305
|
+
events: (framed.events ?? []),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
raw = await this.run(browserSessionId, captureScript(), [{
|
|
310
|
+
context: this.options.context,
|
|
311
|
+
maxChars: this.options.maxPageText,
|
|
312
|
+
maxCells: this.options.maxTableCells,
|
|
313
|
+
...request.tableSelector !== undefined ? { tableSelector: request.tableSelector } : {},
|
|
314
|
+
...request.excerptText !== undefined && request.excerptText !== '' ? { excerptText: request.excerptText } : {},
|
|
315
|
+
...request.target !== undefined ? { target: request.target } : {},
|
|
316
|
+
}], signal);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
return { failures: [{ kind: 'reference', reason: `capture-failed: ${messageOf(error)}` }] };
|
|
321
|
+
}
|
|
322
|
+
if (raw.ok !== true) {
|
|
323
|
+
return { failures: [{ kind: 'reference', reason: textOf(raw.reason, 200) || 'capture-refused' }] };
|
|
324
|
+
}
|
|
325
|
+
const failures = [];
|
|
326
|
+
const parts = [];
|
|
327
|
+
const pageUrl = textOf(raw.url, 4000);
|
|
328
|
+
// Without a page address the reference can never be revealed or checked for
|
|
329
|
+
// "still the same page", so it is not a usable snapshot.
|
|
330
|
+
if (pageUrl === '')
|
|
331
|
+
return { failures: [{ kind: 'reference', reason: 'page-url-missing' }] };
|
|
332
|
+
const events = Array.isArray(raw.events) ? raw.events : [];
|
|
333
|
+
let counter = 0;
|
|
334
|
+
const nextPartId = () => `p${++counter}`;
|
|
335
|
+
if (events.length > this.options.maxParts) {
|
|
336
|
+
failures.push({ kind: 'reference', reason: 'too-many-parts', detail: { parts: events.length, limit: this.options.maxParts } });
|
|
337
|
+
}
|
|
338
|
+
for (const event of events.slice(0, this.options.maxParts)) {
|
|
339
|
+
if (!isRecord(event))
|
|
340
|
+
continue;
|
|
341
|
+
const kind = textOf(event.kind, 20);
|
|
342
|
+
if (kind === 'text') {
|
|
343
|
+
const textPart = this.textPart(event, nextPartId);
|
|
344
|
+
if ('reason' in textPart)
|
|
345
|
+
failures.push(textPart);
|
|
346
|
+
else
|
|
347
|
+
parts.push(textPart);
|
|
348
|
+
}
|
|
349
|
+
else if (kind === 'image') {
|
|
350
|
+
const imagePart = await this.imagePart(browserSessionId, event, nextPartId, signal, {
|
|
351
|
+
verifyImageVersion: request.verifyImageVersion !== false,
|
|
352
|
+
allowVisibleSnapshot: request.allowVisibleSnapshot !== false,
|
|
353
|
+
});
|
|
354
|
+
if ('reason' in imagePart)
|
|
355
|
+
failures.push(imagePart);
|
|
356
|
+
else
|
|
357
|
+
parts.push(imagePart);
|
|
358
|
+
}
|
|
359
|
+
else if (kind === 'table') {
|
|
360
|
+
const tablePart = await this.tablePart(browserSessionId, event, nextPartId, signal, {
|
|
361
|
+
// A cell image is one image, not "whatever region is selected"; a
|
|
362
|
+
// masked visible snapshot of the table would misreport it.
|
|
363
|
+
verifyImageVersion: request.verifyImageVersion !== false,
|
|
364
|
+
allowVisibleSnapshot: false,
|
|
365
|
+
});
|
|
366
|
+
if ('reason' in tablePart)
|
|
367
|
+
failures.push(tablePart);
|
|
368
|
+
else {
|
|
369
|
+
parts.push(tablePart.part);
|
|
370
|
+
parts.push(...tablePart.cellImages);
|
|
371
|
+
failures.push(...tablePart.failures);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
failures.push({ kind: 'reference', reason: 'unsupported-part', detail: { kind } });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (parts.length === 0) {
|
|
379
|
+
failures.push({ kind: 'reference', reason: 'nothing-captured' });
|
|
380
|
+
return { failures };
|
|
381
|
+
}
|
|
382
|
+
if (failures.length > 0 && request.allowPartial !== true)
|
|
383
|
+
return { failures };
|
|
384
|
+
const carrier = request.carrier ?? 'bundled';
|
|
385
|
+
// The comment is the human's own note; bound it so a hostile page cannot
|
|
386
|
+
// turn it into an unbounded record, and trim rather than reject.
|
|
387
|
+
const comment = textOf(request.comment, MAX_REFERENCE_COMMENT).trim();
|
|
388
|
+
const origin = request.origin ?? 'user-selection';
|
|
389
|
+
const entry = request.entry ?? 'agent-tool';
|
|
390
|
+
const referenceId = this.host.newId?.() ?? randomUUID();
|
|
391
|
+
const frameUrl = textOf(raw.frameUrl, 4000) || pageUrl;
|
|
392
|
+
const withoutHash = {
|
|
393
|
+
version: 1,
|
|
394
|
+
provider: 'dsh-browser',
|
|
395
|
+
referenceId,
|
|
396
|
+
owner: { sessionId, ...fromFrozen ? {} : { browserSessionId }, ...request.sourcePageId === undefined ? {} : { sourcePageId: request.sourcePageId } },
|
|
397
|
+
provenance: { origin, entry },
|
|
398
|
+
source: {
|
|
399
|
+
pageUrl,
|
|
400
|
+
title: textOf(raw.title, 500),
|
|
401
|
+
capturedAt: (this.host.now?.() ?? new Date()).toISOString(),
|
|
402
|
+
...frameUrl !== '' ? {
|
|
403
|
+
frameUrl,
|
|
404
|
+
frameRoute: frameSelector !== undefined ? 'frame' : 'main',
|
|
405
|
+
...frameSelector !== undefined ? { frameSelector } : {},
|
|
406
|
+
} : {},
|
|
407
|
+
carrier,
|
|
408
|
+
},
|
|
409
|
+
parts,
|
|
410
|
+
...comment !== '' ? { comment } : {},
|
|
411
|
+
};
|
|
412
|
+
const reference = { ...withoutHash, manifestHash: manifestHashOf(withoutHash) };
|
|
413
|
+
try {
|
|
414
|
+
this.store.append(reference);
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
return { failures: [...failures, { kind: 'reference', reason: `store-refused: ${messageOf(error)}` }] };
|
|
418
|
+
}
|
|
419
|
+
return { reference, failures };
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Tell the page that its capture did not become a reference.
|
|
423
|
+
*
|
|
424
|
+
* A refused capture used to be stderr-only: the bar closed and the reader had
|
|
425
|
+
* no idea why nothing appeared. This is best-effort — a page that navigated
|
|
426
|
+
* away or a carrier without an evaluate path must not fail the capture.
|
|
427
|
+
*
|
|
428
|
+
* @param sessionId - the browser view the bar lives in.
|
|
429
|
+
* @param text - one sentence for the reader.
|
|
430
|
+
*/
|
|
431
|
+
async notify(sessionId, text) {
|
|
432
|
+
try {
|
|
433
|
+
await this.run(sessionId, noticeScript(text), []);
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
// Deliberately ignored: the delivery path already reported the failure.
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Locate one stored reference in its page. Without a `partId` the group's
|
|
441
|
+
* first part is located, which is the group's reading position.
|
|
442
|
+
* @param referenceId - the stored reference.
|
|
443
|
+
* @param request - optional specific part.
|
|
444
|
+
* @param signal - cancels the page evaluations.
|
|
445
|
+
*/
|
|
446
|
+
async reveal(referenceId, request = {}, signal) {
|
|
447
|
+
const reference = this.store.get(referenceId);
|
|
448
|
+
if (reference === undefined)
|
|
449
|
+
return { referenceId, status: 'not-found', pageUrl: '', parts: [], note: 'no such reference is stored' };
|
|
450
|
+
const owner = referenceOwnerKey(reference.owner.sessionId ?? '');
|
|
451
|
+
if (request.ownerSessionId !== undefined && referenceOwnerKey(request.ownerSessionId) !== owner) {
|
|
452
|
+
return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: 'reference belongs to another conversation' };
|
|
453
|
+
}
|
|
454
|
+
const sourcePageId = request.sourcePageId ?? reference.owner.sourcePageId;
|
|
455
|
+
const webPage = sourcePageId?.startsWith('iframe:') ? sourcePageId : undefined;
|
|
456
|
+
if (webPage !== undefined) {
|
|
457
|
+
const target = request.partId === undefined ? reference.parts.slice(0, 1) : reference.parts.filter(part => part.partId === request.partId);
|
|
458
|
+
if (target.length === 0)
|
|
459
|
+
return { referenceId, status: 'not-found', pageUrl: reference.source.pageUrl, parts: [] };
|
|
460
|
+
const status = await this.webSources?.reveal(reference, webPage, request.partId, signal) ?? 'unavailable';
|
|
461
|
+
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' } : {} };
|
|
462
|
+
}
|
|
463
|
+
const captured = reference.owner.browserSessionId;
|
|
464
|
+
const live = captured !== undefined && captured !== '' && this.host.exists(captured) ? captured : undefined;
|
|
465
|
+
let sessionId = live;
|
|
466
|
+
if (sourcePageId !== undefined) {
|
|
467
|
+
const owner = referenceOwnerKey(reference.owner.sessionId ?? '');
|
|
468
|
+
if (!owner || this.sourceSession === undefined)
|
|
469
|
+
return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: 'sidebar source binding unsupported' };
|
|
470
|
+
try {
|
|
471
|
+
sessionId = await this.sourceSession(owner, sourcePageId);
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (sessionId === undefined) {
|
|
478
|
+
if (reference.source.carrier === 'sidebar') {
|
|
479
|
+
try {
|
|
480
|
+
await this.sourceReady?.(owner);
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) };
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
referenceId,
|
|
488
|
+
status: captured === undefined ? 'unavailable' : 'session-unavailable',
|
|
489
|
+
pageUrl: reference.source.pageUrl,
|
|
490
|
+
parts: [],
|
|
491
|
+
note: captured === undefined ? 'reference has no live source binding' : 'the browser session that captured this reference is gone',
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
let facts;
|
|
495
|
+
try {
|
|
496
|
+
facts = await this.run(sessionId, pageFactsScript(), [], signal);
|
|
497
|
+
}
|
|
498
|
+
catch (error) {
|
|
499
|
+
return { referenceId, status: 'unavailable', pageUrl: reference.source.pageUrl, parts: [], note: messageOf(error) };
|
|
500
|
+
}
|
|
501
|
+
const currentUrl = textOf(facts.url, 4000);
|
|
502
|
+
if (!samePage(currentUrl, reference.source.pageUrl)) {
|
|
503
|
+
return {
|
|
504
|
+
referenceId,
|
|
505
|
+
status: 'page-mismatch',
|
|
506
|
+
pageUrl: reference.source.pageUrl,
|
|
507
|
+
currentUrl,
|
|
508
|
+
parts: [],
|
|
509
|
+
note: 'the session is showing another page; open the stored URL before revealing',
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
const target = request.partId === undefined
|
|
513
|
+
? reference.parts.slice(0, 1)
|
|
514
|
+
: reference.parts.filter(part => part.partId === request.partId);
|
|
515
|
+
if (target.length === 0) {
|
|
516
|
+
return { referenceId, status: 'not-found', pageUrl: reference.source.pageUrl, currentUrl, parts: [], note: 'no such part in this reference' };
|
|
517
|
+
}
|
|
518
|
+
const results = [];
|
|
519
|
+
let pageText;
|
|
520
|
+
for (const part of target) {
|
|
521
|
+
if (part.type === 'text') {
|
|
522
|
+
try {
|
|
523
|
+
if (pageText === undefined) {
|
|
524
|
+
const read = await this.run(sessionId, pageTextScript(), [{ maxChars: this.options.maxPageText, legacy: part.content === undefined }], signal);
|
|
525
|
+
pageText = textOf(read.text, this.options.maxPageText);
|
|
526
|
+
}
|
|
527
|
+
const locate = findTextQuote(pageText, part.anchor);
|
|
528
|
+
if (locate.status === 'found' && locate.range !== undefined) {
|
|
529
|
+
const highlight = await this.run(sessionId, highlightScript(), [{
|
|
530
|
+
start: locate.range.start,
|
|
531
|
+
end: locate.range.end,
|
|
532
|
+
maxChars: this.options.maxPageText,
|
|
533
|
+
legacy: part.content === undefined,
|
|
534
|
+
}], signal);
|
|
535
|
+
results.push({
|
|
536
|
+
partId: part.partId,
|
|
537
|
+
type: 'text',
|
|
538
|
+
status: highlight.ok === true ? 'revealed' : 'missing',
|
|
539
|
+
matches: locate.matches.length,
|
|
540
|
+
collapsed: locate.collapsed,
|
|
541
|
+
...highlight.ok === true ? {} : { note: textOf(highlight.reason, 200) || 'highlight-failed' },
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
else {
|
|
545
|
+
results.push({
|
|
546
|
+
partId: part.partId,
|
|
547
|
+
type: 'text',
|
|
548
|
+
status: locate.status === 'ambiguous' ? 'ambiguous' : 'missing',
|
|
549
|
+
matches: locate.matches.length,
|
|
550
|
+
collapsed: locate.collapsed,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
results.push({ partId: part.partId, type: 'text', status: 'missing', note: messageOf(error) });
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
else if (part.type === 'image') {
|
|
559
|
+
const result = await this.revealElement(sessionId, 'image', {
|
|
560
|
+
...part.anchor,
|
|
561
|
+
...part.alt !== undefined ? { alt: part.alt } : {},
|
|
562
|
+
}, signal);
|
|
563
|
+
results.push({ partId: part.partId, type: 'image', status: result.status, matches: result.matches });
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
const cells = part.table.cells.filter(cell => cell.includedAs === 'selection')
|
|
567
|
+
.map(({ row, column }) => ({ row, column }));
|
|
568
|
+
const result = await this.revealElement(sessionId, 'table', part.anchor, signal, cells);
|
|
569
|
+
results.push({ partId: part.partId, type: 'table', status: result.status, matches: result.matches });
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const revealed = results.filter(result => result.status === 'revealed').length;
|
|
573
|
+
const status = revealed === results.length
|
|
574
|
+
? 'revealed'
|
|
575
|
+
: revealed > 0 ? 'partial' : results.some(result => result.status === 'ambiguous') ? 'ambiguous' : 'missing';
|
|
576
|
+
return { referenceId, status, pageUrl: reference.source.pageUrl, currentUrl, parts: results };
|
|
577
|
+
}
|
|
578
|
+
async revealElement(sessionId, kind, anchor, signal, cells) {
|
|
579
|
+
try {
|
|
580
|
+
const result = await this.run(sessionId, revealElementScript(), [{
|
|
581
|
+
kind,
|
|
582
|
+
anchor,
|
|
583
|
+
...cells === undefined ? {} : { cells },
|
|
584
|
+
}], signal);
|
|
585
|
+
const status = result.status === 'found' ? 'revealed' : result.status === 'ambiguous' ? 'ambiguous' : 'missing';
|
|
586
|
+
return { status, ...typeof result.matches === 'number' ? { matches: result.matches } : {} };
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
return { status: 'missing' };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
/** Validate one text event into a part, or a failure. */
|
|
593
|
+
textPart(event, nextPartId) {
|
|
594
|
+
const exact = textOf(event.exact, this.options.maxTextPartLength + 1);
|
|
595
|
+
if (exact.trim() === '')
|
|
596
|
+
return { kind: 'text', reason: 'empty-text' };
|
|
597
|
+
if (event.content === undefined && exact.length > this.options.maxTextPartLength) {
|
|
598
|
+
return { kind: 'text', reason: 'text-too-long', detail: { characters: exact.length, limit: this.options.maxTextPartLength } };
|
|
599
|
+
}
|
|
600
|
+
const content = event.content === undefined ? undefined : normalizeReferenceText(event.content, Infinity);
|
|
601
|
+
if (event.content !== undefined && (content === undefined
|
|
602
|
+
|| referenceTextContent(content).replace(/\s/gu, '') !== exact.replace(/\s/gu, ''))) {
|
|
603
|
+
return { kind: 'text', reason: 'invalid-text-content' };
|
|
604
|
+
}
|
|
605
|
+
if (content !== undefined && !isReferenceText(content, this.options.maxTextPartLength)) {
|
|
606
|
+
return { kind: 'text', reason: 'text-too-long', detail: { characters: renderReferenceText(content).length, limit: this.options.maxTextPartLength } };
|
|
607
|
+
}
|
|
608
|
+
return {
|
|
609
|
+
partId: nextPartId(),
|
|
610
|
+
type: 'text',
|
|
611
|
+
text: exact,
|
|
612
|
+
...(content === undefined ? {} : { content }),
|
|
613
|
+
anchor: {
|
|
614
|
+
exact,
|
|
615
|
+
prefix: textOf(event.prefix, 512),
|
|
616
|
+
suffix: textOf(event.suffix, 512),
|
|
617
|
+
},
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
/** Validate one image event, materialise its bytes, or fail it. */
|
|
621
|
+
async imagePart(sessionId, event, nextPartId, signal, policy = {
|
|
622
|
+
verifyImageVersion: true, allowVisibleSnapshot: true,
|
|
623
|
+
}) {
|
|
624
|
+
const currentSrc = textOf(event.currentSrc, 4000);
|
|
625
|
+
const src = textOf(event.src, 4000);
|
|
626
|
+
const attributeSrc = textOf(event.attributeSrc, 4000);
|
|
627
|
+
const dataUrl = textOf(event.dataUrl, Math.ceil(this.options.maxImageBytes * 4 / 3) + 4096);
|
|
628
|
+
const alt = textOf(event.alt, 500);
|
|
629
|
+
const selector = textOf(event.selector, 1000);
|
|
630
|
+
const path = numberPathOf(event.path);
|
|
631
|
+
if (currentSrc === '' && src === '' && attributeSrc === '' && dataUrl === '' && selector === '' && path === undefined) {
|
|
632
|
+
return { kind: 'image', reason: 'image-has-no-source' };
|
|
633
|
+
}
|
|
634
|
+
const saved = await this.materializeImage(sessionId, {
|
|
635
|
+
urls: [...new Set([dataUrl, currentSrc, src, attributeSrc].filter(url => url !== ''))],
|
|
636
|
+
...path !== undefined ? { path } : {},
|
|
637
|
+
...selector !== '' ? { selector } : {},
|
|
638
|
+
}, signal, policy);
|
|
639
|
+
if ('reason' in saved)
|
|
640
|
+
return { kind: 'image', reason: saved.reason, ...saved.detail !== undefined ? { detail: saved.detail } : {} };
|
|
641
|
+
const partId = nextPartId();
|
|
642
|
+
const anchorSrc = /^data:/i.test(src) ? '' : src;
|
|
643
|
+
const anchorCurrent = /^data:/i.test(currentSrc) ? '' : currentSrc;
|
|
644
|
+
return {
|
|
645
|
+
partId,
|
|
646
|
+
type: 'image',
|
|
647
|
+
assetKey: saved.assetKey,
|
|
648
|
+
representation: saved.representation,
|
|
649
|
+
...alt !== '' ? { alt } : {},
|
|
650
|
+
...textOf(event.caption, 500) !== '' ? { caption: textOf(event.caption, 500) } : {},
|
|
651
|
+
anchor: {
|
|
652
|
+
...anchorSrc !== '' ? { src: anchorSrc } : {},
|
|
653
|
+
...anchorCurrent !== '' ? { currentSrc: anchorCurrent } : {},
|
|
654
|
+
...alt !== '' ? { alt } : {},
|
|
655
|
+
...selector !== '' ? { selector } : {},
|
|
656
|
+
...isRecord(event.geometry) ? { geometry: {
|
|
657
|
+
x: integerOf(event.geometry.x, 0, -1_000_000, 1_000_000),
|
|
658
|
+
y: integerOf(event.geometry.y, 0, -1_000_000, 1_000_000),
|
|
659
|
+
w: integerOf(event.geometry.w, 0, 0, 1_000_000),
|
|
660
|
+
h: integerOf(event.geometry.h, 0, 0, 1_000_000),
|
|
661
|
+
} } : {},
|
|
662
|
+
...saved.versionStatus !== undefined ? { versionStatus: saved.versionStatus } : {},
|
|
663
|
+
...saved.visible !== undefined ? { visible: {
|
|
664
|
+
rects: saved.visible.rects,
|
|
665
|
+
partiallyVisible: saved.visible.partiallyVisible,
|
|
666
|
+
clip: {
|
|
667
|
+
x: saved.visible.clip.x, y: saved.visible.clip.y,
|
|
668
|
+
width: saved.visible.clip.width, height: saved.visible.clip.height,
|
|
669
|
+
},
|
|
670
|
+
dpr: saved.visible.dpr,
|
|
671
|
+
visualScale: saved.visible.visualScale,
|
|
672
|
+
viewport: saved.visible.viewport,
|
|
673
|
+
scroll: saved.visible.scroll,
|
|
674
|
+
} } : {},
|
|
675
|
+
},
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Try the page's real bytes first, then a page-side raster, then — only when
|
|
680
|
+
* the host can take a read-only clipped screenshot — a masked visible-region
|
|
681
|
+
* snapshot. Remember which one the stored asset actually is.
|
|
682
|
+
*
|
|
683
|
+
* B33/B57: a URL may serve a newer asset between selection and download.
|
|
684
|
+
* When the page session can still be probed and its digest disagrees with the
|
|
685
|
+
* downloaded bytes, those bytes are NEVER advertised as 'source-image'.
|
|
686
|
+
* An unprobeable page is reported as unverifiable, not as a verified match.
|
|
687
|
+
*/
|
|
688
|
+
async materializeImage(sessionId, image, signal, policy = {
|
|
689
|
+
verifyImageVersion: true, allowVisibleSnapshot: true,
|
|
690
|
+
}) {
|
|
691
|
+
let versionChangedUrl = '';
|
|
692
|
+
for (const url of image.urls) {
|
|
693
|
+
if (/^data:image\//i.test(url)) {
|
|
694
|
+
const decoded = decodeDataUrl(url);
|
|
695
|
+
if (decoded !== undefined && decoded.bytes.length <= this.options.maxImageBytes) {
|
|
696
|
+
const saved = this.saveAsset(decoded.bytes, '', 'source-image');
|
|
697
|
+
if (saved !== undefined)
|
|
698
|
+
return saved;
|
|
699
|
+
}
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (/^https?:/i.test(url) && this.host.download !== undefined) {
|
|
703
|
+
const temp = join(this.assetDir, '.tmp', `${randomUUID()}.bin`);
|
|
704
|
+
mkdirSync(dirname(temp), { recursive: true });
|
|
705
|
+
try {
|
|
706
|
+
await this.host.download(sessionId, url, temp, signal);
|
|
707
|
+
const bytes = readFileSync(temp);
|
|
708
|
+
if (bytes.length > 0 && bytes.length <= this.options.maxImageBytes) {
|
|
709
|
+
let status = 'unverifiable';
|
|
710
|
+
if (policy.verifyImageVersion) {
|
|
711
|
+
try {
|
|
712
|
+
const probe = await this.run(sessionId, versionProbeScript(), [{ url }], signal);
|
|
713
|
+
status = compareImageVersion(probe, bytes);
|
|
714
|
+
}
|
|
715
|
+
catch {
|
|
716
|
+
// A blocked page fetch, a dead session or a timed-out evaluate
|
|
717
|
+
// is not evidence either way. Keep the old honest behaviour and
|
|
718
|
+
// record the uncertainty in the asset sidecar.
|
|
719
|
+
status = 'unverifiable';
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
if (status === 'changed') {
|
|
723
|
+
versionChangedUrl = url;
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
const saved = this.saveAsset(bytes, url, 'source-image', { versionStatus: status });
|
|
727
|
+
if (saved !== undefined)
|
|
728
|
+
return { ...saved, versionStatus: status };
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
catch { /* the page-side raster below is the next honest attempt */ }
|
|
732
|
+
finally {
|
|
733
|
+
try {
|
|
734
|
+
rmSync(temp, { force: true });
|
|
735
|
+
}
|
|
736
|
+
catch { /* temp file already gone */ }
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
let rasterReason;
|
|
741
|
+
try {
|
|
742
|
+
const raster = await this.run(sessionId, rasterizeScript(), [{
|
|
743
|
+
path: image.path,
|
|
744
|
+
selector: image.selector,
|
|
745
|
+
maxDimension: 1600,
|
|
746
|
+
}], signal);
|
|
747
|
+
if (raster.ok === true && typeof raster.dataUrl === 'string') {
|
|
748
|
+
const decoded = decodeDataUrl(raster.dataUrl);
|
|
749
|
+
if (decoded !== undefined && decoded.bytes.length <= this.options.maxImageBytes) {
|
|
750
|
+
const sourceUrl = image.urls.find(url => !/^data:/i.test(url)) ?? '';
|
|
751
|
+
const saved = this.saveAsset(decoded.bytes, sourceUrl, 'rasterized-image');
|
|
752
|
+
if (saved !== undefined)
|
|
753
|
+
return saved;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
else {
|
|
757
|
+
rasterReason = textOf(raster.reason, 100) || 'raster-failed';
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
catch (error) {
|
|
761
|
+
rasterReason = messageOf(error);
|
|
762
|
+
}
|
|
763
|
+
if (policy.allowVisibleSnapshot) {
|
|
764
|
+
const visible = await this.tryVisibleSnapshot(sessionId, signal);
|
|
765
|
+
if (visible !== undefined)
|
|
766
|
+
return visible;
|
|
767
|
+
}
|
|
768
|
+
if (versionChangedUrl !== '') {
|
|
769
|
+
return {
|
|
770
|
+
reason: 'image-version-changed',
|
|
771
|
+
detail: { url: versionChangedUrl.slice(0, 300), status: 'changed' },
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
if (rasterReason !== undefined)
|
|
775
|
+
return { reason: 'image-unavailable', detail: { page: rasterReason } };
|
|
776
|
+
return { reason: 'image-not-an-image' };
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* B58/B12/B10: mask every rectangle outside the selection, capture only the
|
|
780
|
+
* visible intersection, then remove the mask even when the capture fails.
|
|
781
|
+
* The mask (not an oversized clip) is what keeps a multi-column selection
|
|
782
|
+
* free of the neighbouring column's content.
|
|
783
|
+
*/
|
|
784
|
+
async tryVisibleSnapshot(sessionId, signal) {
|
|
785
|
+
if (this.host.captureVisible === undefined)
|
|
786
|
+
return undefined;
|
|
787
|
+
let facts;
|
|
788
|
+
try {
|
|
789
|
+
facts = validateVisibleFacts(await this.run(sessionId, visibleFactsScript(), [], signal));
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
return undefined;
|
|
793
|
+
}
|
|
794
|
+
if (facts === undefined)
|
|
795
|
+
return undefined;
|
|
796
|
+
const planned = clipFromFacts(facts);
|
|
797
|
+
if (planned === undefined)
|
|
798
|
+
return undefined;
|
|
799
|
+
// The mask is applied BEFORE the screenshot and removed in `finally`. The
|
|
800
|
+
// flag is set before the page call, not after it returns: a timed-out call
|
|
801
|
+
// may still have run, and leaving the shade over the human's page would be a
|
|
802
|
+
// visible, permanent side effect of a failed capture.
|
|
803
|
+
let maskAttempted = false;
|
|
804
|
+
try {
|
|
805
|
+
maskAttempted = true;
|
|
806
|
+
await this.run(sessionId, maskScript(), [{
|
|
807
|
+
rects: facts.rects,
|
|
808
|
+
viewportWidth: facts.viewportWidth,
|
|
809
|
+
viewportHeight: facts.viewportHeight,
|
|
810
|
+
}], signal);
|
|
811
|
+
const shot = await this.host.captureVisible(sessionId, planned.clip, signal);
|
|
812
|
+
const decoded = decodeDataUrl(shot.dataUrl);
|
|
813
|
+
if (decoded === undefined || decoded.bytes.length === 0 || decoded.bytes.length > this.options.maxImageBytes)
|
|
814
|
+
return undefined;
|
|
815
|
+
const saved = this.saveAsset(decoded.bytes, '', 'visible-snapshot', { visible: planned.meta });
|
|
816
|
+
if (saved === undefined)
|
|
817
|
+
return undefined;
|
|
818
|
+
return { ...saved, visible: planned.meta };
|
|
819
|
+
}
|
|
820
|
+
catch {
|
|
821
|
+
return undefined;
|
|
822
|
+
}
|
|
823
|
+
finally {
|
|
824
|
+
if (maskAttempted) {
|
|
825
|
+
// No signal on purpose: an aborted or timed-out capture is exactly when
|
|
826
|
+
// the page most needs its shade removed, so cleanup must not be cancelled.
|
|
827
|
+
try {
|
|
828
|
+
await this.run(sessionId, unmaskScript(), []);
|
|
829
|
+
}
|
|
830
|
+
catch { /* best effort cleanup */ }
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
/** Write content-addressed bytes plus a metadata sidecar. */
|
|
835
|
+
saveAsset(bytes, sourceUrl, representation, extra = {}) {
|
|
836
|
+
const mime = sniffImageMime(bytes);
|
|
837
|
+
if (mime === undefined)
|
|
838
|
+
return undefined;
|
|
839
|
+
const assetKey = createHash('sha256').update(bytes).digest('hex');
|
|
840
|
+
mkdirSync(this.assetDir, { recursive: true });
|
|
841
|
+
const file = join(this.assetDir, `${assetKey}.bin`);
|
|
842
|
+
if (!existsSync(file)) {
|
|
843
|
+
const temp = `${file}.${process.pid}-${randomUUID()}.tmp`;
|
|
844
|
+
writeFileSync(temp, bytes);
|
|
845
|
+
renameSync(temp, file);
|
|
846
|
+
}
|
|
847
|
+
const meta = {
|
|
848
|
+
assetKey,
|
|
849
|
+
mime,
|
|
850
|
+
bytes: bytes.length,
|
|
851
|
+
sourceUrl,
|
|
852
|
+
representation,
|
|
853
|
+
savedAt: (this.host.now?.() ?? new Date()).toISOString(),
|
|
854
|
+
...extra.versionStatus !== undefined ? { versionStatus: extra.versionStatus } : {},
|
|
855
|
+
...extra.visible !== undefined ? { visible: extra.visible } : {},
|
|
856
|
+
};
|
|
857
|
+
const metaFile = join(this.assetDir, `${assetKey}.json`);
|
|
858
|
+
if (!existsSync(metaFile)) {
|
|
859
|
+
// Same atomic temp + rename as the .bin above: two processes (or a crash
|
|
860
|
+
// mid-write) must never leave a half-written sidecar that /asset would
|
|
861
|
+
// silently serve as application/octet-stream.
|
|
862
|
+
const temp = `${metaFile}.${process.pid}-${randomUUID()}.tmp`;
|
|
863
|
+
writeFileSync(temp, JSON.stringify(meta));
|
|
864
|
+
renameSync(temp, metaFile);
|
|
865
|
+
}
|
|
866
|
+
return { assetKey, representation };
|
|
867
|
+
}
|
|
868
|
+
/** Validate one table event into a part plus the image parts its cells carry. */
|
|
869
|
+
async tablePart(sessionId, event, nextPartId, signal, policy = {
|
|
870
|
+
verifyImageVersion: true, allowVisibleSnapshot: false,
|
|
871
|
+
}) {
|
|
872
|
+
const raw = event.table;
|
|
873
|
+
if (!isRecord(raw))
|
|
874
|
+
return { kind: 'table', reason: 'table-missing' };
|
|
875
|
+
const table = raw;
|
|
876
|
+
const rawCells = Array.isArray(table.cells) ? table.cells.map(cell => isRecord(cell) && cell.content !== undefined
|
|
877
|
+
? { ...cell, content: normalizeReferenceText(cell.content) ?? null } : cell) : [];
|
|
878
|
+
if (rawCells.length === 0)
|
|
879
|
+
return { kind: 'table', reason: 'table-empty' };
|
|
880
|
+
if (booleanOf(table.truncated) || rawCells.length > this.options.maxTableCells) {
|
|
881
|
+
return {
|
|
882
|
+
kind: 'table',
|
|
883
|
+
reason: 'table-too-large',
|
|
884
|
+
detail: { cells: rawCells.length, limit: this.options.maxTableCells },
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
if (rawCells.some(cell => isRecord(cell) && cell.content !== undefined && (!isReferenceText(cell.content)
|
|
888
|
+
|| referenceTextContent(cell.content).replace(/\s/gu, '') !== textOf(cell.text, 2000).replace(/\s/gu, '')))) {
|
|
889
|
+
return { kind: 'table', reason: 'invalid-text-content' };
|
|
890
|
+
}
|
|
891
|
+
const failures = [];
|
|
892
|
+
const cellImages = [];
|
|
893
|
+
const cells = [];
|
|
894
|
+
// The table comes first in `parts`, so it takes its id before the cell images it carries:
|
|
895
|
+
// ids must read in part order or a caller citing `p1` would mean the image, not the table.
|
|
896
|
+
const tablePartId = nextPartId();
|
|
897
|
+
let firstSelectedCell;
|
|
898
|
+
for (const candidate of rawCells) {
|
|
899
|
+
if (!isRecord(candidate))
|
|
900
|
+
continue;
|
|
901
|
+
const cell = candidate;
|
|
902
|
+
const row = integerOf(cell.row, -1, 0, 100_000);
|
|
903
|
+
const column = integerOf(cell.column, -1, 0, 10_000);
|
|
904
|
+
if (row < 0 || column < 0)
|
|
905
|
+
continue;
|
|
906
|
+
const role = cell.role === 'header' ? 'header' : 'data';
|
|
907
|
+
const includedAs = cell.includedAs === 'header-context' ? 'header-context' : 'selection';
|
|
908
|
+
const runs = [];
|
|
909
|
+
for (const rawRun of Array.isArray(cell.inlineContent) ? cell.inlineContent.slice(0, 50) : []) {
|
|
910
|
+
if (!isRecord(rawRun))
|
|
911
|
+
continue;
|
|
912
|
+
const run = rawRun;
|
|
913
|
+
if (run.type === 'text') {
|
|
914
|
+
const text = textOf(run.text, 2000);
|
|
915
|
+
if (text !== '')
|
|
916
|
+
runs.push({ type: 'text', text });
|
|
917
|
+
}
|
|
918
|
+
else if (run.type === 'image') {
|
|
919
|
+
const saved = await this.materializeImage(sessionId, {
|
|
920
|
+
urls: [...new Set([textOf(run.currentSrc, 4000), textOf(run.src, 4000)].filter(url => url !== ''))],
|
|
921
|
+
}, signal, policy);
|
|
922
|
+
if ('reason' in saved) {
|
|
923
|
+
failures.push({ kind: 'image', reason: `cell-image: ${saved.reason}`, detail: { row, column } });
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
const partId = nextPartId();
|
|
927
|
+
runs.push({ type: 'image', partId, assetKey: saved.assetKey });
|
|
928
|
+
cellImages.push({
|
|
929
|
+
partId,
|
|
930
|
+
type: 'image',
|
|
931
|
+
assetKey: saved.assetKey,
|
|
932
|
+
representation: saved.representation,
|
|
933
|
+
anchor: {
|
|
934
|
+
...textOf(run.currentSrc, 4000) !== '' ? { currentSrc: textOf(run.currentSrc, 4000) } : {},
|
|
935
|
+
...textOf(run.src, 4000) !== '' ? { src: textOf(run.src, 4000) } : {},
|
|
936
|
+
...textOf(run.alt, 500) !== '' ? { alt: textOf(run.alt, 500) } : {},
|
|
937
|
+
},
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
const snapshot = {
|
|
942
|
+
row,
|
|
943
|
+
column,
|
|
944
|
+
rowSpan: integerOf(cell.rowSpan, 1, 1, 1000),
|
|
945
|
+
columnSpan: integerOf(cell.columnSpan, 1, 1, 200),
|
|
946
|
+
role,
|
|
947
|
+
text: textOf(cell.text, 2000),
|
|
948
|
+
...(cell.content === undefined ? {} : { content: cell.content }),
|
|
949
|
+
includedAs,
|
|
950
|
+
partialText: booleanOf(cell.partialText),
|
|
951
|
+
...runs.length > 0 ? { inlineContent: runs } : {},
|
|
952
|
+
};
|
|
953
|
+
if (firstSelectedCell === undefined && includedAs === 'selection')
|
|
954
|
+
firstSelectedCell = { row, column };
|
|
955
|
+
cells.push(snapshot);
|
|
956
|
+
}
|
|
957
|
+
if (cells.length === 0)
|
|
958
|
+
return { kind: 'table', reason: 'table-empty' };
|
|
959
|
+
const headers = [];
|
|
960
|
+
const firstCells = [];
|
|
961
|
+
for (const cell of cells) {
|
|
962
|
+
// Every header the page captured is a locate hint: one selected header and one kept as
|
|
963
|
+
// context are equally good at recognising the same table after a re-render.
|
|
964
|
+
if (cell.role === 'header' && headers.length < 8 && cell.text !== '' && !headers.includes(cell.text))
|
|
965
|
+
headers.push(cell.text);
|
|
966
|
+
if (cell.row === 0 && firstCells.length < 8)
|
|
967
|
+
firstCells.push(cell.text);
|
|
968
|
+
}
|
|
969
|
+
const completeness = table.completeness === 'visible-rows' || table.completeness === 'dom-table' || table.completeness === 'aria-grid'
|
|
970
|
+
? table.completeness
|
|
971
|
+
: 'selected-cells';
|
|
972
|
+
const anchor = {
|
|
973
|
+
...textOf(event.selector, 1000) !== '' ? { selector: textOf(event.selector, 1000) } : {},
|
|
974
|
+
...textOf(table.caption, 500) !== '' ? { caption: textOf(table.caption, 500) } : {},
|
|
975
|
+
headers,
|
|
976
|
+
firstCells,
|
|
977
|
+
...firstSelectedCell !== undefined ? { cell: firstSelectedCell } : {},
|
|
978
|
+
};
|
|
979
|
+
return {
|
|
980
|
+
part: {
|
|
981
|
+
partId: tablePartId,
|
|
982
|
+
type: 'table',
|
|
983
|
+
table: {
|
|
984
|
+
rowCount: integerOf(table.rowCount, 0, 0, 100_000),
|
|
985
|
+
columnCount: integerOf(table.columnCount, 0, 0, 10_000),
|
|
986
|
+
cells,
|
|
987
|
+
...textOf(table.caption, 500) !== '' ? { caption: textOf(table.caption, 500) } : {},
|
|
988
|
+
completeness,
|
|
989
|
+
normalizationVersion: '1',
|
|
990
|
+
},
|
|
991
|
+
anchor,
|
|
992
|
+
},
|
|
993
|
+
cellImages,
|
|
994
|
+
failures,
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
async run(sessionId, script, args, signal) {
|
|
998
|
+
const value = await this.host.evaluate(sessionId, {
|
|
999
|
+
script,
|
|
1000
|
+
args,
|
|
1001
|
+
timeoutMs: this.options.timeoutMs,
|
|
1002
|
+
}, signal);
|
|
1003
|
+
const parsed = typeof value === 'string' ? JSON.parse(value) : value;
|
|
1004
|
+
if (!isRecord(parsed))
|
|
1005
|
+
throw new Error('browser reference: the page returned no usable result');
|
|
1006
|
+
return parsed;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
function messageOf(error) {
|
|
1010
|
+
return error instanceof Error ? error.message : String(error);
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Project one reference into the compact shape a list or a tool answer shows.
|
|
1014
|
+
* @param reference - the stored snapshot.
|
|
1015
|
+
*/
|
|
1016
|
+
export function summarizeReference(reference) {
|
|
1017
|
+
return {
|
|
1018
|
+
referenceId: reference.referenceId,
|
|
1019
|
+
title: reference.source.title,
|
|
1020
|
+
pageUrl: reference.source.pageUrl,
|
|
1021
|
+
capturedAt: reference.source.capturedAt,
|
|
1022
|
+
carrier: reference.source.carrier,
|
|
1023
|
+
origin: reference.provenance.origin,
|
|
1024
|
+
entry: reference.provenance.entry,
|
|
1025
|
+
partCount: reference.parts.length,
|
|
1026
|
+
parts: reference.parts.map(part => {
|
|
1027
|
+
if (part.type === 'text') {
|
|
1028
|
+
return { partId: part.partId, type: 'text', preview: part.text.replace(/\s+/g, ' ').slice(0, 160) };
|
|
1029
|
+
}
|
|
1030
|
+
if (part.type === 'image') {
|
|
1031
|
+
return { partId: part.partId, type: 'image', preview: part.alt ?? part.caption ?? part.anchor.src ?? '' };
|
|
1032
|
+
}
|
|
1033
|
+
const shape = `${part.table.rowCount}x${part.table.columnCount}`;
|
|
1034
|
+
return { partId: part.partId, type: 'table', preview: part.table.caption !== undefined ? `${part.table.caption} (${shape})` : shape };
|
|
1035
|
+
}),
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Build the service against the plugin's browser runtime.
|
|
1040
|
+
* @param browser - the `ctx.browser` runtime.
|
|
1041
|
+
* @param options - optional caps and store overrides.
|
|
1042
|
+
*/
|
|
1043
|
+
export function createReferenceService(browser, options = {}) {
|
|
1044
|
+
const { store, visibleCapture, ...rest } = options;
|
|
1045
|
+
return new BrowserReferenceService({
|
|
1046
|
+
evaluate: async (sessionId, request, signal) => {
|
|
1047
|
+
const result = await browser.execute(sessionId, {
|
|
1048
|
+
script: request.script,
|
|
1049
|
+
...request.args !== undefined ? { args: request.args } : {},
|
|
1050
|
+
...request.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {},
|
|
1051
|
+
}, signal);
|
|
1052
|
+
if (!result.ok)
|
|
1053
|
+
throw new Error(result.exception);
|
|
1054
|
+
return result.value;
|
|
1055
|
+
},
|
|
1056
|
+
exists: sessionId => browser.exists(sessionId),
|
|
1057
|
+
download: async (sessionId, url, savePath, signal) => {
|
|
1058
|
+
await browser.download(sessionId, { url, savePath }, signal);
|
|
1059
|
+
},
|
|
1060
|
+
...visibleCapture !== undefined ? { captureVisible: visibleCapture } : {},
|
|
1061
|
+
}, store ?? new ReferenceStore(), { webSources: webReferenceSources(browser), ...rest });
|
|
1062
|
+
}
|