dsh-memu-memory 1.4.1 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +108 -108
- package/CHANGELOG.md +169 -848
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -72
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -0
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -840
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9648
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1035
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4911
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -0
- package/lib/preset-mount.js +79 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2518
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1066
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1015 -979
- package/package.json +153 -152
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -455
- package/tests/client-export.test.mjs +521 -520
- package/tests/client-render.test.mjs +2008 -1727
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1586 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -48
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -415
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -616
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -0
- package/tests/preset-mount.test.mjs +124 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -23
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -221
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -212
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -414
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1521 -1429
|
@@ -1,453 +1,506 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import { downloadsDir, warn } from './paths.js'
|
|
4
|
-
import { record } from './activity-log.js'
|
|
5
|
-
import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
|
|
6
|
-
import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
|
|
7
|
-
import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
|
|
8
|
-
import { createEmbeddingDownloadManager } from './embedding-download.js'
|
|
9
|
-
import { createVectorMigrator } from './vector-migration.js'
|
|
10
|
-
import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
|
|
11
|
-
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
12
|
-
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
13
|
-
import { managedEmbeddingRuntime } from './embedding-runtime.js'
|
|
14
|
-
|
|
15
|
-
const root = path.join(downloadsDir(), 'embeddings')
|
|
16
|
-
// 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
|
|
17
|
-
// downloads/embeddings/runtime/<key>。切换/回滚模型永远不碰运行时目录。
|
|
18
|
-
const runtimeRoot = path.join(root, 'runtime')
|
|
19
|
-
let downloader
|
|
20
|
-
let migrator
|
|
21
|
-
let installer
|
|
22
|
-
let runtimeJob = null
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
function
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
job
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
function
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const status =
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
assertProfileVerified(profile)
|
|
219
|
-
return
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
return {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
return
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
export function
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
//
|
|
337
|
-
//
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
}
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
}
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { downloadsDir, warn } from './paths.js'
|
|
4
|
+
import { record } from './activity-log.js'
|
|
5
|
+
import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
|
|
6
|
+
import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
|
|
7
|
+
import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
|
|
8
|
+
import { createEmbeddingDownloadManager } from './embedding-download.js'
|
|
9
|
+
import { createVectorMigrator } from './vector-migration.js'
|
|
10
|
+
import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
|
|
11
|
+
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
12
|
+
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
13
|
+
import { managedEmbeddingRuntime } from './embedding-runtime.js'
|
|
14
|
+
|
|
15
|
+
const root = path.join(downloadsDir(), 'embeddings')
|
|
16
|
+
// 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
|
|
17
|
+
// downloads/embeddings/runtime/<key>。切换/回滚模型永远不碰运行时目录。
|
|
18
|
+
const runtimeRoot = path.join(root, 'runtime')
|
|
19
|
+
let downloader
|
|
20
|
+
let migrator
|
|
21
|
+
let installer
|
|
22
|
+
let runtimeJob = null
|
|
23
|
+
// getLocalVectorState 的短缓存(见该函数):只在没有安装/迁移在跑时生效。
|
|
24
|
+
const VIEW_TTL_MS = 1500
|
|
25
|
+
let viewCache = null
|
|
26
|
+
let vectorMutationBusy = 0
|
|
27
|
+
|
|
28
|
+
function getDownloader() {
|
|
29
|
+
return downloader ||= createEmbeddingDownloadManager({ root })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// warn 走 paths.js 的 sink(index.js 装成 ctx.logger.warn):安装失败必须留可观测信号
|
|
33
|
+
// (§1 规则 10),但它绝不能把召回一起拖垮——召回仍然 fail-open 到词法。
|
|
34
|
+
function getInstaller() {
|
|
35
|
+
return installer ||= managedEmbeddingRuntime({ root: runtimeRoot, logger: { warn: message => warn(message) } })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function envRuntimeDir() {
|
|
39
|
+
const value = String(process.env.DSH_MEMU_EMBED_RUNTIME_DIR || '').trim()
|
|
40
|
+
return value ? path.resolve(value) : null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 目录里真的有一套可 require 的运行时吗(不是「env 设了就算」)。 */
|
|
44
|
+
export function hasEmbeddingRuntimePackages(dir) {
|
|
45
|
+
if (typeof dir !== 'string' || !dir.trim()) return false
|
|
46
|
+
try {
|
|
47
|
+
return fs.statSync(path.join(path.resolve(dir.trim()), 'node_modules', 'onnxruntime-node', 'package.json')).isFile()
|
|
48
|
+
} catch {
|
|
49
|
+
return false
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 运行时状态 = 受管安装事实 + 用户 env 覆盖事实,两者都如实报告。
|
|
55
|
+
* env 指到一个没有运行时的目录时不会被当成 ready,而是回落到受管目录并留 warn。
|
|
56
|
+
*/
|
|
57
|
+
export function localVectorRuntimeStatus(options = {}) {
|
|
58
|
+
const env = envRuntimeDir()
|
|
59
|
+
const envUsable = env != null && hasEmbeddingRuntimePackages(env)
|
|
60
|
+
let status
|
|
61
|
+
try {
|
|
62
|
+
status = getInstaller().getStatus({ deep: options.deep === true, modelId: options.modelId || null })
|
|
63
|
+
} catch (error) {
|
|
64
|
+
status = { status: 'unsupported', ready: false, path: null, platform: null, key: null, error: { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_UNVERIFIED'), message: String(error?.message || error) } }
|
|
65
|
+
}
|
|
66
|
+
if (envUsable) return { ...status, status: 'configured', ready: true, source: 'env', path: env, managedStatus: status.status, error: null }
|
|
67
|
+
return { ...status, source: status.status === 'installed' ? 'managed' : null, ...(env ? { envIgnored: true } : {}) }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// The installer owns the live job; pause/stop must survive the moment after the
|
|
71
|
+
// abort (when that job is already gone) so the UI can still show the partial bytes
|
|
72
|
+
// and let the user switch source before resuming.
|
|
73
|
+
export function runtimeStateView() {
|
|
74
|
+
const base = localVectorRuntimeStatus()
|
|
75
|
+
if (!runtimeJob) return base
|
|
76
|
+
const progress = runtimeJob.progress || base.progress || null
|
|
77
|
+
if (runtimeJob.status === 'downloading') {
|
|
78
|
+
return {
|
|
79
|
+
...base,
|
|
80
|
+
status: 'downloading',
|
|
81
|
+
ready: false,
|
|
82
|
+
path: null,
|
|
83
|
+
downloadSource: runtimeJob.source || base.downloadSource || null,
|
|
84
|
+
progress: progress ? { ...progress, speedBps: Number(progress.speedBps) || 0 } : null,
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
...base,
|
|
89
|
+
status: runtimeJob.status,
|
|
90
|
+
ready: false,
|
|
91
|
+
path: null,
|
|
92
|
+
downloadSource: runtimeJob.source || null,
|
|
93
|
+
progress: progress ? { ...progress, speedBps: 0 } : null,
|
|
94
|
+
error: runtimeJob.error || null,
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 受管安装:只有 confirmed === true 才会联网下载 catalog 里 pin 住的制品。
|
|
100
|
+
* action=pause/stop 只中断当前下载并保留 .part;再次 start 会从稳定缓存续传。
|
|
101
|
+
*/
|
|
102
|
+
export async function installLocalVectorRuntime(options = {}) {
|
|
103
|
+
const action = String(options.action || 'start')
|
|
104
|
+
// 运行时的状态会在这里被改动(开始/暂停/停止),让下一次读取重新算,别把
|
|
105
|
+
// 开始安装前那份缓存当成现状。
|
|
106
|
+
invalidateLocalVectorView()
|
|
107
|
+
const installer = getInstaller()
|
|
108
|
+
if (action === 'pause' || action === 'stop') {
|
|
109
|
+
if (runtimeJob && runtimeJob.status === 'downloading') {
|
|
110
|
+
runtimeJob.stopRequested = action === 'stop'
|
|
111
|
+
runtimeJob.status = action === 'stop' ? 'stopped' : 'paused'
|
|
112
|
+
runtimeJob.progress = runtimeJob.progress ? { ...runtimeJob.progress, speedBps: 0 } : runtimeJob.progress
|
|
113
|
+
try { runtimeJob.controller.abort() } catch {}
|
|
114
|
+
}
|
|
115
|
+
return { runtime: runtimeStateView(), action }
|
|
116
|
+
}
|
|
117
|
+
if (runtimeJob?.status === 'downloading') {
|
|
118
|
+
throw Object.assign(new Error('a managed runtime install is already running'), { code: 'LOCAL_VECTOR_RUNTIME_BUSY' })
|
|
119
|
+
}
|
|
120
|
+
if (runtimeJob?.run) {
|
|
121
|
+
try { await runtimeJob.run } catch {}
|
|
122
|
+
}
|
|
123
|
+
runtimeJob = null
|
|
124
|
+
const controller = new AbortController()
|
|
125
|
+
const onExternalAbort = () => controller.abort()
|
|
126
|
+
options.signal?.addEventListener?.('abort', onExternalAbort, { once: true })
|
|
127
|
+
const job = { status: 'downloading', source: options.source || null, progress: null, controller, stopRequested: false, run: null, error: null }
|
|
128
|
+
runtimeJob = job
|
|
129
|
+
const run = installer.ensure({
|
|
130
|
+
modelId: options.modelId || null,
|
|
131
|
+
confirmed: options.confirmed === true,
|
|
132
|
+
reuseOnly: options.reuseOnly === true,
|
|
133
|
+
source: options.source || null,
|
|
134
|
+
signal: controller.signal,
|
|
135
|
+
onProgress: (progress) => {
|
|
136
|
+
if (runtimeJob === job) job.progress = { ...progress }
|
|
137
|
+
try { options.onProgress?.(progress) } catch {}
|
|
138
|
+
},
|
|
139
|
+
})
|
|
140
|
+
job.run = run
|
|
141
|
+
try {
|
|
142
|
+
const result = await run
|
|
143
|
+
job.status = 'installed'
|
|
144
|
+
if (runtimeJob === job) runtimeJob = null
|
|
145
|
+
invalidateLocalVectorView()
|
|
146
|
+
return { runtime: result, state: getLocalVectorState() }
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (controller.signal.aborted || error?.code === 'LOCAL_VECTOR_RUNTIME_ABORTED' || error?.name === 'AbortError') {
|
|
149
|
+
job.status = job.stopRequested ? 'stopped' : 'paused'
|
|
150
|
+
job.progress = job.progress ? { ...job.progress, speedBps: 0 } : job.progress
|
|
151
|
+
return { runtime: runtimeStateView(), paused: job.status === 'paused', stopped: job.status === 'stopped' }
|
|
152
|
+
}
|
|
153
|
+
job.status = 'failed'
|
|
154
|
+
job.error = { code: String(error?.code || 'LOCAL_VECTOR_RUNTIME_INSTALL_FAILED'), message: String(error?.message || error) }
|
|
155
|
+
throw error
|
|
156
|
+
} finally {
|
|
157
|
+
options.signal?.removeEventListener?.('abort', onExternalAbort)
|
|
158
|
+
if (runtimeJob === job && job.status !== 'paused' && job.status !== 'stopped') runtimeJob = null
|
|
159
|
+
invalidateLocalVectorView()
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 生效的运行时目录:用户显式 env > 已核实的受管目录 > profile 里记录的旧值。 */
|
|
164
|
+
function runtimeDirFor(profile) {
|
|
165
|
+
const env = envRuntimeDir()
|
|
166
|
+
if (env && hasEmbeddingRuntimePackages(env)) return env
|
|
167
|
+
if (env) warn('DSH_MEMU_EMBED_RUNTIME_DIR does not contain the managed runtime packages; using the managed runtime instead')
|
|
168
|
+
const recorded = typeof profile?.runtimeDir === 'string' && profile.runtimeDir.trim() ? profile.runtimeDir.trim() : ''
|
|
169
|
+
if (recorded && hasEmbeddingRuntimePackages(recorded)) return path.resolve(recorded)
|
|
170
|
+
const status = getInstaller().getStatus({ modelId: profile?.catalogId || null })
|
|
171
|
+
return status.status === 'installed' ? status.path : null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function profileFor(catalogId) {
|
|
175
|
+
const id = String(catalogId)
|
|
176
|
+
return profileFromCatalog(id, { modelDir: path.join(root, id), runtimeDir: runtimeDirFor({ catalogId: id }) })
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function installationFor(id, sharedRuntime = null) {
|
|
180
|
+
const status = getDownloader().getStatus(id, { deep: true })
|
|
181
|
+
// 所有可用模型 pin 的是同一个受管 runtime;每个模型各走一遍运行时目录树(几百个文件)
|
|
182
|
+
// 会让每次 getState 多花几百毫秒。上层已经算过一次就复用。
|
|
183
|
+
const runtime = sharedRuntime || localVectorRuntimeStatus({ modelId: id })
|
|
184
|
+
const degraded = status.state === 'installed' && status.verified === false
|
|
185
|
+
return {
|
|
186
|
+
status: degraded ? 'degraded' : status.state,
|
|
187
|
+
installed: status.installed === true && !degraded,
|
|
188
|
+
verified: status.verified ?? null,
|
|
189
|
+
modelDir: status.installed && !degraded ? path.join(root, id) : null,
|
|
190
|
+
runtimeDir: runtime.ready ? runtime.path : null,
|
|
191
|
+
fingerprintMatches: status.fingerprintMatches ?? null,
|
|
192
|
+
error: degraded ? { code: 'EMBEDDING_INSTALL_TAMPERED', message: 'installed embedding files failed deep verification' } : (status.error || null),
|
|
193
|
+
progress: status.progress || null,
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* MemU `commit` 只认 `{ recall_files, resource, user }` 信封(写入与策划路径都走这个形状)。
|
|
199
|
+
* 迁移器原先直接把 `{ name, description, ...entry }` 裸对象传进去:MemU 返回成功却一行
|
|
200
|
+
* 都没写,随后回读不到 → 每条都 `VECTOR_READBACK_FAILED`,整次重建作废。
|
|
201
|
+
*/
|
|
202
|
+
export function migrationCommitPayload(item) {
|
|
203
|
+
const entry = item?.entry || {}
|
|
204
|
+
const text = String(entry.content ?? item?.text ?? '')
|
|
205
|
+
const title = String(entry.title ?? item?.text ?? item?.id ?? '')
|
|
206
|
+
return {
|
|
207
|
+
recall_files: [{ name: String(item?.id ?? ''), track: 'memory', description: title.slice(0, 180), content: text }],
|
|
208
|
+
resource: [],
|
|
209
|
+
user: {},
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function migratorFor() {
|
|
214
|
+
return migrator ||= createVectorMigrator({
|
|
215
|
+
listLibraries: () => listLibraries().map(item => item.id),
|
|
216
|
+
loadIndex: libraryId => libraryId == null ? loadGlobalIndex() : loadPrivateIndex(libraryId),
|
|
217
|
+
commit: ({ db, item, profile }) => {
|
|
218
|
+
assertProfileVerified(profile)
|
|
219
|
+
return memuCommit({
|
|
220
|
+
db,
|
|
221
|
+
vectorProfile: profile,
|
|
222
|
+
route: 'managed-local',
|
|
223
|
+
payload: migrationCommitPayload(item),
|
|
224
|
+
})
|
|
225
|
+
},
|
|
226
|
+
forget: ({ db, itemId }) => memuForget({ db, name: itemId, route: 'managed-local' }),
|
|
227
|
+
listFiles: ({ db, profile }) => {
|
|
228
|
+
assertProfileVerified(profile)
|
|
229
|
+
return memuListFiles({ db, vectorProfile: profile, route: 'managed-local' })
|
|
230
|
+
},
|
|
231
|
+
clearVectorPending: ({ libraryId, ids }) => {
|
|
232
|
+
const wanted = new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))
|
|
233
|
+
if (!wanted.size) return
|
|
234
|
+
const clear = (index) => {
|
|
235
|
+
let touched = 0
|
|
236
|
+
for (const id of wanted) {
|
|
237
|
+
const entry = index.entries?.[id]
|
|
238
|
+
if (entry && entry.vectorPending) { delete entry.vectorPending; touched += 1 }
|
|
239
|
+
}
|
|
240
|
+
return touched
|
|
241
|
+
}
|
|
242
|
+
// The global layer is its own index file; a private library has one each. Nothing
|
|
243
|
+
// crosses between them, so the scope decides which write path to take.
|
|
244
|
+
if (libraryId == null) {
|
|
245
|
+
const index = loadGlobalIndex()
|
|
246
|
+
if (clear(index)) saveGlobalIndex(index)
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
updatePrivateIndex(libraryId, (index) => { clear(index) })
|
|
250
|
+
},
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function getLocalVectorState() {
|
|
255
|
+
const now = Date.now()
|
|
256
|
+
// 完整向量状态包含 catalog、安装记录、代际成员表与缺库扫描,
|
|
257
|
+
// 对设置页的重复查询使用短期缓存以减少读盘。
|
|
258
|
+
// 短 TTL 复用上一次结果;有安装/迁移在跑(vectorMutationBusy / runtimeJob)时
|
|
259
|
+
// 完全不缓存,进度条照旧实时。
|
|
260
|
+
// 只有「真的在下载」的 runtimeJob 才会每帧变(进度);paused/stopped 是静态状态,
|
|
261
|
+
// paused/stopped 不产生下载进度变化,可以继续复用缓存。
|
|
262
|
+
const runtimeMoving = runtimeJob?.status === 'downloading'
|
|
263
|
+
if (!runtimeMoving && vectorMutationBusy === 0 && viewCache && viewCache.until > now) return viewCache.value
|
|
264
|
+
const value = buildLocalVectorState()
|
|
265
|
+
viewCache = (runtimeMoving || vectorMutationBusy > 0) ? null : { until: now + VIEW_TTL_MS, value }
|
|
266
|
+
return value
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** 让下一次 getLocalVectorState 重新算(安装/切换/回滚之后必须调)。 */
|
|
270
|
+
export function invalidateLocalVectorView() { viewCache = null }
|
|
271
|
+
|
|
272
|
+
function buildLocalVectorState() {
|
|
273
|
+
const catalog = getEmbeddingCatalog().map(entry => ({
|
|
274
|
+
id: entry.id,
|
|
275
|
+
displayName: entry.displayName,
|
|
276
|
+
availability: entry.availability,
|
|
277
|
+
dimension: entry.dimension,
|
|
278
|
+
totalBytes: entry.totalBytes,
|
|
279
|
+
languages: Array.isArray(entry.languages) ? [...entry.languages] : [],
|
|
280
|
+
rolesRequired: prefixesRequireRole(entry),
|
|
281
|
+
// 能让用户选的来源(不是目录里写了几个 provider,而是那几个真的固定了 revision)。
|
|
282
|
+
// 顺序就是默认顺序:第一个是 download() 不传 provider 时会用的那个。
|
|
283
|
+
providers: resolveEmbeddingSources(entry).sources.map(source => ({ id: source.provider, label: source.label })),
|
|
284
|
+
pendingReasons: [...(entry.pendingReasons || [])],
|
|
285
|
+
license: entry.license?.base || null,
|
|
286
|
+
}))
|
|
287
|
+
let indexed = null
|
|
288
|
+
try { indexed = migratorFor().membership() } catch { indexed = null }
|
|
289
|
+
const runtime = runtimeStateView()
|
|
290
|
+
return {
|
|
291
|
+
catalog,
|
|
292
|
+
installations: Object.fromEntries(catalog.map(entry => [entry.id, installationFor(entry.id, runtime)])),
|
|
293
|
+
runtime,
|
|
294
|
+
// 2026-11-15 扫雷:向量代际缺库显式化——WebUI/RPC 一眼看到哪个库没进向量库、怎么办。
|
|
295
|
+
vector: { ...vectorStatus(), indexed, missingLibraries: getMissingVectorLibraries({ status: vectorStatus() }) },
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function selectLocalVectorModel(id) {
|
|
300
|
+
const status = getDownloader().getStatus(String(id), { deep: true })
|
|
301
|
+
if (status.state !== 'installed' || status.verified !== true || status.fingerprintMatches === false) {
|
|
302
|
+
const error = new Error('install and verify the local embedding model before selecting it')
|
|
303
|
+
error.code = 'LOCAL_VECTOR_MODEL_NOT_INSTALLED'
|
|
304
|
+
throw error
|
|
305
|
+
}
|
|
306
|
+
setRequestedProfile(profileFor(id), { status: 'requested' })
|
|
307
|
+
invalidateLocalVectorView()
|
|
308
|
+
return getLocalVectorState()
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export async function downloadLocalVectorModel(id, options = {}) {
|
|
312
|
+
const modelId = String(id)
|
|
313
|
+
// provider 只影响「从哪个已固定的来源取字节」;落盘前每个文件都按目录 pin 的
|
|
314
|
+
// sha256 校验,所以换源不会换向量空间,指纹里也没有 provider。
|
|
315
|
+
invalidateLocalVectorView()
|
|
316
|
+
vectorMutationBusy += 1
|
|
317
|
+
try {
|
|
318
|
+
const result = await getDownloader().download(modelId, {
|
|
319
|
+
confirmed: options.confirmed === true,
|
|
320
|
+
...(options.provider ? { provider: String(options.provider) } : {}),
|
|
321
|
+
})
|
|
322
|
+
return { result, runtime: null, state: getLocalVectorState() }
|
|
323
|
+
} finally {
|
|
324
|
+
vectorMutationBusy -= 1
|
|
325
|
+
invalidateLocalVectorView()
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export async function switchLocalVectorProfile(options = {}) {
|
|
330
|
+
const state = vectorStatus()
|
|
331
|
+
const requested = state.requested?.catalogId || options.id
|
|
332
|
+
if (!requested) throw Object.assign(new Error('select a requested local embedding model first'), { code: 'LOCAL_VECTOR_REQUEST_MISSING' })
|
|
333
|
+
const profile = profileFor(requested)
|
|
334
|
+
if (!profile.runtimeDir) throw Object.assign(new Error('a verified managed runtime is required before switching local embeddings; install it from the managed vector settings first'), { code: 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE' })
|
|
335
|
+
// force:同一个 profile 已经 active 时也重建一代。用于库集合变化(如恢复一个曾归档
|
|
336
|
+
// 的库、或首次激活时漏掉了库)后把索引重新追平;不传 force 时保持 already-active
|
|
337
|
+
// 的幂等口径(不重建、不重嵌入)。
|
|
338
|
+
vectorMutationBusy += 1
|
|
339
|
+
try {
|
|
340
|
+
const result = await migratorFor().switchProfile({ profile, force: options.force === true })
|
|
341
|
+
return { result, state: getLocalVectorState() }
|
|
342
|
+
} finally {
|
|
343
|
+
vectorMutationBusy -= 1
|
|
344
|
+
invalidateLocalVectorView()
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export async function rollbackLocalVectorProfile() {
|
|
349
|
+
vectorMutationBusy += 1
|
|
350
|
+
try {
|
|
351
|
+
const result = await migratorFor().rollbackProfile()
|
|
352
|
+
return { result, state: getLocalVectorState() }
|
|
353
|
+
} finally {
|
|
354
|
+
vectorMutationBusy -= 1
|
|
355
|
+
invalidateLocalVectorView()
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function abortLocalVectorMigration() {
|
|
360
|
+
const result = migratorFor().abortPending()
|
|
361
|
+
// 取消本身就是一个状态变化:不清缓存的话,调用方拿到的回包可能是 1.5s 内那份
|
|
362
|
+
// 「仍在迁移中」的过期视图。
|
|
363
|
+
invalidateLocalVectorView()
|
|
364
|
+
return { result, state: getLocalVectorState() }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// 2026-11-15 扫雷补强:向量代际缺库的显式探测与自动追平。
|
|
368
|
+
// 背景:非空库不在当前代际 databases.libraries 里时(profile 切换/迁移中断时缺席),
|
|
369
|
+
// 写入侧 enroll 抛 REBUILD_REQUIRED → commit 降级"仅写索引",召回侧语义腿无 db。
|
|
370
|
+
// 之前只有静默降级,用户没有可行动线索;这里给出状态出口 + 一次自动 force 重建。
|
|
371
|
+
/** 列出「索引非空但不在当前向量代际」的私有库。空库不算:写入路径的 enroll 会自愈。 */
|
|
372
|
+
export function getMissingVectorLibraries({ status = null } = {}) {
|
|
373
|
+
const view = status || vectorStatus()
|
|
374
|
+
if (view.status !== 'active' || !view.active?.databases) return []
|
|
375
|
+
const enrolled = new Set(Object.keys(view.active.databases.libraries || {}))
|
|
376
|
+
const missing = []
|
|
377
|
+
for (const item of listLibraries()) {
|
|
378
|
+
const libraryId = String(item?.id || item || '')
|
|
379
|
+
if (!libraryId || libraryId === 'global' || enrolled.has(libraryId)) continue
|
|
380
|
+
let entries = 0
|
|
381
|
+
try { entries = Object.keys(loadPrivateIndex(libraryId).entries || {}).length } catch { continue }
|
|
382
|
+
if (entries > 0) missing.push(libraryId)
|
|
383
|
+
}
|
|
384
|
+
return missing
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 每个向量代际最多自动重建 2 次(防 embed 端点不可用时空转重试);进程重启后清零,
|
|
388
|
+
// 重启后再试一次是可接受的(缺库状态本身就在账上,不会丢)。
|
|
389
|
+
const autoRebuildAttempts = new Map()
|
|
390
|
+
let autoRebuildInFlight = false
|
|
391
|
+
|
|
392
|
+
export function autoRebuildAttemptCount(generation) {
|
|
393
|
+
return Number(autoRebuildAttempts.get(generation)) || 0
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* 探测到缺库时自动 force 重建向量代际(重嵌入全部库,本地 worker,无 API 费用)。
|
|
398
|
+
* 幂等护栏:向量未激活 / 有迁移在途 / 本进程同代际已试过 2 次 / 已有重建在跑 → 跳过。
|
|
399
|
+
* 失败不抛——调用方(召回降级分支)是热路径,结果走 activity-log 可观测。
|
|
400
|
+
*/
|
|
401
|
+
export async function maybeAutoRebuildVectorGeneration() {
|
|
402
|
+
if (autoRebuildInFlight) return { skipped: 'already-in-flight' }
|
|
403
|
+
const view = vectorStatus()
|
|
404
|
+
if (view.status !== 'active' || !view.active) return { skipped: 'vector-not-active' }
|
|
405
|
+
if (view.pending) return { skipped: 'migration-in-progress' }
|
|
406
|
+
const missing = getMissingVectorLibraries({ status: view })
|
|
407
|
+
if (!missing.length) return { skipped: 'nothing-missing' }
|
|
408
|
+
const generation = view.active.generation
|
|
409
|
+
const attempts = Number(autoRebuildAttempts.get(generation)) || 0
|
|
410
|
+
if (attempts >= 2) return { skipped: 'attempt-cap-reached', generation, missing }
|
|
411
|
+
autoRebuildAttempts.set(generation, attempts + 1)
|
|
412
|
+
autoRebuildInFlight = true
|
|
413
|
+
try {
|
|
414
|
+
warn('vector auto-rebuild: generation ' + generation + ' is missing libraries (' + missing.join(', ') + ') — forcing a shadow rebuild')
|
|
415
|
+
record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建开始', detail: { generation, missing } })
|
|
416
|
+
const result = await switchLocalVectorProfile({ id: view.active.profile?.catalogId ?? null, force: true })
|
|
417
|
+
record({ kind: 'vector', level: 'info', scope: 'global', message: '向量代际缺库,自动 force 重建结束', detail: { generation, missing, result: result?.result ?? null } })
|
|
418
|
+
return { started: true, generation, missing, result: result?.result ?? null }
|
|
419
|
+
} catch (error) {
|
|
420
|
+
const message = String(error?.message || error)
|
|
421
|
+
warn('vector auto-rebuild failed: ' + message)
|
|
422
|
+
record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量代际缺库,自动 force 重建失败', detail: { generation, missing, error: message.slice(0, 300) } })
|
|
423
|
+
return { started: false, generation, missing, error: message.slice(0, 300) }
|
|
424
|
+
} finally {
|
|
425
|
+
autoRebuildInFlight = false
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 启动 loopback worker 并真的打一次 POST /v1/embeddings:200 + 正确维度 + 有限数值才算就绪。
|
|
431
|
+
* 失败一律带 fallback: 'lexical',上游照旧 fail-open,但错误必须留在日志/lastRecallError 里。
|
|
432
|
+
*/
|
|
433
|
+
export async function healthCheckLocalVector(profile, { timeoutMs = 30_000 } = {}) {
|
|
434
|
+
const endpoint = await embeddingWorkerManager().acquire(profile)
|
|
435
|
+
const url = new URL('/v1/embeddings', endpoint.baseUrl).href
|
|
436
|
+
// A profile with different query/document prefixes has no role-less reading: the
|
|
437
|
+
// worker refuses a bare model id rather than pick one. Probe it as a document, which
|
|
438
|
+
// is what the writing path (and the reindex migration) will ask for.
|
|
439
|
+
const servedModel = endpoint.rolesRequired === true ? modelIdForRole(endpoint.model, 'document') : endpoint.model
|
|
440
|
+
let response
|
|
441
|
+
try {
|
|
442
|
+
response = await fetch(url, {
|
|
443
|
+
method: 'POST',
|
|
444
|
+
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + String(endpoint.token) },
|
|
445
|
+
body: JSON.stringify({ model: servedModel, input: ['本地向量健康检查'] }),
|
|
446
|
+
signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 30_000)),
|
|
447
|
+
})
|
|
448
|
+
} catch (error) {
|
|
449
|
+
throw Object.assign(new Error('the local embedding worker did not answer /v1/embeddings: ' + String(error?.message || error)), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
|
|
450
|
+
}
|
|
451
|
+
if (!response.ok) {
|
|
452
|
+
throw Object.assign(new Error('the local embedding worker answered /v1/embeddings with ' + response.status), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', status: response.status })
|
|
453
|
+
}
|
|
454
|
+
const payload = await response.json().catch(() => null)
|
|
455
|
+
const vector = payload?.data?.[0]?.embedding
|
|
456
|
+
const dimension = Array.isArray(vector) ? vector.length : 0
|
|
457
|
+
if (!Array.isArray(vector) || dimension !== Number(profile.dimension)) {
|
|
458
|
+
throw Object.assign(new Error('the local embedding worker returned no ' + Number(profile.dimension) + '-dimension vector'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical', dimension })
|
|
459
|
+
}
|
|
460
|
+
if (!vector.every(value => typeof value === 'number' && Number.isFinite(value))) {
|
|
461
|
+
throw Object.assign(new Error('the local embedding worker returned non-finite vector components'), { code: 'LOCAL_VECTOR_HEALTH_FAILED', fallback: 'lexical' })
|
|
462
|
+
}
|
|
463
|
+
return { ok: true, path: '/v1/embeddings', status: response.status, model: endpoint.model, dimension }
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* 首用引导:runtime 复用(或确认后安装)→ 起 worker → /v1/embeddings 健康检查。
|
|
468
|
+
* 没有云端回退:任一环失败都是 typed error + fallback=lexical。
|
|
469
|
+
*/
|
|
470
|
+
export async function bootstrapLocalVector(options = {}) {
|
|
471
|
+
const state = vectorStatus()
|
|
472
|
+
const catalogId = options.id || state.active?.profile?.catalogId || state.requested?.catalogId || null
|
|
473
|
+
if (!catalogId) throw Object.assign(new Error('select a local embedding model before bootstrapping the local runtime'), { code: 'LOCAL_VECTOR_NOT_SELECTED' })
|
|
474
|
+
const before = localVectorRuntimeStatus({ modelId: catalogId })
|
|
475
|
+
let runtime
|
|
476
|
+
if (before.status === 'configured') {
|
|
477
|
+
runtime = { status: 'configured', ready: true, source: 'env', path: before.path, reused: true }
|
|
478
|
+
} else {
|
|
479
|
+
try {
|
|
480
|
+
runtime = await getInstaller().ensure({
|
|
481
|
+
modelId: catalogId,
|
|
482
|
+
confirmed: options.confirmed === true,
|
|
483
|
+
reuseOnly: options.confirmed !== true,
|
|
484
|
+
signal: options.signal,
|
|
485
|
+
onProgress: options.onProgress,
|
|
486
|
+
})
|
|
487
|
+
} catch (error) {
|
|
488
|
+
// 引导失败照旧 fail-open 到词法:错误如实抛出,但必须带上降级标记。
|
|
489
|
+
if (error && typeof error === 'object' && error.fallback === undefined) error.fallback = 'lexical'
|
|
490
|
+
throw error
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const health = await healthCheckLocalVector(profileFor(catalogId), { timeoutMs: options.timeoutMs })
|
|
494
|
+
return { ok: true, runtime: { status: runtime.status, ready: true, path: runtime.path || null, key: runtime.key || null, source: runtime.source || 'managed', reused: runtime.reused === true }, model: health.model, dimension: health.dimension, health, state: getLocalVectorState() }
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
export async function testLocalVector() {
|
|
498
|
+
return bootstrapLocalVector({ confirmed: false })
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function closeLocalVectorService() {
|
|
502
|
+
// 关服务等于放弃本进程这份视图:下一位读者不该读到上个连接留下的状态。
|
|
503
|
+
invalidateLocalVectorView()
|
|
504
|
+
try { getDownloader().dispose() } catch {}
|
|
505
|
+
try { getInstaller().abort() } catch {}
|
|
506
|
+
}
|