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.
Files changed (389) hide show
  1. package/AGENTS.md +108 -108
  2. package/CHANGELOG.md +169 -848
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -72
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9648
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1035
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4911
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -0
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2518
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1066
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -152
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -48
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -415
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -616
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -0
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -23
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -221
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -212
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. 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 { zipSync, unzipSync, Zip, ZipPassThrough, Unzip, UnzipInflate } from 'fflate'
14
-
15
- const FILE_LIMIT = 8 * 1024 * 1024
16
- const LIBRARY_LIMIT = 500 * 1024 * 1024
17
- const MIME_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }
18
- const SHA = /^[a-f0-9]{64}$/
19
- const captures = new Map()
20
- let activeCaptions = 0
21
- // A v2 bundle is always written with a SHA-256 of memories.json. Legacy v1
22
- // archives predate that field, so they stay importable without it; a v2
23
- // manifest with the field removed (or malformed) must be rejected instead of
24
- // silently trusting an edited body. This is an integrity check against
25
- // truncation/accidental edits, NOT a signature: a caller able to rewrite the
26
- // whole manifest can also downgrade `format` to a legacy name, which is an
27
- // explicit compatibility opt-in rather than a checksum bypass.
28
- const MEDIA_FORMAT = 'dsh-memu-memory-media@2'
29
- const LEGACY_MEDIA_FORMATS = ['dsh-memu-memory-media@1', 'dsh-memu-media@1']
30
- function verifyBundleChecksum(manifest, memories) {
31
- const digest = manifest.memoriesSha256
32
- if (!digest) {
33
- if (!LEGACY_MEDIA_FORMATS.includes(manifest.format)) throw new Error('memories.json checksum missing')
34
- return
35
- }
36
- if (typeof digest !== 'string' || !SHA.test(digest)) throw new Error('memories.json checksum is malformed')
37
- const actual = crypto.createHash('sha256').update(memories).digest('hex')
38
- if (actual !== digest) throw new Error('memories.json checksum mismatch')
39
- }
40
- function poolFile(libraryId) {
41
- if (!isSafeId(libraryId)) throw new Error('invalid library id')
42
- return path.join(indexDir(), `${libraryId}.media.json`)
43
- }
44
- function blobFile(libraryId, sha, ext) {
45
- if (!isSafeId(libraryId) || !SHA.test(sha) || !Object.values(MIME_EXT).includes(ext)) throw new Error('invalid attachment reference')
46
- return path.join(dataDir(), 'attachments', libraryId, `${sha}.${ext}`)
47
- }
48
- function loadPool(libraryId) {
49
- const result = readJsonStrict(poolFile(libraryId))
50
- if (result.ok && result.value?.blobs && typeof result.value.blobs === 'object' && !Array.isArray(result.value.blobs)) return result.value
51
- if (result.missing) return { version: 1, blobs: {}, totals: { bytes: 0, count: 0 } }
52
- throw new Error(`media metadata unavailable: ${result.error?.message || 'invalid shape'}`)
53
- }
54
- function savePool(libraryId, pool) {
55
- const stored = Object.values(pool.blobs).filter(blob => !blob.missing)
56
- pool.totals = { bytes: stored.reduce((sum, blob) => sum + blob.bytes, 0), count: stored.length }
57
- writeJson(poolFile(libraryId), pool)
58
- }
59
-
60
- export function imageTurn(message) {
61
- const blocks = Array.isArray(message?.content) ? message.content : []
62
- const images = blocks.filter(block => block?.type === 'image' && block.attachment)
63
- const text = blocks.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join(' ').trim()
64
- const metadata = images.map(block => {
65
- const ref = block.attachment
66
- return `[图片] ${String(ref.name || '').slice(0, 120)} ${ref.width || '?'}x${ref.height || '?'} ${ref.mediaType || ''}`
67
- }).join(' ')
68
- return { text, imageCount: images.length, images, query: text || metadata }
69
- }
70
-
71
- async function captureImage(ctx, libraryId, ref, contextText, now) {
72
- const mime = ref.mediaType
73
- if (!MIME_EXT[mime]) return null
74
- let bytes = null
75
- let missingReason = ''
76
- if (!(ref.bytes > 0) || ref.bytes > FILE_LIMIT) missingReason = 'image exceeds the 8 MB limit or has no verified byte length'
77
- else {
78
- try {
79
- const service = ctx.get?.('attachments') || ctx.attachments
80
- if (!service?.readImage) throw new Error('host attachments.readImage is unavailable')
81
- const stored = await service.readImage(ref)
82
- if (!(stored?.data instanceof Uint8Array) || stored.data.byteLength > FILE_LIMIT) throw new Error('invalid image bytes or 8 MB limit exceeded')
83
- bytes = Buffer.from(stored.data)
84
- } catch (error) { missingReason = String(error?.message || error) }
85
- }
86
- 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')
87
- return withFileLock(poolFile(libraryId), () => {
88
- const pool = loadPool(libraryId)
89
- const previous = pool.blobs[sha256]
90
- const ext = MIME_EXT[mime]
91
- const file = blobFile(libraryId, sha256, ext)
92
- let stored = !!previous && fs.existsSync(file)
93
- const wasStored = stored
94
- if (!stored && bytes) {
95
- if ((pool.totals.bytes || 0) + bytes.length > LIBRARY_LIMIT) missingReason = 'library image storage exceeds the 500 MB limit'
96
- else {
97
- ensureDir(path.dirname(file))
98
- const temporary = `${file}.tmp-${crypto.randomUUID()}`
99
- try {
100
- fs.writeFileSync(temporary, bytes, { flag: 'wx', mode: 0o600 })
101
- fs.renameSync(temporary, file)
102
- stored = true
103
- } finally { try { fs.rmSync(temporary, { force: true }) } catch {} }
104
- }
105
- }
106
- const at = new Date(now).toISOString()
107
- const blob = {
108
- ...previous, sha256, bytes: bytes?.length || ref.bytes || 0, ext, mime,
109
- w: ref.width || null, h: ref.height || null, firstSeenAt: previous?.firstSeenAt || at,
110
- lastUsedAt: at, useCount: Number(previous?.useCount || 0) + 1, refs: previous?.refs || [],
111
- caption: contextText ? contextText.slice(0, 160) : previous?.caption || (ref.name ? String(ref.name).slice(0, 160) : '[图片]'),
112
- captionBy: contextText ? 'context' : previous?.captionBy || (ref.name ? 'exif' : 'none'),
113
- missing: !stored, missingReason: stored ? null : missingReason || 'image unavailable',
114
- }
115
- pool.blobs[sha256] = blob
116
- try { savePool(libraryId, pool) } catch (error) {
117
- if (stored && !wasStored) { try { fs.unlinkSync(file) } catch {} }
118
- throw error
119
- }
120
- if (blob.missing) warn(`image not saved for ${libraryId}: ${blob.missingReason}`)
121
- return blob
122
- })
123
- }
124
-
125
- export function captureMediaEvent(ctx, session, event, { now = Date.now() } = {}) {
126
- const sessionId = session?.header?.id
127
- if (!sessionId || session?.header?.origin === 'subagent' || event?.type !== 'user/message' || event.data?.source?.kind !== 'user') return Promise.resolve([])
128
- return captureMessageMedia(ctx, session, event.data, {
129
- now, eventKey: event.seq !== undefined ? `seq:${event.seq}` : event.data.id ? `id:${event.data.id}` : null,
130
- })
131
- }
132
-
133
- /** Shared byte collection, without disguising tool results as user events. */
134
- export function captureMessageMedia(ctx, session, message, { now = Date.now(), eventKey = null } = {}) {
135
- const sessionId = session?.header?.id
136
- if (!sessionId || session.header.origin === 'subagent') return Promise.resolve([])
137
- const binding = getSessionBinding(sessionId)
138
- if (!binding?.libraryId || !effectiveScope(binding).useLibrary) return Promise.resolve([])
139
- const turn = imageTurn(message)
140
- if (!turn.imageCount) return Promise.resolve([])
141
- const previous = captures.get(sessionId) || Promise.resolve()
142
- const task = previous.catch(() => {}).then(async () => {
143
- const current = getSessionBinding(sessionId)
144
- if (!current?.libraryId || current.libraryId !== binding.libraryId || !effectiveScope(current).useLibrary) return []
145
- if (eventKey && (current.mediaEvents || []).includes(eventKey)) return []
146
- const received = []
147
- for (const block of turn.images.slice(0, 8)) {
148
- const blob = await captureImage(ctx, binding.libraryId, block.attachment, turn.text, now)
149
- if (blob) received.push({ ...blob, sourceAttachmentId: block.attachment.attachmentId, contextText: turn.text.slice(0, 160), addedAt: stamp() })
150
- }
151
- const fresh = getSessionBinding(sessionId)
152
- if (!fresh || fresh.libraryId !== binding.libraryId || !effectiveScope(fresh).useLibrary) return []
153
- const pending = [...(fresh.pendingMedia || []), ...received].slice(-8)
154
- const hint = received.find(blob => blob.useCount >= 3)
155
- const index = hint ? loadPrivateIndex(binding.libraryId) : null
156
- const hasHabit = hint && Object.values(index.entries).some(entry => entry.track === 'habit' && (entry.attachments || []).some(item => item.sha256 === hint.sha256))
157
- setSessionBinding(sessionId, {
158
- pendingMedia: pending, lastImageCount: turn.imageCount,
159
- mediaEvents: eventKey ? [...(fresh.mediaEvents || []), eventKey].slice(-128) : fresh.mediaEvents || [],
160
- stickerHint: hint && !hasHabit ? { sha256: hint.sha256, useCount: hint.useCount } : fresh.stickerHint || null,
161
- })
162
- for (const blob of received) {
163
- if (blob.captionBy === 'none' && !blob.missing && getSettings().visionCaptionEnabled === true) {
164
- void captionImage(binding.libraryId, blob.sha256).catch(() => warn('optional image description failed; original metadata retained'))
165
- }
166
- }
167
- return received
168
- })
169
- captures.set(sessionId, task)
170
- void task.finally(() => { if (captures.get(sessionId) === task) captures.delete(sessionId) }).catch(() => {})
171
- return task
172
- }
173
-
174
- export function attachmentRefs(libraryId, refs) {
175
- if (refs === undefined) return []
176
- if (!Array.isArray(refs) || refs.length > 8) throw new Error('attachments must contain at most 8 sha256 references')
177
- const pool = loadPool(libraryId)
178
- return [...new Set(refs.map(ref => ref?.sha256))].map(sha => {
179
- if (!SHA.test(String(sha))) throw new Error('attachment sha256 must be 64 lowercase hex characters')
180
- const blob = pool.blobs[sha]
181
- if (!blob) throw new Error('attachment was not received in this library')
182
- return {
183
- kind: blob.useCount >= 3 && Math.max(blob.w || 0, blob.h || 0) < 512 ? 'sticker' : 'image',
184
- sha256: sha, bytes: blob.bytes, w: blob.w, h: blob.h, mime: blob.mime,
185
- caption: blob.caption, captionBy: blob.captionBy, addedAt: blob.firstSeenAt,
186
- lastUsedAt: blob.lastUsedAt, useCount: blob.useCount,
187
- missing: blob.missing || !fs.existsSync(blobFile(libraryId, sha, blob.ext)),
188
- }
189
- })
190
- }
191
-
192
- export function reconcileMedia(libraryId, index, { now = Date.now() } = {}) {
193
- const file = poolFile(libraryId)
194
- if (!fs.existsSync(file)) return
195
- withFileLock(file, () => {
196
- const pool = loadPool(libraryId)
197
- const refs = new Map()
198
- for (const [id, entry] of Object.entries(index.entries || {})) {
199
- if (!isMemoryEligible(entry, { now })) continue
200
- for (const item of entry.attachments || []) {
201
- if (!refs.has(item.sha256)) refs.set(item.sha256, [])
202
- refs.get(item.sha256).push(id)
203
- }
204
- }
205
- let changed = false
206
- for (const [sha, blob] of Object.entries(pool.blobs)) {
207
- const next = refs.get(sha) || []
208
- if (JSON.stringify(blob.refs) !== JSON.stringify(next)) { blob.refs = next; changed = true }
209
- if (!next.length && now - Date.parse(blob.lastUsedAt || blob.firstSeenAt) > 30 * 86_400_000) {
210
- try { fs.rmSync(blobFile(libraryId, sha, blob.ext), { force: true }) } catch (error) { warn(`image cleanup deferred: ${error.code || 'IO error'}`); continue }
211
- delete pool.blobs[sha]
212
- changed = true
213
- }
214
- }
215
- if (changed) savePool(libraryId, pool)
216
- })
217
- }
218
- onPrivateIndexWrite((libraryId, index) => reconcileMedia(libraryId, index))
219
-
220
- function authorize(libraryId, sha256, sessionId) {
221
- if (!getLibrary(libraryId) || !SHA.test(String(sha256))) throw Object.assign(new Error('attachment not found'), { status: 404 })
222
- const binding = getSessionBinding(sessionId)
223
- if (!binding || binding.libraryId !== libraryId || !effectiveScope(binding).useLibrary) throw Object.assign(new Error('attachment scope denied'), { status: 403 })
224
- const entries = Object.values(loadPrivateIndex(libraryId).entries)
225
- const matching = entries.filter(entry => isMemoryEligible(entry) && entry.visibility !== 'secret'
226
- && visibleToSession(entry, sessionId) && (entry.attachments || []).some(item => item.sha256 === sha256))
227
- if (!matching.length) throw Object.assign(new Error('attachment visibility denied'), { status: 403 })
228
- return matching
229
- }
230
-
231
- export function getAttachment({ libraryId, sha256, sessionId }) {
232
- const entries = authorize(libraryId, sha256, sessionId)
233
- const blob = loadPool(libraryId).blobs[sha256]
234
- if (!blob) return { sha256, missing: true }
235
- const allowCaption = entries.every(entry => entry.disclosure !== 'never_say')
236
- return {
237
- sha256, bytes: blob.bytes, w: blob.w, h: blob.h, mime: blob.mime,
238
- caption: allowCaption ? blob.caption : null, captionBy: allowCaption ? blob.captionBy : null,
239
- useCount: blob.useCount, missing: blob.missing || !fs.existsSync(blobFile(libraryId, sha256, blob.ext)),
240
- }
241
- }
242
-
243
- export async function attachmentThumbnail(args) {
244
- const info = getAttachment(args)
245
- if (info.missing) return null
246
- const blob = loadPool(args.libraryId).blobs[args.sha256]
247
- const { default: sharp } = await import('sharp')
248
- const data = await sharp(blobFile(args.libraryId, args.sha256, blob.ext), { limitInputPixels: 40_000_000, animated: false })
249
- .resize({ width: 512, height: 512, fit: 'inside', withoutEnlargement: true }).webp({ quality: 80 }).toBuffer()
250
- return { data, mime: 'image/webp' }
251
- }
252
-
253
- export function attachmentPreview(libraryId, entry) {
254
- if (entry.visibility === 'secret' || entry.disclosure === 'never_say') return (entry.attachments || []).map(item => ({ sha256: item.sha256, missing: item.missing, hidden: true }))
255
- const binding = listSessionBindings().find(binding => binding.libraryId === libraryId && effectiveScope(binding).useLibrary && visibleToSession(entry, binding.sessionId))
256
- return (entry.attachments || []).map(item => ({
257
- ...item, url: binding ? `/dsh-memu-memory/attachment/${encodeURIComponent(libraryId)}/${item.sha256}?sessionId=${encodeURIComponent(binding.sessionId)}` : null,
258
- }))
259
- }
260
-
261
- export async function captionImage(libraryId, sha256) {
262
- if (activeCaptions >= 2) return null
263
- const config = getVisionConfig({ withKey: true })
264
- if (!config.ready || getSettings().visionCaptionEnabled !== true) return null
265
- const blob = loadPool(libraryId).blobs[sha256]
266
- if (!blob || blob.missing || !['none', 'exif'].includes(blob.captionBy)) return null
267
- const index = loadPrivateIndex(libraryId)
268
- const linked = Object.values(index.entries).filter(entry => (entry.attachments || []).some(item => item.sha256 === sha256))
269
- if (linked.some(entry => entry.visibility === 'secret' || entry.disclosure === 'never_say')) return null
270
- const data = fs.readFileSync(blobFile(libraryId, sha256, blob.ext))
271
- if (data.length > FILE_LIMIT) return null
272
- // C7:vision 请求前先缩放。原图最长边 1024px、JPEG q85;不做放大,动图取首帧。
273
- // 配额、sha 去重与 max_tokens 都不变——只改发出去的字节。
274
- const { default: sharp } = await import('sharp')
275
- const prepared = await sharp(data, { limitInputPixels: 40_000_000, animated: false })
276
- .resize({ width: 1024, height: 1024, fit: 'inside', withoutEnlargement: true })
277
- .jpeg({ quality: 85 })
278
- .toBuffer()
279
- const reserved = withFileLock(poolFile(libraryId), () => {
280
- const pool = loadPool(libraryId)
281
- const now = Date.now()
282
- const budget = pool.visionBudget || {}
283
- const hour = Math.floor(now / 3_600_000)
284
- const count = budget.hour === hour ? Number(budget.count || 0) : 0
285
- if (now - Number(budget.lastAt || 0) < 60_000 || count >= 10) return false
286
- pool.visionBudget = { hour, count: count + 1, lastAt: now }
287
- savePool(libraryId, pool)
288
- return true
289
- })
290
- if (!reserved) return null
291
- activeCaptions += 1
292
- try {
293
- const response = await fetch(`${config.baseUrl}/chat/completions`, {
294
- method: 'POST', headers: { 'content-type': 'application/json', ...(config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}) },
295
- signal: AbortSignal.timeout(20_000),
296
- body: JSON.stringify({ model: config.model, max_tokens: 100, temperature: 0,
297
- messages: [{ role: 'user', content: [
298
- { type: 'text', text: loadPrompt('image-caption').text },
299
- { type: 'image_url', image_url: { url: `data:image/jpeg;base64,${prepared.toString('base64')}` } },
300
- ] }] }),
301
- })
302
- if (!response.ok) throw new Error(`vision service returned HTTP ${response.status}`)
303
- const result = await response.json()
304
- const caption = String(result?.choices?.[0]?.message?.content || '').trim().slice(0, 40)
305
- if (!caption) return null
306
- withFileLock(poolFile(libraryId), () => {
307
- const pool = loadPool(libraryId)
308
- const current = pool.blobs[sha256]
309
- if (!current || current.captionBy === 'context') return
310
- current.caption = caption; current.captionBy = 'vision'
311
- savePool(libraryId, pool)
312
- })
313
- return caption
314
- } finally { activeCaptions -= 1 }
315
- }
316
-
317
- export function exportMediaBundle(libraryId, payload) {
318
- const pool = loadPool(libraryId)
319
- const files = {}
320
- const manifest = { format: MEDIA_FORMAT, blobs: {} }
321
- const wanted = new Set(payload.memories.flatMap(entry => (entry.attachments || []).map(item => item.sha256)))
322
- for (const sha of wanted) {
323
- const blob = pool.blobs[sha]
324
- if (!blob || blob.missing) continue
325
- const file = blobFile(libraryId, sha, blob.ext)
326
- if (!fs.existsSync(file)) continue
327
- const data = fs.readFileSync(file)
328
- if (data.length > FILE_LIMIT || crypto.createHash('sha256').update(data).digest('hex') !== sha) throw new Error('attachment integrity check failed')
329
- const name = `attachments/${sha}.${blob.ext}`
330
- files[name] = data
331
- manifest.blobs[sha] = { ...blob, file: name }
332
- }
333
- const memoriesBuffer = Buffer.from(JSON.stringify(payload))
334
- manifest.bundleId = payload?.bundleId || null
335
- manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
336
- files['memories.json'] = memoriesBuffer
337
- files['manifest.json'] = Buffer.from(JSON.stringify(manifest))
338
- return Buffer.from(zipSync(files, { level: 0 }))
339
- }
340
-
341
- export function importMediaBundle(libraryId, archive) {
342
- if (!getLibrary(libraryId)) throw new Error('library not found')
343
- if (!(archive instanceof Uint8Array) || archive.length > LIBRARY_LIMIT + 10 * 1024 * 1024) throw new Error('archive is too large')
344
- let total = 0
345
- const files = unzipSync(archive, { filter: file => {
346
- if (file.originalSize > FILE_LIMIT || (total += file.originalSize) > LIBRARY_LIMIT + FILE_LIMIT) throw new Error('archive expansion exceeds attachment limits')
347
- 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')
348
- return true
349
- } })
350
- let manifest, payload
351
- try {
352
- manifest = JSON.parse(Buffer.from(files['manifest.json'] || []).toString('utf8'))
353
- payload = JSON.parse(Buffer.from(files['memories.json'] || []).toString('utf8'))
354
- } catch {
355
- throw new Error('invalid memory archive')
356
- }
357
- if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
358
- verifyBundleChecksum(manifest, files['memories.json'])
359
- let missing = 0
360
- withFileLock(poolFile(libraryId), () => {
361
- const pool = loadPool(libraryId)
362
- let used = pool.totals.bytes
363
- for (const [sha, blob] of Object.entries(manifest.blobs || {})) {
364
- if (!SHA.test(sha) || !MIME_EXT[blob.mime] || blob.ext !== MIME_EXT[blob.mime]) throw new Error('invalid attachment manifest')
365
- const bytes = files[`attachments/${sha}.${blob.ext}`]
366
- if (!bytes) { missing += 1; continue }
367
- if (crypto.createHash('sha256').update(bytes).digest('hex') !== sha) throw new Error('attachment checksum mismatch')
368
- const target = blobFile(libraryId, sha, blob.ext)
369
- if (!fs.existsSync(target)) {
370
- if (used + bytes.length > LIBRARY_LIMIT) { missing += 1; continue }
371
- ensureDir(path.dirname(target))
372
- fs.writeFileSync(target, bytes, { flag: 'wx', mode: 0o600 })
373
- used += bytes.length
374
- }
375
- pool.blobs[sha] = { ...blob, sha256: sha, bytes: bytes.length, refs: [], missing: false }
376
- }
377
- savePool(libraryId, pool)
378
- })
379
- return { memories: payload.memories, graph: payload.graph || null, missing, bundleId: payload.bundleId || manifest.bundleId || null }
380
- }
381
-
382
- /** Stream the original images; never materialize a 500 MB library as base64. */
383
- export async function streamMediaExport(libraryId, payload, response) {
384
- const pool = loadPool(libraryId)
385
- let failure
386
- const zip = new Zip((error, chunk, final) => {
387
- if (error) { failure = error; response.destroy(error); return }
388
- if (chunk.length) response.write(chunk)
389
- if (final) response.end()
390
- })
391
- const manifest = { format: MEDIA_FORMAT, blobs: {} }
392
- const memoriesBuffer = Buffer.from(JSON.stringify(payload))
393
- manifest.bundleId = payload.bundleId || null
394
- manifest.memoriesSha256 = crypto.createHash('sha256').update(memoriesBuffer).digest('hex')
395
- const push = async (name, source) => {
396
- const entry = new ZipPassThrough(name)
397
- zip.add(entry)
398
- for await (const chunk of source) {
399
- if (failure || response.destroyed) throw failure || new Error('download closed')
400
- entry.push(chunk)
401
- if (response.writableNeedDrain) await once(response, 'drain')
402
- }
403
- entry.push(new Uint8Array(), true)
404
- }
405
- const wanted = new Set(payload.memories.flatMap(entry => (entry.attachments || []).map(item => item.sha256)))
406
- response.writeHead(200, {
407
- 'Content-Type': 'application/zip', 'Content-Disposition': `attachment; filename="${libraryId}.zip"`,
408
- 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff',
409
- })
410
- try {
411
- for (const sha of wanted) {
412
- const blob = pool.blobs[sha]
413
- if (!blob || blob.missing) continue
414
- const file = blobFile(libraryId, sha, blob.ext)
415
- let info
416
- try { info = fs.statSync(file) } catch { continue }
417
- if (info.size > FILE_LIMIT) throw new Error('attachment exceeds export limit')
418
- const name = `attachments/${sha}.${blob.ext}`
419
- await push(name, fs.createReadStream(file, { highWaterMark: 64 * 1024 }))
420
- manifest.blobs[sha] = { ...blob, file: name }
421
- }
422
- await push('memories.json', [memoriesBuffer])
423
- await push('manifest.json', [Buffer.from(JSON.stringify(manifest))])
424
- zip.end()
425
- } catch (error) {
426
- zip.terminate()
427
- response.destroy(error)
428
- throw error
429
- }
430
- }
431
-
432
- export async function importMediaStream(libraryId, request) {
433
- if (!getLibrary(libraryId)) throw new Error('library not found')
434
- const staging = ensureDir(path.join(dataDir(), 'tmp', `import-${crypto.randomUUID()}`))
435
- const files = new Map()
436
- const descriptors = new Set()
437
- let expanded = 0, received = 0, failure
438
- const unzip = new Unzip(file => {
439
- try {
440
- const valid = file.name === 'memories.json' || file.name === 'manifest.json' || /^attachments\/[a-f0-9]{64}\.(png|jpg|gif|webp)$/.test(file.name)
441
- if (!valid || files.has(file.name) || files.size >= 2500) throw new Error('unsupported or duplicate attachment archive path')
442
- const local = path.join(staging, crypto.randomUUID())
443
- const fd = fs.openSync(local, 'wx', 0o600)
444
- descriptors.add(fd)
445
- const item = { file: local, bytes: 0, complete: false }
446
- files.set(file.name, item)
447
- file.ondata = (error, chunk, final) => {
448
- if (failure) return
449
- try {
450
- if (error) throw error
451
- item.bytes += chunk.length; expanded += chunk.length
452
- if (item.bytes > FILE_LIMIT || expanded > LIBRARY_LIMIT + 2 * FILE_LIMIT) throw new Error('archive expansion exceeds storage limits')
453
- fs.writeSync(fd, chunk)
454
- if (final) { fs.closeSync(fd); descriptors.delete(fd); item.complete = true }
455
- } catch (error) { failure = error; file.terminate() }
456
- }
457
- file.start()
458
- } catch (error) { failure = error; file.terminate() }
459
- })
460
- unzip.register(UnzipInflate)
461
- try {
462
- for await (const chunk of request) {
463
- received += chunk.length
464
- if (received > LIBRARY_LIMIT + 2 * FILE_LIMIT) throw new Error('archive exceeds upload limit')
465
- unzip.push(chunk)
466
- if (failure) throw failure
467
- }
468
- unzip.push(new Uint8Array(), true)
469
- if (failure) throw failure
470
- if ([...files.values()].some(item => !item.complete) || !files.has('manifest.json') || !files.has('memories.json')) throw new Error('incomplete memory archive')
471
- let payload, manifest
472
- try {
473
- payload = JSON.parse(fs.readFileSync(files.get('memories.json').file, 'utf8'))
474
- manifest = JSON.parse(fs.readFileSync(files.get('manifest.json').file, 'utf8'))
475
- } catch {
476
- throw new Error('invalid memory archive')
477
- }
478
- if (![MEDIA_FORMAT, ...LEGACY_MEDIA_FORMATS].includes(manifest.format) || !Array.isArray(payload.memories)) throw new Error('invalid memory archive')
479
- verifyBundleChecksum(manifest, fs.readFileSync(files.get('memories.json').file))
480
- let missing = 0
481
- withFileLock(poolFile(libraryId), () => {
482
- const pool = loadPool(libraryId)
483
- let bytesUsed = pool.totals.bytes
484
- const created = []
485
- try {
486
- for (const [sha, blob] of Object.entries(manifest.blobs || {})) {
487
- if (!SHA.test(sha) || !MIME_EXT[blob.mime] || blob.ext !== MIME_EXT[blob.mime]) throw new Error('invalid attachment metadata')
488
- const item = files.get(`attachments/${sha}.${blob.ext}`)
489
- if (!item) { missing++; continue }
490
- const bytes = fs.readFileSync(item.file)
491
- if (crypto.createHash('sha256').update(bytes).digest('hex') !== sha) throw new Error('attachment checksum mismatch')
492
- const target = blobFile(libraryId, sha, blob.ext)
493
- if (!fs.existsSync(target)) {
494
- if (bytesUsed + bytes.length > LIBRARY_LIMIT) { missing++; continue }
495
- ensureDir(path.dirname(target))
496
- fs.copyFileSync(item.file, target, fs.constants.COPYFILE_EXCL)
497
- created.push(target); bytesUsed += bytes.length
498
- }
499
- pool.blobs[sha] = { ...blob, sha256: sha, bytes: bytes.length, refs: [], missing: false }
500
- }
501
- savePool(libraryId, pool)
502
- } catch (error) {
503
- for (const file of created) { try { fs.unlinkSync(file) } catch {} }
504
- throw error
505
- }
506
- })
507
- return { memories: payload.memories, graph: payload.graph, missing, bundleId: payload.bundleId || manifest.bundleId || null }
508
- } finally {
509
- for (const fd of descriptors) { try { fs.closeSync(fd) } catch {} }
510
- if (!path.resolve(staging).startsWith(path.resolve(dataDir(), 'tmp') + path.sep)) throw new Error('invalid archive staging directory')
511
- fs.rmSync(staging, { recursive: true, force: true })
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
+ }