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
package/lib/media.js
CHANGED
|
@@ -1,513 +1,607 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
import { once } from 'node:events'
|
|
5
|
-
import {
|
|
6
|
-
getLibrary, getSessionBinding, setSessionBinding, listSessionBindings,
|
|
7
|
-
effectiveScope, loadPrivateIndex, onPrivateIndexWrite, getSettings,
|
|
8
|
-
} from './state.js'
|
|
9
|
-
import { dataDir, indexDir, isSafeId, ensureDir, readJsonStrict, writeJson, withFileLock, warn, stamp } from './paths.js'
|
|
10
|
-
import { isMemoryEligible, visibleToSession } from './memory.js'
|
|
11
|
-
import { getVisionConfig } from './memu-config.js'
|
|
12
|
-
import { loadPrompt } from './prompts.js'
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (
|
|
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
|
-
const
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
if (!
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
const
|
|
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
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
-
|
|
219
|
-
|
|
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
|
-
if (!
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const
|
|
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
|
-
const
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
return
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
export function
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
357
|
-
if (!
|
|
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
|
-
|
|
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
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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
|
-
}
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import { once } from 'node:events'
|
|
5
|
+
import {
|
|
6
|
+
getLibrary, getSessionBinding, setSessionBinding, listSessionBindings,
|
|
7
|
+
effectiveScope, loadPrivateIndex, onPrivateIndexWrite, getSettings, flushState,
|
|
8
|
+
} from './state.js'
|
|
9
|
+
import { dataDir, indexDir, isSafeId, ensureDir, readJsonStrict, writeJson, withFileLock, warn, stamp } from './paths.js'
|
|
10
|
+
import { isMemoryEligible, visibleToSession } from './memory.js'
|
|
11
|
+
import { getVisionConfig } from './memu-config.js'
|
|
12
|
+
import { loadPrompt } from './prompts.js'
|
|
13
|
+
import { estTokens, truncateToTokens } from './budget.js'
|
|
14
|
+
import { normalizeMemoryContext } from './context.js'
|
|
15
|
+
import { zipSync, unzipSync, Zip, ZipPassThrough, Unzip, UnzipInflate } from 'fflate'
|
|
16
|
+
|
|
17
|
+
const FILE_LIMIT = 8 * 1024 * 1024
|
|
18
|
+
const LIBRARY_LIMIT = 500 * 1024 * 1024
|
|
19
|
+
const MIME_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }
|
|
20
|
+
const SHA = /^[a-f0-9]{64}$/
|
|
21
|
+
const captures = new Map()
|
|
22
|
+
let activeCaptions = 0
|
|
23
|
+
// A v2 bundle is always written with a SHA-256 of memories.json. Legacy v1
|
|
24
|
+
// archives predate that field, so they stay importable without it; a v2
|
|
25
|
+
// manifest with the field removed (or malformed) must be rejected instead of
|
|
26
|
+
// silently trusting an edited body. This is an integrity check against
|
|
27
|
+
// truncation/accidental edits, NOT a signature: a caller able to rewrite the
|
|
28
|
+
// whole manifest can also downgrade `format` to a legacy name, which is an
|
|
29
|
+
// explicit compatibility opt-in rather than a checksum bypass.
|
|
30
|
+
const MEDIA_FORMAT = 'dsh-memu-memory-media@2'
|
|
31
|
+
const LEGACY_MEDIA_FORMATS = ['dsh-memu-memory-media@1', 'dsh-memu-media@1']
|
|
32
|
+
function verifyBundleChecksum(manifest, memories) {
|
|
33
|
+
const digest = manifest.memoriesSha256
|
|
34
|
+
if (!digest) {
|
|
35
|
+
if (!LEGACY_MEDIA_FORMATS.includes(manifest.format)) throw new Error('memories.json checksum missing')
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
if (typeof digest !== 'string' || !SHA.test(digest)) throw new Error('memories.json checksum is malformed')
|
|
39
|
+
const actual = crypto.createHash('sha256').update(memories).digest('hex')
|
|
40
|
+
if (actual !== digest) throw new Error('memories.json checksum mismatch')
|
|
41
|
+
}
|
|
42
|
+
function poolFile(libraryId) {
|
|
43
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
44
|
+
return path.join(indexDir(), `${libraryId}.media.json`)
|
|
45
|
+
}
|
|
46
|
+
function blobFile(libraryId, sha, ext) {
|
|
47
|
+
if (!isSafeId(libraryId) || !SHA.test(sha) || !Object.values(MIME_EXT).includes(ext)) throw new Error('invalid attachment reference')
|
|
48
|
+
return path.join(dataDir(), 'attachments', libraryId, `${sha}.${ext}`)
|
|
49
|
+
}
|
|
50
|
+
function loadPool(libraryId) {
|
|
51
|
+
const result = readJsonStrict(poolFile(libraryId))
|
|
52
|
+
if (result.ok && result.value?.blobs && typeof result.value.blobs === 'object' && !Array.isArray(result.value.blobs)) return result.value
|
|
53
|
+
if (result.missing) return { version: 1, blobs: {}, totals: { bytes: 0, count: 0 } }
|
|
54
|
+
throw new Error(`media metadata unavailable: ${result.error?.message || 'invalid shape'}`)
|
|
55
|
+
}
|
|
56
|
+
function savePool(libraryId, pool) {
|
|
57
|
+
const stored = Object.values(pool.blobs).filter(blob => !blob.missing)
|
|
58
|
+
pool.totals = { bytes: stored.reduce((sum, blob) => sum + blob.bytes, 0), count: stored.length }
|
|
59
|
+
writeJson(poolFile(libraryId), pool)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function imageTurn(message) {
|
|
63
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
64
|
+
const images = blocks.filter(block => block?.type === 'image' && block.attachment)
|
|
65
|
+
const text = blocks.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join(' ').trim()
|
|
66
|
+
const metadata = images.map(block => {
|
|
67
|
+
const ref = block.attachment
|
|
68
|
+
return `[图片] ${String(ref.name || '').slice(0, 120)} ${ref.width || '?'}x${ref.height || '?'} ${ref.mediaType || ''}`
|
|
69
|
+
}).join(' ')
|
|
70
|
+
return { text, imageCount: images.length, images, query: text || metadata }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function captureImage(ctx, libraryId, ref, contextText, now) {
|
|
74
|
+
const mime = ref.mediaType
|
|
75
|
+
if (!MIME_EXT[mime]) return null
|
|
76
|
+
let bytes = null
|
|
77
|
+
let missingReason = ''
|
|
78
|
+
if (!(ref.bytes > 0) || ref.bytes > FILE_LIMIT) missingReason = 'image exceeds the 8 MB limit or has no verified byte length'
|
|
79
|
+
else {
|
|
80
|
+
try {
|
|
81
|
+
const service = ctx.get?.('attachments') || ctx.attachments
|
|
82
|
+
if (!service?.readImage) throw new Error('host attachments.readImage is unavailable')
|
|
83
|
+
const stored = await service.readImage(ref)
|
|
84
|
+
if (!(stored?.data instanceof Uint8Array) || stored.data.byteLength > FILE_LIMIT) throw new Error('invalid image bytes or 8 MB limit exceeded')
|
|
85
|
+
bytes = Buffer.from(stored.data)
|
|
86
|
+
} catch (error) { missingReason = String(error?.message || error) }
|
|
87
|
+
}
|
|
88
|
+
const sha256 = bytes ? crypto.createHash('sha256').update(bytes).digest('hex') : SHA.test(String(ref.attachmentId)) ? ref.attachmentId : crypto.createHash('sha256').update(String(ref.attachmentId || JSON.stringify(ref))).digest('hex')
|
|
89
|
+
return withFileLock(poolFile(libraryId), () => {
|
|
90
|
+
const pool = loadPool(libraryId)
|
|
91
|
+
const previous = pool.blobs[sha256]
|
|
92
|
+
const ext = MIME_EXT[mime]
|
|
93
|
+
const file = blobFile(libraryId, sha256, ext)
|
|
94
|
+
let stored = !!previous && fs.existsSync(file)
|
|
95
|
+
const wasStored = stored
|
|
96
|
+
if (!stored && bytes) {
|
|
97
|
+
if ((pool.totals.bytes || 0) + bytes.length > LIBRARY_LIMIT) missingReason = 'library image storage exceeds the 500 MB limit'
|
|
98
|
+
else {
|
|
99
|
+
ensureDir(path.dirname(file))
|
|
100
|
+
const temporary = `${file}.tmp-${crypto.randomUUID()}`
|
|
101
|
+
try {
|
|
102
|
+
fs.writeFileSync(temporary, bytes, { flag: 'wx', mode: 0o600 })
|
|
103
|
+
fs.renameSync(temporary, file)
|
|
104
|
+
stored = true
|
|
105
|
+
} finally { try { fs.rmSync(temporary, { force: true }) } catch {} }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const at = new Date(now).toISOString()
|
|
109
|
+
const blob = {
|
|
110
|
+
...previous, sha256, bytes: bytes?.length || ref.bytes || 0, ext, mime,
|
|
111
|
+
w: ref.width || null, h: ref.height || null, firstSeenAt: previous?.firstSeenAt || at,
|
|
112
|
+
lastUsedAt: at, useCount: Number(previous?.useCount || 0) + 1, refs: previous?.refs || [],
|
|
113
|
+
caption: contextText ? contextText.slice(0, 160) : previous?.caption || (ref.name ? String(ref.name).slice(0, 160) : '[图片]'),
|
|
114
|
+
captionBy: contextText ? 'context' : previous?.captionBy || (ref.name ? 'exif' : 'none'),
|
|
115
|
+
missing: !stored, missingReason: stored ? null : missingReason || 'image unavailable',
|
|
116
|
+
}
|
|
117
|
+
pool.blobs[sha256] = blob
|
|
118
|
+
try { savePool(libraryId, pool) } catch (error) {
|
|
119
|
+
if (stored && !wasStored) { try { fs.unlinkSync(file) } catch {} }
|
|
120
|
+
throw error
|
|
121
|
+
}
|
|
122
|
+
if (blob.missing) warn(`image not saved for ${libraryId}: ${blob.missingReason}`)
|
|
123
|
+
return blob
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Byte identity never owns queue consumption: each delivery keeps every occurrence.
|
|
128
|
+
export function mediaSessionScope(session, binding = getSessionBinding(session?.header?.id)) {
|
|
129
|
+
const sessionId = session?.header?.id
|
|
130
|
+
const raw = session?.createdAt ?? session?.header?.createdAt
|
|
131
|
+
const time = typeof raw === 'number' ? raw : Date.parse(raw)
|
|
132
|
+
const created = raw === undefined || raw === null || raw === '' ? null : 'created:' + (Number.isFinite(time) ? time : String(raw))
|
|
133
|
+
const incarnation = created || binding?.mediaIncarnation || crypto.randomUUID()
|
|
134
|
+
if (binding && binding.mediaIncarnation !== incarnation) setSessionBinding(sessionId, { mediaIncarnation: incarnation })
|
|
135
|
+
return { sessionId, libraryId: binding?.libraryId || null, incarnation,
|
|
136
|
+
contextKey: JSON.stringify(normalizeMemoryContext(binding?.memoryContext)) }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function mediaMessageKey(message, eventKey) {
|
|
140
|
+
return message?.key ? 'inbound:' + message.key
|
|
141
|
+
: JSON.stringify([message?.producer || 'host.user', message?.id || eventKey || null])
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Legacy unowned rows stay pending: an attachment id is not message ownership. */
|
|
145
|
+
export function selectMediaOccurrences(pending, messages, scope, excludedIds = []) {
|
|
146
|
+
const excluded = new Set(excludedIds)
|
|
147
|
+
return (pending || []).filter(item => item?.occurrenceId && !excluded.has(item.occurrenceId)
|
|
148
|
+
&& item.mediaScope?.sessionId === scope.sessionId && item.mediaScope?.libraryId === scope.libraryId
|
|
149
|
+
&& item.mediaScope?.incarnation === scope.incarnation && item.mediaScope?.contextKey === scope.contextKey
|
|
150
|
+
&& messages.some(message => (item.messageKey === mediaMessageKey(message)
|
|
151
|
+
|| (message.id && item.sourceMessageId === message.id && item.producer === (message.producer || 'host.user')))
|
|
152
|
+
&& JSON.stringify(item.context) === JSON.stringify(normalizeMemoryContext({ ...JSON.parse(scope.contextKey), ...message.context }))))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Whole rows plus envelope fit the budget. IDs describe exactly the represented rows. */
|
|
156
|
+
export function buildMediaInjection(occurrences, budget, { stickerHint = false } = {}) {
|
|
157
|
+
const groups = new Map()
|
|
158
|
+
for (const item of occurrences || []) {
|
|
159
|
+
if (!item?.occurrenceId || !SHA.test(item.sha256)) continue
|
|
160
|
+
const description = String(item.contextText || item.caption || '[图片]').replace(/[\r\n]+/g, ' ')
|
|
161
|
+
const line = item.sha256 + ' · ' + item.captionBy + ': ' + description + (item.missing ? ' · missing' : '')
|
|
162
|
+
const key = JSON.stringify([item.sha256, item.captionBy, description, Boolean(item.missing)])
|
|
163
|
+
if (!groups.has(key)) groups.set(key, { line, description, prefix: item.sha256 + ' · ' + item.captionBy + ': ',
|
|
164
|
+
suffix: item.missing ? ' · missing' : '', ids: [] })
|
|
165
|
+
groups.get(key).ids.push(item.occurrenceId)
|
|
166
|
+
}
|
|
167
|
+
const footer = '只知道描述与引用,不能凭空声称看过像素。attachments 只接受 sha256。'
|
|
168
|
+
const lines = []
|
|
169
|
+
const occurrenceIds = []
|
|
170
|
+
const render = rows => ['<memory-media>', ...rows, footer, '</memory-media>'].join('\n')
|
|
171
|
+
for (const group of groups.values()) {
|
|
172
|
+
let line = group.line
|
|
173
|
+
if (estTokens(render([...lines, line])) > Math.max(0, Number(budget) || 0)) {
|
|
174
|
+
const room = Math.floor(Number(budget) - estTokens(render([...lines, group.prefix + group.suffix])))
|
|
175
|
+
let tokens = Math.max(0, room)
|
|
176
|
+
while (tokens > 0) {
|
|
177
|
+
const shortened = truncateToTokens(group.description, tokens)
|
|
178
|
+
line = group.prefix + shortened + group.suffix
|
|
179
|
+
if (shortened && estTokens(render([...lines, line])) <= budget) break
|
|
180
|
+
tokens -= 1
|
|
181
|
+
}
|
|
182
|
+
// A full hash and at least a short description must survive; never clip the row itself.
|
|
183
|
+
if (tokens < Math.min(8, estTokens(group.description)) || estTokens(render([...lines, line])) > budget) continue
|
|
184
|
+
}
|
|
185
|
+
lines.push(line)
|
|
186
|
+
occurrenceIds.push(...group.ids)
|
|
187
|
+
}
|
|
188
|
+
const omittedOccurrenceIds = (occurrences || []).map(item => item.occurrenceId).filter(id => id && !occurrenceIds.includes(id))
|
|
189
|
+
if (!lines.length) return { text: '', occurrenceIds: [], omittedOccurrenceIds }
|
|
190
|
+
const hint = '同图反复出现,可以用 track=habit 聚合表达习惯,不必逐次写记忆。'
|
|
191
|
+
if (stickerHint && estTokens(render([...lines, hint])) <= budget) lines.push(hint)
|
|
192
|
+
return { text: render(lines), occurrenceIds: [...new Set(occurrenceIds)], omittedOccurrenceIds }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function captureMediaEvent(ctx, session, event, { now = Date.now() } = {}) {
|
|
196
|
+
const sessionId = session?.header?.id
|
|
197
|
+
if (!sessionId || session?.header?.origin === 'subagent' || event?.type !== 'user/message' || event.data?.source?.kind !== 'user') return Promise.resolve([])
|
|
198
|
+
return captureMessageMedia(ctx, session, event.data, {
|
|
199
|
+
now, eventKey: event.seq !== undefined ? `seq:${event.seq}` : event.data.id ? `id:${event.data.id}` : null,
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Shared byte collection, without disguising tool results as user events. */
|
|
204
|
+
export function captureMessageMedia(ctx, session, message, { now = Date.now(), eventKey = null } = {}) {
|
|
205
|
+
const sessionId = session?.header?.id
|
|
206
|
+
if (!sessionId || session.header.origin === 'subagent') return Promise.resolve([])
|
|
207
|
+
const binding = getSessionBinding(sessionId)
|
|
208
|
+
if (!binding?.libraryId || !effectiveScope(binding).useLibrary) return Promise.resolve([])
|
|
209
|
+
const turn = imageTurn(message)
|
|
210
|
+
if (!turn.imageCount) return Promise.resolve([])
|
|
211
|
+
const mediaScope = mediaSessionScope(session, binding)
|
|
212
|
+
const context = normalizeMemoryContext({ ...binding.memoryContext, ...message.context })
|
|
213
|
+
const messageKey = mediaMessageKey(message, eventKey)
|
|
214
|
+
const captureKey = JSON.stringify([mediaScope, context, message.producer || 'host.user', message.id || eventKey || messageKey])
|
|
215
|
+
const previous = captures.get(sessionId) || Promise.resolve()
|
|
216
|
+
const task = previous.catch(() => {}).then(async () => {
|
|
217
|
+
const current = getSessionBinding(sessionId)
|
|
218
|
+
if (!current?.libraryId || current.libraryId !== binding.libraryId || !effectiveScope(current).useLibrary) return []
|
|
219
|
+
if (current.mediaIncarnation !== mediaScope.incarnation
|
|
220
|
+
|| JSON.stringify(normalizeMemoryContext(current.memoryContext)) !== mediaScope.contextKey) return []
|
|
221
|
+
if ((current.mediaEvents || []).includes(captureKey)) return []
|
|
222
|
+
if (message.id && (current.pendingMedia || []).some(item => item.sourceMessageId === message.id
|
|
223
|
+
&& item.producer === (message.producer || 'host.user') && JSON.stringify(item.mediaScope) === JSON.stringify(mediaScope)
|
|
224
|
+
&& JSON.stringify(item.context) === JSON.stringify(context))) return []
|
|
225
|
+
const received = []
|
|
226
|
+
for (const block of turn.images.slice(0, 8)) {
|
|
227
|
+
const blob = await captureImage(ctx, binding.libraryId, block.attachment, turn.text, now)
|
|
228
|
+
if (blob) received.push({ ...blob,
|
|
229
|
+
caption: turn.text.slice(0, 160) || String(block.attachment.name || '[图片]').slice(0, 160),
|
|
230
|
+
captionBy: turn.text ? 'context' : block.attachment.name ? 'exif' : 'none',
|
|
231
|
+
occurrenceId: crypto.randomUUID(), mediaScope, messageKey,
|
|
232
|
+
sourceMessageId: message.id || null, producer: message.producer || 'host.user', eventKey,
|
|
233
|
+
context, sourceAttachmentId: block.attachment.attachmentId, contextText: turn.text, addedAt: stamp() })
|
|
234
|
+
}
|
|
235
|
+
const fresh = getSessionBinding(sessionId)
|
|
236
|
+
if (!fresh || fresh.libraryId !== binding.libraryId || !effectiveScope(fresh).useLibrary) return []
|
|
237
|
+
if (fresh.mediaIncarnation !== mediaScope.incarnation
|
|
238
|
+
|| JSON.stringify(normalizeMemoryContext(fresh.memoryContext)) !== mediaScope.contextKey) return []
|
|
239
|
+
const pending = [...(fresh.pendingMedia || []), ...received]
|
|
240
|
+
const hint = received.find(blob => blob.useCount >= 3)
|
|
241
|
+
const index = hint ? loadPrivateIndex(binding.libraryId) : null
|
|
242
|
+
const hasHabit = hint && Object.values(index.entries).some(entry => entry.track === 'habit' && (entry.attachments || []).some(item => item.sha256 === hint.sha256))
|
|
243
|
+
setSessionBinding(sessionId, {
|
|
244
|
+
pendingMedia: pending, lastMediaPendingCount: pending.length, lastImageCount: turn.imageCount,
|
|
245
|
+
mediaEvents: [...(fresh.mediaEvents || []), captureKey].slice(-128),
|
|
246
|
+
stickerHint: hint && !hasHabit ? { sha256: hint.sha256, useCount: hint.useCount } : fresh.stickerHint || null,
|
|
247
|
+
})
|
|
248
|
+
flushState()
|
|
249
|
+
if (pending.length >= 128) warn(`media backlog for ${sessionId}: ${pending.length} occurrences await admission or a matching message budget`)
|
|
250
|
+
for (const blob of received) {
|
|
251
|
+
if (blob.captionBy === 'none' && !blob.missing && getSettings().visionCaptionEnabled === true) {
|
|
252
|
+
void captionImage(binding.libraryId, blob.sha256).catch(() => warn('optional image description failed; original metadata retained'))
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return received
|
|
256
|
+
})
|
|
257
|
+
captures.set(sessionId, task)
|
|
258
|
+
void task.finally(() => { if (captures.get(sessionId) === task) captures.delete(sessionId) }).catch(() => {})
|
|
259
|
+
return task
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function attachmentRefs(libraryId, refs) {
|
|
263
|
+
if (refs === undefined) return []
|
|
264
|
+
if (!Array.isArray(refs) || refs.length > 8) throw new Error('attachments must contain at most 8 sha256 references')
|
|
265
|
+
const pool = loadPool(libraryId)
|
|
266
|
+
return [...new Set(refs.map(ref => ref?.sha256))].map(sha => {
|
|
267
|
+
if (!SHA.test(String(sha))) throw new Error('attachment sha256 must be 64 lowercase hex characters')
|
|
268
|
+
const blob = pool.blobs[sha]
|
|
269
|
+
if (!blob) throw new Error('attachment was not received in this library')
|
|
270
|
+
return {
|
|
271
|
+
kind: blob.useCount >= 3 && Math.max(blob.w || 0, blob.h || 0) < 512 ? 'sticker' : 'image',
|
|
272
|
+
sha256: sha, bytes: blob.bytes, w: blob.w, h: blob.h, mime: blob.mime,
|
|
273
|
+
caption: blob.caption, captionBy: blob.captionBy, addedAt: blob.firstSeenAt,
|
|
274
|
+
lastUsedAt: blob.lastUsedAt, useCount: blob.useCount,
|
|
275
|
+
missing: blob.missing || !fs.existsSync(blobFile(libraryId, sha, blob.ext)),
|
|
276
|
+
}
|
|
277
|
+
})
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function reconcileMedia(libraryId, index, { now = Date.now() } = {}) {
|
|
281
|
+
const file = poolFile(libraryId)
|
|
282
|
+
if (!fs.existsSync(file)) return
|
|
283
|
+
withFileLock(file, () => {
|
|
284
|
+
const pool = loadPool(libraryId)
|
|
285
|
+
const refs = new Map()
|
|
286
|
+
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
287
|
+
if (!isMemoryEligible(entry, { now })) continue
|
|
288
|
+
for (const item of entry.attachments || []) {
|
|
289
|
+
if (!refs.has(item.sha256)) refs.set(item.sha256, [])
|
|
290
|
+
refs.get(item.sha256).push(id)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
let changed = false
|
|
294
|
+
for (const [sha, blob] of Object.entries(pool.blobs)) {
|
|
295
|
+
const next = refs.get(sha) || []
|
|
296
|
+
if (JSON.stringify(blob.refs) !== JSON.stringify(next)) { blob.refs = next; changed = true }
|
|
297
|
+
if (!next.length && now - Date.parse(blob.lastUsedAt || blob.firstSeenAt) > 30 * 86_400_000) {
|
|
298
|
+
try { fs.rmSync(blobFile(libraryId, sha, blob.ext), { force: true }) } catch (error) { warn(`image cleanup deferred: ${error.code || 'IO error'}`); continue }
|
|
299
|
+
delete pool.blobs[sha]
|
|
300
|
+
changed = true
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (changed) savePool(libraryId, pool)
|
|
304
|
+
})
|
|
305
|
+
}
|
|
306
|
+
onPrivateIndexWrite((libraryId, index) => reconcileMedia(libraryId, index))
|
|
307
|
+
|
|
308
|
+
function authorize(libraryId, sha256, sessionId) {
|
|
309
|
+
if (!getLibrary(libraryId) || !SHA.test(String(sha256))) throw Object.assign(new Error('attachment not found'), { status: 404 })
|
|
310
|
+
const binding = getSessionBinding(sessionId)
|
|
311
|
+
if (!binding || binding.libraryId !== libraryId || !effectiveScope(binding).useLibrary) throw Object.assign(new Error('attachment scope denied'), { status: 403 })
|
|
312
|
+
const entries = Object.values(loadPrivateIndex(libraryId).entries)
|
|
313
|
+
const matching = entries.filter(entry => isMemoryEligible(entry) && entry.visibility !== 'secret'
|
|
314
|
+
&& visibleToSession(entry, sessionId) && (entry.attachments || []).some(item => item.sha256 === sha256))
|
|
315
|
+
if (!matching.length) throw Object.assign(new Error('attachment visibility denied'), { status: 403 })
|
|
316
|
+
return matching
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function getAttachment({ libraryId, sha256, sessionId }) {
|
|
320
|
+
const entries = authorize(libraryId, sha256, sessionId)
|
|
321
|
+
const blob = loadPool(libraryId).blobs[sha256]
|
|
322
|
+
if (!blob) return { sha256, missing: true }
|
|
323
|
+
const allowCaption = entries.every(entry => entry.disclosure !== 'never_say')
|
|
324
|
+
return {
|
|
325
|
+
sha256, bytes: blob.bytes, w: blob.w, h: blob.h, mime: blob.mime,
|
|
326
|
+
caption: allowCaption ? blob.caption : null, captionBy: allowCaption ? blob.captionBy : null,
|
|
327
|
+
useCount: blob.useCount, missing: blob.missing || !fs.existsSync(blobFile(libraryId, sha256, blob.ext)),
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export async function attachmentThumbnail(args) {
|
|
332
|
+
const info = getAttachment(args)
|
|
333
|
+
if (info.missing) return null
|
|
334
|
+
const blob = loadPool(args.libraryId).blobs[args.sha256]
|
|
335
|
+
const { default: sharp } = await import('sharp')
|
|
336
|
+
const data = await sharp(blobFile(args.libraryId, args.sha256, blob.ext), { limitInputPixels: 40_000_000, animated: false })
|
|
337
|
+
.resize({ width: 512, height: 512, fit: 'inside', withoutEnlargement: true }).webp({ quality: 80 }).toBuffer()
|
|
338
|
+
return { data, mime: 'image/webp' }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function attachmentPreview(libraryId, entry) {
|
|
342
|
+
// 绝大多数记忆没有附件。下面那行 `listSessionBindings()` 会读一次 state 并对每条
|
|
343
|
+
// binding 算一遍 effectiveScope,放进列表投影里就是「每条记忆一次全量扫描」
|
|
344
|
+
// Skip that scan when there are no attachments and therefore no URLs to construct.
|
|
345
|
+
const attachments = Array.isArray(entry?.attachments) ? entry.attachments : []
|
|
346
|
+
if (!attachments.length) return []
|
|
347
|
+
if (entry.visibility === 'secret' || entry.disclosure === 'never_say') return attachments.map(item => ({ sha256: item.sha256, missing: item.missing, hidden: true }))
|
|
348
|
+
const binding = listSessionBindings().find(binding => binding.libraryId === libraryId && effectiveScope(binding).useLibrary && visibleToSession(entry, binding.sessionId))
|
|
349
|
+
return attachments.map(item => ({
|
|
350
|
+
...item, url: binding ? `/dsh-memu-memory/attachment/${encodeURIComponent(libraryId)}/${item.sha256}?sessionId=${encodeURIComponent(binding.sessionId)}` : null,
|
|
351
|
+
}))
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export async function captionImage(libraryId, sha256) {
|
|
355
|
+
if (activeCaptions >= 2) return null
|
|
356
|
+
const config = getVisionConfig({ withKey: true })
|
|
357
|
+
if (!config.ready || getSettings().visionCaptionEnabled !== true) return null
|
|
358
|
+
const blob = loadPool(libraryId).blobs[sha256]
|
|
359
|
+
if (!blob || blob.missing || !['none', 'exif'].includes(blob.captionBy)) return null
|
|
360
|
+
const index = loadPrivateIndex(libraryId)
|
|
361
|
+
const linked = Object.values(index.entries).filter(entry => (entry.attachments || []).some(item => item.sha256 === sha256))
|
|
362
|
+
if (linked.some(entry => entry.visibility === 'secret' || entry.disclosure === 'never_say')) return null
|
|
363
|
+
const data = fs.readFileSync(blobFile(libraryId, sha256, blob.ext))
|
|
364
|
+
if (data.length > FILE_LIMIT) return null
|
|
365
|
+
// Resize before vision requests: cap the longest edge at 1024px and use JPEG q85;
|
|
366
|
+
// do not upscale, and use the first frame of animated images.
|
|
367
|
+
// 配额、sha 去重与 max_tokens 都不变——只改发出去的字节。
|
|
368
|
+
const { default: sharp } = await import('sharp')
|
|
369
|
+
const prepared = await sharp(data, { limitInputPixels: 40_000_000, animated: false })
|
|
370
|
+
.resize({ width: 1024, height: 1024, fit: 'inside', withoutEnlargement: true })
|
|
371
|
+
.jpeg({ quality: 85 })
|
|
372
|
+
.toBuffer()
|
|
373
|
+
const reserved = withFileLock(poolFile(libraryId), () => {
|
|
374
|
+
const pool = loadPool(libraryId)
|
|
375
|
+
const now = Date.now()
|
|
376
|
+
const budget = pool.visionBudget || {}
|
|
377
|
+
const hour = Math.floor(now / 3_600_000)
|
|
378
|
+
const count = budget.hour === hour ? Number(budget.count || 0) : 0
|
|
379
|
+
if (now - Number(budget.lastAt || 0) < 60_000 || count >= 10) return false
|
|
380
|
+
pool.visionBudget = { hour, count: count + 1, lastAt: now }
|
|
381
|
+
savePool(libraryId, pool)
|
|
382
|
+
return true
|
|
383
|
+
})
|
|
384
|
+
if (!reserved) return null
|
|
385
|
+
activeCaptions += 1
|
|
386
|
+
try {
|
|
387
|
+
const response = await fetch(`${config.baseUrl}/chat/completions`, {
|
|
388
|
+
method: 'POST', headers: { 'content-type': 'application/json', ...(config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}) },
|
|
389
|
+
signal: AbortSignal.timeout(20_000),
|
|
390
|
+
body: JSON.stringify({ model: config.model, max_tokens: 100, temperature: 0,
|
|
391
|
+
messages: [{ role: 'user', content: [
|
|
392
|
+
{ type: 'text', text: loadPrompt('image-caption').text },
|
|
393
|
+
{ type: 'image_url', image_url: { url: `data:image/jpeg;base64,${prepared.toString('base64')}` } },
|
|
394
|
+
] }] }),
|
|
395
|
+
})
|
|
396
|
+
if (!response.ok) throw new Error(`vision service returned HTTP ${response.status}`)
|
|
397
|
+
const result = await response.json()
|
|
398
|
+
const caption = String(result?.choices?.[0]?.message?.content || '').trim().slice(0, 40)
|
|
399
|
+
if (!caption) return null
|
|
400
|
+
withFileLock(poolFile(libraryId), () => {
|
|
401
|
+
const pool = loadPool(libraryId)
|
|
402
|
+
const current = pool.blobs[sha256]
|
|
403
|
+
if (!current || current.captionBy === 'context') return
|
|
404
|
+
current.caption = caption; current.captionBy = 'vision'
|
|
405
|
+
savePool(libraryId, pool)
|
|
406
|
+
})
|
|
407
|
+
return caption
|
|
408
|
+
} finally { activeCaptions -= 1 }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export function exportMediaBundle(libraryId, payload) {
|
|
412
|
+
const pool = loadPool(libraryId)
|
|
413
|
+
const files = {}
|
|
414
|
+
const manifest = { format: MEDIA_FORMAT, blobs: {} }
|
|
415
|
+
const wanted = new Set(payload.memories.flatMap(entry => (entry.attachments || []).map(item => item.sha256)))
|
|
416
|
+
for (const sha of wanted) {
|
|
417
|
+
const blob = pool.blobs[sha]
|
|
418
|
+
if (!blob || blob.missing) continue
|
|
419
|
+
const file = blobFile(libraryId, sha, blob.ext)
|
|
420
|
+
if (!fs.existsSync(file)) continue
|
|
421
|
+
const data = fs.readFileSync(file)
|
|
422
|
+
if (data.length > FILE_LIMIT || crypto.createHash('sha256').update(data).digest('hex') !== sha) throw new Error('attachment integrity check failed')
|
|
423
|
+
const name = `attachments/${sha}.${blob.ext}`
|
|
424
|
+
files[name] = data
|
|
425
|
+
manifest.blobs[sha] = { ...blob, file: name }
|
|
426
|
+
}
|
|
427
|
+
const memoriesBuffer = Buffer.from(JSON.stringify(payload))
|
|
428
|
+
manifest.bundleId = payload?.bundleId || null
|
|
429
|
+
manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
|
|
430
|
+
files['memories.json'] = memoriesBuffer
|
|
431
|
+
files['manifest.json'] = Buffer.from(JSON.stringify(manifest))
|
|
432
|
+
return Buffer.from(zipSync(files, { level: 0 }))
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export function importMediaBundle(libraryId, archive) {
|
|
436
|
+
if (!getLibrary(libraryId)) throw new Error('library not found')
|
|
437
|
+
if (!(archive instanceof Uint8Array) || archive.length > LIBRARY_LIMIT + 10 * 1024 * 1024) throw new Error('archive is too large')
|
|
438
|
+
let total = 0
|
|
439
|
+
const files = unzipSync(archive, { filter: file => {
|
|
440
|
+
if (file.originalSize > FILE_LIMIT || (total += file.originalSize) > LIBRARY_LIMIT + FILE_LIMIT) throw new Error('archive expansion exceeds attachment limits')
|
|
441
|
+
if (file.name !== 'memories.json' && file.name !== 'manifest.json' && !/^attachments\/[a-f0-9]{64}\.(png|jpg|gif|webp)$/.test(file.name)) throw new Error('archive contains an unsupported path')
|
|
442
|
+
return true
|
|
443
|
+
} })
|
|
444
|
+
let manifest, payload
|
|
445
|
+
try {
|
|
446
|
+
manifest = JSON.parse(Buffer.from(files['manifest.json'] || []).toString('utf8'))
|
|
447
|
+
payload = JSON.parse(Buffer.from(files['memories.json'] || []).toString('utf8'))
|
|
448
|
+
} catch {
|
|
449
|
+
throw new Error('invalid memory archive')
|
|
450
|
+
}
|
|
451
|
+
if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
|
|
452
|
+
verifyBundleChecksum(manifest, files['memories.json'])
|
|
453
|
+
let missing = 0
|
|
454
|
+
withFileLock(poolFile(libraryId), () => {
|
|
455
|
+
const pool = loadPool(libraryId)
|
|
456
|
+
let used = pool.totals.bytes
|
|
457
|
+
for (const [sha, blob] of Object.entries(manifest.blobs || {})) {
|
|
458
|
+
if (!SHA.test(sha) || !MIME_EXT[blob.mime] || blob.ext !== MIME_EXT[blob.mime]) throw new Error('invalid attachment manifest')
|
|
459
|
+
const bytes = files[`attachments/${sha}.${blob.ext}`]
|
|
460
|
+
if (!bytes) { missing += 1; continue }
|
|
461
|
+
if (crypto.createHash('sha256').update(bytes).digest('hex') !== sha) throw new Error('attachment checksum mismatch')
|
|
462
|
+
const target = blobFile(libraryId, sha, blob.ext)
|
|
463
|
+
if (!fs.existsSync(target)) {
|
|
464
|
+
if (used + bytes.length > LIBRARY_LIMIT) { missing += 1; continue }
|
|
465
|
+
ensureDir(path.dirname(target))
|
|
466
|
+
fs.writeFileSync(target, bytes, { flag: 'wx', mode: 0o600 })
|
|
467
|
+
used += bytes.length
|
|
468
|
+
}
|
|
469
|
+
pool.blobs[sha] = { ...blob, sha256: sha, bytes: bytes.length, refs: [], missing: false }
|
|
470
|
+
}
|
|
471
|
+
savePool(libraryId, pool)
|
|
472
|
+
})
|
|
473
|
+
return { memories: payload.memories, graph: payload.graph || null, missing, bundleId: payload.bundleId || manifest.bundleId || null }
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Stream the original images; never materialize a 500 MB library as base64. */
|
|
477
|
+
export async function streamMediaExport(libraryId, payload, response) {
|
|
478
|
+
const pool = loadPool(libraryId)
|
|
479
|
+
let failure
|
|
480
|
+
const zip = new Zip((error, chunk, final) => {
|
|
481
|
+
if (error) { failure = error; response.destroy(error); return }
|
|
482
|
+
if (chunk.length) response.write(chunk)
|
|
483
|
+
if (final) response.end()
|
|
484
|
+
})
|
|
485
|
+
const manifest = { format: MEDIA_FORMAT, blobs: {} }
|
|
486
|
+
const memoriesBuffer = Buffer.from(JSON.stringify(payload))
|
|
487
|
+
manifest.bundleId = payload.bundleId || null
|
|
488
|
+
manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
|
|
489
|
+
const push = async (name, source) => {
|
|
490
|
+
const entry = new ZipPassThrough(name)
|
|
491
|
+
zip.add(entry)
|
|
492
|
+
for await (const chunk of source) {
|
|
493
|
+
if (failure || response.destroyed) throw failure || new Error('download closed')
|
|
494
|
+
entry.push(chunk)
|
|
495
|
+
if (response.writableNeedDrain) await once(response, 'drain')
|
|
496
|
+
}
|
|
497
|
+
entry.push(new Uint8Array(), true)
|
|
498
|
+
}
|
|
499
|
+
const wanted = new Set(payload.memories.flatMap(entry => (entry.attachments || []).map(item => item.sha256)))
|
|
500
|
+
response.writeHead(200, {
|
|
501
|
+
'Content-Type': 'application/zip', 'Content-Disposition': `attachment; filename="${libraryId}.zip"`,
|
|
502
|
+
'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff',
|
|
503
|
+
})
|
|
504
|
+
try {
|
|
505
|
+
for (const sha of wanted) {
|
|
506
|
+
const blob = pool.blobs[sha]
|
|
507
|
+
if (!blob || blob.missing) continue
|
|
508
|
+
const file = blobFile(libraryId, sha, blob.ext)
|
|
509
|
+
let info
|
|
510
|
+
try { info = fs.statSync(file) } catch { continue }
|
|
511
|
+
if (info.size > FILE_LIMIT) throw new Error('attachment exceeds export limit')
|
|
512
|
+
const name = `attachments/${sha}.${blob.ext}`
|
|
513
|
+
await push(name, fs.createReadStream(file, { highWaterMark: 64 * 1024 }))
|
|
514
|
+
manifest.blobs[sha] = { ...blob, file: name }
|
|
515
|
+
}
|
|
516
|
+
await push('memories.json', [memoriesBuffer])
|
|
517
|
+
await push('manifest.json', [Buffer.from(JSON.stringify(manifest))])
|
|
518
|
+
zip.end()
|
|
519
|
+
} catch (error) {
|
|
520
|
+
zip.terminate()
|
|
521
|
+
response.destroy(error)
|
|
522
|
+
throw error
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export async function importMediaStream(libraryId, request) {
|
|
527
|
+
if (!getLibrary(libraryId)) throw new Error('library not found')
|
|
528
|
+
const staging = ensureDir(path.join(dataDir(), 'tmp', `import-${crypto.randomUUID()}`))
|
|
529
|
+
const files = new Map()
|
|
530
|
+
const descriptors = new Set()
|
|
531
|
+
let expanded = 0, received = 0, failure
|
|
532
|
+
const unzip = new Unzip(file => {
|
|
533
|
+
try {
|
|
534
|
+
const valid = file.name === 'memories.json' || file.name === 'manifest.json' || /^attachments\/[a-f0-9]{64}\.(png|jpg|gif|webp)$/.test(file.name)
|
|
535
|
+
if (!valid || files.has(file.name) || files.size >= 2500) throw new Error('unsupported or duplicate attachment archive path')
|
|
536
|
+
const local = path.join(staging, crypto.randomUUID())
|
|
537
|
+
const fd = fs.openSync(local, 'wx', 0o600)
|
|
538
|
+
descriptors.add(fd)
|
|
539
|
+
const item = { file: local, bytes: 0, complete: false }
|
|
540
|
+
files.set(file.name, item)
|
|
541
|
+
file.ondata = (error, chunk, final) => {
|
|
542
|
+
if (failure) return
|
|
543
|
+
try {
|
|
544
|
+
if (error) throw error
|
|
545
|
+
item.bytes += chunk.length; expanded += chunk.length
|
|
546
|
+
if (item.bytes > FILE_LIMIT || expanded > LIBRARY_LIMIT + 2 * FILE_LIMIT) throw new Error('archive expansion exceeds storage limits')
|
|
547
|
+
fs.writeSync(fd, chunk)
|
|
548
|
+
if (final) { fs.closeSync(fd); descriptors.delete(fd); item.complete = true }
|
|
549
|
+
} catch (error) { failure = error; file.terminate() }
|
|
550
|
+
}
|
|
551
|
+
file.start()
|
|
552
|
+
} catch (error) { failure = error; file.terminate() }
|
|
553
|
+
})
|
|
554
|
+
unzip.register(UnzipInflate)
|
|
555
|
+
try {
|
|
556
|
+
for await (const chunk of request) {
|
|
557
|
+
received += chunk.length
|
|
558
|
+
if (received > LIBRARY_LIMIT + 2 * FILE_LIMIT) throw new Error('archive exceeds upload limit')
|
|
559
|
+
unzip.push(chunk)
|
|
560
|
+
if (failure) throw failure
|
|
561
|
+
}
|
|
562
|
+
unzip.push(new Uint8Array(), true)
|
|
563
|
+
if (failure) throw failure
|
|
564
|
+
if ([...files.values()].some(item => !item.complete) || !files.has('manifest.json') || !files.has('memories.json')) throw new Error('incomplete memory archive')
|
|
565
|
+
let payload, manifest
|
|
566
|
+
try {
|
|
567
|
+
payload = JSON.parse(fs.readFileSync(files.get('memories.json').file, 'utf8'))
|
|
568
|
+
manifest = JSON.parse(fs.readFileSync(files.get('manifest.json').file, 'utf8'))
|
|
569
|
+
} catch {
|
|
570
|
+
throw new Error('invalid memory archive')
|
|
571
|
+
}
|
|
572
|
+
if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
|
|
573
|
+
verifyBundleChecksum(manifest, fs.readFileSync(files.get('memories.json').file))
|
|
574
|
+
let missing = 0
|
|
575
|
+
withFileLock(poolFile(libraryId), () => {
|
|
576
|
+
const pool = loadPool(libraryId)
|
|
577
|
+
let bytesUsed = pool.totals.bytes
|
|
578
|
+
const created = []
|
|
579
|
+
try {
|
|
580
|
+
for (const [sha, blob] of Object.entries(manifest.blobs || {})) {
|
|
581
|
+
if (!SHA.test(sha) || !MIME_EXT[blob.mime] || blob.ext !== MIME_EXT[blob.mime]) throw new Error('invalid attachment metadata')
|
|
582
|
+
const item = files.get(`attachments/${sha}.${blob.ext}`)
|
|
583
|
+
if (!item) { missing++; continue }
|
|
584
|
+
const bytes = fs.readFileSync(item.file)
|
|
585
|
+
if (crypto.createHash('sha256').update(bytes).digest('hex') !== sha) throw new Error('attachment checksum mismatch')
|
|
586
|
+
const target = blobFile(libraryId, sha, blob.ext)
|
|
587
|
+
if (!fs.existsSync(target)) {
|
|
588
|
+
if (bytesUsed + bytes.length > LIBRARY_LIMIT) { missing++; continue }
|
|
589
|
+
ensureDir(path.dirname(target))
|
|
590
|
+
fs.copyFileSync(item.file, target, fs.constants.COPYFILE_EXCL)
|
|
591
|
+
created.push(target); bytesUsed += bytes.length
|
|
592
|
+
}
|
|
593
|
+
pool.blobs[sha] = { ...blob, sha256: sha, bytes: bytes.length, refs: [], missing: false }
|
|
594
|
+
}
|
|
595
|
+
savePool(libraryId, pool)
|
|
596
|
+
} catch (error) {
|
|
597
|
+
for (const file of created) { try { fs.unlinkSync(file) } catch {} }
|
|
598
|
+
throw error
|
|
599
|
+
}
|
|
600
|
+
})
|
|
601
|
+
return { memories: payload.memories, graph: payload.graph, missing, bundleId: payload.bundleId || manifest.bundleId || null }
|
|
602
|
+
} finally {
|
|
603
|
+
for (const fd of descriptors) { try { fs.closeSync(fd) } catch {} }
|
|
604
|
+
if (!path.resolve(staging).startsWith(path.resolve(dataDir(), 'tmp') + path.sep)) throw new Error('invalid archive staging directory')
|
|
605
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
606
|
+
}
|
|
607
|
+
}
|