dsh-memu-memory 1.4.2 → 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 -110
- package/CHANGELOG.md +169 -868
- 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 -75
- 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 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- 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 -9751
- 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 -1103
- 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 -4941
- 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 -82
- 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 -2532
- 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 -1091
- 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 -153
- 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 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- 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 -108
- 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 -416
- 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 -617
- 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 -138
- 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 -24
- 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 -222
- 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 -213
- 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 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1521 -1429
|
@@ -1,607 +1,637 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
import {
|
|
5
|
-
getEmbeddingCatalog,
|
|
6
|
-
getEmbeddingModel,
|
|
7
|
-
PROVIDERS,
|
|
8
|
-
readOnnxGraphHeader,
|
|
9
|
-
resolveEmbeddingSources,
|
|
10
|
-
validateEmbeddingManifest,
|
|
11
|
-
} from './embedding-catalog.js'
|
|
12
|
-
|
|
13
|
-
// §14.4/§14.7 受管隔离下载器:
|
|
14
|
-
// staging → bytes/sha256 校验 → 模型 smoke(图头 + config/tokenizer 结构)→ 原子安装。
|
|
15
|
-
// 硬约束:
|
|
16
|
-
// 1. 只有用户在 UI 里明确确认(confirmed: true)才会联网;没有确认就绝不发请求。
|
|
17
|
-
// 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
|
|
18
|
-
// 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
|
|
19
|
-
// 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
|
|
20
|
-
// 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
|
|
21
|
-
// 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
|
|
22
|
-
|
|
23
|
-
const INSTALL_RECORD = 'installed.json'
|
|
24
|
-
const STAGING_DIR = '.staging'
|
|
25
|
-
const TRASH_DIR = '.trash'
|
|
26
|
-
const CACHE_DIR = '.cache'
|
|
27
|
-
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
|
-
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
|
-
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
30
|
-
// S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
|
|
31
|
-
const DEFAULT_FETCH_TIMEOUT_MS = 600_000
|
|
32
|
-
const DEFAULT_STALL_TIMEOUT_MS = 30_000
|
|
33
|
-
|
|
34
|
-
function fail(code, message, extra) {
|
|
35
|
-
const error = new Error(message)
|
|
36
|
-
error.code = code
|
|
37
|
-
if (extra) Object.assign(error, extra)
|
|
38
|
-
return error
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function sha256FileSync(file) {
|
|
42
|
-
const hash = crypto.createHash('sha256')
|
|
43
|
-
const fd = fs.openSync(file, 'r')
|
|
44
|
-
try {
|
|
45
|
-
const buffer = Buffer.allocUnsafe(64 * 1024)
|
|
46
|
-
let read
|
|
47
|
-
while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
|
|
48
|
-
} finally {
|
|
49
|
-
fs.closeSync(fd)
|
|
50
|
-
}
|
|
51
|
-
return hash.digest('hex')
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
|
|
55
|
-
// 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
|
|
56
|
-
function ensureFreeSpace(dir, requiredBytes) {
|
|
57
|
-
if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
|
|
58
|
-
let available = null
|
|
59
|
-
try {
|
|
60
|
-
const stat = fs.statfsSync(dir)
|
|
61
|
-
available = Number(stat.bavail) * Number(stat.bsize)
|
|
62
|
-
} catch {
|
|
63
|
-
return
|
|
64
|
-
}
|
|
65
|
-
if (!Number.isFinite(available) || available <= 0) return
|
|
66
|
-
// 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
|
|
67
|
-
if (available < requiredBytes * 2) {
|
|
68
|
-
throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function isAbort(error, signal) {
|
|
73
|
-
return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function readJsonFile(file) {
|
|
77
|
-
try {
|
|
78
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
79
|
-
} catch {
|
|
80
|
-
return null
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Installed records are local state, not a trusted manifest. Resolve every
|
|
85
|
-
// recorded file without following symlinks out of its model directory.
|
|
86
|
-
function modelFileTarget(dir, relative) {
|
|
87
|
-
const text = String(relative || '')
|
|
88
|
-
if (!text || text.includes('\\') || path.isAbsolute(text)) return null
|
|
89
|
-
const parts = text.split('/')
|
|
90
|
-
if (parts.some(part => !part || part === '.' || part === '..')) return null
|
|
91
|
-
const root = path.resolve(dir)
|
|
92
|
-
const target = path.resolve(root, ...parts)
|
|
93
|
-
if (target !== root && !target.startsWith(root + path.sep)) return null
|
|
94
|
-
try {
|
|
95
|
-
const rootReal = fs.realpathSync(root)
|
|
96
|
-
const targetReal = fs.realpathSync(target)
|
|
97
|
-
if (targetReal !== rootReal && !targetReal.startsWith(rootReal + path.sep)) return null
|
|
98
|
-
} catch {
|
|
99
|
-
return null
|
|
100
|
-
}
|
|
101
|
-
return target
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function isRegularNonSymlink(file) {
|
|
105
|
-
try {
|
|
106
|
-
const stat = fs.lstatSync(file)
|
|
107
|
-
return stat.isFile() && !stat.isSymbolicLink()
|
|
108
|
-
} catch {
|
|
109
|
-
return false
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function writeJsonAtomic(file, value) {
|
|
114
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
115
|
-
const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
|
|
116
|
-
fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
|
|
117
|
-
fs.renameSync(temporary, file)
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* 默认模型 smoke:不需要 onnxruntime。读 config/tokenizer/图头,核对 manifest 声明的
|
|
122
|
-
* 维度、最大长度、输入输出名与 dtype、opset、自包含性、词表规模。真实推理 smoke 要等
|
|
123
|
-
* ORT 装好后再加(§14.11),这里不假装它已经跑过。
|
|
124
|
-
*/
|
|
125
|
-
export async function verifyStagedArtifacts({ entry, dir }) {
|
|
126
|
-
const checks = []
|
|
127
|
-
const fileOf = role => (entry.files || []).find(file => file.role === role) || null
|
|
128
|
-
const bytesOf = role => {
|
|
129
|
-
const file = fileOf(role)
|
|
130
|
-
if (!file) return null
|
|
131
|
-
return fs.readFileSync(path.join(dir, ...String(file.path).split('/')))
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const configBytes = bytesOf('config')
|
|
135
|
-
if (!configBytes) throw new Error('staged artifact has no config.json')
|
|
136
|
-
const config = JSON.parse(configBytes.toString('utf8'))
|
|
137
|
-
if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
|
|
138
|
-
checks.push('config.hidden_size=' + config.hidden_size)
|
|
139
|
-
//
|
|
140
|
-
// (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
|
|
141
|
-
// 而这个选择本来就在 profile 指纹里,可复现。
|
|
142
|
-
if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
|
|
143
|
-
throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
|
|
144
|
-
}
|
|
145
|
-
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
|
|
146
|
-
|
|
147
|
-
const vocabBytes = bytesOf('vocab')
|
|
148
|
-
if (vocabBytes && Number.isInteger(config.vocab_size)) {
|
|
149
|
-
const vocabLines = vocabBytes.toString('utf8').split(/\r?\n/).filter(line => line.length > 0).length
|
|
150
|
-
if (vocabLines !== config.vocab_size) throw new Error(`vocab.txt has ${vocabLines} entries but config.vocab_size is ${config.vocab_size}`)
|
|
151
|
-
checks.push('vocab.txt=' + vocabLines)
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const tokenizerBytes = bytesOf('tokenizer')
|
|
155
|
-
if (tokenizerBytes) {
|
|
156
|
-
const tokenizer = JSON.parse(tokenizerBytes.toString('utf8'))
|
|
157
|
-
const vocab = tokenizer?.model?.vocab
|
|
158
|
-
if (!vocab || typeof vocab !== 'object' || Object.keys(vocab).length < 2) throw new Error('tokenizer.json has no usable model.vocab')
|
|
159
|
-
checks.push('tokenizer.vocab=' + Object.keys(vocab).length)
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const poolingBytes = bytesOf('pooling-config')
|
|
163
|
-
if (poolingBytes) {
|
|
164
|
-
const pooling = JSON.parse(poolingBytes.toString('utf8'))
|
|
165
|
-
if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
|
|
166
|
-
if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
if (
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
//
|
|
197
|
-
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
*
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
const
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
//
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
//
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
if (
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
if (
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
const
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import {
|
|
5
|
+
getEmbeddingCatalog,
|
|
6
|
+
getEmbeddingModel,
|
|
7
|
+
PROVIDERS,
|
|
8
|
+
readOnnxGraphHeader,
|
|
9
|
+
resolveEmbeddingSources,
|
|
10
|
+
validateEmbeddingManifest,
|
|
11
|
+
} from './embedding-catalog.js'
|
|
12
|
+
|
|
13
|
+
// §14.4/§14.7 受管隔离下载器:
|
|
14
|
+
// staging → bytes/sha256 校验 → 模型 smoke(图头 + config/tokenizer 结构)→ 原子安装。
|
|
15
|
+
// 硬约束:
|
|
16
|
+
// 1. 只有用户在 UI 里明确确认(confirmed: true)才会联网;没有确认就绝不发请求。
|
|
17
|
+
// 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
|
|
18
|
+
// 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
|
|
19
|
+
// 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
|
|
20
|
+
// 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
|
|
21
|
+
// 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
|
|
22
|
+
|
|
23
|
+
const INSTALL_RECORD = 'installed.json'
|
|
24
|
+
const STAGING_DIR = '.staging'
|
|
25
|
+
const TRASH_DIR = '.trash'
|
|
26
|
+
const CACHE_DIR = '.cache'
|
|
27
|
+
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
|
+
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
|
+
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
30
|
+
// S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
|
|
31
|
+
const DEFAULT_FETCH_TIMEOUT_MS = 600_000
|
|
32
|
+
const DEFAULT_STALL_TIMEOUT_MS = 30_000
|
|
33
|
+
|
|
34
|
+
function fail(code, message, extra) {
|
|
35
|
+
const error = new Error(message)
|
|
36
|
+
error.code = code
|
|
37
|
+
if (extra) Object.assign(error, extra)
|
|
38
|
+
return error
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sha256FileSync(file) {
|
|
42
|
+
const hash = crypto.createHash('sha256')
|
|
43
|
+
const fd = fs.openSync(file, 'r')
|
|
44
|
+
try {
|
|
45
|
+
const buffer = Buffer.allocUnsafe(64 * 1024)
|
|
46
|
+
let read
|
|
47
|
+
while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
|
|
48
|
+
} finally {
|
|
49
|
+
fs.closeSync(fd)
|
|
50
|
+
}
|
|
51
|
+
return hash.digest('hex')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
|
|
55
|
+
// 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
|
|
56
|
+
function ensureFreeSpace(dir, requiredBytes) {
|
|
57
|
+
if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
|
|
58
|
+
let available = null
|
|
59
|
+
try {
|
|
60
|
+
const stat = fs.statfsSync(dir)
|
|
61
|
+
available = Number(stat.bavail) * Number(stat.bsize)
|
|
62
|
+
} catch {
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
if (!Number.isFinite(available) || available <= 0) return
|
|
66
|
+
// 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
|
|
67
|
+
if (available < requiredBytes * 2) {
|
|
68
|
+
throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isAbort(error, signal) {
|
|
73
|
+
return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readJsonFile(file) {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
79
|
+
} catch {
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Installed records are local state, not a trusted manifest. Resolve every
|
|
85
|
+
// recorded file without following symlinks out of its model directory.
|
|
86
|
+
function modelFileTarget(dir, relative) {
|
|
87
|
+
const text = String(relative || '')
|
|
88
|
+
if (!text || text.includes('\\') || path.isAbsolute(text)) return null
|
|
89
|
+
const parts = text.split('/')
|
|
90
|
+
if (parts.some(part => !part || part === '.' || part === '..')) return null
|
|
91
|
+
const root = path.resolve(dir)
|
|
92
|
+
const target = path.resolve(root, ...parts)
|
|
93
|
+
if (target !== root && !target.startsWith(root + path.sep)) return null
|
|
94
|
+
try {
|
|
95
|
+
const rootReal = fs.realpathSync(root)
|
|
96
|
+
const targetReal = fs.realpathSync(target)
|
|
97
|
+
if (targetReal !== rootReal && !targetReal.startsWith(rootReal + path.sep)) return null
|
|
98
|
+
} catch {
|
|
99
|
+
return null
|
|
100
|
+
}
|
|
101
|
+
return target
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isRegularNonSymlink(file) {
|
|
105
|
+
try {
|
|
106
|
+
const stat = fs.lstatSync(file)
|
|
107
|
+
return stat.isFile() && !stat.isSymbolicLink()
|
|
108
|
+
} catch {
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function writeJsonAtomic(file, value) {
|
|
114
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
115
|
+
const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
|
|
116
|
+
fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
|
|
117
|
+
fs.renameSync(temporary, file)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 默认模型 smoke:不需要 onnxruntime。读 config/tokenizer/图头,核对 manifest 声明的
|
|
122
|
+
* 维度、最大长度、输入输出名与 dtype、opset、自包含性、词表规模。真实推理 smoke 要等
|
|
123
|
+
* ORT 装好后再加(§14.11),这里不假装它已经跑过。
|
|
124
|
+
*/
|
|
125
|
+
export async function verifyStagedArtifacts({ entry, dir }) {
|
|
126
|
+
const checks = []
|
|
127
|
+
const fileOf = role => (entry.files || []).find(file => file.role === role) || null
|
|
128
|
+
const bytesOf = role => {
|
|
129
|
+
const file = fileOf(role)
|
|
130
|
+
if (!file) return null
|
|
131
|
+
return fs.readFileSync(path.join(dir, ...String(file.path).split('/')))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const configBytes = bytesOf('config')
|
|
135
|
+
if (!configBytes) throw new Error('staged artifact has no config.json')
|
|
136
|
+
const config = JSON.parse(configBytes.toString('utf8'))
|
|
137
|
+
if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
|
|
138
|
+
checks.push('config.hidden_size=' + config.hidden_size)
|
|
139
|
+
// 分窗不能超过制品声明的位置上限;使用更小窗口可以控制推理成本
|
|
140
|
+
// (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
|
|
141
|
+
// 而这个选择本来就在 profile 指纹里,可复现。
|
|
142
|
+
if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
|
|
143
|
+
throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
|
|
144
|
+
}
|
|
145
|
+
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
|
|
146
|
+
|
|
147
|
+
const vocabBytes = bytesOf('vocab')
|
|
148
|
+
if (vocabBytes && Number.isInteger(config.vocab_size)) {
|
|
149
|
+
const vocabLines = vocabBytes.toString('utf8').split(/\r?\n/).filter(line => line.length > 0).length
|
|
150
|
+
if (vocabLines !== config.vocab_size) throw new Error(`vocab.txt has ${vocabLines} entries but config.vocab_size is ${config.vocab_size}`)
|
|
151
|
+
checks.push('vocab.txt=' + vocabLines)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const tokenizerBytes = bytesOf('tokenizer')
|
|
155
|
+
if (tokenizerBytes) {
|
|
156
|
+
const tokenizer = JSON.parse(tokenizerBytes.toString('utf8'))
|
|
157
|
+
const vocab = tokenizer?.model?.vocab
|
|
158
|
+
if (!vocab || typeof vocab !== 'object' || Object.keys(vocab).length < 2) throw new Error('tokenizer.json has no usable model.vocab')
|
|
159
|
+
checks.push('tokenizer.vocab=' + Object.keys(vocab).length)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const poolingBytes = bytesOf('pooling-config')
|
|
163
|
+
if (poolingBytes) {
|
|
164
|
+
const pooling = JSON.parse(poolingBytes.toString('utf8'))
|
|
165
|
+
if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
|
|
166
|
+
if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
|
|
167
|
+
// last-token pooling 必须与基座配置中的 lasttoken 声明一致。
|
|
168
|
+
if (entry.pooling === 'last' && pooling.pooling_mode_lasttoken !== true) throw new Error('pooling config is not last-token pooling')
|
|
169
|
+
if (Number.isInteger(pooling.word_embedding_dimension) && pooling.word_embedding_dimension !== entry.dimension) {
|
|
170
|
+
throw new Error(`pooling word_embedding_dimension ${pooling.word_embedding_dimension} does not match dimension ${entry.dimension}`)
|
|
171
|
+
}
|
|
172
|
+
checks.push('pooling=' + entry.pooling)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const graphFile = fileOf('graph')
|
|
176
|
+
if (!graphFile) throw new Error('staged artifact has no graph file')
|
|
177
|
+
const graphBytes = bytesOf('graph')
|
|
178
|
+
const header = readOnnxGraphHeader(graphBytes)
|
|
179
|
+
if (!header.selfContained) throw new Error('graph references external data or has no initializer bytes; this build only installs self-contained graphs')
|
|
180
|
+
checks.push('graph.selfContained=true', 'graph.initializerBytes=' + header.initializerBytes)
|
|
181
|
+
const declared = entry.graph || {}
|
|
182
|
+
const declaredInputs = (declared.inputs || []).map(io => io.name).sort()
|
|
183
|
+
const actualInputs = header.inputs.map(io => io.name).sort()
|
|
184
|
+
if (declaredInputs.join(',') !== actualInputs.join(',')) {
|
|
185
|
+
throw new Error(`graph inputs ${actualInputs.join(',')} do not match manifest ${declaredInputs.join(',')}`)
|
|
186
|
+
}
|
|
187
|
+
for (const io of declared.inputs || []) {
|
|
188
|
+
const actual = header.inputs.find(item => item.name === io.name)
|
|
189
|
+
if (actual.dtype !== io.dtype) throw new Error(`graph input ${io.name} dtype ${actual.dtype} does not match manifest ${io.dtype}`)
|
|
190
|
+
}
|
|
191
|
+
const declaredOutput = (declared.outputs || [])[0]
|
|
192
|
+
const actualOutput = header.outputs[0]
|
|
193
|
+
if (!actualOutput) throw new Error('graph has no outputs')
|
|
194
|
+
if (declaredOutput && actualOutput.name !== declaredOutput.name) throw new Error(`graph output ${actualOutput.name} does not match manifest ${declaredOutput.name}`)
|
|
195
|
+
// float32 与 float16 都能被 worker 池化(fp16 走 Number() 取值),但别的 dtype
|
|
196
|
+
// (int8 输出、string)不是 embedding worker 该假装能吃的东西。声明与实际必须一致。
|
|
197
|
+
if (!['float32', 'float16'].includes(actualOutput.dtype)) throw new Error(`graph output dtype ${actualOutput.dtype} is not float32/float16`)
|
|
198
|
+
if (declaredOutput && declaredOutput.dtype && actualOutput.dtype !== declaredOutput.dtype) {
|
|
199
|
+
throw new Error(`graph output dtype ${actualOutput.dtype} does not match manifest ${declaredOutput.dtype}`)
|
|
200
|
+
}
|
|
201
|
+
const lastDim = Array.isArray(actualOutput.shape) ? actualOutput.shape[actualOutput.shape.length - 1] : null
|
|
202
|
+
if (lastDim !== entry.dimension) throw new Error(`graph output last dim ${lastDim} does not match dimension ${entry.dimension}`)
|
|
203
|
+
checks.push('graph.output=' + actualOutput.name + ':' + actualOutput.dtype + '[' + lastDim + ']')
|
|
204
|
+
if (Number.isInteger(declared.opset)) {
|
|
205
|
+
const defaultOpset = header.opsets.find(opset => !opset.domain)
|
|
206
|
+
if (!defaultOpset || defaultOpset.version !== declared.opset) {
|
|
207
|
+
throw new Error(`graph opset ${defaultOpset?.version} does not match manifest ${declared.opset}`)
|
|
208
|
+
}
|
|
209
|
+
checks.push('graph.opset=' + defaultOpset.version)
|
|
210
|
+
}
|
|
211
|
+
return { ok: true, checks }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* createEmbeddingDownloadManager({ root, catalog?, fetchImpl?, verifyModel? })
|
|
216
|
+
* root: 本插件受管模型目录(复用 paths.js 的数据目录,不要放进宿主 app.asar)。
|
|
217
|
+
*/
|
|
218
|
+
export function createEmbeddingDownloadManager(options = {}) {
|
|
219
|
+
const { root, fetchImpl = fetch, verifyModel, maxFileBytes = DEFAULT_MAX_FILE_BYTES, now = () => new Date().toISOString() } = options
|
|
220
|
+
if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingDownloadManager requires a root directory')
|
|
221
|
+
const baseDir = path.resolve(root)
|
|
222
|
+
const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
|
|
223
|
+
const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
|
|
224
|
+
const extraCatalog = Array.isArray(options.catalog) ? options.catalog : []
|
|
225
|
+
const jobs = new Map()
|
|
226
|
+
// 失败/取消结果单独记账:jobs 只表示「在途」,所以重试不会被误判成 BUSY,
|
|
227
|
+
// 但 UI 仍能读到上一次的失败原因(§14.7 的 failed 状态)。
|
|
228
|
+
const outcomes = new Map()
|
|
229
|
+
|
|
230
|
+
const lookup = id => extraCatalog.find(entry => entry && entry.id === id) || getEmbeddingModel(id)
|
|
231
|
+
|
|
232
|
+
function insideRoot(target) {
|
|
233
|
+
const resolved = path.resolve(target)
|
|
234
|
+
if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) {
|
|
235
|
+
throw fail('EMBEDDING_PATH_ESCAPE', `refusing to touch a path outside the model root: ${resolved}`)
|
|
236
|
+
}
|
|
237
|
+
return resolved
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const modelDir = id => insideRoot(path.join(baseDir, id))
|
|
241
|
+
const recordPath = id => path.join(modelDir(id), INSTALL_RECORD)
|
|
242
|
+
// S-16:续传用的稳定 .part 放在独立 .cache,与 .staging 隔离(staging 仍保持
|
|
243
|
+
// 「安装成功后必须为空」的既有语义)。文件名带 sha256,换源/换版本不会误复用。
|
|
244
|
+
const partPathFor = file => {
|
|
245
|
+
const safe = String(file.path).split('/').pop().replace(/[^A-Za-z0-9._-]+/g, '-')
|
|
246
|
+
return path.join(insideRoot(path.join(baseDir, CACHE_DIR)), `${safe}-${file.sha256}.part`)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function readInstall(entry) {
|
|
250
|
+
const dir = modelDir(entry.id)
|
|
251
|
+
try {
|
|
252
|
+
const dirStat = fs.lstatSync(dir)
|
|
253
|
+
if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
|
|
254
|
+
} catch { return null }
|
|
255
|
+
const record = readJsonFile(recordPath(entry.id))
|
|
256
|
+
if (!record || typeof record !== 'object') return null
|
|
257
|
+
if (record.id !== entry.id) return { ok: false, code: 'EMBEDDING_INSTALL_MISMATCH' }
|
|
258
|
+
const files = Array.isArray(record.files) ? record.files : []
|
|
259
|
+
if (!files.length) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
|
|
260
|
+
for (const file of files) {
|
|
261
|
+
const target = modelFileTarget(dir, file.path)
|
|
262
|
+
if (!target || !isRegularNonSymlink(target)) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
|
|
263
|
+
let stat
|
|
264
|
+
try { stat = fs.lstatSync(target) } catch { return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' } }
|
|
265
|
+
if (stat.size !== file.bytes) return { ok: false, code: 'EMBEDDING_INSTALL_INCOMPLETE' }
|
|
266
|
+
}
|
|
267
|
+
return { ok: true, record }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 深校验需要读取并哈希全部模型文件。按文件 size、mtime 与安装记录中的 sha256
|
|
271
|
+
// 缓存校验结论,避免设置页重复查询时反复读盘;指纹变化后重新校验。
|
|
272
|
+
const deepVerdicts = new Map()
|
|
273
|
+
|
|
274
|
+
function deepFingerprint(dir, record) {
|
|
275
|
+
const parts = []
|
|
276
|
+
for (const file of record.files || []) {
|
|
277
|
+
const target = modelFileTarget(dir, file.path)
|
|
278
|
+
if (!target || !isRegularNonSymlink(target)) return null
|
|
279
|
+
let stat
|
|
280
|
+
try { stat = fs.lstatSync(target) } catch { return null }
|
|
281
|
+
// readInstall 已经查过 size;这里再查一次是因为缓存要能识别「同尺寸换内容」以外
|
|
282
|
+
// 的一切改动,而 mtime 只在真有写入时才变。
|
|
283
|
+
if (stat.size !== file.bytes) return null
|
|
284
|
+
// ino/ctimeMs 一起进指纹:同尺寸 + 同 mtime 的「整体替换」(tar 还原、touch -r、
|
|
285
|
+
// FAT 的 2s 粒度)靠这两项才抓得住。
|
|
286
|
+
parts.push(`${file.path}\u0000${file.bytes}\u0000${stat.mtimeMs}\u0000${stat.ctimeMs}\u0000${stat.ino}\u0000${file.sha256}`)
|
|
287
|
+
}
|
|
288
|
+
return parts.join('\u0001')
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function deepVerify(entry, record) {
|
|
292
|
+
const dir = modelDir(entry.id)
|
|
293
|
+
const key = deepFingerprint(dir, record)
|
|
294
|
+
if (key === null) return false
|
|
295
|
+
const cached = deepVerdicts.get(entry.id)
|
|
296
|
+
if (cached && cached.key === key) return cached.verdict
|
|
297
|
+
let verdict = true
|
|
298
|
+
for (const file of record.files || []) {
|
|
299
|
+
const target = modelFileTarget(dir, file.path)
|
|
300
|
+
if (!target) { verdict = false; break }
|
|
301
|
+
let hash
|
|
302
|
+
try { hash = crypto.createHash('sha256').update(fs.readFileSync(target)).digest('hex') } catch {
|
|
303
|
+
// A transient read failure is not a content verdict; retry unchanged files next time.
|
|
304
|
+
deepVerdicts.delete(entry.id)
|
|
305
|
+
return false
|
|
306
|
+
}
|
|
307
|
+
if (hash !== file.sha256) { verdict = false; break }
|
|
308
|
+
}
|
|
309
|
+
deepVerdicts.set(entry.id, { key, verdict })
|
|
310
|
+
return verdict
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function getStatus(id, statusOptions = {}) {
|
|
314
|
+
const key = typeof id === 'string' ? id : String(id || '')
|
|
315
|
+
const entry = lookup(key)
|
|
316
|
+
if (!entry) {
|
|
317
|
+
return { id: key, known: false, state: 'unknown', installed: false, active: false, downloadable: false, error: { code: 'EMBEDDING_MODEL_UNKNOWN', message: `unknown embedding model: ${key}` } }
|
|
318
|
+
}
|
|
319
|
+
const base = {
|
|
320
|
+
id: entry.id,
|
|
321
|
+
known: true,
|
|
322
|
+
availability: entry.availability,
|
|
323
|
+
downloadable: entry.availability === 'available',
|
|
324
|
+
active: false, // 下载器永远不激活 profile(§14.8);active 由迁移模块负责
|
|
325
|
+
dimension: entry.dimension,
|
|
326
|
+
maxTokens: entry.maxTokens,
|
|
327
|
+
pooling: entry.pooling,
|
|
328
|
+
normalization: entry.normalization,
|
|
329
|
+
totalBytes: entry.totalBytes,
|
|
330
|
+
fingerprint: entry.profileFingerprint,
|
|
331
|
+
license: entry.license?.base || null,
|
|
332
|
+
pendingReasons: [...(entry.pendingReasons || [])],
|
|
333
|
+
}
|
|
334
|
+
const job = jobs.get(entry.id)
|
|
335
|
+
if (job && (job.state === 'downloading' || job.state === 'verifying')) {
|
|
336
|
+
return { ...base, state: job.state, installed: false, provider: job.provider, revision: job.revision, startedAt: job.startedAt, progress: { ...job.progress } }
|
|
337
|
+
}
|
|
338
|
+
const install = readInstall(entry)
|
|
339
|
+
if (install?.ok) {
|
|
340
|
+
return {
|
|
341
|
+
...base,
|
|
342
|
+
state: 'installed',
|
|
343
|
+
installed: true,
|
|
344
|
+
provider: install.record.provider || null,
|
|
345
|
+
revision: install.record.revision || null,
|
|
346
|
+
installedAt: install.record.installedAt || null,
|
|
347
|
+
fingerprintMatches: install.record.fingerprint === entry.profileFingerprint,
|
|
348
|
+
checks: Array.isArray(install.record.checks) ? [...install.record.checks] : [],
|
|
349
|
+
verified: statusOptions.deep ? deepVerify(entry, install.record) : null,
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (install && !install.ok) {
|
|
353
|
+
return { ...base, state: 'failed', installed: false, error: { code: install.code, message: 'existing install record does not match the files on disk' } }
|
|
354
|
+
}
|
|
355
|
+
const outcome = outcomes.get(entry.id)
|
|
356
|
+
if (outcome) return { ...base, state: outcome.state, installed: false, error: outcome.error || null }
|
|
357
|
+
return { ...base, state: 'absent', installed: false }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function download(id, downloadOptions = {}) {
|
|
361
|
+
const { confirmed = false, signal, provider = null } = downloadOptions || {}
|
|
362
|
+
const entry = lookup(typeof id === 'string' ? id : String(id || ''))
|
|
363
|
+
if (!entry) throw fail('EMBEDDING_MODEL_UNKNOWN', `unknown embedding model: ${id}`)
|
|
364
|
+
if (provider !== null && !PROVIDERS[provider]) {
|
|
365
|
+
throw fail('EMBEDDING_PROVIDER_UNKNOWN', `unknown download provider: ${String(provider)}`)
|
|
366
|
+
}
|
|
367
|
+
const report = validateEmbeddingManifest(entry)
|
|
368
|
+
if (!report.ok) {
|
|
369
|
+
throw fail('EMBEDDING_MANIFEST_INVALID', `${entry.id} manifest is not installable: ${report.errors.map(item => item.code).join(', ')}`, { errors: report.errors })
|
|
370
|
+
}
|
|
371
|
+
if (entry.availability !== 'available') {
|
|
372
|
+
throw fail('EMBEDDING_MODEL_UNAVAILABLE', `${entry.id} has no verified artifact; nothing will be downloaded`, { pendingReasons: [...(entry.pendingReasons || [])] })
|
|
373
|
+
}
|
|
374
|
+
if (confirmed !== true) {
|
|
375
|
+
throw fail('EMBEDDING_CONFIRMATION_REQUIRED', 'downloading a model needs explicit user confirmation: download(id, { confirmed: true })')
|
|
376
|
+
}
|
|
377
|
+
if (jobs.has(entry.id)) throw fail('EMBEDDING_DOWNLOAD_BUSY', `${entry.id} is already downloading`)
|
|
378
|
+
if (signal?.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted before it started`)
|
|
379
|
+
// 默认取目录顺序里第一个已固定的来源(Qwen3 卡片因此默认 hf-mirror);显式传
|
|
380
|
+
// provider 时只解析那一个,解析不出可用来源就如实报错,绝不回退到别的源去下载。
|
|
381
|
+
const resolved = provider ? resolveEmbeddingSources(entry, { providers: [provider] }) : resolveEmbeddingSources(entry)
|
|
382
|
+
const source = provider ? resolved.sources.find(item => item.provider === provider) || null : resolved.primary
|
|
383
|
+
if (!source) {
|
|
384
|
+
throw fail('EMBEDDING_SOURCE_UNAVAILABLE', `no source with a pinned revision is available for ${entry.id}${provider ? ' on ' + provider : ''}`, { skipped: resolved.skipped })
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const controller = new AbortController()
|
|
388
|
+
const onAbort = () => controller.abort()
|
|
389
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
390
|
+
const job = {
|
|
391
|
+
id: entry.id,
|
|
392
|
+
state: 'downloading',
|
|
393
|
+
provider: source.provider,
|
|
394
|
+
revision: source.revision,
|
|
395
|
+
startedAt: now(),
|
|
396
|
+
controller,
|
|
397
|
+
progress: { files: source.files.length, done: 0, bytes: 0, totalBytes: entry.totalBytes, current: null },
|
|
398
|
+
}
|
|
399
|
+
jobs.set(entry.id, job)
|
|
400
|
+
outcomes.delete(entry.id)
|
|
401
|
+
let staging = null
|
|
402
|
+
let installed = false
|
|
403
|
+
const parts = []
|
|
404
|
+
try {
|
|
405
|
+
// S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
|
|
406
|
+
fs.mkdirSync(baseDir, { recursive: true })
|
|
407
|
+
ensureFreeSpace(baseDir, entry.totalBytes)
|
|
408
|
+
const stagingRoot = insideRoot(path.join(baseDir, STAGING_DIR))
|
|
409
|
+
fs.mkdirSync(stagingRoot, { recursive: true })
|
|
410
|
+
staging = fs.mkdtempSync(path.join(stagingRoot, `${entry.id}-`))
|
|
411
|
+
for (const file of source.files) {
|
|
412
|
+
if (controller.signal.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`)
|
|
413
|
+
if (!Number.isInteger(file.bytes) || file.bytes < 0) throw fail('EMBEDDING_MANIFEST_INVALID', `file ${file.path} has no exact byte count`)
|
|
414
|
+
if (file.bytes > maxFileBytes) throw fail('EMBEDDING_FILE_TOO_LARGE', `file ${file.path} declares ${file.bytes} bytes, above the ${maxFileBytes} byte cap`)
|
|
415
|
+
const target = path.join(staging, ...String(file.path).split('/'))
|
|
416
|
+
if (!path.resolve(target).startsWith(path.resolve(staging) + path.sep)) throw fail('EMBEDDING_PATH_ESCAPE', `file ${file.path} escapes the staging directory`)
|
|
417
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
418
|
+
job.progress.current = file.path
|
|
419
|
+
|
|
420
|
+
// S-16:稳定 .part 缓存(独立于 .staging)+ Range 续传。半成品只进 .cache,
|
|
421
|
+
// 保持 staging「安装成功后必须为空」的既有语义。
|
|
422
|
+
const part = partPathFor(file)
|
|
423
|
+
parts.push(part)
|
|
424
|
+
fs.mkdirSync(path.dirname(part), { recursive: true })
|
|
425
|
+
let existing = 0
|
|
426
|
+
try { existing = fs.statSync(part).size } catch {}
|
|
427
|
+
if (existing > file.bytes) {
|
|
428
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
429
|
+
existing = 0
|
|
430
|
+
}
|
|
431
|
+
if (existing > 0 && existing === file.bytes) {
|
|
432
|
+
let reusable = false
|
|
433
|
+
try { reusable = sha256FileSync(part) === file.sha256 } catch { reusable = false }
|
|
434
|
+
if (reusable) {
|
|
435
|
+
fs.copyFileSync(part, target)
|
|
436
|
+
job.progress.bytes += file.bytes
|
|
437
|
+
job.progress.done += 1
|
|
438
|
+
continue
|
|
439
|
+
}
|
|
440
|
+
// 长度对但 hash 不符:这份半成品不可信,从头下。
|
|
441
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
442
|
+
existing = 0
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// S-1:总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
|
|
446
|
+
// 连接让 for-await 永久 pending;超时单独记账,别被误判成用户取消。
|
|
447
|
+
let timedOut = false
|
|
448
|
+
const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
|
|
449
|
+
totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
450
|
+
const stallController = new AbortController()
|
|
451
|
+
let stallTimer = null
|
|
452
|
+
const armStall = () => {
|
|
453
|
+
if (stallTimer) clearTimeout(stallTimer)
|
|
454
|
+
stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
|
|
455
|
+
stallTimer.unref?.()
|
|
456
|
+
}
|
|
457
|
+
const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
|
|
458
|
+
const timeoutFailure = cause => fail('EMBEDDING_DOWNLOAD_TIMEOUT', `download of ${file.path} timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
|
|
459
|
+
const abortedFailure = cause => fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause })
|
|
460
|
+
// 磁盘写失败清 .part;超时/取消保留 .part 供下次 Range 续传。
|
|
461
|
+
let removePart = false
|
|
462
|
+
const streamFailure = error => {
|
|
463
|
+
if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
|
|
464
|
+
if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
|
|
465
|
+
if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
|
|
466
|
+
removePart = true
|
|
467
|
+
return fail('EMBEDDING_DISK_FULL', `cannot write ${file.path}: ${error.code}; partial download removed`, { cause: error })
|
|
468
|
+
}
|
|
469
|
+
return error
|
|
470
|
+
}
|
|
471
|
+
armStall()
|
|
472
|
+
const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
|
|
473
|
+
const headers = { 'accept-encoding': 'identity' }
|
|
474
|
+
if (existing > 0) headers.Range = `bytes=${existing}-`
|
|
475
|
+
let response
|
|
476
|
+
try {
|
|
477
|
+
response = await fetchImpl(file.url, { signal, redirect: 'follow', headers })
|
|
478
|
+
} catch (error) {
|
|
479
|
+
if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
|
|
480
|
+
if (isAbort(error, controller.signal)) throw abortedFailure(error)
|
|
481
|
+
throw fail('EMBEDDING_NETWORK_ERROR', `cannot fetch ${file.path} from ${source.provider}: ${error?.message || error}`, { cause: error })
|
|
482
|
+
}
|
|
483
|
+
if (!response || !response.ok) {
|
|
484
|
+
throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
|
|
485
|
+
}
|
|
486
|
+
let append = existing > 0
|
|
487
|
+
if (append && response.status === 200) {
|
|
488
|
+
// 源忽略了 Range,丢弃 .part 从头下,避免把整段内容追加到半成品后面。
|
|
489
|
+
job.progress.bytes = Math.max(0, job.progress.bytes - existing)
|
|
490
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
491
|
+
append = false
|
|
492
|
+
existing = 0
|
|
493
|
+
} else if (append) {
|
|
494
|
+
const contentRange = String(response.headers?.get?.('content-range') || '')
|
|
495
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
|
|
496
|
+
if (response.status !== 206 || !match || Number(match[1]) !== existing || Number(match[3]) !== file.bytes) {
|
|
497
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} returned an unexpected Content-Range for resume: ${contentRange || '(missing)'}`)
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
// 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
|
|
501
|
+
// 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
|
|
502
|
+
const declaredHeader = response.headers?.get?.('content-length')
|
|
503
|
+
const declaredLength = Number(declaredHeader)
|
|
504
|
+
const expectedLength = file.bytes - existing
|
|
505
|
+
if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== expectedLength) {
|
|
506
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the expected ${expectedLength} bytes`)
|
|
507
|
+
}
|
|
508
|
+
let size = existing
|
|
509
|
+
const fd = fs.openSync(part, append ? 'a' : 'w', 0o600)
|
|
510
|
+
try {
|
|
511
|
+
const body = response.body
|
|
512
|
+
if (body && typeof body[Symbol.asyncIterator] === 'function') {
|
|
513
|
+
try {
|
|
514
|
+
for await (const chunk of body) {
|
|
515
|
+
if (controller.signal.aborted) throw abortedFailure(null)
|
|
516
|
+
armStall()
|
|
517
|
+
size += chunk.length
|
|
518
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
519
|
+
fs.writeSync(fd, chunk)
|
|
520
|
+
job.progress.bytes += chunk.length
|
|
521
|
+
}
|
|
522
|
+
} catch (error) { throw streamFailure(error) }
|
|
523
|
+
} else {
|
|
524
|
+
try {
|
|
525
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
526
|
+
size += buffer.length
|
|
527
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
528
|
+
fs.writeSync(fd, buffer)
|
|
529
|
+
job.progress.bytes += buffer.length
|
|
530
|
+
} catch (error) { throw streamFailure(error) }
|
|
531
|
+
}
|
|
532
|
+
} finally {
|
|
533
|
+
clearStall()
|
|
534
|
+
try { fs.closeSync(fd) } catch {}
|
|
535
|
+
if (removePart) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
536
|
+
}
|
|
537
|
+
if (size !== file.bytes) {
|
|
538
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
539
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
|
|
540
|
+
}
|
|
541
|
+
const digest = sha256FileSync(part)
|
|
542
|
+
if (digest !== file.sha256) {
|
|
543
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
544
|
+
throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
|
|
545
|
+
}
|
|
546
|
+
try {
|
|
547
|
+
fs.copyFileSync(part, target)
|
|
548
|
+
} catch (error) {
|
|
549
|
+
throw fail('EMBEDDING_INSTALL_FAILED', `cannot stage ${file.path}: ${error?.code || error?.message || error}; partial download removed`, { cause: error })
|
|
550
|
+
}
|
|
551
|
+
job.progress.done += 1
|
|
552
|
+
}
|
|
553
|
+
job.state = 'verifying'
|
|
554
|
+
job.progress.current = null
|
|
555
|
+
const verifier = typeof verifyModel === 'function' ? verifyModel : verifyStagedArtifacts
|
|
556
|
+
let smoke
|
|
557
|
+
try {
|
|
558
|
+
smoke = await verifier({ id: entry.id, dir: staging, entry, manifest: entry, provider: source.provider, revision: source.revision })
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (isAbort(error, controller.signal)) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause: error })
|
|
561
|
+
throw fail('EMBEDDING_SMOKE_FAILED', `model smoke failed for ${entry.id}: ${error?.message || error}`, { cause: error })
|
|
562
|
+
}
|
|
563
|
+
if (smoke && smoke.ok === false) throw fail('EMBEDDING_SMOKE_FAILED', `model smoke rejected ${entry.id}`, { smoke })
|
|
564
|
+
|
|
565
|
+
const record = {
|
|
566
|
+
id: entry.id,
|
|
567
|
+
revision: source.revision,
|
|
568
|
+
repo: source.repo,
|
|
569
|
+
provider: source.provider,
|
|
570
|
+
fingerprint: entry.profileFingerprint,
|
|
571
|
+
installedAt: now(),
|
|
572
|
+
totalBytes: entry.totalBytes,
|
|
573
|
+
files: (entry.files || []).map(file => ({ path: file.path, role: file.role, bytes: file.bytes, sha256: file.sha256 })),
|
|
574
|
+
checks: Array.isArray(smoke?.checks) ? smoke.checks : [],
|
|
575
|
+
verifiedBy: typeof verifyModel === 'function' ? 'custom-verify-model' : 'sha256+structural-smoke',
|
|
576
|
+
// 明确记录:安装≠启用。active profile 由迁移模块的受验证切换流程负责。
|
|
577
|
+
active: false,
|
|
578
|
+
}
|
|
579
|
+
writeJsonAtomic(path.join(staging, INSTALL_RECORD), record)
|
|
580
|
+
|
|
581
|
+
const finalDir = modelDir(entry.id)
|
|
582
|
+
const previousExists = fs.existsSync(finalDir)
|
|
583
|
+
let trash = null
|
|
584
|
+
if (previousExists) {
|
|
585
|
+
const trashRoot = insideRoot(path.join(baseDir, TRASH_DIR))
|
|
586
|
+
fs.mkdirSync(trashRoot, { recursive: true })
|
|
587
|
+
trash = path.join(trashRoot, `${entry.id}-${crypto.randomUUID()}`)
|
|
588
|
+
fs.renameSync(finalDir, trash)
|
|
589
|
+
}
|
|
590
|
+
try {
|
|
591
|
+
fs.renameSync(staging, finalDir)
|
|
592
|
+
staging = null
|
|
593
|
+
installed = true
|
|
594
|
+
} catch (error) {
|
|
595
|
+
if (trash) { try { fs.renameSync(trash, finalDir) } catch {} }
|
|
596
|
+
throw fail('EMBEDDING_INSTALL_FAILED', `cannot move the verified artifact into place: ${error?.message || error}`, { cause: error })
|
|
597
|
+
}
|
|
598
|
+
if (trash) { try { fs.rmSync(trash, { recursive: true, force: true }) } catch {} }
|
|
599
|
+
job.state = 'installed'
|
|
600
|
+
jobs.delete(entry.id)
|
|
601
|
+
outcomes.delete(entry.id)
|
|
602
|
+
return getStatus(entry.id)
|
|
603
|
+
} catch (error) {
|
|
604
|
+
const aborted = isAbort(error, controller.signal)
|
|
605
|
+
const code = aborted ? 'EMBEDDING_DOWNLOAD_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('EMBEDDING_') ? error.code : 'EMBEDDING_DOWNLOAD_FAILED')
|
|
606
|
+
const failed = code === error?.code ? error : fail(code, `download of ${entry.id} failed: ${error?.message || error}`, { cause: error })
|
|
607
|
+
// S-16:非可续传类失败清掉 .part,别让半成品占空间;网络错误/超时/取消
|
|
608
|
+
// 保留 .part 供下次 Range 续传(S-1)。
|
|
609
|
+
if (!['EMBEDDING_DOWNLOAD_ABORTED', 'EMBEDDING_NETWORK_ERROR', 'EMBEDDING_DOWNLOAD_TIMEOUT'].includes(code)) {
|
|
610
|
+
for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
611
|
+
}
|
|
612
|
+
job.state = aborted ? 'cancelled' : 'failed'
|
|
613
|
+
job.error = { code, message: String(failed.message || error) }
|
|
614
|
+
jobs.delete(entry.id)
|
|
615
|
+
outcomes.set(entry.id, { state: job.state, error: { ...job.error } })
|
|
616
|
+
throw failed
|
|
617
|
+
} finally {
|
|
618
|
+
signal?.removeEventListener('abort', onAbort)
|
|
619
|
+
if (staging && !installed) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
|
|
620
|
+
// 安装成功后本次的 .part 已完成使命,清掉避免长期占空间。
|
|
621
|
+
if (installed) { for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} } }
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function dispose() {
|
|
626
|
+
// 只中止在途下载;状态与错误原因留给 getStatus 展示。
|
|
627
|
+
for (const job of jobs.values()) { try { job.controller?.abort() } catch {} }
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
return {
|
|
631
|
+
root: baseDir,
|
|
632
|
+
catalogIds: [...getEmbeddingCatalog().map(entry => entry.id), ...extraCatalog.map(entry => entry?.id).filter(Boolean)],
|
|
633
|
+
getStatus,
|
|
634
|
+
download,
|
|
635
|
+
dispose,
|
|
636
|
+
}
|
|
637
|
+
}
|