@kingsleyasher/dsh-knowledge-base 0.0.0-stage → 3.1.5
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/ARCHITECTURE.en.md +35 -0
- package/ARCHITECTURE.md +40 -0
- package/BETA4.md +31 -0
- package/BETA7.md +35 -0
- package/BETA8.md +39 -0
- package/BETA9.md +38 -0
- package/CONTRIBUTING.md +5 -0
- package/DEVELOPMENT.en.md +26 -0
- package/DEVELOPMENT.md +27 -0
- package/EXISTING-FRAMEWORK-OPTIMIZATION.md +101 -0
- package/LICENSE +21 -0
- package/MONOREPO.md +34 -0
- package/NPM-EDITION.md +12 -0
- package/PARSING-PREVIEW.md +84 -0
- package/PERFORMANCE.md +43 -0
- package/PRIVACY.md +7 -0
- package/PROJECT-RECORD.en.md +782 -0
- package/PROJECT-RECORD.md +793 -0
- package/README.md +109 -3
- package/README.zh-CN.md +117 -0
- package/RELEASE.en.md +559 -0
- package/RELEASE.md +570 -0
- package/RETRIEVAL.md +93 -0
- package/SECURITY.md +7 -0
- package/THIRD-PARTY-NOTICES.md +5 -0
- package/VERSIONING.en.md +51 -0
- package/VERSIONING.md +50 -0
- package/WORKBENCH.en.md +201 -0
- package/WORKBENCH.md +195 -0
- package/browser-extension/background.js +146 -0
- package/browser-extension/icons/knowledge-base-128.png +0 -0
- package/browser-extension/icons/knowledge-base-16.png +0 -0
- package/browser-extension/icons/knowledge-base-32.png +0 -0
- package/browser-extension/icons/knowledge-base-48.png +0 -0
- package/browser-extension/manifest.json +25 -0
- package/browser-extension/options.html +22 -0
- package/browser-extension/options.js +41 -0
- package/browser-extension/popup.html +17 -0
- package/browser-extension/popup.js +58 -0
- package/browser-extension/style.css +11 -0
- package/cordis.patch.yml +88 -0
- package/docs/LEGACY-246-BOOTSTRAP.md +21 -0
- package/docs/LIBRARY-FRAMEWORK-MIGRATION.md +45 -0
- package/docs/ORIGINAL-FILE-INDEX-ARCHITECTURE.md +43 -0
- package/docs/TODO-LIFECYCLE-VALIDATION.md +42 -0
- package/docs/UPDATE-RECOVERY.en.md +18 -0
- package/docs/UPDATE-RECOVERY.md +70 -0
- package/docs/WINDOWS-SIGNING.md +30 -0
- package/docs/client/ARCHITECTURE.en.md +17 -0
- package/docs/client/ARCHITECTURE.md +17 -0
- package/docs/client/CONTRIBUTING.md +5 -0
- package/docs/client/CROSS-VOLUME-TRASH.md +13 -0
- package/docs/client/DEVELOPMENT.en.md +33 -0
- package/docs/client/DEVELOPMENT.md +33 -0
- package/docs/client/EXISTING-FRAMEWORK-OPTIMIZATION.md +3 -0
- package/docs/client/PERFORMANCE.md +3 -0
- package/docs/client/PRIVACY.md +7 -0
- package/docs/client/PROJECT-RECORD.en.md +199 -0
- package/docs/client/PROJECT-RECORD.md +219 -0
- package/docs/client/README.md +55 -0
- package/docs/client/README.zh-CN.md +45 -0
- package/docs/client/RELEASE.en.md +148 -0
- package/docs/client/RELEASE.md +149 -0
- package/docs/client/RETRIEVAL.md +3 -0
- package/docs/client/SECURITY.md +7 -0
- package/docs/client/THIRD-PARTY-NOTICES.md +5 -0
- package/docs/client/VERSIONING.en.md +9 -0
- package/docs/client/VERSIONING.md +9 -0
- package/docs/client/WORKBENCH.en.md +24 -0
- package/docs/client/WORKBENCH.md +24 -0
- package/docs/client/skills/personal-knowledge-base/SKILL.md +38 -0
- package/docs/releases/client-1.0.1.md +32 -0
- package/docs/releases/client-1.0.2.md +32 -0
- package/docs/releases/client-1.0.3.md +31 -0
- package/docs/releases/client-1.1.1.md +28 -0
- package/docs/releases/client-1.1.2.md +16 -0
- package/docs/releases/client-1.1.4.md +7 -0
- package/docs/releases/client-2.0.0.en.md +13 -0
- package/docs/releases/client-2.0.0.md +13 -0
- package/docs/releases/client-2.0.1.en.md +10 -0
- package/docs/releases/client-2.0.1.md +10 -0
- package/docs/releases/client-2.0.3.en.md +8 -0
- package/docs/releases/client-2.0.3.md +8 -0
- package/docs/releases/plugin-2.4.1.md +24 -0
- package/docs/releases/plugin-2.4.10.md +22 -0
- package/docs/releases/plugin-2.4.11.md +14 -0
- package/docs/releases/plugin-2.4.12.md +14 -0
- package/docs/releases/plugin-2.4.13.md +27 -0
- package/docs/releases/plugin-2.4.14.md +18 -0
- package/docs/releases/plugin-2.4.2.md +31 -0
- package/docs/releases/plugin-2.4.3.md +25 -0
- package/docs/releases/plugin-2.4.4.md +31 -0
- package/docs/releases/plugin-2.4.5.md +23 -0
- package/docs/releases/plugin-2.4.6.md +23 -0
- package/docs/releases/plugin-2.4.7.md +14 -0
- package/docs/releases/plugin-2.4.8.md +14 -0
- package/docs/releases/plugin-2.4.9.md +18 -0
- package/docs/releases/plugin-2.5.10.md +11 -0
- package/docs/releases/plugin-2.5.13.en.md +11 -0
- package/docs/releases/plugin-2.5.13.md +11 -0
- package/docs/releases/plugin-2.5.3.md +28 -0
- package/docs/releases/plugin-2.5.4.md +14 -0
- package/docs/releases/plugin-2.5.5.md +16 -0
- package/docs/releases/plugin-2.5.6.md +3 -0
- package/docs/releases/plugin-2.5.7.md +7 -0
- package/docs/releases/plugin-2.5.8.md +7 -0
- package/docs/releases/plugin-2.5.9.md +7 -0
- package/docs/releases/plugin-3.0.0.en.md +13 -0
- package/docs/releases/plugin-3.0.0.md +13 -0
- package/docs/releases/plugin-3.0.1.en.md +10 -0
- package/docs/releases/plugin-3.0.1.md +10 -0
- package/docs/releases/plugin-3.1.3.en.md +11 -0
- package/docs/releases/plugin-3.1.3.md +11 -0
- package/docs/validation/windows-auto-update-2.4.13.md +31 -0
- package/docs/validation/windows-direct-246-to-2413.md +32 -0
- package/package.json +78 -6
- package/packages/kb-contracts/desktop.js +29 -0
- package/packages/kb-contracts/index.js +132 -0
- package/packages/kb-contracts/node.js +3 -0
- package/packages/kb-contracts/package.json +17 -0
- package/packages/kb-contracts/schema.js +42 -0
- package/packages/kb-contracts/tools.js +1 -0
- package/packages/kb-contracts/version-policy.js +45 -0
- package/packages/kb-core/index.js +9 -0
- package/packages/kb-core/package.json +15 -0
- package/packages/kb-core/src/capture-surface.js +22 -0
- package/packages/kb-core/src/documents.js +105 -0
- package/packages/kb-core/src/embedded.js +29 -0
- package/packages/kb-core/src/file-catalog.js +151 -0
- package/packages/kb-core/src/file-classification.js +60 -0
- package/packages/kb-core/src/flow-workspace.js +66 -0
- package/packages/kb-core/src/flows.js +1136 -0
- package/packages/kb-core/src/fsindex.js +293 -0
- package/packages/kb-core/src/import-service.js +486 -0
- package/packages/kb-core/src/importer.js +909 -0
- package/packages/kb-core/src/inbox-flow.js +2 -0
- package/packages/kb-core/src/index-architecture.js +48 -0
- package/packages/kb-core/src/index-maintenance.js +81 -0
- package/packages/kb-core/src/index-policy-service.js +191 -0
- package/packages/kb-core/src/index-policy.js +121 -0
- package/packages/kb-core/src/kbcore.js +2519 -0
- package/packages/kb-core/src/library-framework.js +186 -0
- package/packages/kb-core/src/library-state.js +68 -0
- package/packages/kb-core/src/managed-files.js +69 -0
- package/packages/kb-core/src/map.js +171 -0
- package/packages/kb-core/src/parse-credentials.js +49 -0
- package/packages/kb-core/src/parse-discovery.js +119 -0
- package/packages/kb-core/src/parse-job-storage.js +40 -0
- package/packages/kb-core/src/parse-native.js +87 -0
- package/packages/kb-core/src/parse-presets.js +46 -0
- package/packages/kb-core/src/parse-source-authority.js +72 -0
- package/packages/kb-core/src/parsing.js +2307 -0
- package/packages/kb-core/src/relation-name-lookup.js +43 -0
- package/packages/kb-core/src/retrieval-api.js +79 -0
- package/packages/kb-core/src/retrieval-cache.js +22 -0
- package/packages/kb-core/src/retrieval-chunks.js +128 -0
- package/packages/kb-core/src/retrieval-pool.js +102 -0
- package/packages/kb-core/src/retrieval-worker.js +190 -0
- package/packages/kb-core/src/retrieval.js +618 -0
- package/packages/kb-core/src/runtime-resources.js +73 -0
- package/packages/kb-core/src/service-ownership.js +18 -0
- package/packages/kb-core/src/source-references.js +61 -0
- package/packages/kb-core/src/storage-io.js +121 -0
- package/packages/kb-core/src/system-upgrades.js +104 -0
- package/packages/kb-core/src/workbench-backup.js +219 -0
- package/packages/kb-core/src/workbench-deliverables.js +73 -0
- package/packages/kb-core/src/workbench-files.js +25 -0
- package/packages/kb-core/src/workbench-inbox.js +57 -0
- package/packages/kb-core/src/workbench-links.js +236 -0
- package/packages/kb-core/src/workbench-question.js +131 -0
- package/packages/kb-core/src/workbench-relation-index.js +110 -0
- package/packages/kb-core/src/workbench-state.js +102 -0
- package/packages/kb-core/src/workbench-trash.js +213 -0
- package/packages/kb-core/src/workbench.js +936 -0
- package/packages/kb-service/auth.js +39 -0
- package/packages/kb-service/build.js +18 -0
- package/packages/kb-service/cli.js +26 -0
- package/packages/kb-service/client.js +64 -0
- package/packages/kb-service/clipper.js +15 -0
- package/packages/kb-service/compatibility.js +34 -0
- package/packages/kb-service/desktop-files.js +514 -0
- package/packages/kb-service/desktop-host-links.js +39 -0
- package/packages/kb-service/dsh-broker.js +64 -0
- package/packages/kb-service/dsh-host.js +168 -0
- package/packages/kb-service/dsh-stream-relay.js +32 -0
- package/packages/kb-service/engines.js +32 -0
- package/packages/kb-service/extension.js +8 -0
- package/packages/kb-service/first-library-handoff.js +28 -0
- package/packages/kb-service/handoff-api.js +22 -0
- package/packages/kb-service/host-adapter.js +151 -0
- package/packages/kb-service/host-assets.js +9 -0
- package/packages/kb-service/host-python.js +30 -0
- package/packages/kb-service/host-updates.js +97 -0
- package/packages/kb-service/inbox-host.js +47 -0
- package/packages/kb-service/inbox-jobs.js +54 -0
- package/packages/kb-service/index.js +3 -0
- package/packages/kb-service/io.js +24 -0
- package/packages/kb-service/launch-lock.js +27 -0
- package/packages/kb-service/launcher.js +18 -0
- package/packages/kb-service/legacy-handoff.js +27 -0
- package/packages/kb-service/legacy-ports.js +18 -0
- package/packages/kb-service/main.js +13 -0
- package/packages/kb-service/memory-channel.js +57 -0
- package/packages/kb-service/memory-sync.js +42 -0
- package/packages/kb-service/migration.js +131 -0
- package/packages/kb-service/native.py +216 -0
- package/packages/kb-service/operations.js +19 -0
- package/packages/kb-service/package.json +1 -0
- package/packages/kb-service/runtime.js +185 -0
- package/packages/kb-service/safe-update.js +104 -0
- package/packages/kb-service/service.js +494 -0
- package/packages/kb-service/tool-definitions.json +934 -0
- package/packages/kb-service/tool-router.js +45 -0
- package/packages/kb-service/vector-profiles.js +41 -0
- package/presets/01-knowledge-agent.patch.yml +347 -0
- package/runtime/python/LICENSE.txt +676 -0
- package/runtime/python/_asyncio.pyd +0 -0
- package/runtime/python/_bz2.pyd +0 -0
- package/runtime/python/_ctypes.pyd +0 -0
- package/runtime/python/_decimal.pyd +0 -0
- package/runtime/python/_elementtree.pyd +0 -0
- package/runtime/python/_hashlib.pyd +0 -0
- package/runtime/python/_lzma.pyd +0 -0
- package/runtime/python/_multiprocessing.pyd +0 -0
- package/runtime/python/_overlapped.pyd +0 -0
- package/runtime/python/_queue.pyd +0 -0
- package/runtime/python/_remote_debugging.pyd +0 -0
- package/runtime/python/_socket.pyd +0 -0
- package/runtime/python/_sqlite3.pyd +0 -0
- package/runtime/python/_ssl.pyd +0 -0
- package/runtime/python/_uuid.pyd +0 -0
- package/runtime/python/_wmi.pyd +0 -0
- package/runtime/python/_zoneinfo.pyd +0 -0
- package/runtime/python/_zstd.pyd +0 -0
- package/runtime/python/libcrypto-3.dll +0 -0
- package/runtime/python/libffi-8.dll +0 -0
- package/runtime/python/libssl-3.dll +0 -0
- package/runtime/python/libtommath.dll +0 -0
- package/runtime/python/pyexpat.pyd +0 -0
- package/runtime/python/python.cat +0 -0
- package/runtime/python/python.exe +0 -0
- package/runtime/python/python3.dll +0 -0
- package/runtime/python/python314._pth +5 -0
- package/runtime/python/python314.dll +0 -0
- package/runtime/python/python314.zip +0 -0
- package/runtime/python/pythonw.exe +0 -0
- package/runtime/python/select.pyd +0 -0
- package/runtime/python/sqlite3.dll +0 -0
- package/runtime/python/unicodedata.pyd +0 -0
- package/runtime/python/vcruntime140.dll +0 -0
- package/runtime/python/vcruntime140_1.dll +0 -0
- package/runtime/python/winsound.pyd +0 -0
- package/skills/personal-knowledge-base/SKILL.md +38 -0
- package/src/client/capture-icon-192.png +0 -0
- package/src/client/capture-icon-512.png +0 -0
- package/src/client/capture-icon.svg +12 -0
- package/src/client/capture-sw.js +10 -0
- package/src/client/capture.css +1 -0
- package/src/client/capture.html +1 -0
- package/src/client/capture.js +37 -0
- package/src/client/capture.webmanifest +1 -0
- package/src/client/inbox-organize-bridge.js +22 -0
- package/src/client/index.js +4975 -0
- package/src/client/knowledge-ui.css +255 -0
- package/src/client/pdfjs/LICENSE +177 -0
- package/src/client/pdfjs/cmaps/78-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78ms-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/78ms-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/83pv-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90ms-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90ms-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90msp-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90msp-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90pv-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/90pv-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Add-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Add-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Add-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Add-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-0.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-1.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-3.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-4.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-5.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-6.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-0.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-1.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-3.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-4.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-5.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-GB1-UCS2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-0.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-1.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-3.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-4.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-5.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-6.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Korea1-0.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Korea1-1.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Korea1-2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmap +0 -0
- package/src/client/pdfjs/cmaps/B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/B5pc-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/B5pc-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS1-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS1-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS2-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/CNS2-V.bcmap +3 -0
- package/src/client/pdfjs/cmaps/ETHK-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/ETHK-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/ETen-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/ETen-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/ETenms-B5-H.bcmap +3 -0
- package/src/client/pdfjs/cmaps/ETenms-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Ext-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Ext-RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Ext-RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Ext-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GB-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GB-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GB-H.bcmap +4 -0
- package/src/client/pdfjs/cmaps/GB-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBK-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBK-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBK2K-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBK2K-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBKp-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBKp-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBT-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBT-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBT-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBT-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBTpc-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBTpc-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBpc-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/GBpc-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKdla-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKdla-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKdlb-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKdlb-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKgccs-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKgccs-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKm314-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKm314-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKm471-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKm471-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKscs-B5-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/HKscs-B5-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Hankaku.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Hiragana.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-Johab-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-Johab-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCms-UHC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCms-UHC-HW-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCms-UHC-HW-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCms-UHC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCpc-EUC-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/KSCpc-EUC-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Katakana.bcmap +0 -0
- package/src/client/pdfjs/cmaps/LICENSE +36 -0
- package/src/client/pdfjs/cmaps/NWP-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/NWP-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/RKSJ-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/RKSJ-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/Roman.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UCS2-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UCS2-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF16-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF16-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF8-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniCNS-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UCS2-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UCS2-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF16-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF16-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF8-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniGB-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UCS2-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UCS2-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF16-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF16-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF8-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISPro-UCS2-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISPro-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UCS2-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UCS2-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF16-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF16-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF32-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF32-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF8-H.bcmap +0 -0
- package/src/client/pdfjs/cmaps/UniKS-UTF8-V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/V.bcmap +0 -0
- package/src/client/pdfjs/cmaps/WP-Symbol.bcmap +0 -0
- package/src/client/pdfjs/pdf.mjs +26779 -0
- package/src/client/pdfjs/pdf.worker.mjs +63420 -0
- package/src/client/pdfjs/standard_fonts/FoxitDingbats.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitFixed.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitFixedBold.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitFixedItalic.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitSerif.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitSerifBold.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitSerifItalic.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/FoxitSymbol.pfb +0 -0
- package/src/client/pdfjs/standard_fonts/LICENSE_FOXIT +27 -0
- package/src/client/pdfjs/standard_fonts/LICENSE_LIBERATION +102 -0
- package/src/client/pdfjs/standard_fonts/LiberationSans-Bold.ttf +0 -0
- package/src/client/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttf +0 -0
- package/src/client/pdfjs/standard_fonts/LiberationSans-Italic.ttf +0 -0
- package/src/client/pdfjs/standard_fonts/LiberationSans-Regular.ttf +0 -0
- package/src/client/pdfjs/wasm/LICENSE_JBIG2 +196 -0
- package/src/client/pdfjs/wasm/LICENSE_OPENJPEG +39 -0
- package/src/client/pdfjs/wasm/LICENSE_PDFJS_JBIG2 +13 -0
- package/src/client/pdfjs/wasm/LICENSE_PDFJS_OPENJPEG +22 -0
- package/src/client/pdfjs/wasm/LICENSE_PDFJS_QCMS +22 -0
- package/src/client/pdfjs/wasm/LICENSE_QCMS +21 -0
- package/src/client/pdfjs/wasm/jbig2.wasm +0 -0
- package/src/client/pdfjs/wasm/openjpeg.wasm +0 -0
- package/src/client/pdfjs/wasm/openjpeg_nowasm_fallback.js +17 -0
- package/src/client/pdfjs/wasm/qcms_bg.wasm +0 -0
- package/src/client/todo-lifecycle-ui.js +58 -0
- package/src/client/workbench-features.js +148 -0
- package/src/client/workbench-relations.js +86 -0
- package/src/client/workbench-theme.css +81 -0
- package/src/client/workbench-ui.js +1761 -0
- package/src/host/capture-surface.js +2 -0
- package/src/host/citation-guard.js +40 -0
- package/src/host/command-description.js +43 -0
- package/src/host/flow-workspace.js +62 -0
- package/src/host/flows.js +2 -0
- package/src/host/fsindex.js +2 -0
- package/src/host/gateway.js +916 -0
- package/src/host/import-service.js +2 -0
- package/src/host/importer.js +2 -0
- package/src/host/index-maintenance.js +2 -0
- package/src/host/index-policy-service.js +2 -0
- package/src/host/index-policy.js +2 -0
- package/src/host/index.js +2220 -0
- package/src/host/kbcore.js +2 -0
- package/src/host/managed-files.js +2 -0
- package/src/host/map.js +2 -0
- package/src/host/parse-credentials.js +2 -0
- package/src/host/parse-discovery.js +2 -0
- package/src/host/parse-native.js +2 -0
- package/src/host/parse-presets.js +2 -0
- package/src/host/parse-source-authority.js +2 -0
- package/src/host/parsing.js +7 -0
- package/src/host/relation-name-lookup.js +2 -0
- package/src/host/retrieval-api.js +2 -0
- package/src/host/retrieval-cache.js +2 -0
- package/src/host/retrieval-chunks.js +2 -0
- package/src/host/retrieval-pool.js +2 -0
- package/src/host/retrieval-worker.js +2 -0
- package/src/host/retrieval.js +2 -0
- package/src/host/runtime-resources.js +2 -0
- package/src/host/selftest.js +747 -0
- package/src/host/storage-io.js +2 -0
- package/src/host/system-upgrades.js +2 -0
- package/src/host/todo-lifecycle.js +66 -0
- package/src/host/updates.js +281 -0
- package/src/host/versioning.js +2 -0
- package/src/host/workbench-backup.js +2 -0
- package/src/host/workbench-deliverables.js +2 -0
- package/src/host/workbench-files.js +2 -0
- package/src/host/workbench-inbox.js +2 -0
- package/src/host/workbench-links.js +2 -0
- package/src/host/workbench-question.js +2 -0
- package/src/host/workbench-relation-index.js +2 -0
- package/src/host/workbench-state.js +2 -0
- package/src/host/workbench-trash.js +2 -0
- package/src/host/workbench.js +5 -0
- package/tools/kb-local-model.py +141 -0
- package/tools/kb-pdf-pages.py +78 -0
- package/tools/kb-transactional-update.py +292 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createSafeUpdate } from './safe-update.js'
|
|
6
|
+
import { readCandidateBuild } from './build.js'
|
|
7
|
+
import { compareStableVersions, readUpdateSourceBytes, startAutomaticChecks, UPDATE_INTERVAL_MS } from '../../src/host/updates.js'
|
|
8
|
+
|
|
9
|
+
const PACKAGE = '@kingsleyasher/dsh-knowledge-base'
|
|
10
|
+
const registry = 'https://registry.npmjs.org'
|
|
11
|
+
const registrySource = { id: 'npm', hosts: ['registry.npmjs.org'], file: url => url }
|
|
12
|
+
const packagePage = 'https://www.npmjs.com/package/' + PACKAGE
|
|
13
|
+
const stable = /^\d+\.\d+\.\d+$/
|
|
14
|
+
const sha512 = /^sha512-[A-Za-z0-9+/]{86}==$/
|
|
15
|
+
|
|
16
|
+
export function createNpmUpdateChecker({ currentVersion, fetch = globalThis.fetch, now = Date.now }) {
|
|
17
|
+
let cache, expiresAt = 0, pending
|
|
18
|
+
return {
|
|
19
|
+
check({ force = false } = {}) {
|
|
20
|
+
if (pending) return pending
|
|
21
|
+
if (!force && cache && now() < expiresAt) return Promise.resolve(cache)
|
|
22
|
+
pending = (async () => {
|
|
23
|
+
const base = { distribution: 'npm', currentVersion, currentChannel: 'stable', channel: 'stable', sourceName: 'npm', notesUrl: packagePage }
|
|
24
|
+
try {
|
|
25
|
+
const url = registry + '/' + encodeURIComponent(PACKAGE) + '/latest'
|
|
26
|
+
const raw = await readUpdateSourceBytes(fetch, registrySource, url, 1024 * 1024, 8000)
|
|
27
|
+
const manifest = JSON.parse(raw)
|
|
28
|
+
const { version, dist } = manifest
|
|
29
|
+
const archiveUrl = registry + '/' + PACKAGE + '/-/dsh-knowledge-base-' + version + '.tgz'
|
|
30
|
+
if (manifest.name !== PACKAGE || !stable.test(version) || dist?.tarball !== archiveUrl || !sha512.test(dist.integrity)) {
|
|
31
|
+
throw Error('npm 返回的版本或安装包信息无效')
|
|
32
|
+
}
|
|
33
|
+
const comparison = compareStableVersions(version, currentVersion)
|
|
34
|
+
return { ...base, ok: true, onlineChecked: true, latestVersion: version, updateAvailable: comparison > 0,
|
|
35
|
+
autoInstallEligible: comparison > 0, ahead: comparison < 0, integrity: dist.integrity, archiveUrl }
|
|
36
|
+
} catch (error) {
|
|
37
|
+
return { ...base, ok: false, updateAvailable: false, error: 'npm 更新检查失败:' + error.message }
|
|
38
|
+
}
|
|
39
|
+
})().then(result => {
|
|
40
|
+
cache = result
|
|
41
|
+
expiresAt = now() + (result.ok ? UPDATE_INTERVAL_MS : 5 * 60 * 1000)
|
|
42
|
+
return result
|
|
43
|
+
}).finally(() => { pending = null })
|
|
44
|
+
return pending
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function createHostUpdates({ ctx, build, profileDir, fetch = globalThis.fetch,
|
|
50
|
+
packageRoot = path.resolve(import.meta.dirname, '../..'), quiesce, resume, withUpdateLock }) {
|
|
51
|
+
const checker = createNpmUpdateChecker({ currentVersion: build.version, fetch })
|
|
52
|
+
const directory = ctx.get('profileContext')?.dir || profileDir
|
|
53
|
+
const installedRoot = directory && path.join(directory, 'node_modules', PACKAGE)
|
|
54
|
+
const hmr = ctx.get('hmr')
|
|
55
|
+
const canActivate = typeof hmr?.runExclusive === 'function' && typeof hmr?.reconcileProfile === 'function'
|
|
56
|
+
const safe = installedRoot && quiesce && withUpdateLock && createSafeUpdate({
|
|
57
|
+
profileDir: directory, packageRoot, installedRoot, journalName: '.kb-npm-updates',
|
|
58
|
+
quiesce, resume, withUpdateLock, activeBuild: build,
|
|
59
|
+
activate: canActivate ? () => hmr.runExclusive(() => hmr.reconcileProfile()) : undefined,
|
|
60
|
+
})
|
|
61
|
+
const installedHere = Boolean(installedRoot && path.relative(installedRoot, packageRoot) === '')
|
|
62
|
+
const supported = Boolean(safe && installedHere)
|
|
63
|
+
const unavailable = () => ({ ok: false, code: 'NPM_MANAGED_UPDATE',
|
|
64
|
+
error: '当前安装模式无法安全交接知识库,请通过 DSH 插件管理器更新 npm 版。' })
|
|
65
|
+
let preparing
|
|
66
|
+
ctx.effect(() => startAutomaticChecks(checker), 'kb-service: npm update checks')
|
|
67
|
+
return {
|
|
68
|
+
async check(body = {}) {
|
|
69
|
+
return { ...await checker.check({ force: body.force === true }), installSupported: supported }
|
|
70
|
+
},
|
|
71
|
+
status: () => supported ? safe.status() : { phase: 'none', installSupported: false },
|
|
72
|
+
install: body => supported ? safe.install(body) : unavailable(),
|
|
73
|
+
async prepare({ expectedVersion } = {}) {
|
|
74
|
+
if (!supported) return unavailable()
|
|
75
|
+
if (preparing) throw Error('另一个 npm 更新正在准备')
|
|
76
|
+
preparing = true
|
|
77
|
+
let temp
|
|
78
|
+
try {
|
|
79
|
+
const installed = await readCandidateBuild(installedRoot)
|
|
80
|
+
if (installed.version !== build.version || installed.buildId !== build.buildId) throw Error('已安装的插件发生变化,请先重启 DSH')
|
|
81
|
+
const release = await checker.check({ force: true })
|
|
82
|
+
if (!release.ok) throw Error(release.error)
|
|
83
|
+
if (!release.updateAvailable || release.latestVersion !== expectedVersion) throw Error('npm 最新版本已变化,请重新检查')
|
|
84
|
+
const raw = await readUpdateSourceBytes(fetch, registrySource, release.archiveUrl, 64 * 1024 * 1024, 20000)
|
|
85
|
+
if ('sha512-' + createHash('sha512').update(raw).digest('base64') !== release.integrity) throw Error('npm 安装包完整性校验失败')
|
|
86
|
+
temp = await mkdtemp(path.join(os.tmpdir(), 'kb-npm-update-'))
|
|
87
|
+
const spec = path.join(temp, 'plugin.tgz')
|
|
88
|
+
await writeFile(spec, raw, { flag: 'wx', mode: 0o600 })
|
|
89
|
+
return await safe.prepare({ spec, latestVersion: expectedVersion, currentVersion: build.version, bytes: raw.length,
|
|
90
|
+
sha256: createHash('sha256').update(raw).digest('hex'), integrity: release.integrity })
|
|
91
|
+
} finally {
|
|
92
|
+
preparing = false
|
|
93
|
+
if (temp) await rm(temp, { recursive: true, force: true }).catch(() => {})
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {INBOX_FLOW} from '../kb-core/src/inbox-flow.js';
|
|
2
|
+
import {prepareFlowConversation} from '../kb-core/src/flow-workspace.js';
|
|
3
|
+
export function createInboxHost({client,getLLM,getWorkspace}){
|
|
4
|
+
let catalog,expires=0;
|
|
5
|
+
async function directory(){
|
|
6
|
+
if(catalog&&Date.now()<expires)return catalog;
|
|
7
|
+
const llm=getLLM(),groups=[],failures=[];if(!llm?.listProviders||!llm?.listModels||!llm?.resolveModelInfo)throw Error('DSH 模型目录尚未就绪');
|
|
8
|
+
for(const p of llm.listProviders())try{const items=[];for(const m of await llm.listModels(p.id))try{const info=await llm.resolveModelInfo(p.id,m.id);items.push({id:m.id,name:info.name||m.name||m.id,reasoning:info.reasoning});}catch{failures.push({name:(p.name||p.id)+' / '+m.id});}groups.push({id:p.id,name:p.name||p.id,models:items});}catch{failures.push({name:p.name||p.id});}
|
|
9
|
+
catalog={ok:true,groups,failures};expires=Date.now()+10000;return catalog;
|
|
10
|
+
}
|
|
11
|
+
async function models(){
|
|
12
|
+
const rows=(await directory()).groups.flatMap(p=>p.models.filter(m=>m.reasoning?.efforts?.some(e=>e.id==='high')).map(m=>({provider:p.id,model:m.id,reasoningEffort:'high'})));
|
|
13
|
+
if(!rows.length)throw Error('没有支持 High 的可用模型');return rows;
|
|
14
|
+
}
|
|
15
|
+
async function status(){return {...await client.call('host.tool',{name:'kb_status',input:{}}),runtimeMode:'service'};}
|
|
16
|
+
return async function handle(body){
|
|
17
|
+
if(body.op==='inbox.organize-context'){const s=await status();return {ok:true,kbId:s.kbId,execution:(await models())[0]};}
|
|
18
|
+
if(body.op==='inbox.organize-bridge'){
|
|
19
|
+
const a={...body};delete a.op;
|
|
20
|
+
if(a.action==='heartbeat'&&!(await models()).some(m=>m.provider===a.execution?.provider&&m.model===a.execution?.model))throw Error('所选模型不可用或不支持 High');
|
|
21
|
+
return {ok:true,...await client.call('inbox.organizeBridge',a)};
|
|
22
|
+
}
|
|
23
|
+
if(body.op==='flows.prepare-conversation'){
|
|
24
|
+
// Custom definitions belong to the shared engine, not the builtin inbox gate.
|
|
25
|
+
if(body.id!==INBOX_FLOW.id){
|
|
26
|
+
return prepareFlowConversation({prepareConversation:input=>client.call('adapter.dispatch',{operation:input})},
|
|
27
|
+
{ensure:async root=>{if(!getWorkspace)throw Error('DSH 流程工作区尚未就绪');return getWorkspace(root);}},body);
|
|
28
|
+
}
|
|
29
|
+
const s=await status();
|
|
30
|
+
const changed={ok:false,reason:'kb-changed',error:'当前知识库已切换,原库的整理请求已停止。请确认当前库后再发起整理。'};
|
|
31
|
+
if(!s.kbId)return {ok:false,reason:'kb-unbound',error:'当前没有已绑定的知识库,未启动整理。'};
|
|
32
|
+
if(body.kbId!==s.kbId)return changed;
|
|
33
|
+
const saved=await client.call('adapter.dispatch',{operation:{op:'flows.get',id:INBOX_FLOW.id}});
|
|
34
|
+
if(!saved?.ok||!saved.flow)return {ok:false,reason:saved?.reason??'flow-unavailable',error:saved?.error??'暂时无法读取整理流程,未启动整理。'};
|
|
35
|
+
if(saved.kbId!==s.kbId)return changed;
|
|
36
|
+
if(body.expectedRevision!==saved.flow.revision)return {ok:false,reason:'flow-changed',error:'整理流程配置已更新,请使用最新配置。'};
|
|
37
|
+
const selected=body.execution===undefined?saved.flow.execution:body.execution;
|
|
38
|
+
const execution=(await models()).find(m=>m.provider===selected?.provider&&m.model===selected?.model);if(!execution||!(await getLLM().resolveModelInfo(execution.provider,execution.model)).reasoning?.efforts?.some(e=>e.id==='high'))throw Error('请先在流程卡中保存支持 High 的可用模型');
|
|
39
|
+
if(!getWorkspace)throw Error('DSH 流程工作区尚未就绪');const workspace=await getWorkspace(s.kbPath);
|
|
40
|
+
return {ok:true,kbId:s.kbId,kbPath:s.kbPath,...workspace,cwd:workspace.workspacePath,flowId:INBOX_FLOW.id,flowRevision:saved.flow.revision,prompt:INBOX_FLOW.prompt,requiredReasoningEffort:'high',execution};
|
|
41
|
+
}
|
|
42
|
+
if(body.op==='flows.models'){
|
|
43
|
+
return directory();
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {randomUUID} from 'node:crypto';
|
|
3
|
+
import {atomic,readJson,error,hash} from './io.js';
|
|
4
|
+
// The service owns request state. Only a live, authorized DSH UI may launch the
|
|
5
|
+
// existing knowledge conversation; the desktop never impersonates a Host.
|
|
6
|
+
export async function createInboxJobs({privateDir,list,connected,now=Date.now}){
|
|
7
|
+
const file=path.join(privateDir,'inbox-organize.json'),runners=new Map();
|
|
8
|
+
let task=await readJson(file,null);
|
|
9
|
+
if(task&&['pending','launching'].includes(task.state)){task={...task,state:'unknown',message:'服务重启,任务发送结果需要在 DSH 会话中核对;未自动重新发送。'};await atomic(file,task);}
|
|
10
|
+
function runner(){return [...runners.values()].find(r=>r.until>now()&&connected(r.grantId));}
|
|
11
|
+
const publicTask=()=>task?{...Object.fromEntries(Object.entries(task).filter(([k])=>!['token','clientId','grantId','signature','paths','operationId'].includes(k))),fileCount:task.paths.length}:null;
|
|
12
|
+
return {
|
|
13
|
+
recoverOperation(id){return task?.operationId===id?publicTask():null;},
|
|
14
|
+
status(){const r=runner();return {ready:!!r,execution:r?.execution,task:publicTask()};},
|
|
15
|
+
async resolve(a){
|
|
16
|
+
if(!task||task.id!==a.taskId||task.state!=='unknown')throw error('CONFLICT','待核对任务已变化,请刷新');
|
|
17
|
+
if(a.confirm!==true||!['launched','failed'].includes(a.state)||a.state==='launched'&&!a.sessionId?.trim())throw error('BAD_REQUEST','请核对原会话并确认结果');
|
|
18
|
+
task={...task,state:a.state,sessionId:a.state==='launched'?a.sessionId:'',resolvedAt:now(),message:a.state==='launched'?'已人工核对:DSH 会话已创建':'已人工核对:未发送,可重新发起整理'};
|
|
19
|
+
await atomic(file,task);return publicTask();
|
|
20
|
+
},
|
|
21
|
+
async request(operationId){
|
|
22
|
+
if(task?.operationId===operationId)return publicTask();
|
|
23
|
+
const r=runner();if(!r)throw error('HOST_UNAVAILABLE','尚未接入可执行整理的 DSH 知识库会话;没有移动或归档文件。');
|
|
24
|
+
const rows=await list(),paths=rows.map(r=>r.path).sort(),signature=hash(paths);
|
|
25
|
+
if(!paths.length)throw error('BAD_REQUEST','收件箱没有待整理文件');
|
|
26
|
+
if(task&&(['pending','launching'].includes(task.state)||task.state==='launched'&&task.signature===signature))return publicTask();
|
|
27
|
+
if(task?.state==='unknown')throw error('RESULT_UNKNOWN','上次任务发送结果未确认,请先在 DSH 核对会话,避免重复整理。');
|
|
28
|
+
task={id:randomUUID(),operationId,state:'pending',paths,signature,createdAt:now(),execution:r.execution,message:'等待 DSH 发起知识库会话'};await atomic(file,task);return publicTask();
|
|
29
|
+
},
|
|
30
|
+
async bridge(a,grantId){
|
|
31
|
+
if(typeof a.clientId!=='string'||!/^[a-zA-Z0-9-]{8,80}$/.test(a.clientId))throw error('BAD_REQUEST','无效的 DSH 客户端身份');
|
|
32
|
+
const key=grantId+':'+a.clientId;
|
|
33
|
+
if(a.action==='heartbeat'){
|
|
34
|
+
if(!a.execution?.provider||!a.execution?.model||a.execution.reasoningEffort!=='high')throw error('BAD_REQUEST','整理流程必须使用 High 模型');
|
|
35
|
+
for(const [k,r]of runners)if(r.until<=now()||!connected(r.grantId))runners.delete(k);
|
|
36
|
+
if(runners.size>=32&&!runners.has(key))throw error('STATE_BUSY','DSH 整理入口数量已满');
|
|
37
|
+
runners.set(key,{grantId,clientId:a.clientId,execution:{provider:a.execution.provider,model:a.execution.model,reasoningEffort:'high'},until:now()+12000});return {ready:true};
|
|
38
|
+
}
|
|
39
|
+
if(a.action==='leave'){runners.delete(key);return {left:true};}
|
|
40
|
+
const r=runners.get(key);if(a.action!=='report'&&(!r||r.until<=now()))throw error('FORBIDDEN','DSH 执行入口已失效');
|
|
41
|
+
if(a.action==='claim'){
|
|
42
|
+
if(!task||task.state!=='pending')return {task:null};
|
|
43
|
+
if(JSON.stringify(task.execution)!==JSON.stringify(r.execution))return {task:null};
|
|
44
|
+
task={...task,state:'launching',clientId:a.clientId,grantId,token:randomUUID(),message:'正在创建 DSH 知识库会话'};await atomic(file,task);return {task:{...publicTask(),token:task.token}};
|
|
45
|
+
}
|
|
46
|
+
if(a.action==='report'){
|
|
47
|
+
if(!task||task.id!==a.taskId||task.clientId!==a.clientId||task.grantId!==grantId||task.token!==a.token||task.state!=='launching')throw error('CONFLICT','任务回执不匹配');
|
|
48
|
+
if(!['launched','failed','unknown'].includes(a.state)||a.state==='launched'&&!a.sessionId)throw error('BAD_REQUEST','无效的会话回执');
|
|
49
|
+
task={...task,state:a.state,sessionId:String(a.sessionId??'').slice(0,128),message:String(a.message??'').slice(0,600),updatedAt:now()};await atomic(file,task);return publicTask();
|
|
50
|
+
}
|
|
51
|
+
throw error('BAD_REQUEST','未知的 DSH 整理动作');
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { readFile, open, rename, mkdir, unlink } from 'node:fs/promises'
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
export const hash = x => createHash('sha256').update(typeof x === 'string' || Buffer.isBuffer(x) ? x : JSON.stringify(x)).digest('hex')
|
|
6
|
+
export const error = (code, message = code) => Object.assign(new Error(message), { code })
|
|
7
|
+
export async function readJson(file, fallback) { try { return JSON.parse(await readFile(file, 'utf8')) } catch (e) { if (e.code === 'ENOENT' && fallback !== undefined) return structuredClone(fallback); throw e } }
|
|
8
|
+
export async function bytes(file) { try { return await readFile(file) } catch (e) { if (e.code === 'ENOENT') return null; throw e } }
|
|
9
|
+
export async function atomic(file, value) {
|
|
10
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
11
|
+
const temp = file + '.tmp-' + randomUUID(), data = Buffer.isBuffer(value) ? value : Buffer.from(JSON.stringify(value, null, 2) + '\n')
|
|
12
|
+
let h
|
|
13
|
+
try { h = await open(temp, 'wx'); await h.writeFile(data); await h.sync(); await h.close(); h = null; await rename(temp, file) }
|
|
14
|
+
finally { await h?.close(); await unlink(temp).catch(e => { if (e.code !== 'ENOENT') throw e }) }
|
|
15
|
+
}
|
|
16
|
+
export function native(python, command, data) {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
const child = spawn(python, ['-I', '-X', 'utf8', path.join(import.meta.dirname, 'native.py'), command], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] })
|
|
19
|
+
let stdout = '', stderr = ''; child.stdout.on('data', b => { stdout += b; if (stdout.length > 2e6) child.kill() }); child.stderr.on('data', b => { stderr += b })
|
|
20
|
+
child.on('error', reject); child.on('exit', code => { if (code) reject(error('NATIVE_FAILED', stderr.slice(-1500))); else { try { resolve(JSON.parse(stdout)) } catch (e) { reject(e) } } })
|
|
21
|
+
child.stdin.end(JSON.stringify(data))
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
export const serialQueue = () => { let tail = Promise.resolve(); return fn => { const next = tail.then(fn); tail = next.catch(() => {}); return next } }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {open,unlink} from 'node:fs/promises';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {readJson,native,error} from './io.js';
|
|
5
|
+
|
|
6
|
+
// A PID alone is insufficient: Windows can reuse it after a crashed launcher.
|
|
7
|
+
export async function claimLaunchLock({privateDir,python,timeoutMs=20000}) {
|
|
8
|
+
const file=path.join(privateDir,'launch.lock'),owner=randomUUID();
|
|
9
|
+
const birth=await native(python,'birth',{pid:process.pid}),deadline=Date.now()+timeoutMs;
|
|
10
|
+
do {
|
|
11
|
+
let handle;
|
|
12
|
+
try {handle=await open(file,'wx');}
|
|
13
|
+
catch(e) {
|
|
14
|
+
if(e.code!=='EEXIST')throw e;
|
|
15
|
+
const held=await readJson(file,null).catch(e=>{if(e instanceof SyntaxError)return null;throw e;});
|
|
16
|
+
if(held&&typeof held.owner==='string'&&Number.isInteger(held.pid)&&held.birth!=null&&await native(python,'birth',{pid:held.pid})!==held.birth){
|
|
17
|
+
const latest=await readJson(file,null);
|
|
18
|
+
if(latest?.owner===held.owner&&latest.pid===held.pid&&latest.birth===held.birth)await unlink(file).catch(e=>{if(e.code!=='ENOENT')throw e;});
|
|
19
|
+
}
|
|
20
|
+
if(Date.now()>=deadline)throw error('STATE_BUSY','资料库启动锁仍被占用或需要核对,未接管存活服务');
|
|
21
|
+
await new Promise(r=>setTimeout(r,100));continue;
|
|
22
|
+
}
|
|
23
|
+
try {await handle.writeFile(JSON.stringify({owner,pid:process.pid,birth}));await handle.sync();}
|
|
24
|
+
catch(e){await handle.close();throw e;}
|
|
25
|
+
return {async release(){await handle.close();if((await readJson(file,null))?.owner===owner)await unlink(file);}};
|
|
26
|
+
}while(true);
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { readJson, native, error } from './io.js'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { open, mkdir } from 'node:fs/promises'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
// This launcher may exit immediately. The independent service owns its lifecycle.
|
|
6
|
+
export async function launchService({ configurationPath, logDirectory, node = process.execPath }) {
|
|
7
|
+
const config=await readJson(configurationPath)
|
|
8
|
+
await native(config.python,'private-dir',{path:path.resolve(config.privateDir)})
|
|
9
|
+
const relative=path.relative(path.resolve(config.privateDir),path.resolve(logDirectory))
|
|
10
|
+
if(relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative))throw error('BAD_REQUEST','Startup logs must stay in the private service directory')
|
|
11
|
+
await mkdir(logDirectory,{recursive:true})
|
|
12
|
+
const stdout=await open(path.join(logDirectory,'service.stdout.log'),'a'),stderr=await open(path.join(logDirectory,'service.stderr.log'),'a')
|
|
13
|
+
try {
|
|
14
|
+
const child=spawn(node,[path.join(import.meta.dirname,'main.js'),path.resolve(configurationPath)],{detached:true,windowsHide:true,env:{...process.env,ELECTRON_RUN_AS_NODE:'1'},stdio:['ignore',stdout.fd,stderr.fd]})
|
|
15
|
+
await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject)})
|
|
16
|
+
child.unref();return {pid:child.pid}
|
|
17
|
+
}finally{await stdout.close();await stderr.close()}
|
|
18
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { readJson, native, error } from './io.js'
|
|
3
|
+
|
|
4
|
+
// Exact runtime fingerprint of the published 2.4.3 package, not a caller label.
|
|
5
|
+
export const LEGACY_243_BUILD = '7ed38d914480a2b3'
|
|
6
|
+
export async function waitForLegacy243({ health, client, privateDir, python, timeoutMs = 60000, pause = ms => new Promise(r => setTimeout(r, ms)), read = readJson, birth = pid => native(python, 'birth', { pid }) }) {
|
|
7
|
+
try {
|
|
8
|
+
if (health.serviceBuildId !== LEGACY_243_BUILD) throw error('CAPABILITY_UNSUPPORTED', '未识别的旧服务,请查看更新恢复说明')
|
|
9
|
+
const ready = await read(path.join(privateDir, 'ready.json'), null)
|
|
10
|
+
if (!ready || ready.bootId !== health.bootId) throw error('BINDING_CHANGED', '旧服务身份已变化')
|
|
11
|
+
const originalBirth = await birth(ready.pid)
|
|
12
|
+
// Never request shutdown from a legacy service without a drain protocol.
|
|
13
|
+
// Releasing this probe allows its existing idle lifecycle to finish. Other
|
|
14
|
+
// clients/tasks are not terminated to make an update proceed.
|
|
15
|
+
client.close()
|
|
16
|
+
const deadline = Date.now() + timeoutMs
|
|
17
|
+
while (Date.now() < deadline) {
|
|
18
|
+
const latest = await read(path.join(privateDir, 'ready.json'), null)
|
|
19
|
+
if (latest?.bootId !== ready.bootId) throw error('BINDING_CHANGED', '其他连接已更换服务,未强制接管')
|
|
20
|
+
const stopped = originalBirth === null || await birth(ready.pid) !== originalBirth
|
|
21
|
+
const receipt = await read(path.join(privateDir, 'last-close.json'), null)
|
|
22
|
+
if (stopped && receipt?.bootId === ready.bootId && receipt.clean === true) return { legacy: true, bootId: ready.bootId }
|
|
23
|
+
await pause(200)
|
|
24
|
+
}
|
|
25
|
+
throw error('SERVICE_UPGRADE_REQUIRED', '旧服务仍有连接或任务,交接已延后;请查看更新恢复说明')
|
|
26
|
+
} finally { client.close() }
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import path from 'node:path';import {error} from './io.js';
|
|
2
|
+
export function createLegacyPorts({kernel,kbId,root,maintenance,changeMaintenance}){
|
|
3
|
+
const wb=op=>kernel.dispatch({...op,expectedKbId:kbId});
|
|
4
|
+
return async function legacy(a){
|
|
5
|
+
if(a.op==='overview'){
|
|
6
|
+
const [st,snap]=await Promise.all([kernel.core.status(),wb({op:'atlas.snapshot',fresh:a.fresh})]);
|
|
7
|
+
return {ok:true,overview:{at:new Date().toISOString(),version:snap.version,identity:{bound:true,kbPath:root,name:path.basename(root),kbId,kbIdShort:kbId.slice(0,8),mode:'read-write',stateDir:st.stateDir},run:{config:st.config,kb:{healthy:st.healthy,reason:st.healthReason},index:st.index,lastCheck:{known:false},scan:{status:snap.coverage.truncated?'partial':'ok',at:new Date().toISOString(),errors:snap.coverage.errors,coverage:snap.coverage}},layers:{entries:snap.totals.knowledge,entriesInIndex:st.counts?.entries,originals:snap.sections.find(s=>s.name==='90-收件箱')?.files??0,drafts:snap.sections.find(s=>s.name==='50-底稿')?.files??0,filesAll:snap.totals.files,physicalEntries:null,foldedSources:null,bytesAll:null,coverage:snap.coverage},issues:st.index?.fresh?[]:[{kind:'index-stale',label:'索引待同步',detail:st.index?.reasonLabel??st.index?.reason??'正在核对原件'}],sections:snap.sections,recent:snap.recent,privacy:{masked:snap.totals.private>0}}};
|
|
8
|
+
}
|
|
9
|
+
if(a.op==='files'){const r=await wb({...a,op:'atlas.list',mode:'name',direct:false});return {ok:true,...r,root,files:r.items};}
|
|
10
|
+
if(a.op==='dirs')return {ok:true,dirs:{current:root,candidate:root,defaultCandidate:root,canWrite:true,bound:root,defaultKnowledgeBase:root,defaultWritable:true}};
|
|
11
|
+
if(a.op==='index-maintenance.status'){const s=await kernel.core.status();return {ok:true,enabled:(await kernel.core.getConfig()).autoIndex!==false,scheduler:maintenance()?.status(),maintenance:kernel.core.maintenanceStatus(),kbId,index:s.index};}
|
|
12
|
+
if(a.op==='index-maintenance.configure'){const r=await kernel.core.setConfig({autoIndex:a.enabled===true});changeMaintenance(a.enabled===true);return r;}
|
|
13
|
+
if(a.op==='index-snapshots')return kernel.core.indexSnapshots({restore:a.restore,expectedKbId:kbId});
|
|
14
|
+
if(a.op==='index-rebuild'){const result=await kernel.core.maintainIndex({full:true,expectedKbId:kbId,expectedRevision:a.expectedRevision,confirmDrop:a.confirmDrop});return {ok:result.ok,result,error:result.ok?undefined:result.detail??result.reason};}
|
|
15
|
+
if(['setup','bind','probe-folder'].includes(a.op)){if(path.resolve(a.path??a.kbPath??root).toLowerCase()!==root.toLowerCase())throw error('BINDING_CHANGED','共库连接绑定当前库;切换库需重新建立该库连接,未切换或改动其他库');return {ok:true,result:{ok:true,bound:true,kbId,kbPath:root,action:'already-bound'},folder:{path:root,kind:'knowledge-base'}};}
|
|
16
|
+
throw error('CAPABILITY_UNSUPPORTED');
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { readJson, atomic } from './io.js'
|
|
2
|
+
import { startService } from './service.js'
|
|
3
|
+
|
|
4
|
+
// This worker scans physical originals. Electron's virtual ASAR entries have
|
|
5
|
+
// synthetic file identities and must not be treated as files in the library.
|
|
6
|
+
if (process.versions.electron) process.noAsar = true
|
|
7
|
+
|
|
8
|
+
// Launch configuration contains paths/handles only. Credentials never appear in argv.
|
|
9
|
+
const options = await readJson(process.argv[2])
|
|
10
|
+
const service = await startService(options)
|
|
11
|
+
await atomic(options.privateDir + '/ready.json', { ready:true,pipe:service.pipe,bootId:service.bootId,pid:process.pid,library:{kbId:service.kbId,instanceId:service.instanceId} })
|
|
12
|
+
process.stdout.write(JSON.stringify({ ready: true, pipe: service.pipe, bootId: service.bootId, library: { kbId: service.kbId, instanceId: service.instanceId } }) + '\n')
|
|
13
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { void service.close() })
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Global memory stays owned by the memory plugin. Only explicitly selected
|
|
2
|
+
// knowledge memories are merged, through this library's authorized dispatcher.
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
const fail=(code,message)=>{throw Object.assign(new Error(message),{code})};
|
|
5
|
+
export const hasMemoryHost=store=>store?.memoryApi?.version===1||typeof store?.globalRequest==='function';
|
|
6
|
+
function memoryView(local,knowledge,shared){
|
|
7
|
+
if(knowledge?.protocol!=='dsh-memory/v1'||knowledge.complete!==true)fail('RESULT_UNKNOWN','知识库记忆快照未完整读取,请重试');
|
|
8
|
+
return {ok:true,...local,entries:[...(local.entries??[]),...knowledge.entries],knowledge:{state:'connected',libraryId:knowledge.libraryId},memory:{mode:shared?'shared':'independent',globalAvailable:shared,changeEvents:true}};
|
|
9
|
+
}
|
|
10
|
+
export function createMemoryChannel({broker,snapshot}){
|
|
11
|
+
const independent=async()=>memoryView({},await snapshot(),false);
|
|
12
|
+
return async function dispatch(operation,caller,operationId=randomUUID()){
|
|
13
|
+
if(!caller.access.includes('admin'))fail('FORBIDDEN','全局记忆需要当前用户的管理权限');
|
|
14
|
+
const {op}=operation;
|
|
15
|
+
if(op==='memory.result'){
|
|
16
|
+
const job=broker.get(operation.taskId,caller.id);
|
|
17
|
+
if(!job.method.startsWith('memory.'))fail('FORBIDDEN','不是记忆任务');
|
|
18
|
+
if(job.error){
|
|
19
|
+
if(job.method==='memory.list'&&['HOST_UNAVAILABLE','HOST_TIMEOUT','RESULT_UNKNOWN'].includes(job.error.code))return independent();
|
|
20
|
+
fail(job.error.code,job.error.message);
|
|
21
|
+
}
|
|
22
|
+
if(job.state!=='completed')return {ok:true,pending:true,taskId:job.id};
|
|
23
|
+
if(job.method!=='memory.list')return {ok:true,...job.result};
|
|
24
|
+
// Never reuse a snapshot across permission changes or library switches.
|
|
25
|
+
const knowledge=await snapshot();
|
|
26
|
+
return memoryView(job.result,knowledge,true);
|
|
27
|
+
}
|
|
28
|
+
if(!['memory.list','memory.add','memory.remove'].includes(op))fail('BAD_REQUEST','未知记忆操作');
|
|
29
|
+
const args=op==='memory.add'?{text:operation.text,title:operation.title??''}:op==='memory.remove'?{entry_id:operation.entry_id}:{};
|
|
30
|
+
if(op==='memory.add'&&(typeof args.text!=='string'||!args.text.trim()||args.text.length>4000||typeof args.title!=='string'||args.title.length>80))fail('BAD_REQUEST','记忆正文为 1–4000 字,标题不超过 80 字');
|
|
31
|
+
if(op==='memory.remove'&&(typeof args.entry_id!=='string'||!args.entry_id.startsWith('memory-')))fail('BAD_REQUEST','知识库记忆请在原文中维护');
|
|
32
|
+
const host=broker.status().hosts.find(h=>h.capabilities.includes('memory-v1'));
|
|
33
|
+
if(!host){
|
|
34
|
+
if(op==='memory.list')return independent();
|
|
35
|
+
fail('CAPABILITY_UNSUPPORTED','当前为独立知识库模式,全局记忆服务未接入');
|
|
36
|
+
}
|
|
37
|
+
const job=await broker.request(op,{...args,hostInstanceId:host.id},caller.id,operationId);
|
|
38
|
+
return {ok:true,pending:true,taskId:job.id};
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function handleMemoryHost(getStore,method,args={},requestId){
|
|
43
|
+
const store=getStore();
|
|
44
|
+
if(!hasMemoryHost(store))fail('HOST_UNAVAILABLE','记忆插件尚未加载');
|
|
45
|
+
const op=({'memory.list':'list','memory.add':'add','memory.remove':'remove'})[method];
|
|
46
|
+
if(!op)fail('BAD_REQUEST','未知记忆操作');
|
|
47
|
+
if(store.memoryApi?.version===1)return store.memoryApi.request('global.'+op,args,requestId);
|
|
48
|
+
return store.globalRequest(op,args,requestId);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function handleEmbeddedMemory(ctx,operation){
|
|
52
|
+
if(operation.op==='memory.list'&&!hasMemoryHost(ctx.get('memoryStore')))return memoryView({},await ctx.get('knowledgeMemory').snapshot(),false);
|
|
53
|
+
const value=await handleMemoryHost(()=>ctx.get('memoryStore'),operation.op,operation,operation.requestId);
|
|
54
|
+
if(operation.op!=='memory.list')return value;
|
|
55
|
+
const knowledge=await ctx.get('knowledgeMemory').snapshot();
|
|
56
|
+
return memoryView(value,knowledge,true);
|
|
57
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Memory-only protocol. Never turn an arbitrary knowledge document into memory. */
|
|
2
|
+
const marks=new Set(['记忆','长期记忆','memory','memories']);
|
|
3
|
+
export function isMemoryRecord(file){
|
|
4
|
+
if(['withdrawn','retracted','deleted','pending','撤回','已撤回','已替代','历史','待确认'].includes(file.status))return false;
|
|
5
|
+
const marker=v=>marks.has(String(v??'').trim().toLowerCase());
|
|
6
|
+
return marker(file.kind)||marker(file.type)||(file.tags??[]).some(marker)||String(file.path??'').split('/').slice(0,-1).some(marker);
|
|
7
|
+
}
|
|
8
|
+
export function createKnowledgeMemoryProvider(dispatch,subscribe,cacheInvalidations=false){
|
|
9
|
+
return {protocol:'dsh-memory/v1',subscribe,cacheInvalidations,async snapshot(context={}){
|
|
10
|
+
const read=operation=>dispatch(operation,context);
|
|
11
|
+
const selected=[];let offset=0,libraryId=null,policy=null;
|
|
12
|
+
for(;;){
|
|
13
|
+
const page=await read({op:'atlas.list',offset,limit:500});
|
|
14
|
+
if(page.ok===false||page.truncated)throw Error('knowledge_memory_snapshot_incomplete');
|
|
15
|
+
libraryId??=page.kbId;policy??=page.policyVersion;
|
|
16
|
+
if(page.kbId!==libraryId||JSON.stringify(page.policyVersion)!==JSON.stringify(policy))throw Error('knowledge_memory_binding_changed');
|
|
17
|
+
selected.push(...page.items.filter(isMemoryRecord));offset+=page.items.length;
|
|
18
|
+
if(offset>=page.total)break;if(!page.items.length)throw Error('knowledge_memory_pagination_stalled');
|
|
19
|
+
}
|
|
20
|
+
const ids=new Map(selected.map(f=>[f.path,'kb:'+libraryId+':'+(f.entryId||f.path)]));
|
|
21
|
+
const entries=[];const edges=[];const seen=new Set;
|
|
22
|
+
for(const file of selected){
|
|
23
|
+
const detail=await read({op:'atlas.detail',path:file.path});
|
|
24
|
+
if(detail.ok===false||detail.content?.truncated||JSON.stringify(detail.policyVersion)!==JSON.stringify(policy))throw Error('knowledge_memory_source_unavailable');
|
|
25
|
+
if(!isMemoryRecord(detail.file??file))continue;
|
|
26
|
+
if(!detail.content?.text)continue;
|
|
27
|
+
// This protocol publishes knowledge memories as read-only global records;
|
|
28
|
+
// explicit project memory requires a project identity and is not promoted.
|
|
29
|
+
if((file.tags??[]).some(t=>['项目记忆','project-memory'].includes(t)))continue;
|
|
30
|
+
entries.push({id:ids.get(file.path),scope:'global',project:null,title:file.title||file.path,text:detail.content.text,quote:detail.content.text,origin:'knowledge',created:0,
|
|
31
|
+
proofs:[{source_id:'kb:'+libraryId+':'+file.path,quote:detail.content.text}],metadata:{kind:'知识库记忆',provider:'knowledge',readOnly:true,revision:detail.content.revision,path:file.path,relations:[]}});
|
|
32
|
+
const graph=await read({op:'atlas.relations',path:file.path,limit:500});
|
|
33
|
+
if(graph.ok===false)throw Error('knowledge_memory_relations_unavailable');
|
|
34
|
+
for(const edge of graph.edges??[]){if(!ids.has(edge.from)||!ids.has(edge.to))continue;const key=JSON.stringify([edge.from,edge.to,edge.type]);if(seen.has(key))continue;seen.add(key);edges.push({from:ids.get(edge.from),to:ids.get(edge.to),type:edge.type||'reference',reason:edge.context||edge.reason||'知识库中已记录的记忆关联'});}
|
|
35
|
+
}
|
|
36
|
+
const valid=new Set(entries.map(e=>e.id));for(const edge of edges)if(valid.has(edge.from)&&valid.has(edge.to))entries.find(e=>e.id===edge.from).metadata.relations.push(edge);
|
|
37
|
+
return {protocol:'dsh-memory/v1',libraryId,complete:true,entries};
|
|
38
|
+
}};
|
|
39
|
+
}
|
|
40
|
+
export function publishKnowledgeMemory(ctx,dispatch,subscribe,cacheInvalidations){
|
|
41
|
+
ctx.provide('knowledgeMemory',createKnowledgeMemoryProvider(dispatch,subscribe,cacheInvalidations));
|
|
42
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { readdir, unlink } from 'node:fs/promises'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { atomic, bytes, hash, readJson, error } from './io.js'
|
|
5
|
+
const blank = kbId => ({ schemaVersion: 1, format: 1, kbId, revision: 0, links: [], captures: [], annotations: [], reading: {}, reviews: {}, trashOperations: {}, tasks: [] })
|
|
6
|
+
const arrays = ['links', 'captures', 'annotations', 'tasks'], maps = ['reading', 'reviews', 'trashOperations']
|
|
7
|
+
const equal = (a, b) => hash(a) === hash(b)
|
|
8
|
+
export function createMigration({ root, privateDir, identity, sources, getWriteSequence, fault = async () => {} }) {
|
|
9
|
+
const plans = new Map(), journalFile = path.join(privateDir, 'migration.json')
|
|
10
|
+
async function assertReconciled() {
|
|
11
|
+
for(const name of ['workbench-user-data.json','workbench-flows.json']) if(await bytes(path.join(root,'.kbmeta',name))) throw error('RECOVERY_REQUIRED','Library recovery copy must be reconciled as an explicit source: '+name)
|
|
12
|
+
const trash=await readdir(path.join(root,'.kbmeta/trash')).catch(e=>{if(e.code==='ENOENT')return [];throw e})
|
|
13
|
+
// Settled legacy recycle-bin entries remain in place. Only an unfinished
|
|
14
|
+
// transaction blocks the handoff; historical trash is not discarded.
|
|
15
|
+
for(const id of trash){
|
|
16
|
+
if(!/^[a-f0-9-]{36}$/i.test(id))throw error('RECOVERY_REQUIRED','Unknown legacy recycle-bin entry')
|
|
17
|
+
const item=await readJson(path.join(root,'.kbmeta/trash',id,'manifest.json'),null)
|
|
18
|
+
if(item?.id!==id||item.kbId!==identity.kbId||item.format!==1||!['stored','restored','purged'].includes(item.state))throw error('RECOVERY_REQUIRED','Finish the legacy recycle-bin transaction before switching writers')
|
|
19
|
+
if(item.state==='stored'){const payload=await bytes(path.join(root,'.kbmeta/trash',id,'payload'));if(!payload||hash(payload)!==item.sha256)throw error('RECOVERY_REQUIRED','Legacy recycle-bin payload did not verify')}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async function collect(ids) {
|
|
23
|
+
await assertReconciled()
|
|
24
|
+
const found = []
|
|
25
|
+
for (const id of ids) {
|
|
26
|
+
const stateDir = sources[id]
|
|
27
|
+
if (!stateDir) throw error('BAD_REQUEST', 'Unknown configured source handle')
|
|
28
|
+
const key = hash(identity.kbId + '\0' + root.toLowerCase()).slice(0, 24)
|
|
29
|
+
const files = ['config.json', 'binding.json', 'workbench/profile.json', 'workbench/libraries/' + key + '.json']
|
|
30
|
+
const raw = await Promise.all(files.map(f => bytes(path.join(stateDir, f))))
|
|
31
|
+
const values = raw.map(b => b ? JSON.parse(b) : null), [config, binding, profile, data] = values
|
|
32
|
+
if (!config || !binding || binding.kbId !== identity.kbId || path.resolve(binding.kbPath).toLowerCase() !== root.toLowerCase()) throw error('BINDING_CHANGED', 'Source binding does not match this library')
|
|
33
|
+
// In-flight engines are outside this phase's handoff scope. Never silently discard.
|
|
34
|
+
for (const dir of ['parse', 'imports', 'flows']) {
|
|
35
|
+
const entries = await readdir(path.join(stateDir, dir)).catch(e => { if (e.code === 'ENOENT') return []; throw e })
|
|
36
|
+
if (entries.length) throw error('RECOVERY_REQUIRED', 'Engine state requires explicit reconciliation before migration: ' + dir)
|
|
37
|
+
}
|
|
38
|
+
found.push({ id, stateDir, files, raw, config, binding, profile, data: data ?? blank(identity.kbId), key })
|
|
39
|
+
}
|
|
40
|
+
return found
|
|
41
|
+
}
|
|
42
|
+
async function preview(ids) {
|
|
43
|
+
if (!Array.isArray(ids) || !ids.length || new Set(ids).size !== ids.length) throw error('BAD_REQUEST', 'Choose distinct source handles')
|
|
44
|
+
const rows = await collect(ids), candidate = blank(identity.kbId), conflicts = []
|
|
45
|
+
let policy = null
|
|
46
|
+
for (const row of rows) {
|
|
47
|
+
const data = row.data
|
|
48
|
+
if (data.format !== 1 || !Number.isSafeInteger(data.revision)) conflicts.push({ sourceId: row.id, reason: 'UNSUPPORTED_FORMAT' })
|
|
49
|
+
for (const field of Object.keys(data)) if (!['schemaVersion', 'kbId', 'format', 'revision', ...arrays, ...maps].includes(field)) conflicts.push({ sourceId: row.id, field, reason: 'UNMAPPED_STATE' })
|
|
50
|
+
for (const field of arrays) {
|
|
51
|
+
if (!Array.isArray(data[field] ?? [])) throw error('RECOVERY_REQUIRED', 'Invalid source array')
|
|
52
|
+
for (const item of data[field] ?? []) {
|
|
53
|
+
if (!item.id) { conflicts.push({ sourceId: row.id, field, reason: 'MISSING_ID' }); continue }
|
|
54
|
+
if (field === 'tasks' && !['done', 'completed', 'failed', 'cancelled'].includes(item.status)) conflicts.push({ sourceId: row.id, field, reason: 'IN_FLIGHT_TASK' })
|
|
55
|
+
const old = candidate[field].find(x => x.id === item.id)
|
|
56
|
+
if (!old) candidate[field].push(item)
|
|
57
|
+
else if (!equal(old, item)) conflicts.push({ sourceId: row.id, field, id: item.id, reason: 'VALUE_CONFLICT' })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for(const field of maps)if(data[field]!==undefined&&(!data[field]||Array.isArray(data[field])||typeof data[field]!=='object'))conflicts.push({sourceId:row.id,field,reason:'INVALID_MAP'})
|
|
61
|
+
for (const field of maps) for (const [key, value] of Object.entries(data[field] && !Array.isArray(data[field]) ? data[field] : {})) {
|
|
62
|
+
if(field==='trashOperations'&&!['moved','restored'].includes(value)){conflicts.push({sourceId:row.id,field,reason:'IN_FLIGHT_TRASH'});continue}
|
|
63
|
+
if (!Object.hasOwn(candidate[field], key)) candidate[field][key] = value
|
|
64
|
+
else if (!equal(candidate[field][key], value)) conflicts.push({ sourceId: row.id, field, reason: 'VALUE_CONFLICT' })
|
|
65
|
+
}
|
|
66
|
+
const next = { schemaVersion: 1, revision: 0, categories: row.config.categories, privateDirs: row.config.privateDirs, excludeFromSearch: row.config.excludeFromSearch, autoIndex:row.config.autoIndex!==false, preferences: row.profile?.libraries?.[row.key]?.value ?? row.profile?.defaults }
|
|
67
|
+
// Conflicting policies block switching, including different privacy/backup settings.
|
|
68
|
+
if (policy && !equal(policy, next)) conflicts.push({ sourceId: row.id, reason: 'POLICY_CONFLICT' })
|
|
69
|
+
policy ??= next
|
|
70
|
+
}
|
|
71
|
+
const id = randomUUID(), sourceDigests = rows.map(row => ({ id: row.id, digest: hash(row.raw.map(b => b ? hash(b) : null)) }))
|
|
72
|
+
const result = { planId: id, ready: !conflicts.length, conflicts, sourceDigests, counts: Object.fromEntries([...arrays, ...maps].map(k => [k, Array.isArray(candidate[k]) ? candidate[k].length : Object.keys(candidate[k]).length])), committed: false }
|
|
73
|
+
plans.set(id, { result, ids, candidate, policy })
|
|
74
|
+
return result
|
|
75
|
+
}
|
|
76
|
+
const targetNames = ['shared-state.json', 'shared-policy.json', 'service-mode.json']
|
|
77
|
+
async function recover(direction = 'rollback') {
|
|
78
|
+
if (!['rollback', 'complete'].includes(direction)) throw error('BAD_REQUEST')
|
|
79
|
+
const journal = await readJson(journalFile, null)
|
|
80
|
+
if (!journal) return { state: 'clean' }
|
|
81
|
+
if (journal.state === 'rolled-back') return { state: journal.state }
|
|
82
|
+
if (journal.state === 'committed' && getWriteSequence() !== journal.writeSequence) throw error('CONFLICT', 'New shared writes exist; export and reconcile before rollback')
|
|
83
|
+
// Validate ALL targets before changing any. Preserve outside edits.
|
|
84
|
+
for (const row of journal.targets) {
|
|
85
|
+
const current = await bytes(path.join(root, '.kbmeta', row.name)), digest = current ? hash(current) : null
|
|
86
|
+
if (digest !== row.beforeHash && digest !== row.afterHash) throw error('RECOVERY_REQUIRED', 'Target changed outside migration; no recovery target was overwritten')
|
|
87
|
+
}
|
|
88
|
+
for (const row of [...journal.targets].reverse()) {
|
|
89
|
+
const data = direction === 'complete' ? row.after : row.before, file = path.join(root, '.kbmeta', row.name)
|
|
90
|
+
if (data === null) await unlink(file).catch(e => { if (e.code !== 'ENOENT') throw e })
|
|
91
|
+
else await atomic(file, Buffer.from(data, 'base64'))
|
|
92
|
+
}
|
|
93
|
+
journal.state = direction === 'complete' ? 'committed' : 'rolled-back'; await atomic(journalFile, journal)
|
|
94
|
+
return { state: journal.state }
|
|
95
|
+
}
|
|
96
|
+
async function commit({ planId, quiescent, ownerToken, instanceId, freshPolicy }) {
|
|
97
|
+
await assertReconciled()
|
|
98
|
+
if (quiescent !== true) throw error('STATE_BUSY', 'A stopped legacy-writer window must be explicitly confirmed')
|
|
99
|
+
const oldJournal = await readJson(journalFile, null)
|
|
100
|
+
if (oldJournal && !['committed', 'rolled-back'].includes(oldJournal.state)) throw error('RECOVERY_REQUIRED')
|
|
101
|
+
if (await bytes(path.join(root, '.kbmeta/service-mode.json'))) throw error('CONFLICT', 'Already in service mode')
|
|
102
|
+
let candidate, policy
|
|
103
|
+
if (planId === 'fresh') {
|
|
104
|
+
if (Object.keys(sources).length || await bytes(path.join(root, '.kbmeta/workbench-user-data.json'))) throw error('CONFLICT', 'Existing state requires a migration preview')
|
|
105
|
+
candidate = blank(identity.kbId); policy = freshPolicy
|
|
106
|
+
} else {
|
|
107
|
+
const plan = plans.get(planId)
|
|
108
|
+
if (!plan?.result.ready) throw error('CONFLICT', 'Resolve preview conflicts first')
|
|
109
|
+
const rows = await collect(plan.ids)
|
|
110
|
+
if (!equal(rows.map(row => ({ id: row.id, digest: hash(row.raw.map(b => b ? hash(b) : null)) })), plan.result.sourceDigests)) throw error('CONFLICT', 'Source changed after preview')
|
|
111
|
+
candidate = plan.candidate; policy = plan.policy
|
|
112
|
+
}
|
|
113
|
+
const values = [candidate, policy, { schemaVersion: 1, kbId: identity.kbId, instanceId, ownerToken, state: 'active' }], targets = []
|
|
114
|
+
for (let i = 0; i < targetNames.length; i++) {
|
|
115
|
+
const name = targetNames[i], before = await bytes(path.join(root, '.kbmeta', name)), after = Buffer.from(JSON.stringify(values[i], null, 2) + '\n')
|
|
116
|
+
if (before) throw error('CONFLICT', 'Existing shared state requires explicit reconciliation')
|
|
117
|
+
targets.push({ name, before: before?.toString('base64') ?? null, beforeHash: before ? hash(before) : null, after: after.toString('base64'), afterHash: hash(after) })
|
|
118
|
+
}
|
|
119
|
+
const journal = { schemaVersion: 1, id: randomUUID(), state: 'prepared', writeSequence: getWriteSequence(), targets }
|
|
120
|
+
await atomic(journalFile, journal)
|
|
121
|
+
// Install barrier FIRST; all compatible old embedded writers now fail closed.
|
|
122
|
+
const order = [targets[2], targets[0], targets[1]]
|
|
123
|
+
try {
|
|
124
|
+
journal.state = 'applying'; await atomic(journalFile, journal)
|
|
125
|
+
for (const row of order) { await atomic(path.join(root, '.kbmeta', row.name), Buffer.from(row.after, 'base64')); await fault('migration:' + row.name) }
|
|
126
|
+
journal.state = 'committed'; await atomic(journalFile, journal)
|
|
127
|
+
return { committed: true, transactionId: journal.id, sourcesPreserved: true }
|
|
128
|
+
} catch (e) { await recover('rollback'); throw e }
|
|
129
|
+
}
|
|
130
|
+
return { preview, commit, recover, journal: () => readJson(journalFile, null) }
|
|
131
|
+
}
|