@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,2307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 解析服务(OCR / ASR)——第二轮新增的受控解析能力。
|
|
3
|
+
*
|
|
4
|
+
* 设计边界(与 AGENTS/第一轮交付一致):
|
|
5
|
+
* · 原件只读:解析只读源文件,从不改写、移动、删除原件。
|
|
6
|
+
* · 结果隔离:全文/分段/页图只落 `<stateDir>/parse/<kbId>/`,不进知识库、不进任何普通 Agent 可读目录。
|
|
7
|
+
* · 凭据不入档:provider 只保存 credentialRef;值只在请求时从环境或 Windows DPAPI 存储读取,
|
|
8
|
+
* 绝不写进任务记录、日志、HTTP 返回或 UI。
|
|
9
|
+
* · 协议与地址分离:protocol 决定"怎么发请求",baseUrl/command 决定"发给谁";
|
|
10
|
+
* 支持某协议不代表兼容任何 HTTP API。
|
|
11
|
+
* · local-only:策略为 local-only 时拒绝一切"真实目标在公网"的提供方 ——
|
|
12
|
+
* **不相信调用方自填的 locality 标签**(2026-10-18 定向审查缺口 1):
|
|
13
|
+
* locality=local/lan 要求目标可静态判为本机/内网;发请求前再按 DNS 实际解析地址复核,
|
|
14
|
+
* 全公网解析一律拒绝,且拒绝发生在**发送正文之前**;跨源重定向逐跳复核。
|
|
15
|
+
* · 管理面与使用面分离(2026-10-18 定向审查缺口 2):提供方增删改、可执行程序/参数、
|
|
16
|
+
* credentialRef、renderCommand、externalPolicy **只允许宿主认可的用户管理入口**改
|
|
17
|
+
* (saveProvider 等要求 viaAdmin),模型提交始终使用设置中的默认提供方。
|
|
18
|
+
* · 不伪造:引擎没给的字段(词级时间戳、置信度、说话人)一律标 unavailable,不生成。
|
|
19
|
+
*
|
|
20
|
+
* 任务状态机:queued → running → succeeded | partial | failed | canceled
|
|
21
|
+
* 重启后 running 的记录一律判为 interrupted:attempts 未用尽则重新排队,否则 failed。
|
|
22
|
+
* 解析成功与落库成功分开记录(job.status 与 job.land.status 相互独立)。
|
|
23
|
+
*/
|
|
24
|
+
import { spawn } from 'node:child_process'
|
|
25
|
+
import { createParseJobStorage } from './parse-job-storage.js'
|
|
26
|
+
import { atomicJson as atomicWriteJson, safePath } from './workbench-state.js'
|
|
27
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
28
|
+
import { promises as dnsPromises } from 'node:dns'
|
|
29
|
+
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
30
|
+
import http from 'node:http'
|
|
31
|
+
import https from 'node:https'
|
|
32
|
+
import net from 'node:net'
|
|
33
|
+
import path from 'node:path'
|
|
34
|
+
import { resolveAssetPath, excludedSource, EXCLUDED_PARTITION, registerDerived } from './index-policy.js'
|
|
35
|
+
import { presetProvider, NATIVE_PROTOCOLS } from './parse-presets.js'
|
|
36
|
+
import { createParseCredentials } from './parse-credentials.js'
|
|
37
|
+
import { createNativeAdapter } from './parse-native.js'
|
|
38
|
+
import { createParseDiscovery } from './parse-discovery.js'
|
|
39
|
+
import { checkRealPath } from './kbcore.js'
|
|
40
|
+
|
|
41
|
+
export const PARSING_SCHEMA_VERSION = 1
|
|
42
|
+
|
|
43
|
+
// Derive display information for old records too; never infer silence from empty ASR text.
|
|
44
|
+
export function parseFailureDetails(job) {
|
|
45
|
+
const units = Array.isArray(job.partial) ? job.partial : job.partial?.failedUnits || []
|
|
46
|
+
const clock = value => {
|
|
47
|
+
if (!Number.isFinite(value) || value < 0) return null
|
|
48
|
+
const seconds = Math.floor(value)
|
|
49
|
+
return [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60].map(v => String(v).padStart(2, '0')).join(':')
|
|
50
|
+
}
|
|
51
|
+
const reasons = {
|
|
52
|
+
EMPTY_TEXT: '模型返回空文本;是否无语音或漏识别,需回听原音频确认',
|
|
53
|
+
PARSE_TIMEOUT: '解析超时,未取得该片段结果(不代表该片段没有语音)',
|
|
54
|
+
LOCAL_MODEL_FAILED: '本地模型未能完成识别',
|
|
55
|
+
LOCAL_GPU_MEMORY: '本地模型显存不足',
|
|
56
|
+
LOCAL_SERVICE_TIMEOUT: '本地模型服务调用超时',
|
|
57
|
+
LOCAL_SERVICE_UNAVAILABLE: '本地模型服务连接失败',
|
|
58
|
+
NETWORK_ERROR: '连接识别服务失败',
|
|
59
|
+
CANCELED: '任务已取消',
|
|
60
|
+
}
|
|
61
|
+
return units.map(unit => {
|
|
62
|
+
const saved = job.chunkResults?.[unit.index]
|
|
63
|
+
const raw = String(unit.code || unit.error || saved?.code || 'UNKNOWN_ERROR')
|
|
64
|
+
const code = raw.split(':')[0]
|
|
65
|
+
const detail = unit.detail || unit.message || saved?.detail || (raw.includes(':') ? raw.slice(raw.indexOf(':') + 1).trim() : '')
|
|
66
|
+
const isPage = unit.unit === 'page' || job.kind === 'ocr'
|
|
67
|
+
const number = Number.isInteger(unit.index) ? unit.index + (isPage ? 0 : 1) : null
|
|
68
|
+
const start = clock(unit.startSec), end = clock(unit.endSec)
|
|
69
|
+
const range = (number === null ? (isPage ? '页面' : '片段') : `第 ${number} ${isPage ? '页' : '段'}`) + (start && end ? `(${start}–${end})` : '')
|
|
70
|
+
const reason = code === 'EMPTY_TEXT' && isPage ? '模型返回空文本;请检查原页是否有文字' : (reasons[code] || '识别失败,请根据错误码检查服务或原件')
|
|
71
|
+
return { ...unit, code, range, reason, detail: String(detail || '') }
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function parseFailureSummary(job) {
|
|
76
|
+
const details = job.failureDetails || parseFailureDetails(job)
|
|
77
|
+
const label = '任务已完成'
|
|
78
|
+
if (details.length) {
|
|
79
|
+
const shown = details.slice(0, 4).map(u => `${u.range}:${u.reason} [${u.code}]`).join(';')
|
|
80
|
+
return `${label};${details.length} ${job.kind === 'asr' ? '段' : '页'}未取得有效结果。${shown}${details.length > 4 ? ';其余范围见任务详情' : ''}`
|
|
81
|
+
}
|
|
82
|
+
const diagnostic = job.diagnostics?.at(-1)
|
|
83
|
+
return `${label}:${diagnostic?.message || diagnostic?.code || job.error?.message || job.error?.detail || job.error?.code || '未记录具体原因,请查看任务详情'}`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const PARSE_PROTOCOLS = {
|
|
87
|
+
ocr: ['deepseek-ocr', 'openai-vision', 'dashscope-ocr', 'baidu-ocr', 'paddle-local', 'paddle-service', 'ppocr-local'],
|
|
88
|
+
asr: ['deepseek-asr', 'openai-audio-transcriptions', 'cli-transcribe', 'dashscope-asr', 'baidu-asr', 'qwen3-local'],
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const PARSE_KINDS = ['ocr', 'asr']
|
|
92
|
+
|
|
93
|
+
export const LOCALITY = ['local', 'lan', 'cloud']
|
|
94
|
+
|
|
95
|
+
export const EXTERNAL_POLICIES = ['local-only', 'allow-configured']
|
|
96
|
+
|
|
97
|
+
export const DEFAULT_FORMATS = {
|
|
98
|
+
ocr: ['png', 'jpg', 'jpeg', 'webp', 'bmp', 'pdf'],
|
|
99
|
+
asr: ['wav', 'mp3', 'm4a', 'mp4', 'flac', 'ogg', 'aac'],
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
const MAX_ATTEMPTS = 2
|
|
104
|
+
const DEFAULT_TIMEOUT_MS = 180_000
|
|
105
|
+
const MAX_TIMEOUT_MS = 30 * 60_000
|
|
106
|
+
const MAX_BYTES_LIMIT = 512 * 1024 * 1024
|
|
107
|
+
const JOBS_KEPT = 200
|
|
108
|
+
|
|
109
|
+
const nowIso = () => new Date().toISOString()
|
|
110
|
+
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex')
|
|
111
|
+
const sha12 = (buf) => sha256(buf).slice(0, 12)
|
|
112
|
+
const toPosix = (p) => String(p).split(path.sep).join('/')
|
|
113
|
+
|
|
114
|
+
// ── 目标地址分级(local-only 的真实判据)────────────────────────────────────
|
|
115
|
+
// 只认"可证明是本机/内网"的目标。域名一律按**实际解析出来的地址**判,
|
|
116
|
+
// 不按调用方填的 locality 判 —— 这是 2026-10-18 审查缺口 1 的直接对策。
|
|
117
|
+
// 注意:198.18.0.0/15 属保留段但本机代理常拿它做 fake-IP(等于把公网域名伪装成内网地址),
|
|
118
|
+
// 因此**一律按公网处理**,不给它留后门。
|
|
119
|
+
const PRIVATE_V4 = [
|
|
120
|
+
[/^10\./, 'private'],
|
|
121
|
+
[/^127\./, 'loopback'],
|
|
122
|
+
[/^169\.254\./, 'link-local'],
|
|
123
|
+
[/^172\.(1[6-9]|2\d|3[01])\./, 'private'],
|
|
124
|
+
[/^192\.168\./, 'private'],
|
|
125
|
+
[/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./, 'private'],
|
|
126
|
+
[/^0\./, 'unspecified'],
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
function classifyV4(ip) {
|
|
130
|
+
for (const [re, kind] of PRIVATE_V4) if (re.test(ip)) return kind
|
|
131
|
+
return 'public'
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 把单个 IP 分级:loopback / private / link-local / unspecified / public / unknown。 */
|
|
135
|
+
export function classifyAddress(ip) {
|
|
136
|
+
const s = String(ip ?? '').trim().replace(/^\[|\]$/g, '')
|
|
137
|
+
if (net.isIPv4(s)) return classifyV4(s)
|
|
138
|
+
if (!net.isIPv6(s)) return 'unknown'
|
|
139
|
+
const lower = s.toLowerCase()
|
|
140
|
+
if (lower === '::1' || lower === '::') return lower === '::1' ? 'loopback' : 'unspecified'
|
|
141
|
+
if (lower.startsWith('::ffff:')) {
|
|
142
|
+
const mapped = lower.slice(7)
|
|
143
|
+
return net.isIPv4(mapped) ? classifyV4(mapped) : 'unknown'
|
|
144
|
+
}
|
|
145
|
+
if (/^f[cd]/.test(lower)) return 'private' // fc00::/7 ULA
|
|
146
|
+
if (/^fe[89ab]/.test(lower)) return 'link-local'
|
|
147
|
+
return 'public'
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 这个名字本身是否"可静态判为本机/内网"(不查 DNS)。 */
|
|
151
|
+
export function isLocalHostName(host) {
|
|
152
|
+
const h = String(host ?? '').trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '')
|
|
153
|
+
if (h === '') return false
|
|
154
|
+
if (h === 'localhost' || h.endsWith('.localhost')) return true
|
|
155
|
+
if (net.isIP(h)) return classifyAddress(h) !== 'public'
|
|
156
|
+
return ['.local', '.lan', '.internal', '.home.arpa', '.localdomain', '.intranet'].some((s) => h.endsWith(s))
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* 静态复核"标签与真实目标是否一致":locality=local/lan 必须能静态判为本机/内网。
|
|
161
|
+
* 域名(example.com 之类)不能靠名字自称 local —— 那正是审查复现的那条绕过路径。
|
|
162
|
+
*/
|
|
163
|
+
export function staticDestinationRefusal(provider) {
|
|
164
|
+
if (provider === null || typeof provider !== 'object') return null
|
|
165
|
+
if (['cli-transcribe', 'qwen3-local', 'paddle-local', 'ppocr-local'].includes(provider.protocol)) return null
|
|
166
|
+
const baseUrl = String(provider.baseUrl ?? '')
|
|
167
|
+
let url
|
|
168
|
+
try {
|
|
169
|
+
url = new URL(baseUrl)
|
|
170
|
+
} catch {
|
|
171
|
+
return { code: 'BAD_URL', message: `提供方 ${provider.id} 的 baseUrl 不是合法地址` }
|
|
172
|
+
}
|
|
173
|
+
const host = url.hostname.replace(/^\[|\]$/g, '')
|
|
174
|
+
if (provider.locality === 'cloud') return null
|
|
175
|
+
if (isLocalHostName(host)) return null
|
|
176
|
+
return {
|
|
177
|
+
code: 'LOCALITY_MISMATCH',
|
|
178
|
+
message: `提供方 ${provider.id} 声明 locality=${provider.locality},但目标 ${host} 无法判为本机/内网地址。`
|
|
179
|
+
+ '如果它确实是公网服务,请把 locality 改成 cloud(并确认 externalPolicy 允许);local-only 从不相信自填标签。',
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 解析域名到全部地址(可注入 lookup,供受控桩测试;默认走系统 DNS)。 */
|
|
184
|
+
async function resolveHost(host, lookup) {
|
|
185
|
+
const h = String(host ?? '').replace(/^\[|\]$/g, '')
|
|
186
|
+
if (net.isIP(h)) return [{ address: h, family: net.isIP(h) }]
|
|
187
|
+
const fn = typeof lookup === 'function' ? lookup : dnsPromises.lookup
|
|
188
|
+
const rows = await fn(h, { all: true, verbatim: true })
|
|
189
|
+
return Array.isArray(rows) ? rows : []
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ── 固定 CLI 的程序/参数策略(审查缺口 2 的第二层)──────────────────────────
|
|
193
|
+
// 管理面已经不给模型改程序了;这里再挡一类"配置写对了但语义等于任意代码"的形态:
|
|
194
|
+
// 解释器的行内求值开关。参数由程序构造,模型永远不进命令行,但配置本身要被拒。
|
|
195
|
+
const INLINE_EXEC_FLAGS = new Set([
|
|
196
|
+
'-e', '--eval', '-p', '--print', '--input-type', '-c', '/c', '/k',
|
|
197
|
+
'-command', '--command', '-encodedcommand', '-enc', '-e:', '-commandwithargs',
|
|
198
|
+
])
|
|
199
|
+
|
|
200
|
+
/** 返回 {code,message} 表示拒绝;null 表示通过。纯函数,管理面与应用面都调它。 */
|
|
201
|
+
export function cliProgramRefusal(provider) {
|
|
202
|
+
if (provider === null || typeof provider !== 'object') return null
|
|
203
|
+
if (provider.protocol !== 'cli-transcribe') return null
|
|
204
|
+
const command = String(provider.command ?? '')
|
|
205
|
+
if (command === '') return { code: 'BAD_COMMAND', message: 'CLI 协议需要固定的可执行程序路径' }
|
|
206
|
+
if (!path.isAbsolute(command)) {
|
|
207
|
+
return { code: 'BAD_COMMAND', message: `CLI 程序必须是绝对路径(收到 ${command}):不按 PATH 解析,避免同名程序劫持` }
|
|
208
|
+
}
|
|
209
|
+
if (!/\.(exe|cmd|bat)$/i.test(command)) {
|
|
210
|
+
return { code: 'BAD_COMMAND', message: `CLI 程序必须是 .exe/.cmd/.bat(收到 ${command})` }
|
|
211
|
+
}
|
|
212
|
+
const args = Array.isArray(provider.args) ? provider.args : []
|
|
213
|
+
for (const a of args) {
|
|
214
|
+
const token = String(a).trim().toLowerCase().split('=')[0]
|
|
215
|
+
if (INLINE_EXEC_FLAGS.has(token)) {
|
|
216
|
+
return {
|
|
217
|
+
code: 'BAD_ARGS',
|
|
218
|
+
message: `参数里出现行内求值开关 ${a}:那等于让配置直接执行任意代码。请改成"固定脚本文件 + 普通参数"的形态。`,
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (/^-[ep]/.test(token) && /^-[ep][\s:]/.test(String(a).trim().toLowerCase())) {
|
|
222
|
+
return { code: 'BAD_ARGS', message: `参数里出现行内求值开关 ${a}` }
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return null
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ── 子进程环境最小化 ────────────────────────────────────────────────────────
|
|
229
|
+
// 解析程序只需要 PATH/临时目录/用户目录这类生存必需项;不把整份宿主环境(含一切
|
|
230
|
+
// 凭据类变量)交给它。HTTP 提供方的凭据走 authHeaders,与子进程环境无关。
|
|
231
|
+
const CHILD_ENV_ALLOW = [
|
|
232
|
+
'PATH', 'Path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'windir', 'SystemDrive',
|
|
233
|
+
'TEMP', 'TMP', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'HOME', 'APPDATA', 'LOCALAPPDATA',
|
|
234
|
+
'COMSPEC', 'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'PYTHONIOENCODING',
|
|
235
|
+
'CUDA_VISIBLE_DEVICES', 'HF_HOME', 'TRANSFORMERS_CACHE',
|
|
236
|
+
]
|
|
237
|
+
|
|
238
|
+
function minimalChildEnv() {
|
|
239
|
+
const env = {}
|
|
240
|
+
for (const key of CHILD_ENV_ALLOW) {
|
|
241
|
+
if (process.env[key] !== undefined) env[key] = process.env[key]
|
|
242
|
+
}
|
|
243
|
+
return env
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function errText(error) {
|
|
247
|
+
return String((error && error.message) || error || 'unknown error')
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
function clampInt(value, min, max, fallback) {
|
|
252
|
+
const n = Number(value)
|
|
253
|
+
if (!Number.isFinite(n)) return fallback
|
|
254
|
+
return Math.min(max, Math.max(min, Math.trunc(n)))
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 提供方 ID:小写字母数字与 - _ ,3..40 位。 */
|
|
258
|
+
export function validProviderId(id) {
|
|
259
|
+
return typeof id === 'string' && /^[a-z0-9][a-z0-9_-]{2,39}$/.test(id)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** credentialRef 只接受"环境变量名"形态,绝不接受 secret 字面量。 */
|
|
263
|
+
export function validCredentialRef(ref) {
|
|
264
|
+
if (ref === '' || ref == null) return true
|
|
265
|
+
if (typeof ref !== 'string') return false
|
|
266
|
+
if (!/^[A-Z][A-Z0-9_]{2,63}$/.test(ref)) return false
|
|
267
|
+
// 看起来像密钥的值直接拒绝(宁可让人改成 env 名)
|
|
268
|
+
if (/^(SK|AK|PK)[-_]/i.test(ref)) return false
|
|
269
|
+
return true
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* 校验并归一化一个提供方定义。
|
|
274
|
+
* 返回 {ok, value} 或 {ok:false, errors:[{field,code,message}]}
|
|
275
|
+
*/
|
|
276
|
+
export function normalizeProvider(input, extra = {}) {
|
|
277
|
+
const errors = []
|
|
278
|
+
let src = input && typeof input === 'object' ? input : {}
|
|
279
|
+
try { src = presetProvider(src) } catch (e) { errors.push({ field: 'vendor', message: e.message }) }
|
|
280
|
+
const id = typeof src.id === 'string' ? src.id.trim() : ''
|
|
281
|
+
if (!validProviderId(id)) errors.push({ field: 'id', code: 'BAD_ID', message: 'id 需为 3..40 位小写字母/数字/-/_' })
|
|
282
|
+
const kind = PARSE_KINDS.includes(src.kind) ? src.kind : ''
|
|
283
|
+
if (kind === '') errors.push({ field: 'kind', code: 'BAD_KIND', message: 'kind 只能是 ocr 或 asr' })
|
|
284
|
+
const protocol = String(src.protocol ?? '').trim()
|
|
285
|
+
if (kind !== '' && !PARSE_PROTOCOLS[kind].includes(protocol)) {
|
|
286
|
+
errors.push({ field: 'protocol', code: 'BAD_PROTOCOL', message: `${kind} 支持的协议:${PARSE_PROTOCOLS[kind].join(' / ')}` })
|
|
287
|
+
}
|
|
288
|
+
const locality = LOCALITY.includes(src.locality) ? src.locality : 'local'
|
|
289
|
+
const isHttp = protocol === 'openai-vision' || protocol === 'openai-audio-transcriptions' || protocol === 'paddle-service' || NATIVE_PROTOCOLS.includes(protocol)
|
|
290
|
+
let baseUrl = ''
|
|
291
|
+
let command = ''
|
|
292
|
+
let args = []
|
|
293
|
+
if (isHttp) {
|
|
294
|
+
baseUrl = typeof src.baseUrl === 'string' ? src.baseUrl.trim().replace(/\/+$/, '') : ''
|
|
295
|
+
if (!/^https?:\/\/[^\s]+$/i.test(baseUrl)) errors.push({ field: 'baseUrl', code: 'BAD_URL', message: 'HTTP 协议需要 http(s) 地址' })
|
|
296
|
+
if (/^http:\/\//i.test(baseUrl) && (locality === 'cloud' || locality === 'lan')) {
|
|
297
|
+
// 记录但不阻断:内网 http 是常见部署;策略层再判
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (['cli-transcribe', 'qwen3-local', 'paddle-local', 'paddle-service', 'ppocr-local'].includes(protocol)) {
|
|
301
|
+
command = typeof src.command === 'string' ? src.command.trim() : ''
|
|
302
|
+
if (protocol !== 'cli-transcribe' && command && !/python(?:\d+(?:\.\d+)*)?(?:\.exe)?$/i.test(path.basename(command))) command = path.join(command, 'Scripts', 'python.exe')
|
|
303
|
+
if (command === '') errors.push({ field: 'command', code: 'BAD_COMMAND', message: 'CLI 协议需要固定的可执行程序路径' })
|
|
304
|
+
if (Array.isArray(src.args)) args = src.args.map((a) => String(a))
|
|
305
|
+
else if (typeof src.args === 'string' && src.args.trim() !== '') errors.push({ field: 'args', code: 'BAD_ARGS', message: 'args 必须是数组(程序参数由程序构造,不接受命令串)' })
|
|
306
|
+
}
|
|
307
|
+
const formats = Array.isArray(src.formats) && src.formats.length > 0
|
|
308
|
+
? [...new Set(src.formats.map((f) => String(f).toLowerCase().replace(/^\./, '')).filter(Boolean))]
|
|
309
|
+
: [...(DEFAULT_FORMATS[kind] || [])]
|
|
310
|
+
if (Array.isArray(src.formats) && src.formats.length === 0) {
|
|
311
|
+
errors.push({ field: 'formats', code: 'BAD_FORMATS', message: 'formats 不能为空数组;不填则用默认值' })
|
|
312
|
+
}
|
|
313
|
+
const credentialRef = typeof src.credentialRef === 'string' ? src.credentialRef.trim() : ''
|
|
314
|
+
if (!validCredentialRef(credentialRef)) errors.push({ field: 'credentialRef', code: 'BAD_CREDENTIAL_REF', message: 'credentialRef 只能填环境变量名(如 KB_OCR_TOKEN),不要粘贴密钥' })
|
|
315
|
+
const value = {
|
|
316
|
+
vendor: ['deepseek', 'openai', 'custom', 'qwen', 'baidu', 'local'].includes(src.vendor) ? src.vendor : 'custom',
|
|
317
|
+
region: src.region || '',
|
|
318
|
+
workspaceId: src.workspaceId || '',
|
|
319
|
+
modelPath: String(src.modelPath || ''),
|
|
320
|
+
ffmpegCommand: String(src.ffmpegCommand || ''),
|
|
321
|
+
layoutModelPath: String(src.layoutModelPath || ''),
|
|
322
|
+
detModelPath: String(src.detModelPath || ''), recModelPath: String(src.recModelPath || ''), dictionaryPath: String(src.dictionaryPath || ''),
|
|
323
|
+
id,
|
|
324
|
+
kind,
|
|
325
|
+
protocol,
|
|
326
|
+
label: typeof src.label === 'string' && src.label.trim() !== '' ? src.label.trim().slice(0, 60) : id,
|
|
327
|
+
locality,
|
|
328
|
+
model: typeof src.model === 'string' ? src.model.trim() : '',
|
|
329
|
+
baseUrl,
|
|
330
|
+
command,
|
|
331
|
+
args,
|
|
332
|
+
// PDF 拆页需要固定 Python(随包脚本);只有管理员能配,模型不能给。
|
|
333
|
+
renderCommand: typeof src.renderCommand === 'string' ? src.renderCommand.trim() : '',
|
|
334
|
+
credentialRef,
|
|
335
|
+
authScheme: src.authScheme === 'bearer' ? 'bearer' : 'none',
|
|
336
|
+
timeoutMs: clampInt(src.timeoutMs, 5_000, MAX_TIMEOUT_MS, DEFAULT_TIMEOUT_MS),
|
|
337
|
+
formats,
|
|
338
|
+
maxBytes: clampInt(src.maxBytes, 1_024, MAX_BYTES_LIMIT, 50 * 1024 * 1024),
|
|
339
|
+
maxPages: clampInt(src.maxPages, 1, src.vendor === 'deepseek' ? 1000 : 300, src.vendor === 'deepseek' ? 1000 : 40),
|
|
340
|
+
enabled: src.enabled !== false,
|
|
341
|
+
notes: typeof src.notes === 'string' ? src.notes.slice(0, 300) : '',
|
|
342
|
+
updatedAt: extra.now ?? nowIso(),
|
|
343
|
+
}
|
|
344
|
+
if (value.renderCommand && !/python(?:\d+(?:\.\d+)*)?(?:\.exe)?$/i.test(path.basename(value.renderCommand))) value.renderCommand = path.join(value.renderCommand, 'Scripts', 'python.exe')
|
|
345
|
+
if (value.ffmpegCommand && !/^ffmpeg(?:\.exe)?$/i.test(path.basename(value.ffmpegCommand))) value.ffmpegCommand = path.join(value.ffmpegCommand, 'ffmpeg.exe')
|
|
346
|
+
if (['qwen3-local', 'paddle-local', 'paddle-service', 'ppocr-local'].includes(protocol)) {
|
|
347
|
+
if (!path.isAbsolute(command) || !/python(?:\d+(?:\.\d+)*)?(?:\.exe)?$/i.test(path.basename(command))) errors.push({ field: 'command', message: '本地适配器需要 Python 可执行文件绝对路径' })
|
|
348
|
+
if (['qwen3-local', 'paddle-local'].includes(protocol) && !path.isAbsolute(value.modelPath)) errors.push({ field: 'modelPath', message: '请选择模型绝对路径' })
|
|
349
|
+
if (['paddle-local', 'paddle-service'].includes(protocol) && !path.isAbsolute(value.layoutModelPath || '')) errors.push({ field: 'layoutModelPath', message: '请选择 PP-DocLayoutV3 版面模型目录' })
|
|
350
|
+
if (protocol === 'ppocr-local' && (!path.isAbsolute(value.detModelPath) || !path.isAbsolute(value.recModelPath))) errors.push({ field: 'modelPath', message: '请选择配套的检测模型、识别模型目录' })
|
|
351
|
+
if (protocol === 'paddle-service') {
|
|
352
|
+
let hostname = ''
|
|
353
|
+
try { hostname = new URL(baseUrl).hostname } catch { /* normal validation below */ }
|
|
354
|
+
if (!['127.0.0.1', '[::1]'].includes(hostname)) errors.push({ field: 'baseUrl', message: '本地版面管线仅支持回环 IP 服务地址' })
|
|
355
|
+
}
|
|
356
|
+
if (locality !== 'local') errors.push({ field: 'locality', message: '本地适配器必须使用本机位置' })
|
|
357
|
+
}
|
|
358
|
+
// 标签必须与真实目标一致:locality=local/lan 而目标是公网域名 → 直接拒(不信自填标签)。
|
|
359
|
+
// 放在最后统一判,是为了让 id/kind/protocol 的错误先报出来(诊断顺序更直观)。
|
|
360
|
+
if (isHttp || protocol === 'cli-transcribe') {
|
|
361
|
+
const refusal = staticDestinationRefusal(value) ?? cliProgramRefusal(value)
|
|
362
|
+
if (refusal) errors.push({ field: protocol === 'cli-transcribe' ? 'command' : 'baseUrl', code: refusal.code, message: refusal.message })
|
|
363
|
+
}
|
|
364
|
+
return errors.length > 0 ? { ok: false, errors } : { ok: true, value }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 解析配置块(stateDir/config.json 的 parsing 字段)的总校验。 */
|
|
368
|
+
export function normalizeParsingConfig(raw) {
|
|
369
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
370
|
+
// Seed only unconfigured installations. Persisted provider lists/defaults and
|
|
371
|
+
// explicit local-only policies continue to be authoritative.
|
|
372
|
+
if (!Array.isArray(src.providers)) return normalizeParsingConfig({
|
|
373
|
+
...src,
|
|
374
|
+
providers: ['ocr', 'asr'].map(kind => ({ id: `deepseek-${kind}`, kind, vendor: 'deepseek', label: `DeepSeek ${kind.toUpperCase()}` })),
|
|
375
|
+
defaultOcr: 'deepseek-ocr', defaultAsr: 'deepseek-asr',
|
|
376
|
+
externalPolicy: src.externalPolicy ?? 'allow-configured',
|
|
377
|
+
})
|
|
378
|
+
const providers = []
|
|
379
|
+
const seen = new Set()
|
|
380
|
+
const errors = []
|
|
381
|
+
for (const item of Array.isArray(src.providers) ? src.providers : []) {
|
|
382
|
+
const n = normalizeProvider(item)
|
|
383
|
+
if (!n.ok) {
|
|
384
|
+
errors.push({ field: 'providers', code: 'BAD_PROVIDER', message: (item && item.id) || '(no id)', detail: n.errors })
|
|
385
|
+
continue
|
|
386
|
+
}
|
|
387
|
+
if (seen.has(n.value.id)) {
|
|
388
|
+
errors.push({ field: 'providers', code: 'DUPLICATE_ID', message: n.value.id })
|
|
389
|
+
continue
|
|
390
|
+
}
|
|
391
|
+
seen.add(n.value.id)
|
|
392
|
+
providers.push(n.value)
|
|
393
|
+
}
|
|
394
|
+
const pick = (kind, id) => {
|
|
395
|
+
if (typeof id !== 'string' || id.trim() === '') return null
|
|
396
|
+
const hit = providers.find((p) => p.id === id && p.kind === kind)
|
|
397
|
+
return hit ? hit.id : null
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
ok: errors.length === 0,
|
|
401
|
+
errors,
|
|
402
|
+
value: {
|
|
403
|
+
schemaVersion: PARSING_SCHEMA_VERSION,
|
|
404
|
+
externalPolicy: EXTERNAL_POLICIES.includes(src.externalPolicy) ? src.externalPolicy : 'local-only',
|
|
405
|
+
providers,
|
|
406
|
+
defaultOcr: pick('ocr', src.defaultOcr),
|
|
407
|
+
defaultAsr: pick('asr', src.defaultAsr),
|
|
408
|
+
},
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 对外展示用:绝不带凭据值,只带"有没有配"。 */
|
|
413
|
+
export function publicProvider(p) {
|
|
414
|
+
return {
|
|
415
|
+
vendor: p.vendor, region: p.region, workspaceId: p.workspaceId,
|
|
416
|
+
modelPath: p.modelPath, ffmpegCommand: p.ffmpegCommand,
|
|
417
|
+
layoutModelPath: p.layoutModelPath, detModelPath: p.detModelPath, recModelPath: p.recModelPath, dictionaryPath: p.dictionaryPath,
|
|
418
|
+
id: p.id,
|
|
419
|
+
kind: p.kind,
|
|
420
|
+
protocol: p.protocol,
|
|
421
|
+
label: p.label,
|
|
422
|
+
locality: p.locality,
|
|
423
|
+
model: p.model,
|
|
424
|
+
baseUrl: p.baseUrl,
|
|
425
|
+
command: p.command,
|
|
426
|
+
renderCommand: p.renderCommand || '',
|
|
427
|
+
args: Array.isArray(p.args) ? p.args : [],
|
|
428
|
+
credentialRef: p.credentialRef,
|
|
429
|
+
credentialConfigured: p.credentialRef === '' ? false : Boolean(process.env[p.credentialRef]),
|
|
430
|
+
authScheme: p.authScheme,
|
|
431
|
+
timeoutMs: p.timeoutMs,
|
|
432
|
+
formats: p.formats,
|
|
433
|
+
maxBytes: p.maxBytes,
|
|
434
|
+
maxPages: p.maxPages,
|
|
435
|
+
enabled: p.enabled,
|
|
436
|
+
notes: p.notes,
|
|
437
|
+
locale: p.locality === 'local' ? '本机' : p.locality === 'lan' ? '内网' : '云端',
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function providerConfigVersion(p) {
|
|
442
|
+
return sha12(Buffer.from(JSON.stringify({ ...p, updatedAt: undefined }), 'utf8'))
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function mimeOf(ext) {
|
|
446
|
+
const map = {
|
|
447
|
+
png: 'image/png',
|
|
448
|
+
jpg: 'image/jpeg',
|
|
449
|
+
jpeg: 'image/jpeg',
|
|
450
|
+
webp: 'image/webp',
|
|
451
|
+
bmp: 'image/bmp',
|
|
452
|
+
pdf: 'application/pdf',
|
|
453
|
+
wav: 'audio/wav',
|
|
454
|
+
mp3: 'audio/mpeg',
|
|
455
|
+
m4a: 'audio/mp4',
|
|
456
|
+
mp4: 'video/mp4',
|
|
457
|
+
flac: 'audio/flac',
|
|
458
|
+
ogg: 'audio/ogg',
|
|
459
|
+
aac: 'audio/aac',
|
|
460
|
+
}
|
|
461
|
+
return map[ext] ?? 'application/octet-stream'
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function listJobFiles(dir) {
|
|
465
|
+
try {
|
|
466
|
+
const names = await readdir(dir)
|
|
467
|
+
return names.filter((n) => n.endsWith('.json'))
|
|
468
|
+
} catch (error) {
|
|
469
|
+
if (error.code === 'ENOENT') return []
|
|
470
|
+
throw error
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* @param {object} deps
|
|
476
|
+
* @param {string} deps.stateDir profile 级状态目录(解析工作区与任务记录都在其下)
|
|
477
|
+
* @param {function} deps.log
|
|
478
|
+
* @param {function} deps.getCore 返回当前 core 实例
|
|
479
|
+
* @param {function} deps.getBinding 返回 {kbPath, kbId}(未绑定则 null)
|
|
480
|
+
* @param {function} [deps.lookup] DNS 解析器(默认 dns.promises.lookup)。**只给受控桩测试用**:
|
|
481
|
+
* 作用是让"域名解析到公网地址 → 发正文前拦下"可以被离线证明。
|
|
482
|
+
*/
|
|
483
|
+
export function createParsingService({ stateDir, log = () => {}, getCore, getBinding, lookup = null, credentialStore = null, nativeRequest = null, onEvent = () => {}, resourceRoot = null, jobStorage = createParseJobStorage() }) {
|
|
484
|
+
const resource = name => { if (!resourceRoot) throw Object.assign(new Error('Parsing helper resource root is required'), { code: 'RESOURCE_ROOT_REQUIRED' }); return path.join(resourceRoot, 'tools', name) }
|
|
485
|
+
const root = path.join(stateDir, 'parse')
|
|
486
|
+
const credentials = credentialStore || createParseCredentials(stateDir)
|
|
487
|
+
// nativeRequest is a transport fixture for offline tests; never exposed in settings.
|
|
488
|
+
const native = createNativeAdapter({ request: async (p, url, init, context) => {
|
|
489
|
+
const gate = await executionGate(p, context.conf)
|
|
490
|
+
if (!gate.ok) return gate
|
|
491
|
+
return (nativeRequest || requestJson)(p, url, init, { ...context, conf: gate.conf })
|
|
492
|
+
}, credentials })
|
|
493
|
+
const discovery = createParseDiscovery({
|
|
494
|
+
savedPaths: async () => (await readParsingConfig()).providers.flatMap(p => [p.modelPath, p.layoutModelPath, p.detModelPath, p.recModelPath, p.command && path.dirname(path.dirname(p.command)), p.ffmpegCommand && path.dirname(p.ffmpegCommand)]).filter(Boolean),
|
|
495
|
+
savedDeployments: async () => (await readParsingConfig()).providers.filter(p => p.locality === 'local'),
|
|
496
|
+
savedServices: async () => (await readParsingConfig()).providers.filter(p => p.locality === 'local' && p.baseUrl).map(p => p.baseUrl),
|
|
497
|
+
probe: async baseUrl => {
|
|
498
|
+
const p = { id: 'local-probe', protocol: 'openai-vision', locality: 'local', enabled: true, baseUrl }
|
|
499
|
+
const r = await requestJson(p, baseUrl + '/models', { method: 'GET' }, { conf: { externalPolicy: 'local-only' }, timeoutMs: 1500 })
|
|
500
|
+
return r.ok ? r.json.data?.find(m => /paddleocr.?vl/i.test(m.id))?.id : null
|
|
501
|
+
},
|
|
502
|
+
})
|
|
503
|
+
const environmentFile = p => path.join(root, 'validation', sha12(Buffer.from(p.id)) + '.json')
|
|
504
|
+
async function managedPublic(p) {
|
|
505
|
+
let environment = null
|
|
506
|
+
try { const saved = JSON.parse(await readFile(environmentFile(p), 'utf8')); if (saved.configVersion === providerConfigVersion(p)) environment = saved } catch { /* not checked */ }
|
|
507
|
+
return { ...publicProvider(p), configVersion: providerConfigVersion(p), credentialConfigured: await credentials.configured(p.credentialRef), environmentCheckedAt: environment?.ok ? environment.checkedAt : null }
|
|
508
|
+
}
|
|
509
|
+
const running = new Map() // jobId → {controller, child}
|
|
510
|
+
const providerLocks = new Map() // providerId → promise chain(本机提供方串行)
|
|
511
|
+
let recovered = false
|
|
512
|
+
const snapshotBinding = b => b?.kbId && b?.kbPath ? { kbId: b.kbId, kbPath: path.resolve(b.kbPath) } : null
|
|
513
|
+
const sameBinding = (a, b) => Boolean(a?.kbId && a?.kbPath && b?.kbPath && a.kbId === b.kbId && path.resolve(a.kbPath) === path.resolve(b.kbPath))
|
|
514
|
+
const bindingFailure = () => ({ ok: false, code: 'BINDING_CHANGED', detail: '知识库绑定已改变,旧任务已停止;请切回原库后重试,已有记录仍保存在原库任务目录' })
|
|
515
|
+
|
|
516
|
+
async function executionGate(provider, conf = {}) {
|
|
517
|
+
if (conf.executionBinding && !sameBinding(conf.executionBinding, await getBinding())) return bindingFailure()
|
|
518
|
+
const current = await readParsingConfig()
|
|
519
|
+
const effective = { ...conf, externalPolicy: conf.externalPolicy === 'local-only' || current.externalPolicy === 'local-only' ? 'local-only' : 'allow-configured' }
|
|
520
|
+
const refusal = policyRefusal(provider, effective)
|
|
521
|
+
return refusal ? { ok: false, code: refusal.code, detail: refusal.message } : { ok: true, conf: effective }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* 本机 GPU 提供方串行:两套模型不假设能同时常驻。
|
|
526
|
+
* 排队中的任务仍是 queued(stage=waiting-provider),可被取消;不静默终止别人的任务。
|
|
527
|
+
*/
|
|
528
|
+
async function withProviderLock(providerId, fn) {
|
|
529
|
+
const prev = providerLocks.get(providerId) ?? Promise.resolve()
|
|
530
|
+
let release
|
|
531
|
+
const gate = new Promise((resolve) => {
|
|
532
|
+
release = resolve
|
|
533
|
+
})
|
|
534
|
+
const chained = prev.then(() => gate)
|
|
535
|
+
providerLocks.set(providerId, chained)
|
|
536
|
+
await prev
|
|
537
|
+
try {
|
|
538
|
+
return await fn()
|
|
539
|
+
} finally {
|
|
540
|
+
release()
|
|
541
|
+
if (providerLocks.get(providerId) === chained) providerLocks.delete(providerId)
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const kbKeyOf = (binding) => (binding && binding.kbId ? String(binding.kbId).replace(/[^a-zA-Z0-9_-]/g, '') : 'unbound')
|
|
546
|
+
const kbDir = (binding) => path.join(root, kbKeyOf(binding))
|
|
547
|
+
const jobsDir = (binding) => path.join(kbDir(binding), 'jobs')
|
|
548
|
+
const resultsDir = (binding) => path.join(kbDir(binding), 'results')
|
|
549
|
+
const tmpDir = (binding) => path.join(kbDir(binding), 'tmp')
|
|
550
|
+
|
|
551
|
+
async function ensureDirs(binding) {
|
|
552
|
+
for (const d of [jobsDir(binding), resultsDir(binding), tmpDir(binding)]) await mkdir(d, { recursive: true })
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async function readParsingConfig() {
|
|
556
|
+
const core = getCore()
|
|
557
|
+
if (!core) return normalizeParsingConfig(null).value
|
|
558
|
+
const conf = await core.getConfig().catch(() => null)
|
|
559
|
+
return normalizeParsingConfig(conf ? conf.parsing : null).value
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function writeParsingConfig(next) {
|
|
563
|
+
const core = getCore()
|
|
564
|
+
if (!core) return { ok: false, reason: 'core-not-ready' }
|
|
565
|
+
const normalized = normalizeParsingConfig(next)
|
|
566
|
+
if (!normalized.ok) return { ok: false, reason: 'invalid-parsing-config', errors: normalized.errors }
|
|
567
|
+
const r = await core.setConfig({ parsing: normalized.value })
|
|
568
|
+
if (!r || r.ok !== true) return { ok: false, reason: (r && r.reason) || 'set-config-failed', detail: r && r.detail }
|
|
569
|
+
return { ok: true, revision: r.revision, parsing: normalized.value }
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ── 提供方管理(**仅管理面**)────────────────────────────────────────────
|
|
573
|
+
// 2026-10-18 定向审查缺口 2:提供方定义里含有"会执行什么程序""把正文发到哪个地址"
|
|
574
|
+
// "读哪个环境变量当凭据"。这些**不能由模型写**。因此四个写操作都要求 viaAdmin
|
|
575
|
+
// (只有宿主认可的用户管理入口 —— 设置页 HTTP 路由 —— 会传它)。模型工具即使
|
|
576
|
+
// 伪造 action 走到这里也只会拿到 ADMIN_ONLY。
|
|
577
|
+
const adminOnly = (op) => ({
|
|
578
|
+
ok: false,
|
|
579
|
+
reason: 'ADMIN_ONLY',
|
|
580
|
+
detail: `${op} 属于管理面操作(会改提供方程序/地址/凭据引用/外发策略),模型不能执行。`
|
|
581
|
+
+ '请在「设置 → 个人知识库 → 解析」里改;模型侧只能在一个已配置好的提供方上提交解析。',
|
|
582
|
+
})
|
|
583
|
+
|
|
584
|
+
async function providersPublic() {
|
|
585
|
+
const conf = await readParsingConfig()
|
|
586
|
+
const history = await listJobs({ limit: JOBS_KEPT })
|
|
587
|
+
const providers = await Promise.all(conf.providers.map(async p => {
|
|
588
|
+
const matching = history.jobs?.filter(j => j.provider.id === p.id && j.provider.configVersion === providerConfigVersion(p)).sort((a,b) => String(b.finishedAt||b.createdAt).localeCompare(String(a.finishedAt||a.createdAt))) || []
|
|
589
|
+
const verified = matching.find(j => j.status === 'succeeded')
|
|
590
|
+
const active = matching.find(j => ['queued', 'running'].includes(j.status))
|
|
591
|
+
return { ...await managedPublic(p), parseVerifiedAt: verified?.finishedAt || null, label: p.label.replace(/(待补齐)|待验证/g, ''), activeJob: active ? { jobId: active.jobId, status: active.status } : null, lastError: null }
|
|
592
|
+
}))
|
|
593
|
+
return {
|
|
594
|
+
ok: true,
|
|
595
|
+
externalPolicy: conf.externalPolicy,
|
|
596
|
+
defaultOcr: conf.defaultOcr,
|
|
597
|
+
defaultAsr: conf.defaultAsr,
|
|
598
|
+
providers,
|
|
599
|
+
protocols: PARSE_PROTOCOLS,
|
|
600
|
+
locality: LOCALITY,
|
|
601
|
+
// 让调用方知道"这些动作不在模型工具里",而不是以为工具坏了
|
|
602
|
+
adminActions: ['save-provider', 'delete-provider', 'default', 'policy'],
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
async function saveProvider(input, { viaAdmin = false, credentialInput = null, clearCredential = false } = {}) {
|
|
607
|
+
if (viaAdmin !== true) return adminOnly('保存提供方')
|
|
608
|
+
const conf = await readParsingConfig()
|
|
609
|
+
input = { ...input }
|
|
610
|
+
if (!input.id) input.id = `${input.kind || 'ocr'}-${randomUUID().slice(0, 12)}`
|
|
611
|
+
const old = conf.providers.find(p => p.id === input.id)
|
|
612
|
+
if (clearCredential) input.credentialRef = ''
|
|
613
|
+
else if (credentialInput?.apiKey?.trim()) {
|
|
614
|
+
// Validate the provider before storing any credential.
|
|
615
|
+
const pre = normalizeProvider(input)
|
|
616
|
+
if (!pre.ok) return { ok: false, reason: 'invalid-provider', errors: pre.errors }
|
|
617
|
+
if (pre.value.vendor === 'baidu' && !credentialInput.secretKey?.trim()) return { ok: false, reason: 'SECRET_KEY_REQUIRED' }
|
|
618
|
+
input.credentialRef = await credentials.save(credentialInput)
|
|
619
|
+
input.authScheme = 'bearer'
|
|
620
|
+
} else if (input.credentialRef === undefined && old) input.credentialRef = old.credentialRef
|
|
621
|
+
const norm = normalizeProvider(input)
|
|
622
|
+
if (!norm.ok) return { ok: false, reason: 'invalid-provider', errors: norm.errors }
|
|
623
|
+
const next = { ...conf, providers: conf.providers.map((p) => ({ ...p })) }
|
|
624
|
+
const at = next.providers.findIndex((p) => p.id === norm.value.id)
|
|
625
|
+
if (at >= 0) {
|
|
626
|
+
if (next.providers[at].kind !== norm.value.kind) {
|
|
627
|
+
return { ok: false, reason: 'kind-immutable', detail: '同一 id 不能改 kind(ocr/asr),请新建一个提供方' }
|
|
628
|
+
}
|
|
629
|
+
next.providers[at] = norm.value
|
|
630
|
+
} else {
|
|
631
|
+
next.providers.push(norm.value)
|
|
632
|
+
}
|
|
633
|
+
if (norm.value.locality !== 'cloud' && norm.value.kind === 'ocr' && next.defaultOcr === null) next.defaultOcr = norm.value.id
|
|
634
|
+
if (norm.value.locality !== 'cloud' && norm.value.kind === 'asr' && next.defaultAsr === null) next.defaultAsr = norm.value.id
|
|
635
|
+
const written = await writeParsingConfig(next)
|
|
636
|
+
if (!written.ok) return written
|
|
637
|
+
log('info', `解析提供方已保存 ${norm.value.id}(${norm.value.kind}/${norm.value.protocol}/${norm.value.locality})`)
|
|
638
|
+
return { ok: true, provider: await managedPublic(norm.value), revision: written.revision, defaults: { ocr: written.parsing.defaultOcr, asr: written.parsing.defaultAsr } }
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
async function deleteProvider(id, { viaAdmin = false } = {}) {
|
|
642
|
+
if (viaAdmin !== true) return adminOnly('删除提供方')
|
|
643
|
+
const conf = await readParsingConfig()
|
|
644
|
+
const hit = conf.providers.find((p) => p.id === id)
|
|
645
|
+
if (!hit) return { ok: false, reason: 'not-found', detail: '没有这个提供方' }
|
|
646
|
+
const next = {
|
|
647
|
+
...conf,
|
|
648
|
+
providers: conf.providers.filter((p) => p.id !== id),
|
|
649
|
+
defaultOcr: conf.defaultOcr === id ? null : conf.defaultOcr,
|
|
650
|
+
defaultAsr: conf.defaultAsr === id ? null : conf.defaultAsr,
|
|
651
|
+
}
|
|
652
|
+
const written = await writeParsingConfig(next)
|
|
653
|
+
if (!written.ok) return written
|
|
654
|
+
return { ok: true, removed: id, defaults: { ocr: written.parsing.defaultOcr, asr: written.parsing.defaultAsr } }
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
async function setDefaults({ kind, id }, { viaAdmin = false } = {}) {
|
|
658
|
+
if (viaAdmin !== true) return adminOnly('设置默认提供方')
|
|
659
|
+
if (!PARSE_KINDS.includes(kind)) return { ok: false, reason: 'bad-kind' }
|
|
660
|
+
const conf = await readParsingConfig()
|
|
661
|
+
if (id !== null && id !== '') {
|
|
662
|
+
const hit = conf.providers.find((p) => p.id === id && p.kind === kind)
|
|
663
|
+
if (!hit) return { ok: false, reason: 'not-found', detail: `没有 ${kind} 提供方 ${id}` }
|
|
664
|
+
}
|
|
665
|
+
const next = { ...conf, defaultOcr: kind === 'ocr' ? (id || null) : conf.defaultOcr, defaultAsr: kind === 'asr' ? (id || null) : conf.defaultAsr }
|
|
666
|
+
const written = await writeParsingConfig(next)
|
|
667
|
+
if (!written.ok) return written
|
|
668
|
+
return { ok: true, defaults: { ocr: written.parsing.defaultOcr, asr: written.parsing.defaultAsr } }
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
async function setPolicy(policy, { viaAdmin = false } = {}) {
|
|
672
|
+
if (viaAdmin !== true) return adminOnly('修改外发策略')
|
|
673
|
+
if (!EXTERNAL_POLICIES.includes(policy)) return { ok: false, reason: 'bad-policy', detail: `可用:${EXTERNAL_POLICIES.join(' / ')}` }
|
|
674
|
+
const conf = await readParsingConfig()
|
|
675
|
+
const written = await writeParsingConfig({ ...conf, externalPolicy: policy })
|
|
676
|
+
if (!written.ok) return written
|
|
677
|
+
return { ok: true, externalPolicy: written.parsing.externalPolicy }
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* 策略闸门(**同步部分**):只做能静态判定的拒绝。
|
|
682
|
+
* · local-only 下云提供方一律拒绝;
|
|
683
|
+
* · 停用的拒绝;
|
|
684
|
+
* · locality 标签与目标不一致(公网域名自称 local)拒绝 —— 这一条不看策略,
|
|
685
|
+
* 因为"标签说谎"在任何策略下都不是可接受的配置。
|
|
686
|
+
* 真正发请求前还会做 DNS/IP 复核(asyncDestinationRefusal),那一步才是"发正文之前"的最后一道。
|
|
687
|
+
*/
|
|
688
|
+
function policyRefusal(provider, conf) {
|
|
689
|
+
if (provider.locality === 'cloud' && conf.externalPolicy === 'local-only') {
|
|
690
|
+
return {
|
|
691
|
+
code: 'LOCAL_ONLY_BLOCKED',
|
|
692
|
+
message: `当前策略是 local-only:禁止把原件送去云端提供方 ${provider.id}。改用本机/内网提供方,或由管理员显式改为 allow-configured。`,
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (provider.enabled !== true) return { code: 'PROVIDER_DISABLED', message: `提供方 ${provider.id} 已停用` }
|
|
696
|
+
const mismatch = staticDestinationRefusal(provider)
|
|
697
|
+
if (mismatch) return mismatch
|
|
698
|
+
const cli = cliProgramRefusal(provider)
|
|
699
|
+
if (cli) return cli
|
|
700
|
+
return null
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function pickProvider(conf, kind, providerId) {
|
|
704
|
+
const wanted = typeof providerId === 'string' && providerId !== '' ? providerId : kind === 'ocr' ? conf.defaultOcr : conf.defaultAsr
|
|
705
|
+
if (!wanted) {
|
|
706
|
+
return { error: { code: 'NO_DEFAULT_PROVIDER', message: `未配置 ${kind.toUpperCase()} 默认提供方:请先在设置页添加并设为默认` } }
|
|
707
|
+
}
|
|
708
|
+
const hit = conf.providers.find((p) => p.id === wanted && p.kind === kind)
|
|
709
|
+
if (!hit) return { error: { code: 'PROVIDER_NOT_FOUND', message: `没有 ${kind} 提供方 ${wanted}` } }
|
|
710
|
+
const refused = policyRefusal(hit, conf)
|
|
711
|
+
if (refused) return { error: refused }
|
|
712
|
+
return { provider: hit }
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// ── HTTP / CLI 适配器 ───────────────────────────────────────────────────
|
|
716
|
+
async function authHeaders(provider, diagnostics) {
|
|
717
|
+
const headers = {}
|
|
718
|
+
if (provider.credentialRef === '' || provider.authScheme === 'none') return headers
|
|
719
|
+
const value = (await credentials.read(provider.credentialRef)).apiKey
|
|
720
|
+
if (!value) {
|
|
721
|
+
diagnostics.push({ code: 'MISSING_CREDENTIAL', message: `提供方 ${provider.id} 引用的凭据 ${provider.credentialRef} 在宿主环境里没有值` })
|
|
722
|
+
throw Object.assign(new Error('MISSING_CREDENTIAL'), { code: 'MISSING_CREDENTIAL' })
|
|
723
|
+
}
|
|
724
|
+
headers.Authorization = `Bearer ${value}`
|
|
725
|
+
return headers
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function mergeSignals(signals) {
|
|
729
|
+
const list = signals.filter(Boolean)
|
|
730
|
+
if (list.length === 0) return undefined
|
|
731
|
+
if (list.length === 1) return list[0]
|
|
732
|
+
const controller = new AbortController()
|
|
733
|
+
const onAbort = (s) => () => controller.abort(s.reason ?? new Error('aborted'))
|
|
734
|
+
for (const s of list) {
|
|
735
|
+
if (s.aborted) {
|
|
736
|
+
controller.abort(s.reason)
|
|
737
|
+
break
|
|
738
|
+
}
|
|
739
|
+
s.addEventListener('abort', onAbort(s), { once: true })
|
|
740
|
+
}
|
|
741
|
+
return controller.signal
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* 真实目标复核(**发正文之前**的最后一道,2026-10-18 审查缺口 1)。
|
|
746
|
+
* 把目标域名解析成全部地址,只要出现公网地址:
|
|
747
|
+
* · local-only → 直接拒绝(无论 locality 标签怎么写);
|
|
748
|
+
* · locality 不是 cloud → 判为标签与事实不符,拒绝。
|
|
749
|
+
* 通过时返回**已核对的那个地址**,连接期用它直接建连(不再二次查 DNS),
|
|
750
|
+
* 于是"解析完再被换成别的地址"这条路走不通。
|
|
751
|
+
*/
|
|
752
|
+
async function checkTarget(urlString, provider, conf) {
|
|
753
|
+
if (provider.protocol === 'cli-transcribe') return { ok: true, pinned: null }
|
|
754
|
+
let url
|
|
755
|
+
try {
|
|
756
|
+
url = new URL(String(urlString))
|
|
757
|
+
} catch {
|
|
758
|
+
return { ok: false, code: 'BAD_URL', detail: '目标地址不合法:' + String(urlString) }
|
|
759
|
+
}
|
|
760
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
761
|
+
return { ok: false, code: 'BAD_URL', detail: '只支持 http(s) 目标:' + String(urlString) }
|
|
762
|
+
}
|
|
763
|
+
const host = url.hostname.replace(/^\[|\]$/g, '')
|
|
764
|
+
let rows
|
|
765
|
+
try {
|
|
766
|
+
rows = await resolveHost(host, lookup)
|
|
767
|
+
} catch (error) {
|
|
768
|
+
return { ok: false, code: 'DNS_FAILED', detail: `解析 ${host} 失败:${errText(error)}` }
|
|
769
|
+
}
|
|
770
|
+
const usable = rows.filter((r) => r && typeof r.address === 'string' && net.isIP(r.address) !== 0)
|
|
771
|
+
if (usable.length === 0) return { ok: false, code: 'DNS_NO_ADDRESS', detail: `解析 ${host} 没有得到可用地址` }
|
|
772
|
+
const publicRows = usable.filter((r) => classifyAddress(r.address) === 'public')
|
|
773
|
+
if (publicRows.length > 0) {
|
|
774
|
+
const sample = publicRows[0].address
|
|
775
|
+
if (conf.externalPolicy === 'local-only') {
|
|
776
|
+
return {
|
|
777
|
+
ok: false,
|
|
778
|
+
code: 'LOCAL_ONLY_DESTINATION_BLOCKED',
|
|
779
|
+
detail: `local-only:${host} 解析到公网地址 ${sample},请求在发送正文之前被拦下(提供方 ${provider.id},标签 locality=${provider.locality} 不作数)`,
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
if (provider.locality !== 'cloud') {
|
|
783
|
+
return {
|
|
784
|
+
ok: false,
|
|
785
|
+
code: 'LOCALITY_MISMATCH',
|
|
786
|
+
detail: `提供方 ${provider.id} 声明 locality=${provider.locality},但 ${host} 解析到公网地址 ${sample}:标签与真实目标不一致,拒绝发送。`,
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
const chosen = usable[0]
|
|
791
|
+
const family = Number(chosen.family) || net.isIP(chosen.address)
|
|
792
|
+
return { ok: true, pinned: { address: chosen.address, family } }
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* 单跳 HTTP:**固定连到已核对的地址**(连接期不再查 DNS)。
|
|
797
|
+
* 不用全局 fetch —— 它没法钉住解析结果,"先查再连"之间仍可能被换掉。
|
|
798
|
+
*/
|
|
799
|
+
function httpOnce({ url, method, headers, body, timeoutMs, signal, pinned }) {
|
|
800
|
+
return new Promise((resolve) => {
|
|
801
|
+
let u
|
|
802
|
+
try {
|
|
803
|
+
u = new URL(String(url))
|
|
804
|
+
} catch {
|
|
805
|
+
resolve({ ok: false, code: 'BAD_URL', detail: '目标地址不合法' })
|
|
806
|
+
return
|
|
807
|
+
}
|
|
808
|
+
const isHttps = u.protocol === 'https:'
|
|
809
|
+
const mod = isHttps ? https : http
|
|
810
|
+
const rawHost = u.hostname.replace(/^\[|\]$/g, '')
|
|
811
|
+
const family = pinned !== null ? Number(pinned.family) || net.isIP(pinned.address) : 0
|
|
812
|
+
const lookupFn = (hostname, options, cb) => {
|
|
813
|
+
const address = pinned !== null ? pinned.address : hostname
|
|
814
|
+
if (options !== null && typeof options === 'object' && options.all === true) cb(null, [{ address, family }])
|
|
815
|
+
else cb(null, address, family)
|
|
816
|
+
}
|
|
817
|
+
const payload = body === undefined || body === null ? null : Buffer.isBuffer(body) ? body : Buffer.from(String(body))
|
|
818
|
+
const outHeaders = { ...(headers ?? {}) }
|
|
819
|
+
if (payload !== null) outHeaders['content-length'] = String(payload.length)
|
|
820
|
+
let settled = false
|
|
821
|
+
let timer = null
|
|
822
|
+
const onAbort = () => {
|
|
823
|
+
try {
|
|
824
|
+
req.destroy(Object.assign(new Error('已取消'), { code: 'CANCELED' }))
|
|
825
|
+
} catch {
|
|
826
|
+
/* ignore */
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const finish = (value) => {
|
|
830
|
+
if (settled) return
|
|
831
|
+
settled = true
|
|
832
|
+
if (timer !== null) clearTimeout(timer)
|
|
833
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
834
|
+
resolve(value)
|
|
835
|
+
}
|
|
836
|
+
let req
|
|
837
|
+
try {
|
|
838
|
+
req = mod.request({
|
|
839
|
+
protocol: u.protocol,
|
|
840
|
+
hostname: rawHost,
|
|
841
|
+
port: u.port !== '' ? Number(u.port) : isHttps ? 443 : 80,
|
|
842
|
+
path: (u.pathname === '' ? '/' : u.pathname) + (u.search ?? ''),
|
|
843
|
+
method: method ?? 'GET',
|
|
844
|
+
headers: outHeaders,
|
|
845
|
+
lookup: lookupFn,
|
|
846
|
+
servername: isHttps && net.isIP(rawHost) === 0 ? rawHost : undefined,
|
|
847
|
+
timeout: timeoutMs,
|
|
848
|
+
})
|
|
849
|
+
} catch (error) {
|
|
850
|
+
finish({ ok: false, code: 'NETWORK_ERROR', detail: errText(error) })
|
|
851
|
+
return
|
|
852
|
+
}
|
|
853
|
+
timer = setTimeout(() => {
|
|
854
|
+
try {
|
|
855
|
+
req.destroy(Object.assign(new Error('PARSE_TIMEOUT'), { code: 'PARSE_TIMEOUT' }))
|
|
856
|
+
} catch {
|
|
857
|
+
/* ignore */
|
|
858
|
+
}
|
|
859
|
+
}, timeoutMs)
|
|
860
|
+
if (signal) {
|
|
861
|
+
if (signal.aborted) onAbort()
|
|
862
|
+
else signal.addEventListener('abort', onAbort, { once: true })
|
|
863
|
+
}
|
|
864
|
+
req.on('response', (res) => {
|
|
865
|
+
const chunks = []
|
|
866
|
+
let total = 0
|
|
867
|
+
res.on('data', (chunk) => {
|
|
868
|
+
total += chunk.length
|
|
869
|
+
if (total > 32 * 1024 * 1024) {
|
|
870
|
+
finish({ ok: false, code: 'RESPONSE_TOO_LARGE', detail: '响应超过 32MB,已中止' })
|
|
871
|
+
try {
|
|
872
|
+
req.destroy()
|
|
873
|
+
} catch {
|
|
874
|
+
/* ignore */
|
|
875
|
+
}
|
|
876
|
+
return
|
|
877
|
+
}
|
|
878
|
+
chunks.push(chunk)
|
|
879
|
+
})
|
|
880
|
+
res.on('end', () => {
|
|
881
|
+
finish({
|
|
882
|
+
ok: true,
|
|
883
|
+
status: Number(res.statusCode) || 0,
|
|
884
|
+
headers: res.headers,
|
|
885
|
+
buffer: Buffer.concat(chunks),
|
|
886
|
+
})
|
|
887
|
+
})
|
|
888
|
+
res.on('error', (error) => finish({ ok: false, code: 'NETWORK_ERROR', detail: errText(error) }))
|
|
889
|
+
})
|
|
890
|
+
req.on('timeout', () => {
|
|
891
|
+
try {
|
|
892
|
+
req.destroy(Object.assign(new Error('PARSE_TIMEOUT'), { code: 'PARSE_TIMEOUT' }))
|
|
893
|
+
} catch {
|
|
894
|
+
/* ignore */
|
|
895
|
+
}
|
|
896
|
+
})
|
|
897
|
+
req.on('error', (error) => {
|
|
898
|
+
const code = (error && error.code) || 'NETWORK_ERROR'
|
|
899
|
+
finish({ ok: false, code: code === 'ABORT_ERR' ? 'CANCELED' : code, detail: errText(error) })
|
|
900
|
+
})
|
|
901
|
+
if (payload !== null) req.write(payload)
|
|
902
|
+
req.end()
|
|
903
|
+
})
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* 固定请求器:手动处理重定向,每一跳都重新核目标。
|
|
908
|
+
* 规则:
|
|
909
|
+
* · 跨源重定向在 local-only / 非 cloud 提供方下一律拒绝(不允许"服务端一句话把请求带去别处");
|
|
910
|
+
* · 换源时**不转发正文**(301/302/303 转 GET;307/308 跨源直接拒绝)——否则等于把原件送去别处;
|
|
911
|
+
* · 每一跳都做 checkTarget:DNS 在这段时间里被改掉也拦得住。
|
|
912
|
+
*/
|
|
913
|
+
async function requestJson(provider, url, init, { signal, timeoutMs, conf }) {
|
|
914
|
+
const controller = new AbortController()
|
|
915
|
+
const timer = setTimeout(() => controller.abort(Object.assign(new Error('PARSE_TIMEOUT'), { code: 'PARSE_TIMEOUT' })), timeoutMs)
|
|
916
|
+
const merged = mergeSignals([signal, controller.signal])
|
|
917
|
+
try {
|
|
918
|
+
let target = url
|
|
919
|
+
let method = init.method ?? 'GET'
|
|
920
|
+
let body = init.body
|
|
921
|
+
let headers = init.headers ?? {}
|
|
922
|
+
for (let hop = 0; hop < 4; hop++) {
|
|
923
|
+
const gate = await executionGate(provider, conf)
|
|
924
|
+
if (!gate.ok) return gate
|
|
925
|
+
conf = gate.conf
|
|
926
|
+
const checked = await checkTarget(target, provider, conf)
|
|
927
|
+
if (checked.ok !== true) return { ok: false, code: checked.code, detail: checked.detail }
|
|
928
|
+
// DNS may have waited while the user disabled cloud processing.
|
|
929
|
+
const beforeSend = await executionGate(provider, conf)
|
|
930
|
+
if (!beforeSend.ok) return beforeSend
|
|
931
|
+
conf = beforeSend.conf
|
|
932
|
+
const sameOriginAsStart = new URL(target).origin === new URL(url).origin
|
|
933
|
+
const res = await httpOnce({
|
|
934
|
+
url: target,
|
|
935
|
+
method,
|
|
936
|
+
headers,
|
|
937
|
+
body: sameOriginAsStart ? body : null,
|
|
938
|
+
timeoutMs,
|
|
939
|
+
signal: merged,
|
|
940
|
+
pinned: checked.pinned,
|
|
941
|
+
})
|
|
942
|
+
if (res.ok !== true) return res
|
|
943
|
+
const status = res.status
|
|
944
|
+
if (status >= 300 && status < 400) {
|
|
945
|
+
if (NATIVE_PROTOCOLS.includes(provider.protocol)) return { ok: false, code: 'REDIRECT_BLOCKED', detail: '原生服务不允许重定向凭据或原件' }
|
|
946
|
+
const loc = res.headers && res.headers.location ? String(res.headers.location) : ''
|
|
947
|
+
if (loc === '') return { ok: false, status, code: 'REDIRECT_WITHOUT_LOCATION', detail: '服务端返回重定向但没有 Location' }
|
|
948
|
+
let nextUrl
|
|
949
|
+
try {
|
|
950
|
+
nextUrl = new URL(loc, target)
|
|
951
|
+
} catch {
|
|
952
|
+
return { ok: false, status, code: 'BAD_REDIRECT', detail: 'Location 不是合法地址:' + loc }
|
|
953
|
+
}
|
|
954
|
+
const sameOrigin = nextUrl.origin === new URL(target).origin
|
|
955
|
+
if (!sameOrigin && (conf.externalPolicy === 'local-only' || provider.locality !== 'cloud')) {
|
|
956
|
+
return {
|
|
957
|
+
ok: false,
|
|
958
|
+
status,
|
|
959
|
+
code: 'REDIRECT_BLOCKED',
|
|
960
|
+
detail: `拒绝跨源重定向:${new URL(target).origin} → ${nextUrl.origin}(策略 ${conf.externalPolicy},提供方 locality=${provider.locality})`,
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (!sameOrigin) {
|
|
964
|
+
if (status === 307 || status === 308) {
|
|
965
|
+
return { ok: false, status, code: 'REDIRECT_BODY_BLOCKED', detail: '拒绝把请求正文转发到另一个源(307/308 跨源)' }
|
|
966
|
+
}
|
|
967
|
+
method = 'GET'
|
|
968
|
+
body = null
|
|
969
|
+
headers = Object.fromEntries(Object.entries(headers).filter(([k]) => !['content-type', 'authorization'].includes(k.toLowerCase())))
|
|
970
|
+
}
|
|
971
|
+
target = nextUrl.toString()
|
|
972
|
+
continue
|
|
973
|
+
}
|
|
974
|
+
const text = res.buffer.toString('utf8')
|
|
975
|
+
if (status < 200 || status >= 300) return { ok: false, status, code: 'HTTP_' + status, detail: '服务返回错误;请检查权限、额度、地域及输入格式' }
|
|
976
|
+
try {
|
|
977
|
+
return { ok: true, status, json: JSON.parse(text), rawLength: text.length }
|
|
978
|
+
} catch {
|
|
979
|
+
return { ok: false, status, code: 'BAD_JSON', detail: '服务未返回有效 JSON' }
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
return { ok: false, code: 'TOO_MANY_REDIRECTS', detail: '重定向超过 4 跳' }
|
|
983
|
+
} catch (error) {
|
|
984
|
+
const code = (error && error.code) || (error && error.name === 'AbortError' ? 'PARSE_TIMEOUT' : 'NETWORK_ERROR')
|
|
985
|
+
return { ok: false, code, detail: errText(error) }
|
|
986
|
+
} finally {
|
|
987
|
+
clearTimeout(timer)
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/** OCR:openai-vision —— 明确的 HTTP 协议(POST {baseUrl}/chat/completions + image_url data URI)。 */
|
|
992
|
+
async function ocrOneImage(provider, conf, imagePath, { signal, diagnostics }) {
|
|
993
|
+
if (NATIVE_PROTOCOLS.includes(provider.protocol)) {
|
|
994
|
+
const r = await native.image(provider, imagePath, mimeOf(path.extname(imagePath).slice(1)), { signal, timeoutMs: provider.timeoutMs, conf })
|
|
995
|
+
if (r.requestId) diagnostics.push({ code: 'PROVIDER_REQUEST', requestId: String(r.requestId), at: nowIso() })
|
|
996
|
+
return r
|
|
997
|
+
}
|
|
998
|
+
if (['paddle-local', 'paddle-service', 'ppocr-local'].includes(provider.protocol)) return localModel(provider, imagePath, { signal, diagnostics })
|
|
999
|
+
const buf = await readFile(imagePath)
|
|
1000
|
+
const ext = path.extname(imagePath).slice(1).toLowerCase()
|
|
1001
|
+
const b64 = buf.toString('base64')
|
|
1002
|
+
const body = {
|
|
1003
|
+
model: provider.model || 'ocr',
|
|
1004
|
+
messages: [
|
|
1005
|
+
{
|
|
1006
|
+
role: 'user',
|
|
1007
|
+
content: [
|
|
1008
|
+
{ type: 'text', text: '请识别图中的全部文字,按阅读顺序输出 Markdown;表格用 Markdown 表格。不要补充原文没有的内容。' },
|
|
1009
|
+
{ type: 'image_url', image_url: { url: `data:${mimeOf(ext)};base64,${b64}` } },
|
|
1010
|
+
],
|
|
1011
|
+
},
|
|
1012
|
+
],
|
|
1013
|
+
temperature: 0,
|
|
1014
|
+
max_tokens: 4096,
|
|
1015
|
+
}
|
|
1016
|
+
let headers
|
|
1017
|
+
try {
|
|
1018
|
+
headers = { 'content-type': 'application/json', ...await authHeaders(provider, diagnostics) }
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
return { ok: false, code: (error && error.code) || 'AUTH_ERROR', detail: errText(error) }
|
|
1021
|
+
}
|
|
1022
|
+
const r = await requestJson(provider, `${provider.baseUrl}/chat/completions`, { method: 'POST', headers, body: JSON.stringify(body) }, { signal, timeoutMs: provider.timeoutMs, conf })
|
|
1023
|
+
if (!r.ok) return { ok: false, code: r.code, detail: r.detail ?? '', status: r.status ?? null }
|
|
1024
|
+
const choice = r.json && Array.isArray(r.json.choices) ? r.json.choices[0] : null
|
|
1025
|
+
const text = choice && choice.message && typeof choice.message.content === 'string' ? choice.message.content : ''
|
|
1026
|
+
if (text.trim() === '') return { ok: false, code: 'EMPTY_TEXT', detail: '提供方返回 200 但正文为空(可能是纯图形页)' }
|
|
1027
|
+
return {
|
|
1028
|
+
ok: true,
|
|
1029
|
+
text,
|
|
1030
|
+
usage: r.json && r.json.usage ? { promptTokens: r.json.usage.prompt_tokens ?? null, completionTokens: r.json.usage.completion_tokens ?? null, source: 'provider' } : null,
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** 用随包固定脚本把 PDF 拆成逐页 PNG(并读出文字层,文本页可跳过 OCR)。 */
|
|
1035
|
+
async function renderPdfPages(provider, pdfPath, outDir, { signal, maxPages, onChild }) {
|
|
1036
|
+
const python = provider.renderCommand || provider.command
|
|
1037
|
+
const posixPython = process.platform !== 'win32' && path.isAbsolute(python || '') && /^python(?:\d+(?:\.\d+)*)?$/.test(path.basename(python || ''))
|
|
1038
|
+
if (!python || !/\.(exe|cmd|bat)$/i.test(python) && !posixPython) {
|
|
1039
|
+
return { ok: false, code: 'NO_RENDERER', detail: 'PDF 需要提供方配置 renderCommand 指向固定 Python 可执行文件(如本机 ocr-venv 的 python.exe)' }
|
|
1040
|
+
}
|
|
1041
|
+
await mkdir(outDir, { recursive: true })
|
|
1042
|
+
// 子进程管道下 Python 的 stdout 用本地 ANSI 代码页(中文 Windows 上是 GBK),
|
|
1043
|
+
// 而本模块按 UTF-8 解码;不加 -X utf8 时含中文的路径会变成乱码,文件读不到。
|
|
1044
|
+
// 本文件其他 Python 调用都带 -X utf8,这里必须与它们一致。
|
|
1045
|
+
const args = ['-X', 'utf8', resource('kb-pdf-pages.py'), '--pdf', pdfPath, '--outdir', outDir, '--dpi', '150', '--max-pages', String(maxPages)]
|
|
1046
|
+
const r = await runChild(python, args, { signal, timeoutMs: 300_000, onChild })
|
|
1047
|
+
if (!r.ok) return { ok: false, code: r.code || 'RENDER_FAILED', detail: (r.stderr || r.stdout || '').slice(-800) }
|
|
1048
|
+
try {
|
|
1049
|
+
const parsed = JSON.parse(r.stdout.trim().split('\n').pop())
|
|
1050
|
+
return { ok: true, pages: parsed.pages ?? [], pageCount: parsed.pageCount ?? 0, truncated: parsed.truncated === true }
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
return { ok: false, code: 'RENDER_BAD_OUTPUT', detail: errText(error) + ' | ' + String(r.stdout).slice(0, 300) }
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function runChild(command, args, { signal, timeoutMs, cwd, onChild }) {
|
|
1057
|
+
return new Promise((resolve) => {
|
|
1058
|
+
let child
|
|
1059
|
+
try {
|
|
1060
|
+
// 环境最小化:只给生存必需项。凭据类变量一律不进子进程环境
|
|
1061
|
+
// (HTTP 提供方的凭据走 authHeaders,与子进程无关)。
|
|
1062
|
+
child = spawn(command, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: minimalChildEnv() })
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
resolve({ ok: false, code: 'SPAWN_FAILED', detail: errText(error) })
|
|
1065
|
+
return
|
|
1066
|
+
}
|
|
1067
|
+
if (typeof onChild === 'function') onChild(child)
|
|
1068
|
+
let stdout = ''
|
|
1069
|
+
let stderr = ''
|
|
1070
|
+
let settled = false
|
|
1071
|
+
const timer = setTimeout(() => {
|
|
1072
|
+
if (settled) return
|
|
1073
|
+
settled = true
|
|
1074
|
+
try {
|
|
1075
|
+
child.kill()
|
|
1076
|
+
} catch {
|
|
1077
|
+
/* ignore */
|
|
1078
|
+
}
|
|
1079
|
+
resolve({ ok: false, code: 'PARSE_TIMEOUT', detail: `子进程超过 ${timeoutMs}ms 未返回`, stdout, stderr })
|
|
1080
|
+
}, timeoutMs)
|
|
1081
|
+
const onAbort = () => {
|
|
1082
|
+
if (settled) return
|
|
1083
|
+
settled = true
|
|
1084
|
+
clearTimeout(timer)
|
|
1085
|
+
try {
|
|
1086
|
+
child.kill()
|
|
1087
|
+
} catch {
|
|
1088
|
+
/* ignore */
|
|
1089
|
+
}
|
|
1090
|
+
resolve({ ok: false, code: 'CANCELED', detail: '已取消', stdout, stderr })
|
|
1091
|
+
}
|
|
1092
|
+
if (signal) {
|
|
1093
|
+
if (signal.aborted) {
|
|
1094
|
+
onAbort()
|
|
1095
|
+
return
|
|
1096
|
+
}
|
|
1097
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1098
|
+
}
|
|
1099
|
+
child.stdout.on('data', (d) => {
|
|
1100
|
+
stdout += d.toString('utf8')
|
|
1101
|
+
if (stdout.length > 4_000_000) stdout = stdout.slice(-2_000_000)
|
|
1102
|
+
})
|
|
1103
|
+
child.stderr.on('data', (d) => {
|
|
1104
|
+
stderr += d.toString('utf8')
|
|
1105
|
+
if (stderr.length > 200_000) stderr = stderr.slice(-100_000)
|
|
1106
|
+
})
|
|
1107
|
+
child.on('error', (error) => {
|
|
1108
|
+
if (settled) return
|
|
1109
|
+
settled = true
|
|
1110
|
+
clearTimeout(timer)
|
|
1111
|
+
resolve({ ok: false, code: 'SPAWN_FAILED', detail: errText(error), stdout, stderr })
|
|
1112
|
+
})
|
|
1113
|
+
child.on('close', (code) => {
|
|
1114
|
+
if (settled) return
|
|
1115
|
+
settled = true
|
|
1116
|
+
clearTimeout(timer)
|
|
1117
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
1118
|
+
resolve(code === 0 ? { ok: true, code: 0, stdout, stderr } : { ok: false, code: 'EXIT_' + code, stdout, stderr })
|
|
1119
|
+
})
|
|
1120
|
+
})
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** ASR:cli-transcribe —— 固定程序 + 程序构造的参数(模型参数永不进入命令行)。 */
|
|
1124
|
+
async function asrViaCli(provider, audioPath, outDir, { signal, diagnostics, entry }) {
|
|
1125
|
+
const outFile = path.join(outDir, 'transcript.txt')
|
|
1126
|
+
const args = [...provider.args, audioPath, '--out', outFile]
|
|
1127
|
+
const r = await runChild(provider.command, args, { signal, timeoutMs: provider.timeoutMs, cwd: outDir, onChild: (c) => { entry.child = c } })
|
|
1128
|
+
if (!r.ok) return { ok: false, code: r.code, detail: (r.stderr || r.stdout || '').slice(-800) }
|
|
1129
|
+
let text
|
|
1130
|
+
try {
|
|
1131
|
+
text = await readFile(outFile, 'utf8')
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
return { ok: false, code: 'NO_TRANSCRIPT_FILE', detail: '转写程序没有生成预期输出文件:' + errText(error) }
|
|
1134
|
+
}
|
|
1135
|
+
if (text.trim() === '') return { ok: false, code: 'EMPTY_TEXT', detail: '转写结果为空' }
|
|
1136
|
+
return { ok: true, text, segments: parseAsrSegments(text) }
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* multipart/form-data 自己拼(不再用全局 FormData):
|
|
1141
|
+
* 因为它要跟着**已核对的固定连接**一起发出去,必须是一个字节串。
|
|
1142
|
+
*/
|
|
1143
|
+
function buildMultipart(fields, file) {
|
|
1144
|
+
const boundary = '----kbparse' + randomUUID().replace(/-/g, '')
|
|
1145
|
+
const parts = []
|
|
1146
|
+
for (const [name, value] of fields) {
|
|
1147
|
+
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`, 'utf8'))
|
|
1148
|
+
}
|
|
1149
|
+
if (file) {
|
|
1150
|
+
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${file.field}"; filename="${file.filename}"\r\nContent-Type: ${file.contentType}\r\n\r\n`, 'utf8'))
|
|
1151
|
+
parts.push(file.data)
|
|
1152
|
+
parts.push(Buffer.from('\r\n', 'utf8'))
|
|
1153
|
+
}
|
|
1154
|
+
parts.push(Buffer.from(`--${boundary}--\r\n`, 'utf8'))
|
|
1155
|
+
return { body: Buffer.concat(parts), contentType: `multipart/form-data; boundary=${boundary}` }
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** ASR:openai-audio-transcriptions —— 明确协议(multipart/form-data,字段 file/model)。 */
|
|
1159
|
+
async function asrViaHttp(provider, audioPath, { signal, diagnostics, conf }) {
|
|
1160
|
+
const buf = await readFile(audioPath)
|
|
1161
|
+
const ext = path.extname(audioPath).slice(1).toLowerCase()
|
|
1162
|
+
const fields = []
|
|
1163
|
+
if (provider.model) fields.push(['model', provider.model])
|
|
1164
|
+
fields.push(['response_format', 'json'])
|
|
1165
|
+
const form = buildMultipart(fields, {
|
|
1166
|
+
field: 'file',
|
|
1167
|
+
filename: path.basename(audioPath),
|
|
1168
|
+
contentType: mimeOf(ext),
|
|
1169
|
+
data: buf,
|
|
1170
|
+
})
|
|
1171
|
+
let headers
|
|
1172
|
+
try {
|
|
1173
|
+
headers = { 'content-type': form.contentType, ...await authHeaders(provider, diagnostics) }
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
return { ok: false, code: (error && error.code) || 'AUTH_ERROR', detail: errText(error) }
|
|
1176
|
+
}
|
|
1177
|
+
const r = await requestJson(provider, `${provider.baseUrl}/audio/transcriptions`, { method: 'POST', headers, body: form.body }, { signal, timeoutMs: provider.timeoutMs, conf })
|
|
1178
|
+
if (!r.ok) return { ok: false, code: r.code, detail: r.detail ?? '', status: r.status ?? null }
|
|
1179
|
+
const text = typeof r.json?.text === 'string' ? r.json.text : ''
|
|
1180
|
+
if (text.trim() === '') return { ok: false, code: 'EMPTY_TEXT', detail: '提供方返回 200 但 text 为空' }
|
|
1181
|
+
return { ok: true, text, segments: Array.isArray(r.json?.segments) ? mapHttpSegments(r.json.segments) : null, usage: r.json?.usage ?? null }
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/** 从本地转写文本里恢复分段位置(脚本自己写的【起–止 分钟】前缀,不伪造)。 */
|
|
1185
|
+
function parseAsrSegments(text) {
|
|
1186
|
+
const out = []
|
|
1187
|
+
const re = /【\s*([\d.]+)\s*[–\-—~]\s*([\d.]+)\s*分钟】([\s\S]*?)(?=【|$)/g
|
|
1188
|
+
let m
|
|
1189
|
+
while ((m = re.exec(text)) !== null) {
|
|
1190
|
+
const startSec = Math.round(Number(m[1]) * 60)
|
|
1191
|
+
const endSec = Math.round(Number(m[2]) * 60)
|
|
1192
|
+
out.push({ index: out.length, startSec, endSec, text: m[3].trim(), granularity: 'chunk' })
|
|
1193
|
+
}
|
|
1194
|
+
return out.length > 0 ? out : null
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
function mapHttpSegments(segments) {
|
|
1198
|
+
return segments.map((s, i) => ({
|
|
1199
|
+
index: i,
|
|
1200
|
+
startSec: Number.isFinite(Number(s.start)) ? Number(s.start) : null,
|
|
1201
|
+
endSec: Number.isFinite(Number(s.end)) ? Number(s.end) : null,
|
|
1202
|
+
text: typeof s.text === 'string' ? s.text : '',
|
|
1203
|
+
granularity: 'provider',
|
|
1204
|
+
}))
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// ── 任务记录 ────────────────────────────────────────────────────────────
|
|
1208
|
+
const jobPath = (binding, jobId) => path.join(jobsDir(binding), jobId + '.json')
|
|
1209
|
+
|
|
1210
|
+
async function readJob(jobId, bindingIn) {
|
|
1211
|
+
const candidates = []
|
|
1212
|
+
const binding = snapshotBinding(bindingIn || await getBinding())
|
|
1213
|
+
if (binding) candidates.push(jobPath(binding, jobId))
|
|
1214
|
+
if (candidates.length === 0) return null
|
|
1215
|
+
for (const p of candidates) {
|
|
1216
|
+
try {
|
|
1217
|
+
const job = await jobStorage.read(p)
|
|
1218
|
+
if (job.kbId !== binding.kbId || job.binding && !sameBinding(job.binding, binding)) return null
|
|
1219
|
+
return job
|
|
1220
|
+
} catch {
|
|
1221
|
+
continue
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
return null
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
const jobWriteChains = new Map()
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* 任务记录原子写。
|
|
1231
|
+
* Windows 上 `rename(tmp, file)` 在目标同时被另一个写者替换时会抛 EPERM,
|
|
1232
|
+
* 而心跳(5s)、进度回调、终态写会并发发生 → 必须按 jobId 串行,且 tmp 名唯一。
|
|
1233
|
+
*/
|
|
1234
|
+
async function writeJob(binding, job) {
|
|
1235
|
+
if (!binding || job.kbId !== binding.kbId || job.binding && !sameBinding(job.binding, binding)) throw Object.assign(new Error('拒绝把旧任务写入其他知识库的任务目录'), { code: 'JOB_BINDING_MISMATCH' })
|
|
1236
|
+
const key = job.jobId + '|' + kbKeyOf(binding)
|
|
1237
|
+
const prev = jobWriteChains.get(key) ?? Promise.resolve()
|
|
1238
|
+
let release
|
|
1239
|
+
const gate = new Promise((resolve) => {
|
|
1240
|
+
release = resolve
|
|
1241
|
+
})
|
|
1242
|
+
const chained = prev.then(() => gate)
|
|
1243
|
+
jobWriteChains.set(key, chained)
|
|
1244
|
+
await prev
|
|
1245
|
+
try {
|
|
1246
|
+
await ensureDirs(binding)
|
|
1247
|
+
const file = jobPath(binding, job.jobId)
|
|
1248
|
+
if (!job.source.external && job.result && ['succeeded','partial'].includes(job.status) && excludedSource(binding.kbPath, resolveAssetPath(binding.kbPath, job.source.relPath))) {
|
|
1249
|
+
const core = getCore()
|
|
1250
|
+
await core._internal.withMutationLock(binding.kbPath, async () => {
|
|
1251
|
+
const source = resolveAssetPath(binding.kbPath, job.source.relPath)
|
|
1252
|
+
if (!excludedSource(binding.kbPath, source)) return
|
|
1253
|
+
const rel = EXCLUDED_PARTITION + '/解析文件/' + job.jobId + '.md'
|
|
1254
|
+
const target = await safePath(binding.kbPath, rel, { missing: true })
|
|
1255
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
1256
|
+
const text = '---\nsource: ' + JSON.stringify(source) + '\n---\n\n' + String(job.result.plainText ?? job.result.text ?? '')
|
|
1257
|
+
const temp = target + '.' + randomUUID() + '.tmp'
|
|
1258
|
+
await writeFile(temp, text, { encoding: 'utf8', flag: 'wx' }); await rename(temp, target)
|
|
1259
|
+
await registerDerived(binding.kbPath, source, rel, '50-底稿/解析文件/' + job.jobId + '.md')
|
|
1260
|
+
job.materializedFile = rel
|
|
1261
|
+
})
|
|
1262
|
+
}
|
|
1263
|
+
try { await jobStorage.write(file, job) }
|
|
1264
|
+
catch (error) { throw Object.assign(error, { jobStateWriteFailed: true }) }
|
|
1265
|
+
try { onEvent({ type: 'parse-jobs-changed', kbId: binding.kbId, jobId: job.jobId }) } catch { /* subscriber cannot undo a durable write */ }
|
|
1266
|
+
return job
|
|
1267
|
+
} finally {
|
|
1268
|
+
release()
|
|
1269
|
+
if (jobWriteChains.get(key) === chained) jobWriteChains.delete(key)
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
const failureRecovery = () => ({
|
|
1274
|
+
automaticFallbackAllowed: false,
|
|
1275
|
+
requiresUserConfirmation: true,
|
|
1276
|
+
nextAction: 'ask-user',
|
|
1277
|
+
instruction: '解析已停止。向用户说明当前服务与具体错误,询问修复配置还是切换服务;得到本次明确同意前,不得使用本机模型、其他云端、脚本、HTTP 或记忆中的旧方案继续解析。切换默认服务须由用户在设置页操作。',
|
|
1278
|
+
})
|
|
1279
|
+
|
|
1280
|
+
function publicJob(job) {
|
|
1281
|
+
return {
|
|
1282
|
+
jobId: job.jobId,
|
|
1283
|
+
kind: job.kind,
|
|
1284
|
+
status: job.status,
|
|
1285
|
+
stage: job.stage,
|
|
1286
|
+
purpose: job.purpose,
|
|
1287
|
+
source: { relPath: job.source.relPath, external: job.source.external === true, sha256: job.source.sha256, bytes: job.source.bytes, format: job.source.format },
|
|
1288
|
+
provider: job.provider,
|
|
1289
|
+
progress: job.kind === 'asr' && ['partial', 'succeeded'].includes(job.status) && Array.isArray(job.result?.segments)
|
|
1290
|
+
? { ...job.progress, segmentsDone: job.result.segments.filter(s => s.status !== 'failed').length }
|
|
1291
|
+
: job.progress,
|
|
1292
|
+
attempts: job.attempts,
|
|
1293
|
+
maxAttempts: job.maxAttempts,
|
|
1294
|
+
createdAt: job.createdAt,
|
|
1295
|
+
startedAt: job.startedAt,
|
|
1296
|
+
heartbeatAt: job.heartbeatAt,
|
|
1297
|
+
finishedAt: job.finishedAt,
|
|
1298
|
+
cancelRequestedAt: job.cancelRequestedAt,
|
|
1299
|
+
result: job.result
|
|
1300
|
+
? {
|
|
1301
|
+
textChars: job.result.textChars,
|
|
1302
|
+
pageCount: job.result.pageCount,
|
|
1303
|
+
pages: job.result.pages?.map((p) => ({ page: p.page, chars: p.chars, method: p.method, status: p.status })) ?? [],
|
|
1304
|
+
segments: job.result.segments?.map((s) => ({ index: s.index, startSec: s.startSec, endSec: s.endSec, chars: (s.text ?? '').length, status: s.status || 'ok', granularity: s.granularity })) ?? [],
|
|
1305
|
+
method: job.result.method,
|
|
1306
|
+
usage: job.result.usage ?? null,
|
|
1307
|
+
unavailable: job.result.unavailable ?? [],
|
|
1308
|
+
}
|
|
1309
|
+
: null,
|
|
1310
|
+
partial: job.partial,
|
|
1311
|
+
failureDetails: parseFailureDetails(job),
|
|
1312
|
+
failureSummary: ['partial', 'failed'].includes(job.status) ? parseFailureSummary(job) : null,
|
|
1313
|
+
...(['partial', 'failed'].includes(job.status) ? { recovery: failureRecovery() } : {}),
|
|
1314
|
+
land: job.land,
|
|
1315
|
+
diagnostics: job.diagnostics,
|
|
1316
|
+
requestedBy: job.requestedBy,
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
function newJobId(kind) {
|
|
1321
|
+
const stamp = new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)
|
|
1322
|
+
return `${kind}-${stamp}-${randomUUID().slice(0, 8)}`
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
/** 源文件定位:必须在当前绑定库内(真实路径也在内),只读。 */
|
|
1326
|
+
async function resolveSource(sourceRel, bindingIn) {
|
|
1327
|
+
const binding = snapshotBinding(bindingIn || await getBinding())
|
|
1328
|
+
if (!binding || !binding.kbPath) return { ok: false, code: 'KB_UNBOUND', message: '知识库未绑定:先选择并绑定知识库文件夹' }
|
|
1329
|
+
const rel = resolveAssetPath(binding.kbPath, String(sourceRel ?? '').trim().replace(/\\/g, '/'))
|
|
1330
|
+
if (rel === '') return { ok: false, code: 'NO_SOURCE', message: '缺少 sourceRel(库内相对路径)' }
|
|
1331
|
+
if (path.posix.isAbsolute(rel) || rel.split('/').includes('..')) {
|
|
1332
|
+
return { ok: false, code: 'SOURCE_ESCAPE', message: 'sourceRel 必须是库内相对路径,且不能含 ..' }
|
|
1333
|
+
}
|
|
1334
|
+
const rootAbs = path.resolve(binding.kbPath)
|
|
1335
|
+
const abs = path.resolve(rootAbs, rel)
|
|
1336
|
+
const inside = (child, parent) => {
|
|
1337
|
+
const r = path.relative(parent, child)
|
|
1338
|
+
return r !== '' && !r.startsWith('..') && !path.isAbsolute(r)
|
|
1339
|
+
}
|
|
1340
|
+
if (!inside(abs, rootAbs)) return { ok: false, code: 'SOURCE_ESCAPE', message: '解析路径越出知识库根目录' }
|
|
1341
|
+
const followLinks = (await getCore()?.getConfig())?.followLinks === true
|
|
1342
|
+
const guard = await checkRealPath(rootAbs, abs, { followLinks })
|
|
1343
|
+
if (!guard.ok) return { ok: false, code: 'SOURCE_ESCAPE', message: '原件真实路径或目录联接不符合知识库访问规则:' + guard.detail }
|
|
1344
|
+
let st
|
|
1345
|
+
try {
|
|
1346
|
+
st = await stat(abs)
|
|
1347
|
+
} catch {
|
|
1348
|
+
return { ok: false, code: 'SOURCE_MISSING', message: '原件不存在:' + toPosix(rel) }
|
|
1349
|
+
}
|
|
1350
|
+
if (!st.isFile()) return { ok: false, code: 'SOURCE_NOT_FILE', message: '只支持单个文件原件' }
|
|
1351
|
+
return { ok: true, abs, rel: toPosix(rel), bytes: st.size, rootAbs }
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
async function jobSource(job, binding) {
|
|
1355
|
+
if (!job.source.external) return resolveSource(job.source.relPath, binding)
|
|
1356
|
+
if (!/^[a-f0-9-]{36}\.[a-z0-9]+$/.test(job.source.storedName || '')) return { ok: false, code: 'SOURCE_DENIED', message: '外部原件快照无效' }
|
|
1357
|
+
try {
|
|
1358
|
+
const abs = await safePath(kbDir(binding), 'sources/' + job.source.storedName), st = await stat(abs)
|
|
1359
|
+
return { ok: st.isFile(), abs, bytes: st.size }
|
|
1360
|
+
} catch { return { ok: false, code: 'SOURCE_MISSING', message: '外部原件快照不存在' } }
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
// ── 提交任务 ────────────────────────────────────────────────────────────
|
|
1364
|
+
async function submit(input, options = {}) {
|
|
1365
|
+
const binding = snapshotBinding(await getBinding()), requestId = randomUUID(), requestedBy = options.requestedBy || { via: 'unknown' }
|
|
1366
|
+
if (!binding) return { ok: false, requestId, reason: 'KB_UNBOUND', detail: '请先绑定知识库,以确定解析服务与记录归属' }
|
|
1367
|
+
const record = { requestId, kbId: binding.kbId, binding, kind: ['ocr', 'asr'].includes(input?.kind) ? input.kind : null, createdAt: nowIso(), status: 'submitted', requestedBy,
|
|
1368
|
+
source: { relPath: options.authorizedSource ? options.authorizedSource.name : String(input?.sourceRel || ''), external: Boolean(options.authorizedSource) } }
|
|
1369
|
+
const recordPath = path.join(kbDir(binding), 'requests', requestId + '.json')
|
|
1370
|
+
await atomicWriteJson(recordPath, record)
|
|
1371
|
+
let out
|
|
1372
|
+
try { out = await submitExecution(input, options) }
|
|
1373
|
+
catch (error) { out = { ok: false, reason: error.code || 'SUBMIT_FAILED', detail: error.message } }
|
|
1374
|
+
Object.assign(record, { status: out.ok ? out.deduped ? 'reused' : 'accepted' : 'rejected', jobId: out.jobId || null, reason: out.reason || null, detail: out.detail || null })
|
|
1375
|
+
try { await atomicWriteJson(recordPath, record) }
|
|
1376
|
+
catch (error) { out = { ...out, warning: '任务状态已返回,但提交记录更新失败;请凭任务编号查看任务。' }; log('warn', '解析提交记录更新失败:' + (error.code || 'write-error')) }
|
|
1377
|
+
onEvent({ type: 'parse-jobs-changed', kbId: binding.kbId })
|
|
1378
|
+
return { ...out, requestId, ...(!out.ok ? { recovery: failureRecovery() } : {}) }
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
async function recordRejection({ kind, requestedBy, failure }) {
|
|
1382
|
+
const binding = snapshotBinding(await getBinding()), requestId = randomUUID()
|
|
1383
|
+
if (!binding) return { requestId }
|
|
1384
|
+
// Unauthorized paths are deliberately not retained in rejection history.
|
|
1385
|
+
await atomicWriteJson(path.join(kbDir(binding), 'requests', requestId + '.json'), { requestId, kbId: binding.kbId, binding, kind: ['ocr', 'asr'].includes(kind) ? kind : null, createdAt: nowIso(), status: 'rejected', requestedBy, source: { relPath: '', external: true }, reason: failure.reason, detail: failure.detail, jobId: null })
|
|
1386
|
+
onEvent({ type: 'parse-jobs-changed', kbId: binding.kbId })
|
|
1387
|
+
return { requestId }
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
async function submitExecution(input, { requestedBy, authorizedSource } = {}) {
|
|
1391
|
+
const binding = snapshotBinding(await getBinding())
|
|
1392
|
+
if (!binding || !binding.kbId) return { ok: false, reason: 'KB_UNBOUND', detail: '知识库未绑定或未初始化' }
|
|
1393
|
+
const kindIn = String(input?.kind ?? '').trim()
|
|
1394
|
+
if (!PARSE_KINDS.includes(kindIn)) return { ok: false, reason: 'BAD_KIND', detail: 'kind 只能是 ocr 或 asr' }
|
|
1395
|
+
const conf = await readParsingConfig()
|
|
1396
|
+
// Caller provenance is supplied by the host, never by model arguments.
|
|
1397
|
+
// A remembered provider ID cannot override the user's current default.
|
|
1398
|
+
const toolDefault = requestedBy?.via === 'tool'
|
|
1399
|
+
const picked = pickProvider(conf, kindIn, toolDefault ? undefined : input?.providerId)
|
|
1400
|
+
if (picked.error) return { ok: false, reason: picked.error.code, detail: picked.error.message }
|
|
1401
|
+
const provider = picked.provider
|
|
1402
|
+
const src = authorizedSource ? { ok: true, ...authorizedSource, rel: authorizedSource.name } : await resolveSource(input?.sourceRel, binding)
|
|
1403
|
+
if (!src.ok) return { ok: false, reason: src.code, detail: src.message }
|
|
1404
|
+
const format = path.extname(src.rel).slice(1).toLowerCase()
|
|
1405
|
+
if (!provider.formats.includes(format)) {
|
|
1406
|
+
return {
|
|
1407
|
+
ok: false,
|
|
1408
|
+
reason: 'UNSUPPORTED_FORMAT',
|
|
1409
|
+
detail: `提供方 ${provider.id} 不支持 .${format};它支持:${provider.formats.join(' / ')}`,
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
if (src.bytes > provider.maxBytes) {
|
|
1413
|
+
return { ok: false, reason: 'FILE_TOO_LARGE', detail: `原件 ${src.bytes} 字节超过提供方上限 ${provider.maxBytes} 字节` }
|
|
1414
|
+
}
|
|
1415
|
+
const sha = sha256(src.data || await readFile(src.abs))
|
|
1416
|
+
const cfgVer = providerConfigVersion(provider)
|
|
1417
|
+
const dedupeKey = sha256(Buffer.from([sha, kindIn, provider.id, cfgVer, provider.model].join('|'), 'utf8')).slice(0, 24)
|
|
1418
|
+
|
|
1419
|
+
// 去重:同原件 + 同类型 + 同提供方/配置版本 + 已成功/部分成功 → 直接复用,不重复计费/重复建条目
|
|
1420
|
+
const existing = await findJobByDedupe(binding, dedupeKey, { reuseTerminalOnly: true, requestedBy, external: Boolean(authorizedSource) })
|
|
1421
|
+
if (existing) {
|
|
1422
|
+
return { ok: true, deduped: true, jobId: existing.jobId, status: existing.status, job: publicJob(existing), detail: '同一原件与同一提供方配置已有解析结果,复用(未重复请求引擎)' }
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
let externalStored = null
|
|
1426
|
+
if (authorizedSource) {
|
|
1427
|
+
externalStored = randomUUID() + '.' + format
|
|
1428
|
+
const storage = path.join(kbDir(binding), 'sources')
|
|
1429
|
+
await mkdir(storage, { recursive: true })
|
|
1430
|
+
const bytes = src.data || await readFile(src.abs)
|
|
1431
|
+
if (sha256(bytes) !== sha) return { ok: false, reason: 'SOURCE_CHANGED', detail: '文件在提交期间发生变化,请重新选择' }
|
|
1432
|
+
await writeFile(path.join(storage, externalStored), bytes, { flag: 'wx' })
|
|
1433
|
+
}
|
|
1434
|
+
const job = {
|
|
1435
|
+
schemaVersion: PARSING_SCHEMA_VERSION,
|
|
1436
|
+
jobId: newJobId(kindIn),
|
|
1437
|
+
kbId: binding.kbId,
|
|
1438
|
+
binding,
|
|
1439
|
+
kind: kindIn,
|
|
1440
|
+
purpose: typeof input?.purpose === 'string' ? input.purpose.slice(0, 200) : '',
|
|
1441
|
+
requestedBy: requestedBy ?? { via: 'unknown' },
|
|
1442
|
+
source: { relPath: src.rel, absPath: authorizedSource ? undefined : src.abs, external: Boolean(authorizedSource), storedName: externalStored, sha256: sha, bytes: src.bytes, format },
|
|
1443
|
+
provider: {
|
|
1444
|
+
id: provider.id,
|
|
1445
|
+
selectionSource: toolDefault || !input?.providerId ? 'settings-default' : 'explicit',
|
|
1446
|
+
protocol: provider.protocol,
|
|
1447
|
+
model: provider.model,
|
|
1448
|
+
locality: provider.locality,
|
|
1449
|
+
configVersion: cfgVer,
|
|
1450
|
+
credentialRef: provider.credentialRef,
|
|
1451
|
+
},
|
|
1452
|
+
configSnapshot: {
|
|
1453
|
+
parsingSchemaVersion: PARSING_SCHEMA_VERSION,
|
|
1454
|
+
externalPolicy: conf.externalPolicy,
|
|
1455
|
+
provider: { ...provider, args: [...provider.args] },
|
|
1456
|
+
},
|
|
1457
|
+
status: 'queued',
|
|
1458
|
+
stage: 'queued',
|
|
1459
|
+
progress: { pagesTotal: null, pagesDone: 0, segmentsTotal: null, segmentsDone: 0 },
|
|
1460
|
+
attempts: 0,
|
|
1461
|
+
maxAttempts: MAX_ATTEMPTS,
|
|
1462
|
+
dedupeKey,
|
|
1463
|
+
createdAt: nowIso(),
|
|
1464
|
+
startedAt: null,
|
|
1465
|
+
heartbeatAt: null,
|
|
1466
|
+
finishedAt: null,
|
|
1467
|
+
cancelRequestedAt: null,
|
|
1468
|
+
result: null,
|
|
1469
|
+
partial: null,
|
|
1470
|
+
land: { status: 'none', entryId: null, revision: null, at: null, error: null },
|
|
1471
|
+
diagnostics: [],
|
|
1472
|
+
retryOf: typeof input?.retryOf === 'string' ? input.retryOf : null,
|
|
1473
|
+
}
|
|
1474
|
+
await writeJob(binding, job)
|
|
1475
|
+
log('info', `解析任务已排队 ${job.jobId}(${job.kind} ← ${job.source.relPath} via ${provider.id})`)
|
|
1476
|
+
launchJob(job.jobId, binding)
|
|
1477
|
+
return { ok: true, deduped: false, jobId: job.jobId, status: 'queued', job: publicJob(job) }
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
async function findJobByDedupe(binding, dedupeKey, { reuseTerminalOnly, requestedBy, external } = {}) {
|
|
1481
|
+
const dir = jobsDir(binding)
|
|
1482
|
+
const files = await listJobFiles(dir)
|
|
1483
|
+
let best = null
|
|
1484
|
+
for (const f of files) {
|
|
1485
|
+
try {
|
|
1486
|
+
const j = await jobStorage.read(path.join(dir, f))
|
|
1487
|
+
if (j.kbId !== binding.kbId || j.binding && !sameBinding(j.binding, binding)) continue
|
|
1488
|
+
if (j.dedupeKey !== dedupeKey) continue
|
|
1489
|
+
if (Boolean(j.source?.external) !== Boolean(external)) continue
|
|
1490
|
+
if (requestedBy?.via === 'tool' && j.requestedBy?.session !== requestedBy.session) continue
|
|
1491
|
+
if (reuseTerminalOnly && !['succeeded', 'partial'].includes(j.status)) continue
|
|
1492
|
+
if (best === null || String(j.createdAt) > String(best.createdAt)) best = j
|
|
1493
|
+
} catch {
|
|
1494
|
+
continue
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
return best
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// ── 执行 ────────────────────────────────────────────────────────────────
|
|
1501
|
+
function launchJob(jobId, binding) {
|
|
1502
|
+
// A final guard also covers failures in lookup and error reporting itself.
|
|
1503
|
+
void runJob(jobId, binding).catch(() => {
|
|
1504
|
+
try { log('error', `解析任务 ${jobId} 后台处理失败,原任务记录已保留`) } catch { /* logger unavailable */ }
|
|
1505
|
+
})
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
async function runJob(jobId, bindingIn) {
|
|
1509
|
+
const binding = snapshotBinding(bindingIn || await getBinding())
|
|
1510
|
+
if (!binding) return
|
|
1511
|
+
const job = await readJob(jobId, binding)
|
|
1512
|
+
if (!job || running.has(jobId) || job.status !== 'queued') return
|
|
1513
|
+
const controller = new AbortController()
|
|
1514
|
+
const entry = { controller, child: null, job, binding, bindingChanged: false, heartbeat: null }
|
|
1515
|
+
running.set(jobId, entry)
|
|
1516
|
+
try {
|
|
1517
|
+
await executeJob(jobId, binding, job, entry, controller)
|
|
1518
|
+
} catch (error) {
|
|
1519
|
+
clearInterval(entry.heartbeat)
|
|
1520
|
+
controller.abort()
|
|
1521
|
+
job.status = 'failed'
|
|
1522
|
+
job.stage = 'failed'
|
|
1523
|
+
job.finishedAt = nowIso()
|
|
1524
|
+
const diagnostic = { code: error.jobStateWriteFailed ? 'JOB_STATE_WRITE_FAILED' : 'JOB_BACKGROUND_FAILED', cause: error.code || 'PARSE_FAILED', message: '后台任务未能完成;请检查任务诊断后重试', at: nowIso() }
|
|
1525
|
+
job.diagnostics = [...(job.diagnostics ?? []), diagnostic]
|
|
1526
|
+
let persisted = false
|
|
1527
|
+
try { await writeJob(binding, job); persisted = true } catch { /* retain last durable record */ }
|
|
1528
|
+
try { log('error', `解析任务 ${jobId} 后台失败 [${diagnostic.cause}];失败状态${persisted ? '已保存' : '未能保存,原记录已保留'}`) } catch { /* logger unavailable */ }
|
|
1529
|
+
try { onEvent({ type: 'parse-job-error', kbId: binding.kbId, jobId, code: diagnostic.code, cause: diagnostic.cause, persisted }) } catch { /* subscriber unavailable */ }
|
|
1530
|
+
} finally {
|
|
1531
|
+
clearInterval(entry.heartbeat)
|
|
1532
|
+
if (running.get(jobId) === entry) running.delete(jobId)
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
async function executeJob(jobId, binding, job, entry, controller) {
|
|
1537
|
+
const conf = normalizeParsingConfig(job.configSnapshot?.provider ? { externalPolicy: job.configSnapshot.externalPolicy, providers: [job.configSnapshot.provider], defaultOcr: job.kind === 'ocr' ? job.configSnapshot.provider.id : null, defaultAsr: job.kind === 'asr' ? job.configSnapshot.provider.id : null } : null).value
|
|
1538
|
+
const provider = job.configSnapshot.provider
|
|
1539
|
+
conf.executionBinding = binding
|
|
1540
|
+
const diagnostics = []
|
|
1541
|
+
const work = path.join(tmpDir(binding), jobId)
|
|
1542
|
+
// 执行前先核一次真实目标:拦在"起引擎/发正文"之前,比事后记一条诊断有意义
|
|
1543
|
+
// (同一条判据在每次 HTTP 请求前还会再核一次,防 DNS 在这段时间里被改)。
|
|
1544
|
+
if (!['cli-transcribe', 'qwen3-local', 'paddle-local', 'ppocr-local'].includes(provider.protocol)) {
|
|
1545
|
+
const pre = await checkTarget(provider.baseUrl, provider, conf)
|
|
1546
|
+
if (pre.ok !== true) {
|
|
1547
|
+
job.status = 'failed'
|
|
1548
|
+
job.stage = 'failed'
|
|
1549
|
+
job.startedAt = nowIso()
|
|
1550
|
+
job.finishedAt = job.startedAt
|
|
1551
|
+
job.attempts += 1
|
|
1552
|
+
job.diagnostics = [{ code: pre.code, message: pre.detail ?? '', at: nowIso() }]
|
|
1553
|
+
await writeJob(binding, job)
|
|
1554
|
+
log('warn', `解析任务 ${jobId} 在发送前被策略拦下:${pre.code}`)
|
|
1555
|
+
return
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
const cliRefusal = cliProgramRefusal(provider)
|
|
1559
|
+
if (cliRefusal) {
|
|
1560
|
+
job.status = 'failed'
|
|
1561
|
+
job.stage = 'failed'
|
|
1562
|
+
job.startedAt = nowIso()
|
|
1563
|
+
job.finishedAt = job.startedAt
|
|
1564
|
+
job.attempts += 1
|
|
1565
|
+
job.diagnostics = [{ code: cliRefusal.code, message: cliRefusal.message, at: nowIso() }]
|
|
1566
|
+
await writeJob(binding, job)
|
|
1567
|
+
log('warn', `解析任务 ${jobId} 的 CLI 配置被策略拒绝:${cliRefusal.code}`)
|
|
1568
|
+
return
|
|
1569
|
+
}
|
|
1570
|
+
job.status = 'running'
|
|
1571
|
+
job.stage = job.kind === 'ocr' ? 'rendering' : 'transcribing'
|
|
1572
|
+
job.startedAt = nowIso()
|
|
1573
|
+
job.heartbeatAt = job.startedAt
|
|
1574
|
+
job.attempts += 1
|
|
1575
|
+
await writeJob(binding, job)
|
|
1576
|
+
const heartbeat = entry.heartbeat = setInterval(() => { void (async () => {
|
|
1577
|
+
if (!sameBinding(binding, await getBinding())) { entry.bindingChanged = true; controller.abort(Object.assign(new Error('binding changed'), { code: 'BINDING_CHANGED' })) }
|
|
1578
|
+
job.heartbeatAt = nowIso()
|
|
1579
|
+
await writeJob(binding, job)
|
|
1580
|
+
})().catch(() => { log('warn', `解析任务 ${jobId} 心跳写入失败,任务记录仍归属原库`) }) }, 5000)
|
|
1581
|
+
const t0 = Date.now()
|
|
1582
|
+
let outcome
|
|
1583
|
+
// 本机提供方串行:绝不假设两套模型能同时常驻;排队期间仍是 queued(可取消)
|
|
1584
|
+
const serialLocal = provider.locality === 'local'
|
|
1585
|
+
try {
|
|
1586
|
+
await mkdir(work, { recursive: true })
|
|
1587
|
+
const body = async () => {
|
|
1588
|
+
if (job.cancelRequestedAt !== null) return { ok: false, code: 'CANCELED', detail: '已取消' }
|
|
1589
|
+
const gate = await executionGate(provider, conf)
|
|
1590
|
+
if (!gate.ok) return gate
|
|
1591
|
+
const source = await jobSource(job, binding)
|
|
1592
|
+
if (!source.ok) return { ok: false, code: source.code, detail: source.message }
|
|
1593
|
+
const bytes = await readFile(source.abs)
|
|
1594
|
+
const verified = await jobSource(job, binding)
|
|
1595
|
+
if (!verified.ok) return { ok: false, code: verified.code, detail: verified.message }
|
|
1596
|
+
if (sha256(bytes) !== job.source.sha256) return { ok: false, code: 'SOURCE_CHANGED', detail: '原件已变化,请新建解析任务;不复用旧片段' }
|
|
1597
|
+
// Engines consume an immutable task copy, never a live source link.
|
|
1598
|
+
entry.sourcePath = path.join(work, 'source.' + job.source.format)
|
|
1599
|
+
await writeFile(entry.sourcePath, bytes)
|
|
1600
|
+
job.stage = job.kind === 'ocr' ? 'rendering' : 'transcribing'
|
|
1601
|
+
job.heartbeatAt = nowIso()
|
|
1602
|
+
await writeJob(binding, job)
|
|
1603
|
+
if (job.kind === 'ocr') return await runOcr(provider, conf, job, work, entry, diagnostics)
|
|
1604
|
+
return await runAsr(provider, conf, job, work, entry, diagnostics)
|
|
1605
|
+
}
|
|
1606
|
+
if (serialLocal) {
|
|
1607
|
+
job.note = 'serialized-local-provider'
|
|
1608
|
+
job.stage = 'waiting-provider'
|
|
1609
|
+
job.status = 'queued'
|
|
1610
|
+
await writeJob(binding, job)
|
|
1611
|
+
outcome = await withProviderLock('local-gpu', async () => {
|
|
1612
|
+
// 排队期间可能已被取消:必须以磁盘上的最新记录为准(内存里的是旧副本)
|
|
1613
|
+
const fresh = await readJob(job.jobId, binding)
|
|
1614
|
+
if (fresh && fresh.cancelRequestedAt !== null) {
|
|
1615
|
+
job.cancelRequestedAt = fresh.cancelRequestedAt
|
|
1616
|
+
return { ok: false, code: 'CANCELED', detail: '排队期间已取消' }
|
|
1617
|
+
}
|
|
1618
|
+
job.status = 'running'
|
|
1619
|
+
return await body()
|
|
1620
|
+
})
|
|
1621
|
+
} else {
|
|
1622
|
+
outcome = await body()
|
|
1623
|
+
}
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
outcome = { ok: false, code: (error && error.code) || 'PARSE_FAILED', detail: errText(error) }
|
|
1626
|
+
} finally {
|
|
1627
|
+
clearInterval(heartbeat)
|
|
1628
|
+
await rm(work, { recursive: true, force: true }).catch(() => {})
|
|
1629
|
+
}
|
|
1630
|
+
const elapsedMs = Date.now() - t0
|
|
1631
|
+
job.finishedAt = nowIso()
|
|
1632
|
+
job.diagnostics = diagnostics
|
|
1633
|
+
// 取消状态可能只写在磁盘上(cancel() 写盘,而内存里这份是旧的):以磁盘为准
|
|
1634
|
+
const latestOnDisk = await readJob(job.jobId, binding)
|
|
1635
|
+
if (entry.bindingChanged || !sameBinding(binding, await getBinding())) outcome = { ...outcome, ...bindingFailure() }
|
|
1636
|
+
if (latestOnDisk && latestOnDisk.cancelRequestedAt !== null) {
|
|
1637
|
+
job.cancelRequestedAt = latestOnDisk.cancelRequestedAt
|
|
1638
|
+
job.canceledBy = latestOnDisk.canceledBy ?? job.canceledBy ?? null
|
|
1639
|
+
}
|
|
1640
|
+
if (job.cancelRequestedAt !== null) {
|
|
1641
|
+
job.status = 'canceled'
|
|
1642
|
+
job.stage = 'canceled'
|
|
1643
|
+
} else if (outcome.ok && outcome.partial && outcome.partial.length > 0) {
|
|
1644
|
+
job.status = 'partial'
|
|
1645
|
+
job.stage = 'done'
|
|
1646
|
+
job.result = outcome.result
|
|
1647
|
+
job.partial = { failedUnits: outcome.partial, note: '部分页/段失败;成功部分已保存为底稿,失败范围见 failedUnits' }
|
|
1648
|
+
} else if (outcome.ok) {
|
|
1649
|
+
job.status = 'succeeded'
|
|
1650
|
+
job.stage = 'done'
|
|
1651
|
+
job.result = outcome.result
|
|
1652
|
+
job.partial = null
|
|
1653
|
+
} else {
|
|
1654
|
+
job.status = 'failed'
|
|
1655
|
+
job.stage = 'failed'
|
|
1656
|
+
job.partial = outcome.partial ?? null
|
|
1657
|
+
job.result = outcome.result ?? null
|
|
1658
|
+
job.diagnostics = [...diagnostics, { code: outcome.code || 'PARSE_FAILED', message: outcome.detail || '', at: nowIso() }]
|
|
1659
|
+
}
|
|
1660
|
+
job.progress.elapsedMs = elapsedMs
|
|
1661
|
+
await writeJob(binding, job)
|
|
1662
|
+
log(job.status === 'failed' ? 'warn' : 'info', `解析任务 ${jobId} → ${job.status}(${elapsedMs}ms${job.result ? ',' + job.result.textChars + ' 字' : ''})`)
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
async function runOcr(provider, conf, job, work, entry, diagnostics) {
|
|
1666
|
+
if (provider.protocol === 'deepseek-ocr') {
|
|
1667
|
+
const gate = await executionGate(provider, conf)
|
|
1668
|
+
if (!gate.ok) return gate
|
|
1669
|
+
job.stage = 'recognizing'
|
|
1670
|
+
await writeJob(entry.binding, job)
|
|
1671
|
+
const r = await native.image(provider, entry.sourcePath, mimeOf(job.source.format), { signal: entry.controller.signal, timeoutMs: provider.timeoutMs, conf, extension: job.source.format })
|
|
1672
|
+
if (!r.ok) return r
|
|
1673
|
+
const pages = r.pages.slice(0, provider.maxPages).map(p => ({ page: p.index + 1, text: p.text, chars: p.text.length, method: 'deepseek-ocr', status: p.finish_reason === 'stop' ? 'ok' : 'partial' }))
|
|
1674
|
+
const partial = r.pages.filter(p => p.finish_reason === 'length' || p.index >= provider.maxPages).map(p => ({ unit: 'page', index: p.index + 1, code: p.finish_reason === 'length' ? 'OUTPUT_TRUNCATED' : 'PAGES_TRUNCATED' }))
|
|
1675
|
+
job.progress.pagesTotal = r.pageCount
|
|
1676
|
+
job.progress.pagesDone = pages.length
|
|
1677
|
+
if (!r.text.trim()) return { ok: false, code: 'EMPTY_TEXT' }
|
|
1678
|
+
const result = finalizeOcr(job, pages, 'deepseek-ocr', { pageCount: r.pageCount, diagnostics })
|
|
1679
|
+
result.usage = r.usage ? { ...r.usage, source: 'provider' } : result.usage
|
|
1680
|
+
return { ok: true, result, partial }
|
|
1681
|
+
}
|
|
1682
|
+
const fmt = job.source.format
|
|
1683
|
+
const pages = []
|
|
1684
|
+
let pageCount = 0
|
|
1685
|
+
let method = 'vision-per-image'
|
|
1686
|
+
if (fmt === 'pdf') {
|
|
1687
|
+
job.stage = 'rendering'
|
|
1688
|
+
job.progress.pagesTotal = null
|
|
1689
|
+
await writeJob(entry.binding, job)
|
|
1690
|
+
const rendered = await renderPdfPages(provider, entry.sourcePath, path.join(work, 'pages'), { signal: entry.controller.signal, maxPages: provider.maxPages, onChild: (c) => { entry.child = c } })
|
|
1691
|
+
if (!rendered.ok) return { ok: false, code: rendered.code, detail: rendered.detail }
|
|
1692
|
+
pageCount = rendered.pageCount
|
|
1693
|
+
method = 'vision-per-page'
|
|
1694
|
+
job.progress.pagesTotal = rendered.pages.length
|
|
1695
|
+
if (rendered.truncated) diagnostics.push({ code: 'PAGES_TRUNCATED', message: `PDF 共 ${rendered.pageCount} 页,超过提供方上限 ${provider.maxPages} 页,只解析前 ${rendered.pages.length} 页`, at: nowIso() })
|
|
1696
|
+
job.stage = 'recognizing'
|
|
1697
|
+
for (const p of rendered.pages) {
|
|
1698
|
+
if (entry.controller.signal.aborted) return { ok: false, code: 'CANCELED', detail: '已取消' }
|
|
1699
|
+
const gate = await executionGate(provider, conf)
|
|
1700
|
+
if (!gate.ok) {
|
|
1701
|
+
const missing = rendered.pages.filter(row => !pages.some(done => done.page === row.page)).map(row => ({ unit: 'page', index: row.page, error: gate.code }))
|
|
1702
|
+
return { ...gate, partial: { failedUnits: missing, note: '未继续解析的页面已明确标记,已有结果保留在原库任务中' }, result: finalizeOcr(job, pages, method, { pageCount, diagnostics }) }
|
|
1703
|
+
}
|
|
1704
|
+
const pageNo = p.page
|
|
1705
|
+
if (typeof p.text === 'string' && p.text.trim().length >= 20) {
|
|
1706
|
+
// 文字层可直接抽取:不再送 OCR(文本 PDF 走直读,不浪费引擎)
|
|
1707
|
+
pages.push({ page: pageNo, chars: p.text.trim().length, method: 'text-layer', status: 'ok', text: p.text })
|
|
1708
|
+
} else {
|
|
1709
|
+
const one = await ocrOneImage(provider, conf, p.image, { signal: entry.controller.signal, diagnostics })
|
|
1710
|
+
if (one.ok) pages.push({ page: pageNo, chars: one.text.length, method: 'ocr', status: 'ok', text: one.text, usage: one.usage ?? null })
|
|
1711
|
+
else pages.push({ page: pageNo, chars: 0, method: 'ocr', status: 'failed', text: '', error: one.code + (one.detail ? ': ' + one.detail : '') })
|
|
1712
|
+
}
|
|
1713
|
+
job.progress.pagesDone = pages.length
|
|
1714
|
+
job.heartbeatAt = nowIso()
|
|
1715
|
+
await writeJob(entry.binding, job)
|
|
1716
|
+
}
|
|
1717
|
+
const failed = pages.filter((p) => p.status !== 'ok')
|
|
1718
|
+
const result = finalizeOcr(job, pages, method, { pageCount, diagnostics })
|
|
1719
|
+
if (pages.length === 0) return { ok: false, code: 'NO_PAGES', detail: '没有可解析的页' }
|
|
1720
|
+
if (failed.length === pages.length) return { ok: false, code: 'ALL_PAGES_FAILED', detail: failed[0]?.error || '所有页都失败', partial: failed.map((p) => ({ unit: 'page', index: p.page, error: p.error })), result }
|
|
1721
|
+
if (failed.length > 0) return { ok: true, partial: failed.map((p) => ({ unit: 'page', index: p.page, error: p.error })), result }
|
|
1722
|
+
return { ok: true, result }
|
|
1723
|
+
}
|
|
1724
|
+
// 单张图片
|
|
1725
|
+
job.progress.pagesTotal = 1
|
|
1726
|
+
job.stage = 'recognizing'
|
|
1727
|
+
await writeJob(entry.binding, job)
|
|
1728
|
+
const one = await ocrOneImage(provider, conf, entry.sourcePath, { signal: entry.controller.signal, diagnostics })
|
|
1729
|
+
if (!one.ok) return { ok: false, code: one.code, detail: one.detail }
|
|
1730
|
+
pages.push({ page: 1, chars: one.text.length, method: 'ocr', status: 'ok', text: one.text, usage: one.usage ?? null })
|
|
1731
|
+
job.progress.pagesDone = 1
|
|
1732
|
+
const result = finalizeOcr(job, pages, method, { pageCount: 1, diagnostics })
|
|
1733
|
+
return { ok: true, result }
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
function finalizeOcr(job, pages, method, extra) {
|
|
1737
|
+
const text = pages.map((p) => (pages.length > 1 ? `===== 第 ${p.page} 页 =====\n${p.text ?? ''}` : p.text ?? '')).join('\n\n').trim()
|
|
1738
|
+
const usage = pages.reduce(
|
|
1739
|
+
(acc, p) => {
|
|
1740
|
+
if (!p.usage) return acc
|
|
1741
|
+
acc.promptTokens = (acc.promptTokens ?? 0) + (p.usage.promptTokens ?? 0)
|
|
1742
|
+
acc.completionTokens = (acc.completionTokens ?? 0) + (p.usage.completionTokens ?? 0)
|
|
1743
|
+
acc.pages = (acc.pages ?? 0) + 1
|
|
1744
|
+
return acc
|
|
1745
|
+
},
|
|
1746
|
+
{},
|
|
1747
|
+
)
|
|
1748
|
+
return {
|
|
1749
|
+
text,
|
|
1750
|
+
textChars: text.length,
|
|
1751
|
+
pageCount: extra.pageCount,
|
|
1752
|
+
pages: pages.map((p) => ({ page: p.page, chars: p.chars, method: p.method, status: p.status })),
|
|
1753
|
+
segments: [],
|
|
1754
|
+
method,
|
|
1755
|
+
usage: Object.keys(usage).length > 0 ? { ...usage, source: 'provider' } : { available: false, reason: '提供方没有返回 usage' },
|
|
1756
|
+
unavailable: ['wordLevelTimestamps', 'confidence', 'speakerLabels'],
|
|
1757
|
+
diagnostics: extra.diagnostics ?? [],
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
async function localModel(provider, file, { signal }) {
|
|
1762
|
+
const work = path.dirname(file)
|
|
1763
|
+
const manifest = path.join(root, `ocr-${randomUUID()}.json`)
|
|
1764
|
+
const out = manifest + '.out'
|
|
1765
|
+
try {
|
|
1766
|
+
await mkdir(root, { recursive: true })
|
|
1767
|
+
await writeFile(manifest, JSON.stringify([{ index: 0, file }]), 'utf8')
|
|
1768
|
+
const r = await runChild(provider.command, ['-X', 'utf8', resource('kb-local-model.py'), '--kind', 'ocr', ...localArguments(provider), '--manifest', manifest, '--out', out], { signal, timeoutMs: provider.timeoutMs, cwd: work })
|
|
1769
|
+
if (!r.ok) return { ok: false, code: r.code, detail: '本地 OCR 执行失败;请检查运行环境和模型' }
|
|
1770
|
+
return JSON.parse(await readFile(out, 'utf8'))[0] || { ok: false, code: 'EMPTY_TEXT' }
|
|
1771
|
+
} finally { await rm(manifest, { force: true }); await rm(out, { force: true }) }
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
function localArguments(p) {
|
|
1775
|
+
return ['--protocol', p.protocol, '--model', p.modelPath || '', '--layout-model', p.layoutModelPath || '', '--service-url', p.baseUrl || '', '--service-model', p.model || '', '--det-model', p.detModelPath || '', '--rec-model', p.recModelPath || '', '--dictionary', p.dictionaryPath || '']
|
|
1776
|
+
}
|
|
1777
|
+
async function chunkedAsr(provider, conf, job, work, entry, diagnostics) {
|
|
1778
|
+
const signal = entry.controller.signal
|
|
1779
|
+
const seconds = provider.protocol === 'qwen3-local' ? 60 : 50
|
|
1780
|
+
const ffmpeg = provider.ffmpegCommand || 'ffmpeg'
|
|
1781
|
+
const converted = await runChild(ffmpeg, ['-nostdin', '-y', '-v', 'error', '-i', entry.sourcePath, '-vn', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', '-f', 'segment', '-segment_time', String(seconds), '-reset_timestamps', '1', path.join(work, 'chunk-%05d.wav')], { signal, timeoutMs: provider.timeoutMs, cwd: work, onChild: c => { entry.child = c } })
|
|
1782
|
+
if (!converted.ok) return { ok: false, code: converted.code, detail: '音频转换失败;请在高级设置中检查 FFmpeg 路径' }
|
|
1783
|
+
const files = (await readdir(work)).filter(n => /^chunk-\d{5}\.wav$/.test(n)).sort()
|
|
1784
|
+
if (!files.length || files.length > 1000) return { ok: false, code: 'BAD_CHUNK_COUNT', detail: '音频片段为空或超过 1000 段' }
|
|
1785
|
+
job.chunkResults = job.chunkResults || {}
|
|
1786
|
+
// Source hash and provider snapshot belong to this job and are immutable.
|
|
1787
|
+
// Checkpoints survive failed attempts and host restarts; only failures rerun.
|
|
1788
|
+
const checkpoint = path.join(root, 'checkpoints', job.jobId + '.json')
|
|
1789
|
+
if (provider.protocol === 'qwen3-local') {
|
|
1790
|
+
try { for (const r of JSON.parse(await readFile(checkpoint, 'utf8'))) if (r.ok) job.chunkResults[r.index] = r } catch { /* first attempt */ }
|
|
1791
|
+
}
|
|
1792
|
+
job.progress.segmentsTotal = files.length
|
|
1793
|
+
job.progress.segmentsDone = Object.values(job.chunkResults).filter(r => r.ok).length
|
|
1794
|
+
await writeJob(entry.binding, job)
|
|
1795
|
+
let localResults = []
|
|
1796
|
+
if (provider.protocol === 'qwen3-local') {
|
|
1797
|
+
await mkdir(path.dirname(checkpoint), { recursive: true })
|
|
1798
|
+
const manifest = path.join(work, 'manifest.json')
|
|
1799
|
+
const pending = files.flatMap((file, index) => job.chunkResults[index]?.ok ? [] : [{ index, file: path.join(work, file) }])
|
|
1800
|
+
if (pending.length) {
|
|
1801
|
+
// Write successful earlier pieces too so an interrupted retry never loses them.
|
|
1802
|
+
const output = checkpoint + '.attempt'
|
|
1803
|
+
await writeFile(manifest, JSON.stringify(pending), 'utf8')
|
|
1804
|
+
const capture = async () => {
|
|
1805
|
+
try {
|
|
1806
|
+
const rows = JSON.parse(await readFile(output, 'utf8'))
|
|
1807
|
+
for (const r of rows) if (r.ok) job.chunkResults[r.index] = r
|
|
1808
|
+
await writeFile(checkpoint, JSON.stringify(Object.values(job.chunkResults)), 'utf8')
|
|
1809
|
+
job.progress.segmentsDone = Object.values(job.chunkResults).filter(r => r.ok).length
|
|
1810
|
+
await writeJob(entry.binding, job)
|
|
1811
|
+
} catch { /* helper has not completed a piece yet */ }
|
|
1812
|
+
}
|
|
1813
|
+
let captureChain = Promise.resolve()
|
|
1814
|
+
const timer = setInterval(() => { captureChain = captureChain.then(capture) }, 1000)
|
|
1815
|
+
let r
|
|
1816
|
+
try {
|
|
1817
|
+
r = await runChild(provider.command, ['-X', 'utf8', resource('kb-local-model.py'), '--kind', 'asr', '--model', provider.modelPath, '--manifest', manifest, '--out', output], { signal, timeoutMs: provider.timeoutMs, cwd: work, onChild: c => { entry.child = c } })
|
|
1818
|
+
} finally { clearInterval(timer); await captureChain; await capture() }
|
|
1819
|
+
try { localResults = JSON.parse(await readFile(output, 'utf8')) } catch { /* failed before first piece */ }
|
|
1820
|
+
for (const piece of pending) if (!localResults.some(r => r.index === piece.index)) localResults.push({ index: piece.index, ok: false, code: r?.code || 'LOCAL_MODEL_FAILED', detail: r?.detail || '本地识别程序未返回该片段结果' })
|
|
1821
|
+
await rm(output, { force: true })
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
const segments = [], failedUnits = []
|
|
1825
|
+
let offset = 0
|
|
1826
|
+
for (let index = 0; index < files.length; index++) {
|
|
1827
|
+
if (signal.aborted) return { ok: false, code: 'CANCELED' }
|
|
1828
|
+
const gate = await executionGate(provider, conf)
|
|
1829
|
+
if (!gate.ok) return { ...gate, partial: { failedUnits: files.slice(index).map((_f, i) => ({ index: index + i, code: gate.code })) } }
|
|
1830
|
+
const data = await readFile(path.join(work, files[index]))
|
|
1831
|
+
let audioBytes = 0
|
|
1832
|
+
for (let pos = 12; pos + 8 <= data.length;) {
|
|
1833
|
+
const size = data.readUInt32LE(pos + 4)
|
|
1834
|
+
if (data.toString('ascii', pos, pos + 4) === 'data') { audioBytes = Math.min(size, data.length - pos - 8); break }
|
|
1835
|
+
pos += 8 + size + (size % 2)
|
|
1836
|
+
}
|
|
1837
|
+
const duration = audioBytes / 32000
|
|
1838
|
+
let r = job.chunkResults[index]
|
|
1839
|
+
if (!r?.ok) r = provider.protocol === 'qwen3-local' ? localResults.find(r => r.index === index) : await native.recognize(provider, data, 'audio/wav', { signal, timeoutMs: provider.timeoutMs, conf })
|
|
1840
|
+
r = r || { ok: false, code: 'LOCAL_MODEL_FAILED' }
|
|
1841
|
+
job.chunkResults[index] = { ...r, index }
|
|
1842
|
+
if (r.requestId) diagnostics.push({ code: 'PROVIDER_REQUEST', requestId: String(r.requestId), segment: index, at: nowIso() })
|
|
1843
|
+
segments.push({ index, startSec: offset, endSec: offset + duration, text: r.ok ? r.text : `[第 ${index + 1} 段识别失败:${r.code}]`, status: r.ok ? 'ok' : 'failed', granularity: 'chunk' })
|
|
1844
|
+
if (!r.ok) failedUnits.push({ index, startSec: offset, endSec: offset + duration, code: r.code, detail: r.detail || '' })
|
|
1845
|
+
offset += duration
|
|
1846
|
+
job.progress.segmentsDone = Object.values(job.chunkResults).filter(r => r.ok).length
|
|
1847
|
+
await writeJob(entry.binding, job)
|
|
1848
|
+
}
|
|
1849
|
+
if (failedUnits.length === files.length) return { ok: false, code: 'ALL_CHUNKS_FAILED', detail: '全部片段识别失败,成功片段会在重试时复用', partial: { failedUnits } }
|
|
1850
|
+
const usage = Object.values(job.chunkResults).filter(r => r.ok && r.usage).map(r => ({ index: r.index, usage: r.usage }))
|
|
1851
|
+
return { ok: true, text: segments.map(s => s.text).join('\n'), segments, failedUnits, usage: usage.length ? { successfulChunks: usage, note: '成功片段的服务商用量;不包含失败请求的计费' } : null }
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
async function runAsr(provider, conf, job, work, entry, diagnostics) {
|
|
1855
|
+
job.stage = 'transcribing'
|
|
1856
|
+
await writeJob(entry.binding, job)
|
|
1857
|
+
let out
|
|
1858
|
+
if (provider.protocol === 'cli-transcribe') out = await asrViaCli(provider, entry.sourcePath, work, { signal: entry.controller.signal, diagnostics, entry })
|
|
1859
|
+
else if (['deepseek-asr', 'dashscope-asr', 'baidu-asr', 'qwen3-local'].includes(provider.protocol)) out = await chunkedAsr(provider, conf, job, work, entry, diagnostics)
|
|
1860
|
+
else out = await asrViaHttp(provider, entry.sourcePath, { signal: entry.controller.signal, diagnostics, conf })
|
|
1861
|
+
if (!out.ok) return { ok: false, code: out.code, detail: out.detail, partial: out.partial }
|
|
1862
|
+
const segments = out.segments ?? null
|
|
1863
|
+
if (segments === null) diagnostics.push({ code: 'SEGMENTS_UNAVAILABLE', message: '引擎没有给出分段位置:只保存全文,不伪造时间轴', at: nowIso() })
|
|
1864
|
+
job.progress.segmentsTotal = segments ? segments.length : null
|
|
1865
|
+
job.progress.segmentsDone = segments ? segments.filter(s => s.status !== 'failed').length : null
|
|
1866
|
+
const transcript = segments ? segments.map((s) => s.text).join('\n') : out.text
|
|
1867
|
+
const durationHint = segments ? segments.reduce((m, s) => Math.max(m, s.endSec ?? 0), 0) : null
|
|
1868
|
+
const result = {
|
|
1869
|
+
text: out.text,
|
|
1870
|
+
plainText: transcript,
|
|
1871
|
+
textChars: (transcript || '').length,
|
|
1872
|
+
pageCount: null,
|
|
1873
|
+
pages: [],
|
|
1874
|
+
segments: segments ?? [],
|
|
1875
|
+
durationSec: durationHint,
|
|
1876
|
+
method: provider.protocol,
|
|
1877
|
+
usage: out.usage ? { ...out.usage, source: 'provider' } : { available: false, reason: '提供方没有返回 usage' },
|
|
1878
|
+
unavailable: ['wordLevelTimestamps', 'confidence', 'speakerLabels'],
|
|
1879
|
+
diagnostics,
|
|
1880
|
+
}
|
|
1881
|
+
if ((transcript || '').trim() === '') return { ok: false, code: 'EMPTY_TEXT', detail: '转写结果为空' }
|
|
1882
|
+
return { ok: true, result, partial: out.failedUnits || [] }
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
// ── 取消 / 重试 ─────────────────────────────────────────────────────────
|
|
1886
|
+
async function cancel(jobId, { by } = {}) {
|
|
1887
|
+
const binding = await getBinding()
|
|
1888
|
+
const job = await readJob(jobId, binding)
|
|
1889
|
+
if (!job) return { ok: false, reason: 'not-found' }
|
|
1890
|
+
if (['succeeded', 'partial', 'failed', 'canceled'].includes(job.status)) {
|
|
1891
|
+
return { ok: false, reason: 'already-terminal', status: job.status, detail: '任务已结束,无法取消' }
|
|
1892
|
+
}
|
|
1893
|
+
job.cancelRequestedAt = nowIso()
|
|
1894
|
+
job.canceledBy = by ?? { via: 'unknown' }
|
|
1895
|
+
await writeJob(binding, job)
|
|
1896
|
+
const live = running.get(jobId)
|
|
1897
|
+
if (live) {
|
|
1898
|
+
// 关键:执行中的那份内存在写盘时会覆盖磁盘上的取消标记 → 同步到它,别被覆盖回去
|
|
1899
|
+
if (live.job) {
|
|
1900
|
+
live.job.cancelRequestedAt = job.cancelRequestedAt
|
|
1901
|
+
live.job.canceledBy = job.canceledBy
|
|
1902
|
+
}
|
|
1903
|
+
live.controller.abort(Object.assign(new Error('canceled'), { code: 'CANCELED' }))
|
|
1904
|
+
}
|
|
1905
|
+
// 排队中的任务立刻终止(不等执行)
|
|
1906
|
+
if (job.status === 'queued' && !live) {
|
|
1907
|
+
job.status = 'canceled'
|
|
1908
|
+
job.stage = 'canceled'
|
|
1909
|
+
job.finishedAt = nowIso()
|
|
1910
|
+
await writeJob(binding, job)
|
|
1911
|
+
}
|
|
1912
|
+
return { ok: true, jobId, status: job.status, cancelRequestedAt: job.cancelRequestedAt }
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
async function retry(jobId, { reason } = {}) {
|
|
1916
|
+
const binding = await getBinding()
|
|
1917
|
+
const job = await readJob(jobId, binding)
|
|
1918
|
+
if (!job) return { ok: false, reason: 'not-found' }
|
|
1919
|
+
// 解析成功但落库失败:只重试提交,不重复请求引擎
|
|
1920
|
+
if (job.result && (job.status === 'succeeded' || (job.status === 'partial' && !job.chunkResults)) && job.land?.status !== 'landed') {
|
|
1921
|
+
return { ok: true, retryKind: 'land-only', jobId, detail: '解析结果已存在:只重试落库,不重复请求引擎', land: job.land }
|
|
1922
|
+
}
|
|
1923
|
+
if (!['failed', 'canceled', 'partial'].includes(job.status)) {
|
|
1924
|
+
return { ok: false, reason: 'not-retryable', detail: `状态 ${job.status} 不能重试` }
|
|
1925
|
+
}
|
|
1926
|
+
if (job.attempts >= job.maxAttempts) {
|
|
1927
|
+
return { ok: false, reason: 'attempts-exhausted', detail: `已尝试 ${job.attempts} 次(上限 ${job.maxAttempts});请检查提供方或用新的解析请求` }
|
|
1928
|
+
}
|
|
1929
|
+
job.status = 'queued'
|
|
1930
|
+
job.stage = 'queued'
|
|
1931
|
+
job.result = null
|
|
1932
|
+
job.partial = null
|
|
1933
|
+
job.cancelRequestedAt = null
|
|
1934
|
+
job.finishedAt = null
|
|
1935
|
+
job.diagnostics = [...(job.diagnostics ?? []), { code: 'RETRY', message: String(reason ?? '手动重试'), at: nowIso() }]
|
|
1936
|
+
await writeJob(binding, job)
|
|
1937
|
+
launchJob(job.jobId, binding)
|
|
1938
|
+
return { ok: true, retryKind: 'parse', jobId, status: 'queued', attempts: job.attempts }
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
// ── 结果读取(有界) ────────────────────────────────────────────────────
|
|
1942
|
+
async function readResult(jobId, { offset = 0, limit = 4000, pages: pageFilter = null, segments: segFilter = null } = {}) {
|
|
1943
|
+
const binding = await getBinding()
|
|
1944
|
+
const job = await readJob(jobId, binding)
|
|
1945
|
+
if (!job) return { ok: false, reason: 'not-found' }
|
|
1946
|
+
if (!job.result) return { ok: false, reason: 'no-result', status: job.status, detail: job.status === 'failed' ? parseFailureSummary(job) : '任务还没有结果', provider: job.provider, ...(['failed', 'partial'].includes(job.status) ? { recovery: failureRecovery() } : {}) }
|
|
1947
|
+
const full = String(job.result.text ?? '')
|
|
1948
|
+
const start = clampInt(offset, 0, full.length, 0)
|
|
1949
|
+
const take = clampInt(limit, 1, 20000, 4000)
|
|
1950
|
+
let body = full.slice(start, start + take)
|
|
1951
|
+
if (Array.isArray(pageFilter) && pageFilter.length > 0) {
|
|
1952
|
+
body = String(job.result.text ?? '')
|
|
1953
|
+
.split(/===== 第 (\d+) 页 =====/)
|
|
1954
|
+
.reduce((acc, chunk, i, all) => {
|
|
1955
|
+
if (i % 2 === 1) {
|
|
1956
|
+
const no = Number(chunk)
|
|
1957
|
+
if (pageFilter.includes(no)) acc.push('===== 第 ' + no + ' 页 =====\n' + (all[i + 1] ?? ''))
|
|
1958
|
+
}
|
|
1959
|
+
return acc
|
|
1960
|
+
}, [])
|
|
1961
|
+
.join('\n')
|
|
1962
|
+
.slice(start, start + take)
|
|
1963
|
+
}
|
|
1964
|
+
return {
|
|
1965
|
+
ok: true,
|
|
1966
|
+
jobId,
|
|
1967
|
+
status: job.status,
|
|
1968
|
+
textChars: full.length,
|
|
1969
|
+
...(['partial', 'failed'].includes(job.status) ? { recovery: failureRecovery(), failureSummary: parseFailureSummary(job) } : {}),
|
|
1970
|
+
offset: start,
|
|
1971
|
+
returned: body.length,
|
|
1972
|
+
truncated: start + take < full.length,
|
|
1973
|
+
text: body,
|
|
1974
|
+
pages: job.result.pages ?? [],
|
|
1975
|
+
segments: segFilter === null ? (job.result.segments ?? []) : (job.result.segments ?? []).filter((s) => segFilter.includes(s.index)),
|
|
1976
|
+
usage: job.result.usage ?? null,
|
|
1977
|
+
unavailable: job.result.unavailable ?? [],
|
|
1978
|
+
note: '这是可追溯底稿,不是已校订知识;逐字引用请回原件',
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
// ── 落库 ────────────────────────────────────────────────────────────────
|
|
1983
|
+
async function land(jobId, opts = {}) {
|
|
1984
|
+
const binding = await getBinding()
|
|
1985
|
+
const core = getCore()
|
|
1986
|
+
if (!core) return { ok: false, reason: 'core-not-ready' }
|
|
1987
|
+
const job = await readJob(jobId, binding)
|
|
1988
|
+
if (!job) return { ok: false, reason: 'not-found' }
|
|
1989
|
+
if (job.land?.status === 'landed') {
|
|
1990
|
+
return { ok: true, alreadyLanded: true, jobId, entryId: job.land.entryId, revision: job.land.revision, detail: '这条解析结果已经落库过(不会重复建条目)' }
|
|
1991
|
+
}
|
|
1992
|
+
if (!job.result) return { ok: false, reason: 'no-result', detail: `解析还没有结果(status=${job.status})` }
|
|
1993
|
+
if (job.status === 'failed' || job.status === 'canceled') return { ok: false, reason: 'parse-not-successful', status: job.status }
|
|
1994
|
+
let sourceRel = resolveAssetPath(binding.kbPath, job.source.relPath)
|
|
1995
|
+
if (job.source.external) {
|
|
1996
|
+
// Explicit land imports an immutable original before creating a KB reference.
|
|
1997
|
+
sourceRel = '90-收件箱/解析原件/' + job.jobId + '.' + job.source.format
|
|
1998
|
+
await core._internal.withMutationLock(binding.kbPath, async () => {
|
|
1999
|
+
if (!sameBinding(binding, await getBinding())) throw Object.assign(new Error('知识库绑定已改变,未入库'), { code: 'BINDING_CHANGED' })
|
|
2000
|
+
const original = await jobSource(job, binding)
|
|
2001
|
+
if (!original.ok) throw Object.assign(new Error(original.message), { code: original.code })
|
|
2002
|
+
const bytes = await readFile(original.abs)
|
|
2003
|
+
if (sha256(bytes) !== job.source.sha256) throw Object.assign(new Error('解析原件快照已变化'), { code: 'SOURCE_CHANGED' })
|
|
2004
|
+
const directory = await safePath(binding.kbPath, '90-收件箱/解析原件', { missing: true })
|
|
2005
|
+
await mkdir(directory, { recursive: true })
|
|
2006
|
+
const destination = await safePath(binding.kbPath, sourceRel, { missing: true })
|
|
2007
|
+
try { await writeFile(destination, bytes, { flag: 'wx' }) }
|
|
2008
|
+
catch (error) { if (error.code !== 'EEXIST' || sha256(await readFile(destination)) !== job.source.sha256) throw error }
|
|
2009
|
+
})
|
|
2010
|
+
}
|
|
2011
|
+
const title = typeof opts.title === 'string' && opts.title.trim() !== ''
|
|
2012
|
+
? opts.title.trim()
|
|
2013
|
+
: `${job.kind === 'ocr' ? 'OCR' : '语音转写'}底稿 · ${path.posix.basename(job.source.relPath)}`
|
|
2014
|
+
const kind = typeof opts.kind === 'string' && opts.kind !== '' ? opts.kind : '素材'
|
|
2015
|
+
const tags = Array.isArray(opts.tags) ? opts.tags.map(String) : [job.kind === 'ocr' ? 'OCR' : '语音转写', '解析底稿']
|
|
2016
|
+
const provenance = [
|
|
2017
|
+
'',
|
|
2018
|
+
'---',
|
|
2019
|
+
'## 解析来源',
|
|
2020
|
+
'',
|
|
2021
|
+
`- 原件:\`${sourceRel}\`(sha256 \`${job.source.sha256}\`)`,
|
|
2022
|
+
`- 解析类型:${job.kind === 'ocr' ? 'OCR' : '语音转写'};提供方:${job.provider.id}(${job.provider.protocol} / ${job.provider.locality} / ${job.provider.model || '未标模型'})`,
|
|
2023
|
+
`- 配置版本:\`${job.provider.configVersion}\`;任务:\`${job.jobId}\`;状态:${job.status}${job.partial ? '(部分失败:' + (job.partial.failedUnits ?? []).length + ' 处)' : ''}`,
|
|
2024
|
+
job.result.pages?.length ? `- 覆盖页:${job.result.pages.map((p) => p.page).join(', ')}(时长/页数:${job.result.pageCount ?? '未知'})` : '',
|
|
2025
|
+
job.result.segments?.length ? `- 分段:${job.result.segments.length} 段(每段起止见任务记录)` : '',
|
|
2026
|
+
`- 引擎未提供:${(job.result.unavailable ?? []).join(' / ') || '无'}`,
|
|
2027
|
+
'',
|
|
2028
|
+
'> 这是可追溯底稿,不是已校订知识;逐字引用请回原件。',
|
|
2029
|
+
].filter(Boolean).join('\n')
|
|
2030
|
+
const content = `${String(job.result.plainText ?? job.result.text).trim()}\n${provenance}\n`
|
|
2031
|
+
const args = { kind, title, content, tags, source: sourceRel, requestId: 'parse-' + job.jobId, expectedBinding: snapshotBinding(binding) }
|
|
2032
|
+
const r = await (opts.entryId
|
|
2033
|
+
? core.updateEntry({
|
|
2034
|
+
entryId: opts.entryId,
|
|
2035
|
+
expectedRevision: opts.expectedRevision,
|
|
2036
|
+
patch: { title, tags, source: sourceRel },
|
|
2037
|
+
content,
|
|
2038
|
+
requestId: 'parse-' + job.jobId + '-upd',
|
|
2039
|
+
expectedBinding: snapshotBinding(binding),
|
|
2040
|
+
})
|
|
2041
|
+
: core.createEntry(args))
|
|
2042
|
+
if (!r || r.ok !== true) {
|
|
2043
|
+
job.land = { status: r && r.conflict ? 'conflict' : 'failed', entryId: opts.entryId ?? null, revision: null, at: nowIso(), error: (r && (r.reason || r.detail)) || 'land-failed' }
|
|
2044
|
+
await writeJob(binding, job)
|
|
2045
|
+
return { ok: false, reason: job.land.error, conflict: Boolean(r && r.conflict), jobId, land: job.land, detail: '解析结果已保留;修正后可只重试落库(retry),不会重复请求引擎' }
|
|
2046
|
+
}
|
|
2047
|
+
job.land = { status: 'landed', entryId: r.entryId ?? opts.entryId ?? null, revision: r.revision ?? null, at: nowIso(), error: null, path: r.path ?? null }
|
|
2048
|
+
await writeJob(binding, job)
|
|
2049
|
+
return { ok: true, jobId, land: job.land, entryId: job.land.entryId }
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// ── 列表 / 恢复 ─────────────────────────────────────────────────────────
|
|
2053
|
+
async function listJobs({ limit = 20, offset = 0, kind = null, status = null, filter = null } = {}) {
|
|
2054
|
+
const binding = await getBinding()
|
|
2055
|
+
if (!binding || !binding.kbId) return { ok: true, jobs: [], note: '未绑定知识库' }
|
|
2056
|
+
const dir = jobsDir(binding)
|
|
2057
|
+
const files = await listJobFiles(dir)
|
|
2058
|
+
let jobs = [], unreadable = 0
|
|
2059
|
+
for (const f of files) {
|
|
2060
|
+
try {
|
|
2061
|
+
const j = await jobStorage.read(path.join(dir, f))
|
|
2062
|
+
if (j.kbId !== binding.kbId || j.binding && !sameBinding(j.binding, binding)) continue
|
|
2063
|
+
if (kind && j.kind !== kind) continue
|
|
2064
|
+
if (status === 'completed' ? !['succeeded', 'partial', 'failed'].includes(j.status) : status && j.status !== status) continue
|
|
2065
|
+
jobs.push(publicJob(j))
|
|
2066
|
+
} catch {
|
|
2067
|
+
unreadable++; continue
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
jobs.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
2071
|
+
if (filter) jobs = await filter(jobs)
|
|
2072
|
+
const start = clampInt(offset, 0, Number.MAX_SAFE_INTEGER, 0), pageSize = clampInt(limit, 1, JOBS_KEPT, 20)
|
|
2073
|
+
return { ok: true, jobs: jobs.slice(start, start + pageSize), total: jobs.length, offset: start, limit: pageSize, ...(unreadable ? { warning: `${unreadable} 条任务记录无法读取,原记录已保留` } : {}) }
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
async function listRequests({ limit = 20, offset = 0, kind = null, filter = null } = {}) {
|
|
2077
|
+
const binding = await getBinding()
|
|
2078
|
+
if (!binding?.kbId) return { ok: true, requests: [], total: 0 }
|
|
2079
|
+
const dir = path.join(kbDir(binding), 'requests'), files = await listJobFiles(dir)
|
|
2080
|
+
let rows = [], unreadable = 0
|
|
2081
|
+
for (const file of files) {
|
|
2082
|
+
try { const r = JSON.parse(await readFile(path.join(dir, file), 'utf8')); if (sameBinding(r.binding, binding) && (!kind || r.kind === kind)) rows.push(r) }
|
|
2083
|
+
catch { unreadable++ }
|
|
2084
|
+
}
|
|
2085
|
+
if (filter) rows = await filter(rows)
|
|
2086
|
+
rows.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
2087
|
+
const start = clampInt(offset, 0, Number.MAX_SAFE_INTEGER, 0), pageSize = clampInt(limit, 1, 200, 20)
|
|
2088
|
+
return { ok: true, requests: rows.slice(start, start + pageSize), total: rows.length, offset: start, limit: pageSize, ...(unreadable ? { warning: '部分提交记录无法读取,原记录已保留' } : {}) }
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
/** 启动恢复:running 的记录不可能还活着,必须明确结局,不能永久挂起。 */
|
|
2092
|
+
async function recover() {
|
|
2093
|
+
if (recovered) return { ok: true, scanned: 0, recovered: 0 }
|
|
2094
|
+
recovered = true
|
|
2095
|
+
const binding = await getBinding()
|
|
2096
|
+
if (!binding || !binding.kbId) return { ok: true, scanned: 0, recovered: 0, note: '未绑定' }
|
|
2097
|
+
const dir = jobsDir(binding)
|
|
2098
|
+
const files = await listJobFiles(dir)
|
|
2099
|
+
let fixed = 0
|
|
2100
|
+
for (const f of files) {
|
|
2101
|
+
const file = path.join(dir, f)
|
|
2102
|
+
let j
|
|
2103
|
+
try {
|
|
2104
|
+
j = await jobStorage.read(file)
|
|
2105
|
+
} catch {
|
|
2106
|
+
continue
|
|
2107
|
+
}
|
|
2108
|
+
if (j.status !== 'running' && j.status !== 'queued') continue
|
|
2109
|
+
if (j.kbId !== binding.kbId || j.binding && !sameBinding(j.binding, binding)) continue
|
|
2110
|
+
if (running.has(j.jobId)) continue
|
|
2111
|
+
const requeue = j.attempts < (j.maxAttempts ?? MAX_ATTEMPTS) && j.status === 'running'
|
|
2112
|
+
j.diagnostics = [...(j.diagnostics ?? []), { code: 'INTERRUPTED', message: `宿主重启:任务停在 ${j.status}/${j.stage},未观察到结束`, at: nowIso() }]
|
|
2113
|
+
if (requeue) {
|
|
2114
|
+
j.status = 'queued'
|
|
2115
|
+
j.stage = 'queued'
|
|
2116
|
+
j.note = 'requeued-after-restart'
|
|
2117
|
+
await writeJob(binding, j)
|
|
2118
|
+
launchJob(j.jobId, binding)
|
|
2119
|
+
} else {
|
|
2120
|
+
j.status = 'failed'
|
|
2121
|
+
j.stage = 'failed'
|
|
2122
|
+
j.finishedAt = nowIso()
|
|
2123
|
+
j.partial = j.partial ?? { failedUnits: [], note: '重启中断,未完成' }
|
|
2124
|
+
await writeJob(binding, j)
|
|
2125
|
+
}
|
|
2126
|
+
fixed += 1
|
|
2127
|
+
}
|
|
2128
|
+
if (fixed > 0) log('warn', `解析任务恢复:处理 ${fixed} 条中断记录`)
|
|
2129
|
+
await pruneJobs(binding)
|
|
2130
|
+
return { ok: true, scanned: files.length, recovered: fixed }
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
async function pruneJobs(binding) {
|
|
2134
|
+
const dir = jobsDir(binding)
|
|
2135
|
+
const files = await listJobFiles(dir)
|
|
2136
|
+
if (files.length <= JOBS_KEPT) return
|
|
2137
|
+
const rows = []
|
|
2138
|
+
for (const f of files) {
|
|
2139
|
+
try {
|
|
2140
|
+
const j = await jobStorage.read(path.join(dir, f))
|
|
2141
|
+
rows.push({ f, at: j.createdAt, terminal: ['succeeded', 'partial', 'failed', 'canceled'].includes(j.status) })
|
|
2142
|
+
} catch {
|
|
2143
|
+
rows.push({ f, at: '', terminal: true })
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
rows.sort((a, b) => String(a.at).localeCompare(String(b.at)))
|
|
2147
|
+
const drop = rows.filter((r) => r.terminal).slice(0, Math.max(0, rows.length - JOBS_KEPT))
|
|
2148
|
+
for (const r of drop) {
|
|
2149
|
+
await rm(path.join(dir, r.f), { force: true }).catch(() => {})
|
|
2150
|
+
await rm(path.join(root, 'checkpoints', r.f), { force: true }).catch(() => {})
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
/** 连接测试:只验证"这个地址/程序通不通",**不冒充解析通过**。 */
|
|
2155
|
+
async function testConnection(providerId) {
|
|
2156
|
+
const provider = (await readParsingConfig()).providers.find(p => p.id === providerId)
|
|
2157
|
+
const result = await checkConnection(providerId)
|
|
2158
|
+
if (provider && ['qwen3-local', 'paddle-local', 'paddle-service', 'ppocr-local'].includes(provider.protocol)) {
|
|
2159
|
+
const file = environmentFile(provider)
|
|
2160
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
2161
|
+
const tmp = file + '.tmp-' + randomUUID()
|
|
2162
|
+
await writeFile(tmp, JSON.stringify({ configVersion: providerConfigVersion(provider), checkedAt: nowIso(), ok: result.ok }), 'utf8')
|
|
2163
|
+
await rename(tmp, file)
|
|
2164
|
+
}
|
|
2165
|
+
return result
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
async function checkConnection(providerId) {
|
|
2169
|
+
const conf = await readParsingConfig()
|
|
2170
|
+
const provider = conf.providers.find((p) => p.id === providerId)
|
|
2171
|
+
if (!provider) return { ok: false, reason: 'not-found' }
|
|
2172
|
+
const refused = policyRefusal(provider, conf)
|
|
2173
|
+
if (refused) return { ok: false, reason: refused.code, detail: refused.message, kind: 'policy' }
|
|
2174
|
+
const diagnostics = []
|
|
2175
|
+
const t0 = Date.now()
|
|
2176
|
+
if (['cli-transcribe', 'qwen3-local', 'paddle-local', 'paddle-service', 'ppocr-local'].includes(provider.protocol)) {
|
|
2177
|
+
try {
|
|
2178
|
+
const st = await stat(provider.command)
|
|
2179
|
+
if (!st.isFile()) return { ok: false, reason: 'BAD_COMMAND', detail: 'command 不是文件' }
|
|
2180
|
+
} catch {
|
|
2181
|
+
return { ok: false, reason: 'COMMAND_MISSING', detail: '找不到可执行程序:' + provider.command, kind: 'connection' }
|
|
2182
|
+
}
|
|
2183
|
+
if (provider.protocol !== 'cli-transcribe') {
|
|
2184
|
+
try {
|
|
2185
|
+
if (['qwen3-local', 'paddle-local'].includes(provider.protocol) && !(await stat(provider.modelPath)).isDirectory()) throw new Error('not-directory')
|
|
2186
|
+
if (provider.kind === 'asr' && provider.ffmpegCommand) await stat(provider.ffmpegCommand)
|
|
2187
|
+
} catch { return { ok: false, kind: 'connection', reason: 'LOCAL_DEPENDENCY_MISSING', detail: '模型目录或 FFmpeg 不存在,请检查高级设置' } }
|
|
2188
|
+
const r = await runChild(provider.command, ['-X', 'utf8', resource('kb-local-model.py'), '--check', '--kind', provider.kind, ...localArguments(provider)], { timeoutMs: 20000 })
|
|
2189
|
+
if (!r.ok) return { ok: false, kind: 'connection', reason: r.code, detail: '无法检查本地 Python 环境' }
|
|
2190
|
+
try {
|
|
2191
|
+
const check = JSON.parse(r.stdout.trim().split('\n').pop())
|
|
2192
|
+
if (check.ok && provider.kind === 'ocr') {
|
|
2193
|
+
const render = await runChild(provider.renderCommand || provider.command, ['-X', 'utf8', '-c', 'import importlib.util,json; print(json.dumps({"ok":bool(importlib.util.find_spec("pymupdf") or importlib.util.find_spec("fitz"))}))'], { timeoutMs: 20000 })
|
|
2194
|
+
if (!render.ok || !render.stdout.includes('"ok": true')) return { ok: false, kind: 'environment', reason: 'PDF_RENDER_MISSING', detail: 'OCR 环境存在;PDF 渲染环境缺少 PyMuPDF,请在高级设置中选择另一个已安装环境。图片识别仍可单独测试。' }
|
|
2195
|
+
}
|
|
2196
|
+
return check.ok ? { ok: true, kind: 'connection', detail: '模型目录及依赖存在(未加载模型);需测试解析验证。' + (provider.kind === 'ocr' ? '已找到版面分析及 PDF 渲染依赖。' : '') } : { ok: false, kind: 'connection', reason: 'LOCAL_DEPENDENCY_MISSING', detail: '缺少依赖:' + check.missing.join('、') }
|
|
2197
|
+
} catch { return { ok: false, kind: 'connection', reason: 'LOCAL_CHECK_FAILED', detail: '环境检查未返回有效结果' } }
|
|
2198
|
+
}
|
|
2199
|
+
for (const a of provider.args) {
|
|
2200
|
+
if (a.toLowerCase().endsWith('.py') || a.toLowerCase().endsWith('.cmd')) {
|
|
2201
|
+
try {
|
|
2202
|
+
await stat(a)
|
|
2203
|
+
} catch {
|
|
2204
|
+
return { ok: false, reason: 'ARG_MISSING', detail: '参数里的脚本不存在:' + a, kind: 'connection' }
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
return { ok: true, kind: 'connection', latencyMs: Date.now() - t0, detail: '固定程序与脚本存在(这只证明"能找到程序",不证明转写可用)', note: '解析请用 testParse(真实小样本)' }
|
|
2209
|
+
}
|
|
2210
|
+
if (NATIVE_PROTOCOLS.includes(provider.protocol)) return native.connection(provider, { timeoutMs: Math.min(provider.timeoutMs, 20000), conf })
|
|
2211
|
+
let headers
|
|
2212
|
+
try {
|
|
2213
|
+
headers = await authHeaders(provider, diagnostics)
|
|
2214
|
+
} catch (error) {
|
|
2215
|
+
return { ok: false, reason: (error && error.code) || 'AUTH_ERROR', detail: errText(error), kind: 'auth', diagnostics }
|
|
2216
|
+
}
|
|
2217
|
+
const r = await requestJson(provider, `${provider.baseUrl}/models`, { method: 'GET', headers }, { timeoutMs: Math.min(provider.timeoutMs, 20_000), conf, signal: null })
|
|
2218
|
+
if (!r.ok) return { ok: false, kind: 'connection', reason: r.code, detail: r.detail ?? '', status: r.status ?? null, diagnostics }
|
|
2219
|
+
const models = Array.isArray(r.json?.data) ? r.json.data.map((m) => m.id).filter(Boolean) : []
|
|
2220
|
+
const modelOk = provider.model === '' ? null : models.includes(provider.model)
|
|
2221
|
+
return {
|
|
2222
|
+
ok: true,
|
|
2223
|
+
kind: 'connection',
|
|
2224
|
+
latencyMs: Date.now() - t0,
|
|
2225
|
+
models,
|
|
2226
|
+
modelConfigured: provider.model || null,
|
|
2227
|
+
modelPresent: modelOk,
|
|
2228
|
+
detail: (modelOk === false ? `服务在线,但模型列表里没有 ${provider.model}` : '服务在线') + (provider.kind === 'ocr' ? `;PDF 渲染程序${provider.renderCommand && await stat(provider.renderCommand).then(s => s.isFile()).catch(() => false) ? '存在,需用 PDF 测试验证' : '未配置或不存在'};视觉接口不包含版面分析管线` : ''),
|
|
2229
|
+
note: '这只证明"地址与鉴权通",不证明解析可用;请用 testParse 真实跑一个小样本',
|
|
2230
|
+
diagnostics,
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
/** 真实小样本解析:走同一条任务服务(不是另开一条捷径)。 */
|
|
2235
|
+
async function testParse({ providerId, sourceRel, kind } = {}, { requestedBy, authorizedSource } = {}) {
|
|
2236
|
+
const conf = await readParsingConfig()
|
|
2237
|
+
const toolDefault = requestedBy?.via === 'tool'
|
|
2238
|
+
const selectedId = toolDefault ? (kind === 'ocr' ? conf.defaultOcr : conf.defaultAsr) : providerId
|
|
2239
|
+
const provider = conf.providers.find((p) => p.id === selectedId)
|
|
2240
|
+
const submitted = await submit({ kind: kind ?? (toolDefault ? undefined : provider?.kind), providerId, sourceRel, purpose: 'provider-test' }, { requestedBy: requestedBy ?? { via: 'test' }, authorizedSource })
|
|
2241
|
+
if (!submitted.ok) return submitted
|
|
2242
|
+
const jobId = submitted.jobId
|
|
2243
|
+
const deadline = Date.now() + Math.min((provider?.timeoutMs || 600000) + 30_000, 10 * 60_000)
|
|
2244
|
+
while (Date.now() < deadline) {
|
|
2245
|
+
const j = await readJob(jobId)
|
|
2246
|
+
if (j && ['succeeded', 'partial', 'failed', 'canceled'].includes(j.status)) {
|
|
2247
|
+
const preview = j.result?.text ? String(j.result.text).slice(0, 120) : ''
|
|
2248
|
+
return {
|
|
2249
|
+
ok: j.status === 'succeeded' || j.status === 'partial',
|
|
2250
|
+
jobId,
|
|
2251
|
+
requestId: submitted.requestId,
|
|
2252
|
+
deduped: submitted.deduped,
|
|
2253
|
+
status: j.status,
|
|
2254
|
+
textChars: j.result?.textChars ?? 0,
|
|
2255
|
+
preview,
|
|
2256
|
+
diagnostics: j.diagnostics,
|
|
2257
|
+
note: '真实解析(同一条任务服务),结果已落底稿;这只是小样本,不代表全库准确率',
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
await new Promise((r) => setTimeout(r, 500))
|
|
2261
|
+
}
|
|
2262
|
+
return { ok: false, requestId: submitted.requestId, jobId, status: 'timeout-wait', detail: '等待解析超过上限;任务仍在后台(去任务列表看状态)' }
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
return {
|
|
2266
|
+
async scanStart(input, { viaAdmin = false } = {}) { return viaAdmin ? discovery.start(input) : adminOnly('扫描本机') },
|
|
2267
|
+
scanStatus(id, { viaAdmin = false } = {}) { return viaAdmin ? discovery.get(id) : adminOnly('查看扫描') },
|
|
2268
|
+
scanCancel(id, { viaAdmin = false } = {}) { return viaAdmin ? discovery.cancel(id) : adminOnly('取消扫描') },
|
|
2269
|
+
async scanAdd(scanId, resultId, { viaAdmin = false } = {}) {
|
|
2270
|
+
if (!viaAdmin) return adminOnly('添加扫描结果')
|
|
2271
|
+
const candidate = discovery.candidate(scanId, resultId)
|
|
2272
|
+
return candidate ? saveProvider(candidate, { viaAdmin: true }) : { ok: false, reason: 'CANDIDATE_NOT_READY' }
|
|
2273
|
+
},
|
|
2274
|
+
providersPublic,
|
|
2275
|
+
saveProvider,
|
|
2276
|
+
deleteProvider,
|
|
2277
|
+
setDefaults,
|
|
2278
|
+
setPolicy,
|
|
2279
|
+
submit,
|
|
2280
|
+
recordRejection,
|
|
2281
|
+
listJobs,
|
|
2282
|
+
listRequests,
|
|
2283
|
+
readResult,
|
|
2284
|
+
cancel,
|
|
2285
|
+
retry,
|
|
2286
|
+
land,
|
|
2287
|
+
recover,
|
|
2288
|
+
testConnection,
|
|
2289
|
+
testParse,
|
|
2290
|
+
readJob,
|
|
2291
|
+
publicJob,
|
|
2292
|
+
_internal: {
|
|
2293
|
+
resolveSource,
|
|
2294
|
+
normalizeParsingConfig,
|
|
2295
|
+
normalizeProvider,
|
|
2296
|
+
providerConfigVersion,
|
|
2297
|
+
parseAsrSegments,
|
|
2298
|
+
policyRefusal,
|
|
2299
|
+
// 2026-10-18 定向修复:这三项让"公网冒充 local / 行内求值 / 地址分级"可以离线自证
|
|
2300
|
+
staticDestinationRefusal,
|
|
2301
|
+
classifyAddress,
|
|
2302
|
+
isLocalHostName,
|
|
2303
|
+
cliProgramRefusal,
|
|
2304
|
+
checkTarget,
|
|
2305
|
+
},
|
|
2306
|
+
}
|
|
2307
|
+
}
|