@kingsleyasher/dsh-knowledge-base 0.0.0-stage → 3.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +9 -0
- package/PARSING-PREVIEW.md +84 -0
- package/PERFORMANCE.md +43 -0
- package/PRIVACY.md +7 -0
- package/PROJECT-RECORD.en.md +778 -0
- package/PROJECT-RECORD.md +789 -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 +11 -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 +4980 -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 +2224 -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 +284 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import path from 'node:path';import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {atomic,readJson,error,hash} from './io.js';
|
|
3
|
+
|
|
4
|
+
// One authenticated Host owns a job claim. Prompts never go to a second Host
|
|
5
|
+
// after an ambiguous delivery; durable records contain no prompt text.
|
|
6
|
+
export async function createDshBroker({privateDir,alive,emit,now=Date.now}){
|
|
7
|
+
const file=path.join(privateDir,'dsh-jobs.json'),hosts=new Map(),sessions=new Map(),jobs=new Map(),waiters=new Map();
|
|
8
|
+
const prior=await readJson(file,[]);for(const j of prior)jobs.set(j.id,{...j,...(['queued','running'].includes(j.state)?{state:'unknown',error:{code:'RESULT_UNKNOWN',message:'服务重启,请核对 DSH 会话;任务未自动重发'}}:{})});
|
|
9
|
+
const persist=()=>{for(const j of [...jobs.values()].slice(0,-200))if(!['queued','running'].includes(j.state))jobs.delete(j.id);return atomic(file,[...jobs.values()].map(({args,token,result,...j})=>({...j,result:['dsh.createSession','dsh.prompt','dsh.selectModel','dsh.cancel','dsh.follow'].includes(j.method)?result??null:null})).slice(-200));};
|
|
10
|
+
const publicJob=j=>{const {args,token,...out}=j;return out};
|
|
11
|
+
const live=h=>h&&h.until>now()&&alive(h.owner);
|
|
12
|
+
let memoryHostId=null;
|
|
13
|
+
async function publishMemoryHost(){
|
|
14
|
+
const id=[...hosts.values()].find(h=>live(h)&&h.capabilities.includes('memory-v1'))?.id??null;
|
|
15
|
+
if(id===memoryHostId)return;
|
|
16
|
+
const previous=memoryHostId;memoryHostId=id;
|
|
17
|
+
try{await emit({type:'memory-changed',hostInstanceId:id,available:id!==null});}
|
|
18
|
+
catch(error){if(memoryHostId===id)memoryHostId=previous;throw error;}
|
|
19
|
+
}
|
|
20
|
+
function selected(id){const h=id?hosts.get(id):[...hosts.values()].find(live);if(!live(h))throw error('HOST_UNAVAILABLE','DSH 未连接,依赖模型的操作暂不可用');return h;}
|
|
21
|
+
function authorizeSession(h,id){if(id&&!sessions.get(h.id)?.has(id))throw error('FORBIDDEN','会话不属于该知识库的已授权工作区');}
|
|
22
|
+
return {
|
|
23
|
+
status(){return {busy:[...jobs.values()].some(j=>['queued','running'].includes(j.state)),online:[...hosts.values()].some(live),hosts:[...hosts.values()].filter(live).map(({owner,until,...h})=>h)};},
|
|
24
|
+
scope(hostId){const h=selected(hostId);return {hostInstanceId:h.id,workspaces:[h.workspaceId],sessions:[...(sessions.get(h.id)??[])]};},
|
|
25
|
+
async request(method,args,grantId,operationId){
|
|
26
|
+
const old=[...jobs.values()].find(j=>j.operationId===operationId&&j.grantId===grantId);if(old)return publicJob(old);
|
|
27
|
+
const h=selected(args.hostInstanceId);if(args.workspaceId&&args.workspaceId!==h.workspaceId)throw error('FORBIDDEN');if(!(grantId==='internal'&&method==='flow.cancel'))authorizeSession(h,args.sessionId);
|
|
28
|
+
const active=[...jobs.values()].filter(j=>['queued','running'].includes(j.state));if(active.length>=32)throw error('STATE_BUSY','DSH 任务队列已满');
|
|
29
|
+
const id=randomUUID(),j={id,operationId,grantId,hostId:h.id,method,args,state:'queued',createdAt:now(),fingerprint:hash({method,args})};jobs.set(id,j);await persist();return publicJob(j);
|
|
30
|
+
},
|
|
31
|
+
get(id,grantId){const j=jobs.get(id);if(!j||j.grantId!==grantId)throw error('NOT_FOUND');return publicJob(j);},
|
|
32
|
+
recover(operationId){const j=[...jobs.values()].find(j=>j.operationId===operationId);return j?publicJob(j):null;},
|
|
33
|
+
async invoke(method,args,{signal}={}){
|
|
34
|
+
signal?.throwIfAborted();const h=selected(),j=await this.request(method,{...args,hostInstanceId:h.id},'internal',randomUUID());
|
|
35
|
+
return new Promise((resolve,reject)=>{const cleanup=()=>signal?.removeEventListener('abort',cancel),timer=setTimeout(()=>{cleanup();waiters.delete(j.id);reject(error('RESULT_UNKNOWN','DSH 执行未确认,请查看该会话,不自动重复执行'));},300000);
|
|
36
|
+
const cancel=()=>{clearTimeout(timer);cleanup();waiters.delete(j.id);const row=jobs.get(j.id);if(row?.state==='queued'){row.state='canceled';delete row.args;void persist();}else if(method==='flow.delegate')void this.request('flow.cancel',{hostInstanceId:h.id,sessionId:j.id},'internal',randomUUID()).catch(()=>{});reject(error('CANCELED','流程已取消'));};
|
|
37
|
+
timer.unref?.();waiters.set(j.id,{resolve,reject,timer,cleanup});signal?.addEventListener('abort',cancel,{once:true});if(signal?.aborted)cancel();
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
async audit(){let changed=false;for(const j of jobs.values())if(['queued','running'].includes(j.state)&&!live(hosts.get(j.hostId))){const running=j.state==='running';j.state=running?'unknown':'failed';j.error={code:running?'RESULT_UNKNOWN':'HOST_UNAVAILABLE',message:running?'DSH 已断线,请核对会话;未自动重发':'DSH 离线,任务尚未发送'};delete j.args;const w=waiters.get(j.id);if(w){clearTimeout(w.timer);w.cleanup?.();waiters.delete(j.id);w.reject(error(j.error.code,j.error.message));}changed=true;}if(changed)await persist();await publishMemoryHost();return changed;},
|
|
41
|
+
async bridge(a,owner){
|
|
42
|
+
if(a.action==='register'){
|
|
43
|
+
if(!a.workspaceId||!a.label||!Array.isArray(a.capabilities))throw error('BAD_REQUEST');const old=hosts.get(a.hostInstanceId);if(live(old)&&old.owner!==owner)throw error('FORBIDDEN');
|
|
44
|
+
hosts.set(a.hostInstanceId,{id:a.hostInstanceId,label:a.label,workspaceId:a.workspaceId,workspacePath:a.workspacePath,capabilities:a.capabilities,owner,until:now()+8000});sessions.set(a.hostInstanceId,old?.workspaceId===a.workspaceId?sessions.get(a.hostInstanceId)??new Set():new Set());await publishMemoryHost();return {registered:true};
|
|
45
|
+
}
|
|
46
|
+
const h=hosts.get(a.hostInstanceId);if(!h||h.owner!==owner)throw error('FORBIDDEN');
|
|
47
|
+
if(a.action==='leave'){hosts.delete(h.id);await publishMemoryHost();return {left:true};}
|
|
48
|
+
h.until=now()+8000;
|
|
49
|
+
if(a.action==='poll'){
|
|
50
|
+
const j=[...jobs.values()].find(j=>j.hostId===h.id&&j.state==='queued');if(!j)return {task:null};j.state='running';j.token=randomUUID();await persist();return {task:{id:j.id,method:j.method,args:j.args,token:j.token}};
|
|
51
|
+
}
|
|
52
|
+
if(a.action==='memory-changed'){await emit({type:'memory-changed',hostInstanceId:h.id,revision:String(a.revision??'').slice(0,128)});return {published:true};}
|
|
53
|
+
if(a.action==='event'){authorizeSession(h,a.sessionId);if(Buffer.byteLength(JSON.stringify(a.data))>500000)throw error('BAD_REQUEST');await emit({hostInstanceId:h.id,sessionId:a.sessionId,data:a.data});return {published:true};}
|
|
54
|
+
if(a.action==='result'){
|
|
55
|
+
const j=jobs.get(a.taskId);if(!j||j.hostId!==h.id||j.token!==a.token||j.state!=='running')throw error('CONFLICT');
|
|
56
|
+
j.state=a.error?'failed':'completed';j.result=a.result??null;j.error=a.error?{code:String(a.error.code??'HOST_UNAVAILABLE').slice(0,64),message:String(a.error.message??'DSH 操作失败').slice(0,600)}:null;j.finishedAt=now();
|
|
57
|
+
if(!a.error){if(j.method==='dsh.createSession'&&j.result?.sessionId)sessions.get(h.id).add(j.result.sessionId);if(j.method==='dsh.sessions')for(const row of j.result?.items??[])if(row.sessionId)sessions.get(h.id).add(row.sessionId);}
|
|
58
|
+
delete j.args;await persist();const w=waiters.get(j.id);if(w){clearTimeout(w.timer);w.cleanup?.();waiters.delete(j.id);j.error?w.reject(error(j.error.code,j.error.message)):w.resolve(j.result);}return {received:true};
|
|
59
|
+
}
|
|
60
|
+
throw error('BAD_REQUEST');
|
|
61
|
+
},
|
|
62
|
+
dispose(){for(const w of waiters.values()){clearTimeout(w.timer);w.cleanup?.();w.reject(error('HOST_UNAVAILABLE'));}waiters.clear();},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import {handleMemoryHost,hasMemoryHost} from './memory-channel.js';
|
|
2
|
+
import {randomUUID} from 'node:crypto';import path from 'node:path';import {readFile,stat} from 'node:fs/promises';import {safePath} from '../kb-core/src/workbench-state.js';import {hash} from './io.js';
|
|
3
|
+
import {INBOX_FLOW} from '../kb-core/src/inbox-flow.js';
|
|
4
|
+
import {relayDshStream,chatHistoryFrame} from './dsh-stream-relay.js';
|
|
5
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
6
|
+
|
|
7
|
+
// Adapted to the installed DSH 0.2.1-rc.5 SessionController schemas. The Host
|
|
8
|
+
// owns sessions, model credentials and streaming; no conversation DB is copied.
|
|
9
|
+
export function createDshHostPort({ctx,workspace,libraryRoot,send,ownsSession=()=>true,onSessionCreated=async()=>{}}){
|
|
10
|
+
const controller=()=>ctx.get('sessionController'),follows=new Map(),snapshots=new Map(),created=new Set(),canceled=new Set();let modelCache,modelExpires=0;
|
|
11
|
+
const signal=()=>AbortSignal.timeout(15000);
|
|
12
|
+
function assertReady(){const c=controller();if(!c?.create||!c?.prompt||!c?.follow||!c?.modelCatalog)throw Error('当前 DSH 未提供所需会话接口');return c;}
|
|
13
|
+
function visibleIds(){const registry=ctx.get('workspaceRegistry'),registered=registry?.list()?.find(w=>w.id===workspace.workspaceId),archived=new Set(registry?.archivedSessionIds??[]);return new Set((registered?.sessionIds??[]).filter(id=>!archived.has(id)&&ownsSession(id)));}
|
|
14
|
+
function allowed(id){if(!visibleIds().has(id))throw Object.assign(Error('会话已删除、归档或不属于知识库工作区'),{code:'FORBIDDEN'});}
|
|
15
|
+
function withTurnState(sessionId,frame){
|
|
16
|
+
const agent=ctx.get('agents')?.get(sessionId),boundary=agent&&ctx.get('sessionProjections')?.stateOf(agent.session,'turnBoundary');
|
|
17
|
+
return boundary?{...frame,turnState:{active:boundary.openTurnStartSeq!==null,asOfSeq:agent.session.seq-1}}:frame;
|
|
18
|
+
}
|
|
19
|
+
async function snapshot(sessionId,limit=100){
|
|
20
|
+
const c=assertReady(),abort=new AbortController(),timer=setTimeout(()=>abort.abort(),15000),iterator=c.follow({address:{kind:'session',sessionId},assistantStream:true,maxMessages:limit},abort.signal)[Symbol.asyncIterator]();
|
|
21
|
+
try{for(let i=0;i<12;i++){const next=await iterator.next();if(next.done)break;if(next.value.type==='snapshot'){const frame=chatHistoryFrame(withTurnState(sessionId,next.value));snapshots.set(sessionId,frame);return frame;}}throw Error('未收到 DSH 会话快照');}
|
|
22
|
+
finally{clearTimeout(timer);abort.abort();void iterator.return?.().catch(()=>{});}
|
|
23
|
+
}
|
|
24
|
+
async function create(requestId,preset='knowledge'){const result=await assertReady().create({workspaceId:workspace.workspaceId,agentPreset:preset,...(requestId?{sessionId:requestId}:{})});await onSessionCreated(result.sessionId);created.add(result.sessionId);return result;}
|
|
25
|
+
async function select(sessionId,execution){if(execution?.provider&&execution?.model)return controller().selectModel({sessionId,provider:execution.provider,model:execution.model,...(execution.reasoningEffort?{reasoningEffort:execution.reasoningEffort}:{})});}
|
|
26
|
+
async function prompt(sessionId,text,requestId,references=[]){
|
|
27
|
+
const content=[{type:'text',text}];let size=0;
|
|
28
|
+
for(const ref of references){
|
|
29
|
+
if(!libraryRoot)throw Error('附件来源未绑定');const file=await safePath(libraryRoot,ref.path),before=await stat(file,{bigint:true}),revision=s=>'fs:'+hash([String(s.dev),String(s.ino),String(s.size),String(s.mtimeNs),String(s.ctimeNs)]);
|
|
30
|
+
if(revision(before)!==ref.revision)throw Object.assign(Error('附件已更新,请重新选择'),{code:'CONFLICT'});size+=Number(before.size);if(size>16*1024*1024)throw Error('附件总大小超过 16MB');
|
|
31
|
+
const data=await readFile(file),after=await stat(file,{bigint:true});if(revision(after)!==ref.revision)throw Object.assign(Error('附件读取期间已更新'),{code:'CONFLICT'});
|
|
32
|
+
const uploads=ctx.get('fileUploads');if(!uploads?.upload)throw Error('当前 DSH 未启用文件附件');const {agent,error}=await controller().resolveAgent(sessionId);if(error)throw error;
|
|
33
|
+
const receipt=await uploads.upload(agent,{name:path.basename(file),data:data.toString('base64')},signal());content.push({type:'file',receiptId:receipt.receiptId});
|
|
34
|
+
}
|
|
35
|
+
return controller().prompt({sessionId,requestId:requestId??randomUUID(),mode:'queue',content,clientTimeZone:'Asia/Shanghai'},signal());
|
|
36
|
+
}
|
|
37
|
+
const interactions=new Map(),disposers=[];
|
|
38
|
+
function handles(agent){if(!agent||!follows.has(agent.id))return false;try{allowed(agent.id);return ctx.get('agents')?.get(agent.id)===agent;}catch{return false;}}
|
|
39
|
+
function interaction(kind,request,next){
|
|
40
|
+
if(!handles(request.agent))return next();const id=randomUUID(),revision=randomUUID(),sessionId=request.agent.id;
|
|
41
|
+
return new Promise((resolve,reject)=>{
|
|
42
|
+
let claim,settled=false;
|
|
43
|
+
const finish=(answer,failed=false)=>{if(settled)return;settled=true;clearTimeout(timer);void claim?.return?.().catch(()=>{});request.signal?.removeEventListener('abort',abort);interactions.delete(id);void send(sessionId,{type:'interaction-closed',id}).catch(()=>{});failed?reject(answer):resolve(answer);};
|
|
44
|
+
const abort=()=>finish(kind==='approval'?'cancelled':Object.assign(Error('提问已取消'),{code:'ASK_ABORTED'}),kind!=='approval');
|
|
45
|
+
const timer=setTimeout(abort,300000);timer.unref?.();
|
|
46
|
+
if(kind==='questions'&&request.wait?.callId){const questions=request.agent.ctx.get('userQuestions')??ctx.get('userQuestions');claim=questions?.attachWait(request.agent,request.wait.callId,request.signal)[Symbol.asyncIterator]();void claim?.next().catch(()=>{});}
|
|
47
|
+
const data={id,revision,kind,sessionId,...(kind==='approval'?{toolName:request.toolName,reason:request.reason}:{questions:request.questions,callId:request.wait?.callId})};
|
|
48
|
+
interactions.set(id,{data,finish});request.signal?.addEventListener('abort',abort,{once:true});if(request.signal?.aborted){abort();return;}void send(sessionId,{type:'interaction',...data}).catch(abort);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if(ctx.on){disposers.push(ctx.on('approval/request',(req,next)=>interaction('approval',req,next)));disposers.push(ctx.on('user-questions/request',(req,next)=>interaction('questions',req,next)));}
|
|
52
|
+
|
|
53
|
+
const boundAgents=new WeakSet();
|
|
54
|
+
async function bindAgent(sessionId){const {agent,error}=await assertReady().resolveAgent(sessionId);if(error)throw error;if(!boundAgents.has(agent)){boundAgents.add(agent);disposers.push(agent.ctx.on('approval/request',(req,next)=>interaction('approval',req,next),true));disposers.push(agent.ctx.on('user-questions/request',(req,next)=>interaction('questions',req,next),true));}return agent;}
|
|
55
|
+
async function follow(sessionId){
|
|
56
|
+
await bindAgent(sessionId);
|
|
57
|
+
if(follows.has(sessionId))return {following:true};if(follows.size>=8){const [id,c]=follows.entries().next().value;c.abort();follows.delete(id);}
|
|
58
|
+
const abort=new AbortController();follows.set(sessionId,abort);
|
|
59
|
+
void (async()=>{let attempt=0;try{while(!abort.signal.aborted){const streamAbort=new AbortController(),stop=()=>streamAbort.abort();abort.signal.addEventListener('abort',stop,{once:true});try{
|
|
60
|
+
allowed(sessionId);const native=assertReady().follow({address:{kind:'session',sessionId},assistantStream:true,maxMessages:30},streamAbort.signal);
|
|
61
|
+
const source=(async function*(){for await(const received of native){const frame=received.type==='snapshot'?chatHistoryFrame(withTurnState(sessionId,received)):received.type==='event'?chatHistoryFrame({records:[received]}).records[0]:received;if(frame.type==='snapshot'){snapshots.set(sessionId,frame);attempt=0;}yield frame;}})();
|
|
62
|
+
await relayDshStream({source,send:frame=>send(sessionId,frame),abort:stop,signal:streamAbort.signal});if(abort.signal.aborted)break;
|
|
63
|
+
}catch(e){if(abort.signal.aborted)break;console.warn('[kb-dsh-stream]',String(e.code??e.name??'STREAM_INTERRUPTED').slice(0,80));if(['FORBIDDEN','NOT_FOUND','FRAME_TOO_LARGE'].includes(e.code)){await send(sessionId,{type:'resync-required',message:'该会话已不可用,请重新选择聊天。',terminal:true}).catch(()=>{});break;}}
|
|
64
|
+
finally{abort.signal.removeEventListener('abort',stop);streamAbort.abort();}
|
|
65
|
+
await send(sessionId,{type:'resync-required',message:'正在自动恢复会话连接…'}).catch(()=>{});await delay(Math.min(5000,250*2**Math.min(attempt++,5)),undefined,{signal:abort.signal});
|
|
66
|
+
}}catch(e){if(!abort.signal.aborted)console.warn('[kb-dsh-stream]',String(e.code??e.name));}finally{if(follows.get(sessionId)===abort)follows.delete(sessionId);}})();return {following:true};
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
ready(){try{assertReady();return true}catch{return false}},
|
|
70
|
+
async models(){if(modelCache&&Date.now()<modelExpires)return modelCache;const result=await assertReady().modelCatalog();modelCache=result;modelExpires=Date.now()+10000;return result;},
|
|
71
|
+
async inbox(task){
|
|
72
|
+
const catalog=await this.models(),routes=catalog.groups.flatMap(g=>g.models.filter(m=>m.reasoning?.efforts?.some(e=>e.id==='high')).map(m=>({provider:g.id,model:m.id,reasoningEffort:'high'})));
|
|
73
|
+
const execution=task.execution??routes[0];if(!execution||!routes.some(r=>r.provider===execution.provider&&r.model===execution.model))throw Error('整理收件箱需要支持 High 的可用模型');
|
|
74
|
+
let sessionId='',sendAttempted=false;try{sessionId=(await create(task.id)).sessionId;await select(sessionId,execution);sendAttempted=true;await prompt(sessionId,INBOX_FLOW.prompt,task.id);return sessionId;}catch(e){e.sessionId=sessionId;e.sendAttempted=sendAttempted;throw e;}
|
|
75
|
+
},
|
|
76
|
+
async handle(method,a={},taskId){
|
|
77
|
+
if(method.startsWith('memory.'))return handleMemoryHost(()=>ctx.get('memoryStore'),method,a,taskId);
|
|
78
|
+
const c=assertReady();
|
|
79
|
+
if(method==='models'||method==='dsh.modelCatalog')return this.models();
|
|
80
|
+
if(method==='workspace')return workspace;
|
|
81
|
+
if(method==='dsh.presets'){const registry=ctx.get('agentPresets');return {presets:registry?await registry.compositionInventory():[]};}
|
|
82
|
+
|
|
83
|
+
if(method==='dsh.sessions'){const rows=(await c.list({},signal())).items,ids=visibleIds();return {items:rows.filter(r=>ids.has(r.sessionId))};}
|
|
84
|
+
if(method==='dsh.createSession')return create(taskId,a.preset);
|
|
85
|
+
if(method==='flow.cancel'){canceled.add(a.sessionId);if(canceled.size>200)canceled.delete(canceled.values().next().value);if(created.has(a.sessionId))await c.cancel({sessionId:a.sessionId});return {cancelled:true};}
|
|
86
|
+
if(a.sessionId)allowed(a.sessionId);
|
|
87
|
+
if(method==='dsh.capabilities'){
|
|
88
|
+
const catalog=ctx.get('sessionSkillCatalog'),presets=ctx.get('agentPresets');let skills=[],skillError='';try{skills=(await catalog?.list({sessionId:a.sessionId},signal()))?.skills??[];}catch(e){skillError=e.message;}
|
|
89
|
+
const composition=await presets?.compositionInventory()??[];
|
|
90
|
+
return {skills,skillError,presets:composition,attachments:!!ctx.get('fileUploads'),interactions:true};
|
|
91
|
+
}
|
|
92
|
+
if(method==='dsh.selectPreset'){const {agent,error}=await c.resolveAgent(a.sessionId);if(error)throw error;return {preset:await ctx.get('agentPresets').select(agent,a.preset)};}
|
|
93
|
+
if(method==='dsh.interactions')return {items:[...interactions.values()].filter(x=>x.data.sessionId===a.sessionId).map(x=>x.data)};
|
|
94
|
+
if(method==='dsh.answerInteraction'){
|
|
95
|
+
const row=interactions.get(a.eventId);if(!row||row.data.sessionId!==a.sessionId||row.data.revision!==a.interactionRevision)throw Object.assign(Error('交互已过期,请刷新'),{code:'INTERACTION_EXPIRED'});
|
|
96
|
+
if(row.data.kind==='approval'){
|
|
97
|
+
if(!['allowed-once','rejected'].includes(a.answer?.outcome))throw Error('审批结果无效');row.finish(a.answer.outcome);
|
|
98
|
+
}else{
|
|
99
|
+
const answers=a.answer?.answers,questions=row.data.questions;if(!Array.isArray(answers)||answers.length!==questions.length||new Set(answers.map(x=>x.id)).size!==questions.length)throw Error('请回答每个问题');
|
|
100
|
+
for(const q of questions){const ans=answers.find(x=>x.id===q.id);if(!ans||!Array.isArray(ans.selected)||ans.selected.some(x=>!(q.options??[]).some(o=>o.label===x))||ans.custom!=null&&typeof ans.custom!=='string')throw Error('问题答案无效');if(!q.multiSelect&&ans.selected.length>1)throw Error('此问题只允许单选');}row.finish({answers});
|
|
101
|
+
}return {accepted:true};
|
|
102
|
+
}
|
|
103
|
+
if(method==='dsh.selectModel')return select(a.sessionId,a);
|
|
104
|
+
if(method==='dsh.prompt')return prompt(a.sessionId,a.text,taskId,a.references);
|
|
105
|
+
if(method==='dsh.cancel')return c.cancel({sessionId:a.sessionId});
|
|
106
|
+
if(method==='dsh.follow')return follow(a.sessionId);
|
|
107
|
+
if(method==='dsh.history'){
|
|
108
|
+
const current=a.beforeSeq!=null&&snapshots.has(a.sessionId)?snapshots.get(a.sessionId):await snapshot(a.sessionId,a.limit),cut=a.throughSeq??current.cursor;
|
|
109
|
+
if(a.beforeSeq!=null)return {...chatHistoryFrame(await c.page({address:{kind:'session',sessionId:a.sessionId},throughSeq:cut,beforeSeq:a.beforeSeq,maxMessages:a.limit},signal())),cursor:cut};
|
|
110
|
+
return {records:current.records,hasMore:current.hasMore,cursor:cut,projections:current.projections,turnState:current.turnState,assistantStream:current.assistantStream};
|
|
111
|
+
}
|
|
112
|
+
if(method==='file.open')return c.openWorkspacePath(a,signal());
|
|
113
|
+
if(method==='flow.delegate'){
|
|
114
|
+
const checkCanceled=()=>{if(canceled.has(taskId))throw Object.assign(Error('流程已取消'),{code:'CANCELED'});};checkCanceled();const result=await create(taskId);checkCanceled();await select(result.sessionId,a.execution);checkCanceled();await prompt(result.sessionId,a.task,taskId);
|
|
115
|
+
const resolved=await c.resolveAgent(result.sessionId);if(resolved.error)throw resolved.error;await resolved.agent.whenIdle();checkCanceled();const s=await snapshot(result.sessionId,100);
|
|
116
|
+
const answers=s.records.filter(r=>r.event?.type==='assistant/message').map(r=>textParts(r.event.data?.message?.content));return {answer:answers.join('\n'),target:'knowledge',preset:'knowledge',subagentId:result.sessionId,kind:a.kind};
|
|
117
|
+
}
|
|
118
|
+
throw Object.assign(Error('DSH 不支持此接口'),{code:'CAPABILITY_UNSUPPORTED'});
|
|
119
|
+
},
|
|
120
|
+
dispose(){for(const dispose of disposers)dispose?.();for(const row of interactions.values())row.finish(row.data.kind==='approval'?'cancelled':Object.assign(Error('会话连接已关闭'),{code:'ASK_ABORTED'}),row.data.kind!=='approval');interactions.clear();for(const c of follows.values())c.abort();follows.clear();snapshots.clear();canceled.clear();},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function textParts(value){return typeof value==='string'?value:Array.isArray(value)?value.filter(p=>p.type==='text').map(p=>p.text??'').join(''):'';}
|
|
124
|
+
|
|
125
|
+
export function startDshHostBridge({client,ctx,workspace,libraryRoot,label,ensureWorkspace,ownsSession,onSessionCreated,onError=()=>{}}){
|
|
126
|
+
let memoryRevision,memoryAvailable,memoryApi,unsubscribeMemory,pendingMemoryRevision;
|
|
127
|
+
const hostInstanceId=randomUUID(),jobs=new Set(),inboxId='host-'+hostInstanceId;let disposed=false,timer,pumping=false,inboxChecking=false,nextInbox=0,nextRegister=0;
|
|
128
|
+
const call=async(method,args)=>{try{return await client.call(method,args);}catch(e){if(e.code!=='POLICY_CHANGED')throw e;return client.call(method,args);}};
|
|
129
|
+
const port=createDshHostPort({ctx,workspace,libraryRoot,ownsSession,onSessionCreated,send:(sessionId,data)=>call('host.bridge',{action:'event',hostInstanceId,sessionId,data})});
|
|
130
|
+
const result=(task,value,failure)=>{
|
|
131
|
+
if(!failure&&Buffer.byteLength(JSON.stringify(value)??'null')>700000)failure=Object.assign(Error('会话内容超过单次同步上限,请分批加载历史。'),{code:'FRAME_TOO_LARGE'});
|
|
132
|
+
return call('host.bridge',{action:'result',hostInstanceId,taskId:task.id,token:task.token,...(failure?{error:{code:failure.code??'HOST_UNAVAILABLE',message:'DSH 操作未完成:'+String(failure.message).slice(0,500)}}:{result:value})});
|
|
133
|
+
};
|
|
134
|
+
async function dispatch(task){
|
|
135
|
+
let timer;
|
|
136
|
+
try{return await Promise.race([port.handle(task.method,task.args,task.id),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Object.assign(Error('宿主操作超时,请重新连接;该操作未自动重发。'),{code:'HOST_TIMEOUT'})),18000);timer.unref?.();})]);}
|
|
137
|
+
finally{clearTimeout(timer);}
|
|
138
|
+
}
|
|
139
|
+
async function pump(){
|
|
140
|
+
if(disposed||pumping)return;pumping=true;
|
|
141
|
+
try{
|
|
142
|
+
if(!port.ready())return;
|
|
143
|
+
if(ensureWorkspace&&!ctx.get('workspaceRegistry')?.list()?.some(w=>w.id===workspace.workspaceId)){
|
|
144
|
+
// Refresh the registry identity before admitting another task. Never replay
|
|
145
|
+
// an already dispatched prompt when the previous workspace disappeared.
|
|
146
|
+
await call('host.bridge',{action:'leave',hostInstanceId}).catch(()=>{});
|
|
147
|
+
const refreshed=await ensureWorkspace();Object.assign(workspace,refreshed);nextRegister=0;
|
|
148
|
+
}
|
|
149
|
+
const memory=ctx.get('memoryStore');
|
|
150
|
+
const available=hasMemoryHost(memory);
|
|
151
|
+
if(available!==memoryAvailable){memoryAvailable=available;nextRegister=0;memoryRevision=undefined;}
|
|
152
|
+
const api=memory?.memoryApi?.version===1?memory.memoryApi:undefined;
|
|
153
|
+
if(api!==memoryApi){
|
|
154
|
+
unsubscribeMemory?.();pendingMemoryRevision=undefined;memoryApi=api;
|
|
155
|
+
unsubscribeMemory=api?.subscribe(({revision})=>{pendingMemoryRevision=revision;});
|
|
156
|
+
}
|
|
157
|
+
if(Date.now()>=nextRegister){await call('host.bridge',{action:'register',hostInstanceId,label,workspaceId:workspace.workspaceId,workspacePath:workspace.workspacePath,capabilities:[...(available?['memory-v1']:[]),'sessions','history','prompt','cancel','models','stream','reasoning','presets','skills','attachments','interactions','knowledge-flows']});nextRegister=Date.now()+2000;}
|
|
158
|
+
const revision=api?pendingMemoryRevision:memory?.revision;
|
|
159
|
+
if(revision&&revision!==memoryRevision){await call('host.bridge',{action:'memory-changed',hostInstanceId,revision});memoryRevision=revision;}
|
|
160
|
+
while(jobs.size<4){const {task}=await call('host.bridge',{action:'poll',hostInstanceId});if(!task)break;jobs.add(task.id);void dispatch(task).then(v=>result(task,v),e=>result(task,null,e)).catch(onError).finally(()=>jobs.delete(task.id));}
|
|
161
|
+
if(!inboxChecking&&Date.now()>nextInbox){inboxChecking=true;nextInbox=Date.now()+5000;void(async()=>{
|
|
162
|
+
const catalog=await port.models(),execution=catalog.groups.flatMap(g=>g.models.filter(m=>m.reasoning?.efforts?.some(e=>e.id==='high')).map(m=>({provider:g.id,model:m.id,reasoningEffort:'high'})))[0];
|
|
163
|
+
if(execution){await call('inbox.organizeBridge',{action:'heartbeat',clientId:inboxId,execution});const r=await call('inbox.organizeBridge',{action:'claim',clientId:inboxId});if(r.task){const t=r.task;void port.inbox(t).then(sessionId=>call('inbox.organizeBridge',{action:'report',clientId:inboxId,taskId:t.id,token:t.token,state:'launched',sessionId,message:'已在 DSH 发起整理会话,归档进度以共享清单和会话为准。'})).catch(e=>call('inbox.organizeBridge',{action:'report',clientId:inboxId,taskId:t.id,token:t.token,state:e.sendAttempted?'unknown':'failed',sessionId:e.sessionId??'',message:'整理会话未确认:'+String(e.message).slice(0,500)})).catch(onError);}}
|
|
164
|
+
})().catch(onError).finally(()=>{inboxChecking=false;});}
|
|
165
|
+
}catch(e){nextRegister=0;onError(e)}finally{pumping=false;if(!disposed)timer=setTimeout(pump,200);}
|
|
166
|
+
}
|
|
167
|
+
void pump();return {hostInstanceId,port,dispose(){disposed=true;clearTimeout(timer);unsubscribeMemory?.();port.dispose();void call('host.bridge',{action:'leave',hostInstanceId}).catch(()=>{});void call('inbox.organizeBridge',{action:'leave',clientId:inboxId}).catch(()=>{});}};
|
|
168
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Drain the native stream independently of pipe latency. Frames stay ordered;
|
|
2
|
+
// adjacent token frames are batched, and the queue has a strict byte budget.
|
|
3
|
+
export async function relayDshStream({source,send,abort,signal,maxBytes=1_000_000}){
|
|
4
|
+
const queue=[];let bytes=0,reading=true,wake,readError;
|
|
5
|
+
const notify=()=>{wake?.();wake=null;};
|
|
6
|
+
const reader=(async()=>{try{for await(const frame of source){signal.throwIfAborted();const size=Buffer.byteLength(JSON.stringify(frame));if(bytes+size>maxBytes)throw Object.assign(Error('native stream relay backlog'),{code:'STREAM_BACKLOG'});
|
|
7
|
+
const tail=queue.at(-1);if(frame.type==='assistant-stream'&&tail?.value.type==='assistant-stream-batch'&&tail.value.frames.length<64&&tail.size+size<180000){tail.value.frames.push(frame.frame);tail.size+=size;}else queue.push({value:frame.type==='assistant-stream'?{type:'assistant-stream-batch',frames:[frame.frame]}:frame,size});bytes+=size;notify();
|
|
8
|
+
}}catch(e){readError=e;}finally{reading=false;notify();}})();
|
|
9
|
+
try{while(reading||queue.length){if(!queue.length){await new Promise(r=>{wake=r;});continue;}await new Promise(r=>setTimeout(r,16));const item=queue.shift();bytes-=item.size;await send(item.value);}await reader;if(readError)throw readError;}
|
|
10
|
+
catch(e){abort();await reader.catch(()=>{});throw e;}finally{queue.length=0;}
|
|
11
|
+
}
|
|
12
|
+
export function boundedSnapshot(frame,limit=420000){
|
|
13
|
+
if(frame.type!=='snapshot'||Buffer.byteLength(JSON.stringify(frame))<=limit)return frame;
|
|
14
|
+
const records=[...(frame.records??[])];let result={...frame,records,hasMore:true};
|
|
15
|
+
while(records.length&&Buffer.byteLength(JSON.stringify(result))>limit)records.shift();
|
|
16
|
+
if(Buffer.byteLength(JSON.stringify(result))>limit)result={...result,assistantStream:undefined,contentDeferred:true};
|
|
17
|
+
if(Buffer.byteLength(JSON.stringify(result))>limit)throw Object.assign(Error('snapshot metadata exceeds bridge limit'),{code:'FRAME_TOO_LARGE'});
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Keep sequence-bearing records for pagination, but never send raw tool payloads
|
|
22
|
+
// to the chat surface. This also keeps large tool output below the pipe budget.
|
|
23
|
+
export function chatHistoryFrame(frame){
|
|
24
|
+
const record=r=>{const e=r.event??r;if(!e.type)return r;
|
|
25
|
+
if(e.type.startsWith('tool/'))return {...r,event:{type:e.type,seq:e.seq,data:{}}};
|
|
26
|
+
const m=e.type==='assistant/message'?e.data?.message:e.type==='user/message'?e.data:null;
|
|
27
|
+
if(!m)return r;
|
|
28
|
+
const content=Array.isArray(m.content)?m.content.map(p=>p.type==='tool-call'?{type:p.type,name:p.name??p.toolName??'工具'}:p.type==='tool-result'?{type:p.type}:p):m.content;
|
|
29
|
+
return {...r,event:{...e,data:e.type==='assistant/message'?{...e.data,message:{...m,content}}:{...m,content}}};
|
|
30
|
+
};
|
|
31
|
+
return boundedSnapshot({...frame,type:'snapshot',records:(frame.records??[]).map(record)});
|
|
32
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {createParsingService,createImportService,createFlowEngine} from '../kb-core/index.js';
|
|
3
|
+
import {error} from './io.js';
|
|
4
|
+
|
|
5
|
+
export function createEngines({kernel,stateDir,root,resourceRoot,online,invoke,notify,getWorkspace}){
|
|
6
|
+
const parsing=createParsingService({stateDir,getCore:()=>kernel.core,getBinding:()=>kernel.core.status(),resourceRoot,onEvent:notify});
|
|
7
|
+
const imports=createImportService({stateDir,getBaseConfig:()=>kernel.core.getConfig(),getCurrentCore:()=>kernel.core,getParsingService:()=>parsing,
|
|
8
|
+
coreFactory:options=>{if(options.kbPath&&path.resolve(options.kbPath)!==path.resolve(root))throw error('FORBIDDEN','共库导入不能改变目标库');return kernel.core;},commitBinding:async()=>({ok:true,unchanged:true})});
|
|
9
|
+
const flows=createFlowEngine({stateDir,core:kernel.core,targetId:'knowledge',delegate:async req=>{if(!online())throw error('HOST_UNAVAILABLE','DSH 离线,不能执行需要模型的流程');return invoke('flow.delegate',{task:req.task,kind:req.kind,context:req.context,execution:req.execution,label:req.label},{signal:req.signal});},parseStep:async req=>{if(!online())throw error('HOST_UNAVAILABLE','DSH 离线,不能执行解析流程');return parsing.submit(req,{requestedBy:{via:'flow'}});}});
|
|
10
|
+
async function dispatch(a,{admin=false,session='host-ui',knowledge=false,authorizedSource}={}){
|
|
11
|
+
const op=a.op;
|
|
12
|
+
if(op.startsWith('flows.')){
|
|
13
|
+
const action=op.slice(6)==='set-enabled'?'enable':op.slice(6);if(['run','prepare-conversation'].includes(action)&&!online())throw error('HOST_UNAVAILABLE','DSH 离线,模型流程暂不可用');
|
|
14
|
+
if(action==='list')return flows.list({includeArchived:a.includeArchived});if(action==='get')return flows.get(a.id);if(action==='resolve')return flows.resolve(a.text);if(action==='save')return flows.save(a);if(action==='execution')return flows.setExecution(a);if(action==='enable')return flows.setEnabled(a.id,a.enabled);if(action==='archive')return flows.archive(a.id,a.restored);if(action==='delete')return flows.archive(a.id);if(action==='run'){const r=await flows.start(a);if(r.run){r.run={...r.run};delete r.run.promise;}return r;}if(action==='cancel')return flows.cancel(a.runId??a.id);if(action==='runs')return flows.runs({flowId:a.flowId??a.id,runId:a.runId,limit:a.limit});if(action==='prepare-conversation'){const r=await flows.prepareConversation(a);return r.ok?{...r,...getWorkspace()}:r;}if(action==='models')return online()?invoke('models',{}):{ok:false,groups:[],reason:'HOST_UNAVAILABLE'};
|
|
15
|
+
}
|
|
16
|
+
if(op.startsWith('parse.')){
|
|
17
|
+
const action=op.slice(6),manage={viaAdmin:admin},requestedBy={via:admin?'ui':'tool',session},owns=j=>admin||knowledge&&!j.source?.external||j.requestedBy?.session===session;
|
|
18
|
+
const filter=async jobs=>kernel.workbench.filterJobs(jobs.filter(owns));
|
|
19
|
+
if(a.jobId&&!admin){const j=await parsing.readJob(a.jobId);if(!j||!owns(j))throw error('FORBIDDEN','解析任务不属于当前会话');}
|
|
20
|
+
if(['submit','retry','test-parse'].includes(action)&&!online())throw error('HOST_UNAVAILABLE','DSH 离线,模型解析暂不可用');
|
|
21
|
+
if(action==='providers')return parsing.providersPublic();if(action==='provider.save')return parsing.saveProvider(a.provider,{...manage,credentialInput:a.credentials,clearCredential:a.clearCredential===true});if(action==='provider.delete')return parsing.deleteProvider(a.providerId,manage);if(action==='default')return parsing.setDefaults({kind:a.kind,id:a.providerId},manage);if(action==='policy')return parsing.setPolicy(a.externalPolicy,manage);
|
|
22
|
+
if(action==='scan.start')return parsing.scanStart({mode:a.mode,directory:a.directory},manage);if(action==='scan.status')return parsing.scanStatus(a.scanId,manage);if(action==='scan.cancel')return parsing.scanCancel(a.scanId,manage);if(action==='scan.add')return parsing.scanAdd(a.scanId,a.resultId,manage);
|
|
23
|
+
if(action==='test-connection')return parsing.testConnection(a.providerId);if(action==='test-parse')return parsing.testParse(a,{requestedBy,authorizedSource});if(action==='submit')return parsing.submit(a,{requestedBy,authorizedSource});if(action==='jobs')return parsing.listJobs({...a,filter});if(action==='requests')return parsing.listRequests({...a,filter:async rows=>rows.filter(owns)});if(action==='job')return {ok:true,job:await parsing.publicJob(await parsing.readJob(a.jobId))};if(action==='result')return parsing.readResult(a.jobId,a);if(action==='cancel')return parsing.cancel(a.jobId,{by:requestedBy});if(action==='retry')return parsing.retry(a.jobId,{reason:'共享界面重试'});if(action==='land')return parsing.land(a.jobId,a);
|
|
24
|
+
}
|
|
25
|
+
if(op.startsWith('import.')){
|
|
26
|
+
const action=op.slice(7);if(action==='status')return imports.status(a);if(action==='waiting')return imports.waiting(a);if(action==='plan'){if(a.mode!=='copy'&&path.resolve(a.source??'')!==path.resolve(root))throw error('BINDING_CHANGED','请使用复制导入,原位置挂载需要先连接目标库');return imports.plan({...a,current:await kernel.core.status()});}if(action==='start'||action==='run')return imports.start(a);if(action==='cancel')return imports.cancel(a);if(action==='parse'){if(!online())throw error('HOST_UNAVAILABLE');return imports.parseItem(a,{requestedBy:{via:admin?'ui':'tool',session}});}
|
|
27
|
+
}
|
|
28
|
+
throw error('BAD_REQUEST','未知引擎接口');
|
|
29
|
+
}
|
|
30
|
+
const gatedParsing=new Proxy(parsing,{get(target,key){const value=Reflect.get(target,key);if(['submit','testParse','retry'].includes(key))return (...args)=>{if(!online())throw error('HOST_UNAVAILABLE','DSH 离线,模型解析暂不可用');return value.apply(target,args)};return typeof value==='function'?value.bind(target):value;}});
|
|
31
|
+
return {async upgradeBusy(){const [running,queued,imported]=await Promise.all([parsing.listJobs({status:'running',limit:1}),parsing.listJobs({status:'queued',limit:1}),imports.status()]);return !!(running.warning||queued.warning||running.total>0||queued.total>0||imported.imports?.some(x=>x.running)||flows.activeRuns().length);},parsing:gatedParsing,imports,flows,dispatch,async recover(){await parsing.recover();},dispose(){flows.dispose?.();parsing.dispose?.();}};
|
|
32
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import path from 'node:path';import {readdir,readFile} from 'node:fs/promises';
|
|
2
|
+
const table=Array.from({length:256},(_,n)=>{for(let i=0;i<8;i++)n=n&1?0xedb88320^(n>>>1):n>>>1;return n>>>0});
|
|
3
|
+
const crc=bytes=>{let n=0xffffffff;for(const byte of bytes)n=table[(n^byte)&255]^(n>>>8);return (n^0xffffffff)>>>0};
|
|
4
|
+
export async function extensionArchive(root){
|
|
5
|
+
const entries=[];async function walk(folder,prefix=''){for(const e of await readdir(folder,{withFileTypes:true})){if(e.isSymbolicLink())throw Error('扩展资源不能包含链接');if(e.isDirectory())await walk(path.join(folder,e.name),prefix+e.name+'/');else if(e.isFile())entries.push({name:prefix+e.name,data:await readFile(path.join(folder,e.name))});}}await walk(root);
|
|
6
|
+
const local=[],central=[];let offset=0;for(const item of entries){const name=Buffer.from(item.name),sum=crc(item.data),h=Buffer.alloc(30);h.writeUInt32LE(0x04034b50);h.writeUInt16LE(20,4);h.writeUInt16LE(0x800,6);h.writeUInt32LE(sum,14);h.writeUInt32LE(item.data.length,18);h.writeUInt32LE(item.data.length,22);h.writeUInt16LE(name.length,26);local.push(h,name,item.data);const c=Buffer.alloc(46);c.writeUInt32LE(0x02014b50);c.writeUInt16LE(20,4);c.writeUInt16LE(20,6);c.writeUInt16LE(0x800,8);c.writeUInt32LE(sum,16);c.writeUInt32LE(item.data.length,20);c.writeUInt32LE(item.data.length,24);c.writeUInt16LE(name.length,28);c.writeUInt32LE(offset,42);central.push(c,name);offset+=h.length+name.length+item.data.length;}
|
|
7
|
+
const directory=Buffer.concat(central),end=Buffer.alloc(22);end.writeUInt32LE(0x06054b50);end.writeUInt16LE(entries.length,8);end.writeUInt16LE(entries.length,10);end.writeUInt32LE(directory.length,12);end.writeUInt32LE(offset,16);return {ok:true,filename:'knowledge-base-browser-extension.zip',base64:Buffer.concat([...local,directory,end]).toString('base64')};
|
|
8
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
|
|
3
|
+
export const FIRST_LIBRARY_RESTART = '共享知识库已建立,当前插件需要重新连接。请完全退出并重新打开 DSH;无需再次建库或删除文件。'
|
|
4
|
+
|
|
5
|
+
// Keep the completed receipt for this embedded Host lifetime. Repeated requests
|
|
6
|
+
// must not fall back into the now-forbidden embedded writer after activation.
|
|
7
|
+
export function createFirstLibraryHandoff(setup) {
|
|
8
|
+
let receipt, pending
|
|
9
|
+
return {
|
|
10
|
+
get receipt() { return receipt },
|
|
11
|
+
async select(target) {
|
|
12
|
+
if (receipt) {
|
|
13
|
+
if (path.resolve(target) !== path.resolve(receipt.kbPath)) throw Object.assign(new Error(FIRST_LIBRARY_RESTART), {code:'SERVICE_RESTART_REQUIRED'})
|
|
14
|
+
return receipt
|
|
15
|
+
}
|
|
16
|
+
if (pending) {
|
|
17
|
+
await pending
|
|
18
|
+
return this.select(target)
|
|
19
|
+
}
|
|
20
|
+
pending = Promise.resolve().then(() => setup(target))
|
|
21
|
+
try {
|
|
22
|
+
const result = await pending
|
|
23
|
+
if (result?.restartRequired) receipt = {...result, note:FIRST_LIBRARY_RESTART}
|
|
24
|
+
return receipt ?? result
|
|
25
|
+
} finally { pending = null }
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Keep the API route present while the service adapter is being prepared.
|
|
2
|
+
export function createHandoffApi() {
|
|
3
|
+
let delegate = null, phase = 'starting', code
|
|
4
|
+
const status = () => ({ phase, failed: phase === 'failed', ...(code ? { code } : {}) })
|
|
5
|
+
return {
|
|
6
|
+
status,
|
|
7
|
+
fail(error) { phase = 'failed'; code = error.code || 'UPGRADE_HANDOFF_FAILED' },
|
|
8
|
+
attach(handler) {
|
|
9
|
+
delegate = handler; phase = 'ready'; code = undefined
|
|
10
|
+
return () => { if (delegate === handler) { delegate = null; phase = 'starting' } }
|
|
11
|
+
},
|
|
12
|
+
handle(req, res) {
|
|
13
|
+
if (delegate) return delegate(req, res)
|
|
14
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
15
|
+
res.setHeader('cache-control', 'no-store')
|
|
16
|
+
if (!['GET', 'POST'].includes(req.method)) { res.statusCode = 405; res.end(JSON.stringify({ ok: false, error: 'method not allowed' })); return }
|
|
17
|
+
res.statusCode = 503; res.setHeader('retry-after', '1')
|
|
18
|
+
res.end(JSON.stringify({ ok: false, code: phase === 'starting' ? 'SERVICE_STARTING' : code,
|
|
19
|
+
requestNotExecuted: true, error: phase === 'starting' ? '知识库服务准备中,请稍候…' : '知识库服务准备未完成,请查看更新恢复说明' }))
|
|
20
|
+
},
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import {createHostUpdates} from './host-updates.js';
|
|
2
|
+
import {publishKnowledgeMemory} from './memory-sync.js';
|
|
3
|
+
import {normalizeToolResult} from './tool-router.js';
|
|
4
|
+
import {atomic,readJson,serialQueue} from './io.js';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import {AsyncLocalStorage} from "node:async_hooks";
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { readFile } from 'node:fs/promises'
|
|
9
|
+
import { connectService } from './client.js'
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import {createInboxHost} from './inbox-host.js'
|
|
12
|
+
import {connectRuntime,defaultServiceHome} from './runtime.js'
|
|
13
|
+
import {exportPluginVector} from './vector-profiles.js'
|
|
14
|
+
import {startDshHostBridge} from './dsh-host.js'
|
|
15
|
+
import {startDesktopHostLinks} from './desktop-host-links.js'
|
|
16
|
+
import {createParseSourceAuthority} from '../kb-core/src/parse-source-authority.js'
|
|
17
|
+
import {createFlowWorkspaceManager} from '../kb-core/src/flow-workspace.js'
|
|
18
|
+
import {registerHostAssets} from './host-assets.js'
|
|
19
|
+
// Called only by an explicitly configured Host. It never starts an embedded writer.
|
|
20
|
+
export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gatewayApply, createCitationGuard, build, getFlowWorkspace,installApi,legacyStateDir,profileDir,library,python='python' }) {
|
|
21
|
+
const definitions = JSON.parse(await readFile(new URL('./tool-definitions.json', import.meta.url),'utf8'))
|
|
22
|
+
const runtime=config.serviceConnection?null:await connectRuntime({library,home:config.shared?.home??defaultServiceHome(),python:config.shared?.python??python,kind:'dsh-adapter',preferredVersion:build.version,candidateRoot:config.shared?.candidateRoot??process.env.KB_SHARED_CANDIDATE_ROOT,required:['workspace.read','providers.get','host.bridge']})
|
|
23
|
+
const primaryClient=runtime?.client??await connectService({...config.serviceConnection,kind:'dsh-adapter'}),routing=new AsyncLocalStorage();const client=new Proxy(primaryClient,{get(target,key){const source=routing.getStore()??target,value=Reflect.get(source,key);return typeof value==='function'?value.bind(source):value}})
|
|
24
|
+
if(createCitationGuard){const guard=createCitationGuard({validate:(operation,agentId)=>{const target=desktopLinks?.clientForAgent(ctx.get('agents')?.get(agentId));if(target===null)throw Error('该会话知识库已断开');return (target??primaryClient).call('workspace.read',{operation});},log:message=>console.warn('[kb-citations] '+message)});ctx.effect(()=>ctx.on('agent/turn-stopping',guard),'kb-service: final citation check')}
|
|
25
|
+
if(legacyStateDir)try{const s=await client.call('host.tool',{name:'kb_status',input:{}}),provider=await exportPluginVector({stateDir:legacyStateDir,root:s.kbPath,kbId:s.kbId,sourceId:'profile:'+path.basename(profileDir??legacyStateDir)});if(provider)await client.call('providers.syncPlugin',provider)}catch{/* Existing shared settings remain authoritative. */}
|
|
26
|
+
const inboxHost=createInboxHost({client,getLLM:()=>ctx.get('llm'),getWorkspace:getFlowWorkspace})
|
|
27
|
+
const routeFile=path.join(legacyStateDir??profileDir??path.join(os.homedir(),'.dsh/knowledge-desktop-client'),'desktop-session-libraries.json'),sessionOwners=await readJson(routeFile,{}),saveRoute=serialQueue();
|
|
28
|
+
const primaryId=primaryClient.welcome.library.instanceId;
|
|
29
|
+
const memoryListeners=new Set();
|
|
30
|
+
const notifyMemory=event=>{if(event.event!=='memory.changed')for(const listener of memoryListeners)listener(event)};
|
|
31
|
+
const recordSession=(instanceId,id)=>saveRoute(async()=>{
|
|
32
|
+
const previous=ownerFor(id);
|
|
33
|
+
sessionOwners[id]=instanceId;
|
|
34
|
+
if(previous!==ownerFor(id))notifyMemory({event:'connection.changed'});
|
|
35
|
+
await atomic(routeFile,sessionOwners);
|
|
36
|
+
});
|
|
37
|
+
const ownerFor=id=>sessionOwners[id]&&sessionOwners[id]!==primaryId?sessionOwners[id]:undefined;
|
|
38
|
+
const workspaceManager=createFlowWorkspaceManager({getRegistry:()=>controllerScope.get('workspaceRegistry'),isolated:true,displayName:'知识库客户端',singleName:true});
|
|
39
|
+
let nativeBridge,desktopLinks,bridgeTimer,bridgeError='',controllerScope
|
|
40
|
+
const sharedStatus=async()=>({...await client.call('host.tool',{name:'kb_status',input:{}}),serviceRuntimeVersion:(await client.call('service.health')).coreVersion,build,runtimeMode:'service',inboxServerManaged:!!nativeBridge,dshConnection:{controller:!!controllerScope,error:bridgeError}})
|
|
41
|
+
let starting=false
|
|
42
|
+
async function ensureBridge(){if(starting||nativeBridge||!controllerScope)return;starting=true;try{const s=await sharedStatus(),workspace=await workspaceManager.ensure(library);nativeBridge=startDshHostBridge({client,ctx:controllerScope,workspace,ensureWorkspace:()=>workspaceManager.ensure(library),ownsSession:id=>!sessionOwners[id]||sessionOwners[id]===primaryId,onSessionCreated:id=>recordSession(primaryId,id),libraryRoot:s.kbPath,label:'DSH · '+path.basename(profileDir??'当前 Host'),onError:e=>{bridgeError=e.code??e.message;}});bridgeError=''}catch(e){if(bridgeError!==e.message)console.warn('[kb-service] DSH bridge pending:',e.message);bridgeError=e.message;}finally{starting=false}}
|
|
43
|
+
ctx.inject(['sessionController','workspaceRegistry','llm'],scope=>{controllerScope=scope;void ensureBridge();desktopLinks=startDesktopHostLinks({ctx:scope,python,connectRuntime,startBridge:startDshHostBridge,primaryRoot:library,ownerFor,recordSession,workspaceFor:()=>workspaceManager.ensure(library),onLibraryEvent:notifyMemory,onError:e=>{bridgeError=e.code??e.message;}});scope.effect(()=>()=>{void desktopLinks?.dispose();nativeBridge?.dispose();nativeBridge=null;controllerScope=null},'kb-service: detach native Host')})
|
|
44
|
+
bridgeTimer=setInterval(()=>void ensureBridge(),1000);bridgeTimer.unref?.();void ensureBridge()
|
|
45
|
+
ctx.effect(()=>()=>{clearInterval(bridgeTimer);nativeBridge?.dispose()},'kb-service: native DSH bridge')
|
|
46
|
+
publishKnowledgeMemory(ctx,(operation,context)=>{
|
|
47
|
+
const agent=context?.session?ctx.get('agents')?.get(context.session):null;
|
|
48
|
+
if(context?.session&&!agent){
|
|
49
|
+
if(context.purpose!=='memory-management')throw Error('knowledge_memory_session_unavailable');
|
|
50
|
+
const owner=ownerFor(context.session);
|
|
51
|
+
const historicalClient=owner?desktopLinks?.clientForLibrary(owner):primaryClient;
|
|
52
|
+
if(!historicalClient)throw Error('knowledge_memory_library_disconnected');
|
|
53
|
+
return historicalClient.call('workspace.read',{operation});
|
|
54
|
+
}
|
|
55
|
+
if(agent&&ownerFor(agent.id)&&!desktopLinks)throw Error('knowledge_memory_library_disconnected');
|
|
56
|
+
const target=agent?desktopLinks?.clientForAgent(agent):undefined;
|
|
57
|
+
if(target===null)throw Error('knowledge_memory_library_disconnected');
|
|
58
|
+
return (target??primaryClient).call('workspace.read',{operation});
|
|
59
|
+
},listener=>{memoryListeners.add(listener);const off=primaryClient.subscribe(ev=>{if(ev.event!=='memory.changed')listener(ev)});return()=>{off();memoryListeners.delete(listener)}},!!runtime);
|
|
60
|
+
let connected = true
|
|
61
|
+
ctx.effect(() => () => { connected=false;nativeBridge?.dispose();void runtime?.close();client.close() }, 'kb-service: close Host connection')
|
|
62
|
+
function trusted(exec,name,input) {
|
|
63
|
+
if (!exec) return true // direct trusted Host/UI invocation, no wire caller claims
|
|
64
|
+
const agent = exec.agent, agents = ctx.get('agents')
|
|
65
|
+
if (!agent || agents?.get(agent.id)!==agent) return false
|
|
66
|
+
const header=agent.session?.header??{}
|
|
67
|
+
if(!(name==='kb_import'&&input?.action==='parse'))return true
|
|
68
|
+
return isLiveKnowledgeGrant(agent,agents) || header.agentPreset==='knowledge' && header.origin!=='subagent' && !header.parentSession
|
|
69
|
+
}
|
|
70
|
+
function knowledge(exec){const agent=exec?.agent;if(!agent||ctx.get('agents')?.get(agent.id)!==agent)return false;const h=agent.session?.header??{};return isLiveKnowledgeGrant(agent,ctx.get('agents'))||h.agentPreset==='knowledge'&&h.origin!=='subagent'&&!h.parentSession}
|
|
71
|
+
const parseSources=createParseSourceAuthority({getAgents:()=>ctx.get('agents'),getBinding:()=>client.call('host.tool',{name:'kb_status',input:{}}),getController:()=>ctx.get('sessionController'),knowledgeCaller:exec=>knowledge(exec)?{ok:true}:{ok:false,reason:'FORBIDDEN',detail:'库内资料需要知识库会话授权'}})
|
|
72
|
+
async function parseInput(input,exec){
|
|
73
|
+
const a={...input};if(!['source','submit','test-parse'].includes(a.action))return {input:a};
|
|
74
|
+
if([a.sourcePath,a.sourceRef,a.sourceRel,a.attachmentId].filter(Boolean).length>1)throw Error('请选择一种解析来源');
|
|
75
|
+
let ref;if(a.attachmentId)ref=await parseSources.issueAttachment(a.attachmentId,exec);else if(a.sourcePath)ref=await parseSources.issue(a.sourcePath,exec);
|
|
76
|
+
if(ref&&a.action==='source')return {immediate:{ok:true,action:'source',...ref}};
|
|
77
|
+
if(ref?.sourceRel)a.sourceRel=ref.sourceRel;
|
|
78
|
+
const token=a.sourceRef??ref?.sourceRef;delete a.attachmentId;delete a.sourcePath;delete a.sourceRef;
|
|
79
|
+
if(!token)return {input:a};
|
|
80
|
+
const source=await parseSources.resolve(token,exec),data=source.data??await readFile(source.abs);if(data.length>64*1024*1024)throw Error('外部解析原件超过 64 MiB,请分段导入');
|
|
81
|
+
let stageId;for(let at=0;at<Math.max(1,data.length);at+=220000){const r=await client.call('desktop.importStage',{name:source.name,data:data.subarray(at,at+220000).toString('base64'),final:at+220000>=data.length,...(stageId?{stageId}:{})});stageId=r.stageId;}
|
|
82
|
+
return {input:a,sourceStage:stageId};
|
|
83
|
+
}
|
|
84
|
+
const tools = ctx.get('tools')
|
|
85
|
+
if (!tools) throw Error('Host tools service is required')
|
|
86
|
+
const parseRule = 'OCR / ASR 必须使用 kb_parse,服务选择以当前设置为准,优先于所有记忆中的偏好或旧脚本。默认服务缺少 API 配置、凭据、额度、连接失败或部分失败时必须停止,向用户说明服务和具体错误并询问修复配置还是切换服务;未经用户本次明确同意,禁止自动切换本机模型、其他云端、脚本或 HTTP。默认值只能由用户在解析设置页修改。仅用户本次明确指定外部方式才执行该次例外,例外不延续。'
|
|
87
|
+
const systemPrompt = ctx.get('systemPrompt')
|
|
88
|
+
if (typeof systemPrompt?.context === 'function') ctx.effect(() => systemPrompt.context({ name:'kb:parse-policy', order:600, interpolate:false, text:parseRule }), 'kb-service: parse policy')
|
|
89
|
+
for (const definition of definitions) {
|
|
90
|
+
const entry = { name:definition.name, description:definition.name === 'kb_parse' ? parseRule + '用 action=submit、kind=asr/ocr 和 sourcePath/sourceRef/sourceRel 提交;action=providers 查询当前设置,job/result 查看任务和结果。providerId 不能覆盖会话默认服务。' : '共享知识库服务:'+definition.name, parameters:definition.parameters,
|
|
91
|
+
output:{schema:definition.outputSchema,render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
|
|
92
|
+
isConcurrencySafe:()=>false,
|
|
93
|
+
async execute(input,exec) {const invoke=async()=>{const target=desktopLinks?.clientForAgent(exec?.agent);if(target===null)return {ok:false,reason:'HOST_UNAVAILABLE'};return routing.run(target??primaryClient,async()=>{
|
|
94
|
+
if (!trusted(exec,definition.name,input)) return {ok:false,reason:'CALLER_UNVERIFIED'}
|
|
95
|
+
try {
|
|
96
|
+
if (!connected) return {ok:false,reason:'HOST_UNAVAILABLE'}
|
|
97
|
+
const requestId = input?.requestId ? 'host-'+definition.name+'-'+input.requestId : randomUUID()
|
|
98
|
+
const parsed=definition.name==='kb_parse'?await parseInput(input??{},exec):{input:input??{}};if(parsed.immediate)return parsed.immediate
|
|
99
|
+
const value = await client.call('host.tool',{name:definition.name,input:parsed.input,hostAuthority:knowledge(exec)?'knowledge':'workspace',...(parsed.sourceStage?{sourceStage:parsed.sourceStage}:{}),...(exec?.agent?.id?{hostSession:String(exec.agent.id)}:{})},{requestId})
|
|
100
|
+
if (definition.name==='kb_status') return {...value,build,service:{connected:true,...client.welcome.library}}
|
|
101
|
+
return value
|
|
102
|
+
} catch(e) {return {ok:false,reason:e.code??'HOST_UNAVAILABLE',error:e.message}}
|
|
103
|
+
});};return normalizeToolResult(definition.name,input,await invoke());},
|
|
104
|
+
}
|
|
105
|
+
ctx.effect(()=>tools.register(entry),'kb-service: '+entry.name)
|
|
106
|
+
}
|
|
107
|
+
if (gatewayApply && !ctx.get('tools').get('knowledge_request')) {
|
|
108
|
+
const gateway={...(config.gateway??{})}
|
|
109
|
+
gateway.targets ??= [{id:'knowledge',preset:'knowledge',cwd:'',describe:'知识库管家',toolName:'knowledge_request'}]
|
|
110
|
+
gateway.resolveTarget=async target=>{if(target.id!=='knowledge')return target;const status=await client.call('host.tool',{name:'kb_status',input:{}});if(!status.bound||!status.kbPath)throw Error('Shared library unavailable');return {...target,preset:'knowledge',cwd:status.kbPath}}
|
|
111
|
+
gatewayApply(ctx,gateway)
|
|
112
|
+
}
|
|
113
|
+
const send=(res,status,value)=>{res.statusCode=status;res.setHeader('content-type','application/json; charset=utf-8');res.end(JSON.stringify(value))}
|
|
114
|
+
const sameOrigin=req=>req.headers['sec-fetch-site']!=='cross-site' && (!req.headers.origin || (()=>{try{return new URL(req.headers.origin).host===req.headers.host}catch{return false}})())
|
|
115
|
+
const updates=createHostUpdates({ctx,build,profileDir,quiesce:runtime?()=>runtime.prepareUpgrade():null,resume:runtime?()=>runtime.resume():null,withUpdateLock:runtime?task=>runtime.withUpdateLock(task):undefined});
|
|
116
|
+
const server=ctx.get('webServer')
|
|
117
|
+
if(server?.register) {
|
|
118
|
+
await registerHostAssets({ctx,server,root:path.resolve(import.meta.dirname,'../..'),client,send,sameOrigin})
|
|
119
|
+
const apiHandler=async(req,res)=>{
|
|
120
|
+
if(!sameOrigin(req)) return send(res,403,{ok:false,code:'FORBIDDEN'})
|
|
121
|
+
try {
|
|
122
|
+
if(req.method==='GET') return send(res,200,{ok:true,status:{...await sharedStatus(),build}})
|
|
123
|
+
if(req.method!=='POST'||String(req.headers['content-type']??'').split(';')[0].trim()!=='application/json') return send(res,403,{ok:false,code:'FORBIDDEN'})
|
|
124
|
+
let size=0;const chunks=[]
|
|
125
|
+
for await (const chunk of req){size+=chunk.length;if(size>900000) return send(res,413,{ok:false,code:'BAD_REQUEST'});chunks.push(chunk)}
|
|
126
|
+
const body=JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
127
|
+
const aliases={'import-plan':'import.plan','import-run':'import.run','import-status':'import.status','import-cancel':'import.cancel','import-waiting':'import.waiting','import-parse':'import.parse'};body.op=aliases[body.op]??body.op
|
|
128
|
+
if(body.op==='updates.check')return send(res,200,await updates.check(body))
|
|
129
|
+
if(body.op==='updates.install')return send(res,200,await updates.install(body))
|
|
130
|
+
if(body.op==='updates.status')return send(res,200,await updates.status())
|
|
131
|
+
if(body.op==='updates.prepare')return send(res,200,await updates.prepare(body))
|
|
132
|
+
if(body.op==='pick-dir'){const cap=ctx.get('directoryPicker')?.capability();if(cap?.kind!=='native'||!cap.pick)return send(res,200,{ok:false,reason:'no-directory-picker'});const path=await cap.pick(AbortSignal.timeout(300000));return send(res,200,{ok:true,path,canceled:!path});}
|
|
133
|
+
if(body.op==='atlas.file-action'){const f=await client.call('desktop.stat',{path:body.path}),s=await sharedStatus(),c=controllerScope?.get('sessionController');if(!c?.openWorkspacePath)throw Error('DSH 本机文件操作未连接');return send(res,200,{ok:true,...await c.openWorkspacePath({path:path.join(s.kbPath,f.path),action:body.action},AbortSignal.timeout(15000))});}
|
|
134
|
+
if(body.op==='status') return send(res,200,{ok:true,status:await sharedStatus()})
|
|
135
|
+
const inbox=await inboxHost(body);if(inbox)return send(res,200,inbox)
|
|
136
|
+
if(body.op==='index.policy.set')return send(res,200,await client.call('policy.setIndexExcluded',{paths:body.paths??[body.path],excluded:body.excluded,expectedRevision:body.expectedPolicyRevision},{requestId:body.requestId??randomUUID()}))
|
|
137
|
+
return send(res,200,await client.call('adapter.dispatch',{operation:body},{requestId:body.requestId??randomUUID()}))
|
|
138
|
+
}catch(e){send(res,200,{ok:false,code:e.code??'HOST_UNAVAILABLE',error:e.message})}
|
|
139
|
+
};
|
|
140
|
+
ctx.effect(()=>installApi?installApi(apiHandler):server.register({kind:'exact',path:'/kb-core/api',handler:apiHandler}),'kb-service: existing workbench API')
|
|
141
|
+
ctx.effect(()=>server.register({kind:'exact',path:'/kb-core/workbench-events',handler:async(req,res)=>{
|
|
142
|
+
if(req.method!=='GET'||!sameOrigin(req))return send(res,403,{ok:false})
|
|
143
|
+
res.writeHead(200,{'content-type':'text/event-stream','cache-control':'no-store'})
|
|
144
|
+
res.write(': shared-service\n\n')
|
|
145
|
+
const off=client.subscribe(event=>res.write('data: '+JSON.stringify(event)+'\n\n'))
|
|
146
|
+
try{await client.call('events.subscribe')}catch(e){res.write('data: '+JSON.stringify({type:'service-unavailable',code:e.code})+'\n\n')}
|
|
147
|
+
const heartbeat=setInterval(()=>res.write(': heartbeat\n\n'),15000);res.once('close',()=>{off();clearInterval(heartbeat)})
|
|
148
|
+
}}),'kb-service: existing workbench events')
|
|
149
|
+
}
|
|
150
|
+
return {mode:'service',tools:definitions.map(x=>x.name),client}
|
|
151
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import path from 'node:path';import {readFile,readdir} from 'node:fs/promises';import {captureDocument,sharedDraft} from '../kb-core/src/capture-surface.js';
|
|
2
|
+
export async function registerHostAssets({ctx,server,root,client,send,sameOrigin}){
|
|
3
|
+
const register=(url,handler)=>ctx.effect(()=>server.register({kind:'exact',path:url,handler}),'kb-service: '+url);
|
|
4
|
+
register('/kb-core/collect',async(req,res)=>{try{if(!sameOrigin(req))return send(res,403,{ok:false});const draft=await sharedDraft(req);res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'});res.end(captureDocument(await readFile(path.join(root,'src/client/capture.html'),'utf8'),draft));}catch(e){send(res,400,{ok:false,error:e.message})}});
|
|
5
|
+
const assets=[['capture.js','text/javascript'],['capture-sw.js','text/javascript'],['capture.css','text/css'],['capture.webmanifest','application/manifest+json'],['capture-icon.svg','image/svg+xml'],['capture-icon-192.png','image/png'],['capture-icon-512.png','image/png'],['pdfjs/pdf.mjs','text/javascript'],['pdfjs/pdf.worker.mjs','text/javascript']];
|
|
6
|
+
for(const folder of ['cmaps','standard_fonts','wasm'])for(const name of await readdir(path.join(root,'src/client/pdfjs',folder)))assets.push(['pdfjs/'+folder+'/'+name,name.endsWith('.js')?'text/javascript':name.endsWith('.wasm')?'application/wasm':'application/octet-stream']);
|
|
7
|
+
for(const [file,mime]of assets){const url='/kb-core/'+(file==='pdfjs/pdf.mjs'?'pdfjs.mjs':file==='pdfjs/pdf.worker.mjs'?'pdf.worker.mjs':file.startsWith('pdfjs/')?'pdf-assets/'+file.slice(6):file);register(url,async(req,res)=>{if(req.method!=='GET'||!sameOrigin(req))return send(res,403,{ok:false});try{res.writeHead(200,{'content-type':mime,'cache-control':'private, max-age=3600','x-content-type-options':'nosniff'});res.end(await readFile(path.join(root,'src/client',file)));}catch{res.destroy();}});}
|
|
8
|
+
register('/kb-core/clip',async(req,res)=>{const origin=String(req.headers.origin??'');if(!/^chrome-extension:\/\/[a-p]{32}$/.test(origin))return send(res,403,{ok:false});res.setHeader('access-control-allow-origin',origin);res.setHeader('vary','Origin');if(req.method==='OPTIONS'){res.writeHead(204,{'access-control-allow-methods':'POST','access-control-allow-headers':'content-type, authorization'});return res.end();}if(req.method!=='POST')return send(res,405,{ok:false});try{let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>900000)return send(res,413,{ok:false});chunks.push(chunk);}const {clipper}=await client.call('service.health');if(!clipper?.endpoint)throw Error('剪藏服务未连接');const url=new URL(clipper.endpoint);if(url.hostname!=='127.0.0.1'||url.protocol!=='http:')throw Error('剪藏地址无效');const response=await fetch(url.origin+'/kb-core/clip',{method:'POST',headers:{'content-type':'application/json',origin,authorization:String(req.headers.authorization??'')},body:Buffer.concat(chunks),signal:AbortSignal.timeout(10000)});send(res,response.status,await response.json());}catch(e){send(res,503,{ok:false,error:'共库剪藏暂不可用,请重试'});}});
|
|
9
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import {createHash,randomUUID} from 'node:crypto'
|
|
4
|
+
import {readdir,readFile,mkdir,rename,copyFile,stat} from 'node:fs/promises'
|
|
5
|
+
|
|
6
|
+
// Windows locks loaded executables/DLLs. Run helpers outside the replaceable bundle.
|
|
7
|
+
export async function resolveHostPython(packageRoot,{home=path.join(os.homedir(),'.dsh','runtime','knowledge-python')}={}) {
|
|
8
|
+
const source=path.join(packageRoot,'runtime','python'),files=[]
|
|
9
|
+
async function walk(dir,prefix='') {
|
|
10
|
+
for(const row of (await readdir(dir,{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name))) {
|
|
11
|
+
if(row.isSymbolicLink())throw Error('Python runtime must not contain links')
|
|
12
|
+
const rel=path.join(prefix,row.name)
|
|
13
|
+
if(row.isDirectory())await walk(path.join(dir,row.name),rel)
|
|
14
|
+
else if(row.isFile())files.push({rel,digest:createHash('sha256').update(await readFile(path.join(source,rel))).digest('hex')})
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
try{await stat(path.join(source,'python.exe'))}catch(e){if(e.code==='ENOENT')return 'python';throw e}
|
|
18
|
+
await walk(source)
|
|
19
|
+
const key=createHash('sha256').update(JSON.stringify(files)).digest('hex').slice(0,24),target=path.join(home,key)
|
|
20
|
+
async function verified() {
|
|
21
|
+
try {for(const f of files)if(createHash('sha256').update(await readFile(path.join(target,f.rel))).digest('hex')!==f.digest)return false;return true}
|
|
22
|
+
catch(e){if(e.code==='ENOENT')return false;throw e}
|
|
23
|
+
}
|
|
24
|
+
if(await verified())return path.join(target,'python.exe')
|
|
25
|
+
const temp=path.join(home,key+'.tmp-'+randomUUID());await mkdir(temp,{recursive:true})
|
|
26
|
+
for(const f of files){const dest=path.join(temp,f.rel);await mkdir(path.dirname(dest),{recursive:true});await copyFile(path.join(source,f.rel),dest)}
|
|
27
|
+
try{await rename(temp,target)}catch(e){if(!await verified())throw e}
|
|
28
|
+
if(!await verified())throw Error('Copied Python runtime failed verification')
|
|
29
|
+
return path.join(target,'python.exe')
|
|
30
|
+
}
|