@jjh32456/longlive 0.0.0-stage → 2.0.0

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 (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,698 @@
1
+ /**
2
+ * Optional local embeddings for semantic recall (A3).
3
+ *
4
+ * Everything here is lazy and degradable:
5
+ * - importing this file never touches the filesystem and never loads ONNX;
6
+ * - `onnxruntime-node` is an optionalDependency, imported only when an
7
+ * operator turns `embedding.enabled` on;
8
+ * - a missing model / tokenizer / runtime is a coded error that the caller
9
+ * turns into "fall back to keyword recall", never a crash and never a
10
+ * startup failure.
11
+ *
12
+ * The model shape this module expects is a BERT-family encoder exported to
13
+ * ONNX with `input_ids` / `attention_mask` / `token_type_ids` and
14
+ * `last_hidden_state` (e.g. Xenova/bge-small-zh-v1.5). Pooling is CLS (BGE's
15
+ * documented pooling), then L2 normalization, so cosine = dot product.
16
+ *
17
+ * Tokenization is implemented in-tree (BertNormalizer + BertPreTokenizer +
18
+ * WordPiece) because pulling @xenova/transformers would add a much larger
19
+ * dependency than the ONNX runtime itself. The tokenizer JSON is the source of
20
+ * truth; this file does not hardcode a vocabulary.
21
+ */
22
+
23
+ import { createHash } from 'node:crypto';
24
+ import fs from 'node:fs';
25
+ import fsp from 'node:fs/promises';
26
+ import path from 'node:path';
27
+
28
+ export const EMBEDDING_VERSION = 1;
29
+
30
+ export const EMBEDDING_DEFAULTS = Object.freeze({
31
+ enabled: true,
32
+ modelPath: '',
33
+ maxSeqLen: 256,
34
+ queryInstruction: '为这个句子生成表示以用于检索相关文章:',
35
+ maxChunksPerCard: 6,
36
+ maxChunkChars: 400,
37
+ batchSize: 1,
38
+ });
39
+
40
+ /** Cosmetic/codec errors: each one is a reason to fall back, never to throw. */
41
+ export function embeddingError(code, message) {
42
+ const error = new Error(message);
43
+ error.code = code;
44
+ return error;
45
+ }
46
+
47
+ function bool(value) {
48
+ return value === true;
49
+ }
50
+
51
+ function positiveInt(value, fallback, max) {
52
+ const number = Number(value);
53
+ if (!Number.isFinite(number) || number <= 0) return fallback;
54
+ return Math.min(max, Math.max(1, Math.floor(number)));
55
+ }
56
+
57
+ function text(value) {
58
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : '';
59
+ }
60
+
61
+ /**
62
+ * Normalize the operator-facing `embedding` block.
63
+ *
64
+ * `embedder` is a test seam: an object `{modelFingerprint, dim,
65
+ * embedQuery(text), embedDocument(text)}` that replaces the ONNX provider.
66
+ * Production config is plain JSON and never carries it.
67
+ */
68
+ export function normalizeEmbeddingConfig(input, { memoryRoot = null } = {}) {
69
+ const value = input && typeof input === 'object' ? input : {};
70
+ const enabled = value.enabled !== false;
71
+ const modelPath = text(value.modelPath);
72
+ const cacheDirRaw = text(value.cacheDir);
73
+ const cacheDir = cacheDirRaw
74
+ ? (path.isAbsolute(cacheDirRaw) ? path.resolve(cacheDirRaw) : path.resolve(memoryRoot ?? process.cwd(), cacheDirRaw))
75
+ : (memoryRoot ? path.join(memoryRoot, '.longlive', 'embeddings') : '');
76
+ const embedder = value.embedder && typeof value.embedder === 'object'
77
+ && typeof value.embedder.embedQuery === 'function'
78
+ && typeof value.embedder.embedDocument === 'function'
79
+ ? value.embedder
80
+ : null;
81
+ return {
82
+ enabled,
83
+ modelPath,
84
+ cacheDir,
85
+ maxSeqLen: positiveInt(value.maxSeqLen, EMBEDDING_DEFAULTS.maxSeqLen, 512),
86
+ queryInstruction: typeof value.queryInstruction === 'string'
87
+ ? value.queryInstruction
88
+ : EMBEDDING_DEFAULTS.queryInstruction,
89
+ maxChunksPerCard: positiveInt(value.maxChunksPerCard, EMBEDDING_DEFAULTS.maxChunksPerCard, 32),
90
+ maxChunkChars: positiveInt(value.maxChunkChars, EMBEDDING_DEFAULTS.maxChunkChars, 4000),
91
+ keywordWeight: Number.isFinite(Number(value.keywordWeight)) ? Math.max(0, Number(value.keywordWeight)) : 0.6,
92
+ vectorWeight: Number.isFinite(Number(value.vectorWeight)) ? Math.max(0, Number(value.vectorWeight)) : 0.4,
93
+ // Raw cosine needed when a card has zero keyword hits (semantic-only
94
+ // admission). Calibrated against bge-small-zh-v1.5 on this memory tree:
95
+ // unrelated silent queries peaked at 0.498, so 0.55 keeps them out while
96
+ // still admitting true paraphrases around 0.58+.
97
+ semanticAdmit: Number.isFinite(Number(value.semanticAdmit)) ? Number(value.semanticAdmit) : 0.55,
98
+ minFusedScore: Number.isFinite(Number(value.minFusedScore)) ? Number(value.minFusedScore) : 0.2,
99
+ embedder,
100
+ };
101
+ }
102
+
103
+ /** SHA-256 (hex) of a string; used for cache keys, not for security. */
104
+ export function digest(value) {
105
+ return createHash('sha256').update(String(value ?? ''), 'utf8').digest('hex');
106
+ }
107
+
108
+ /* ------------------------------------------------------------------ *
109
+ * 1. BERT tokenizer (normalizer + pre-tokenizer + WordPiece)
110
+ * ------------------------------------------------------------------ */
111
+
112
+ function isWhitespace(cp) {
113
+ return cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d || cp === 0x0c
114
+ || cp === 0x0b || cp === 0x00a0 || cp === 0x2028 || cp === 0x2029
115
+ || cp === 0x3000 || (cp >= 0x1680 && cp <= 0x1680) || (cp >= 0x2000 && cp <= 0x200a);
116
+ }
117
+
118
+ function isControl(cp) {
119
+ if (cp === 0x09 || cp === 0x0a || cp === 0x0d) return false;
120
+ return (cp >= 0x00 && cp <= 0x1f) || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)
121
+ || cp === 0xad || (cp >= 0x0600 && cp <= 0x0605) || cp === 0x061c || cp === 0x06dd
122
+ || cp === 0x070f || cp === 0x180e || (cp >= 0x200b && cp <= 0x200f)
123
+ || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2060 && cp <= 0x2064)
124
+ || (cp >= 0x2066 && cp <= 0x206f) || cp === 0xfeff || (cp >= 0xfff9 && cp <= 0xfffb)
125
+ || (cp >= 0xfff9 && cp <= 0xfffb);
126
+ }
127
+
128
+ function isPunctuation(cp) {
129
+ return (cp >= 33 && cp <= 47) || (cp >= 58 && cp <= 64) || (cp >= 91 && cp <= 96)
130
+ || (cp >= 123 && cp <= 126) || (cp >= 0x2000 && cp <= 0x206f)
131
+ || (cp >= 0x2e00 && cp <= 0x2e7f) || (cp >= 0x3000 && cp <= 0x303f)
132
+ || (cp >= 0xff00 && cp <= 0xff0f) || (cp >= 0xff1a && cp <= 0xff20)
133
+ || (cp >= 0xff3b && cp <= 0xff40) || (cp >= 0xff5b && cp <= 0xff65);
134
+ }
135
+
136
+ /** CJK ideographs, Hiragana/Katakana, Hangul: one token per character. */
137
+ function isChineseChar(cp) {
138
+ return (cp >= 0x4e00 && cp <= 0x9fff) || (cp >= 0x3400 && cp <= 0x4dbf)
139
+ || (cp >= 0x20000 && cp <= 0x2a6df) || (cp >= 0x2a700 && cp <= 0x2b73f)
140
+ || (cp >= 0x2b740 && cp <= 0x2b81f) || (cp >= 0x2b820 && cp <= 0x2ceaf)
141
+ || (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0x2f800 && cp <= 0x2fa1f)
142
+ || (cp >= 0x3040 && cp <= 0x309f) || (cp >= 0x30a0 && cp <= 0x30ff)
143
+ || (cp >= 0x31f0 && cp <= 0x31ff) || (cp >= 0xac00 && cp <= 0xd7af)
144
+ || (cp >= 0x1100 && cp <= 0x11ff);
145
+ }
146
+
147
+ function stripAccents(value) {
148
+ return String(value).normalize('NFD').replace(/[\u0300-\u036f]/g, '');
149
+ }
150
+
151
+ export function bertBasicNormalize(value, options = {}) {
152
+ let out = '';
153
+ const chars = Array.from(String(value ?? ''));
154
+ for (const ch of chars) {
155
+ const cp = ch.codePointAt(0);
156
+ if (cp === 0 || cp === 0xfffd || isControl(cp)) continue;
157
+ if (isWhitespace(cp)) { out += ' '; continue; }
158
+ if (options.handleChineseChars !== false && isChineseChar(cp)) out += ` ${ch} `;
159
+ else out += ch;
160
+ }
161
+ if (options.lowercase === true) out = out.toLowerCase();
162
+ if (options.stripAccents === true) out = stripAccents(out);
163
+ return out;
164
+ }
165
+
166
+ export function bertPreTokenize(normalized) {
167
+ const collected = [];
168
+ let current = '';
169
+ const flush = () => {
170
+ if (current !== '') { collected.push(current); current = ''; }
171
+ };
172
+ for (const ch of Array.from(String(normalized ?? ''))) {
173
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { flush(); continue; }
174
+ const cp = ch.codePointAt(0);
175
+ if (isPunctuation(cp)) { flush(); collected.push(ch); continue; }
176
+ current += ch;
177
+ }
178
+ flush();
179
+ return collected;
180
+ }
181
+
182
+ export function wordPiece(word, vocab, { unkToken = '[UNK]', prefix = '##', maxChars = 100 } = {}) {
183
+ const chars = Array.from(String(word ?? ''));
184
+ if (chars.length > maxChars) return [unkToken];
185
+ const out = [];
186
+ let start = 0;
187
+ while (start < chars.length) {
188
+ let end = chars.length;
189
+ let piece = null;
190
+ while (start < end) {
191
+ const candidate = (start > 0 ? prefix : '') + chars.slice(start, end).join('');
192
+ if (Object.prototype.hasOwnProperty.call(vocab, candidate)) { piece = candidate; break; }
193
+ end -= 1;
194
+ }
195
+ if (piece === null) return [unkToken];
196
+ out.push(piece);
197
+ start = end;
198
+ }
199
+ return out;
200
+ }
201
+
202
+ /**
203
+ * Load `tokenizer.json` and return `{encode(text, {maxLen}), decode(ids)}`.
204
+ * The WordPiece model is read from the file, not assumed.
205
+ */
206
+ export function loadTokenizer(tokenizerPath) {
207
+ let raw;
208
+ try {
209
+ raw = JSON.parse(fs.readFileSync(tokenizerPath, 'utf8'));
210
+ } catch (error) {
211
+ throw embeddingError('E_EMBEDDING_TOKENIZER', `读不到 tokenizer.json(${tokenizerPath}):${error?.message ?? error}`);
212
+ }
213
+ const model = raw?.model;
214
+ if (!model || model.type !== 'WordPiece' || !model.vocab || typeof model.vocab !== 'object') {
215
+ throw embeddingError('E_EMBEDDING_TOKENIZER', 'tokenizer.json 不是 WordPiece 模型(需要 model.vocab)');
216
+ }
217
+ const vocab = model.vocab;
218
+ const idToToken = new Array(Object.keys(vocab).length);
219
+ for (const [token, id] of Object.entries(vocab)) {
220
+ if (Number.isInteger(id) && id >= 0) idToToken[id] = token;
221
+ }
222
+ const added = new Map();
223
+ for (const item of Array.isArray(raw?.added_tokens) ? raw.added_tokens : []) {
224
+ if (item && Number.isInteger(item.id) && typeof item.content === 'string') added.set(item.content, item.id);
225
+ }
226
+ const normalizer = raw?.normalizer && typeof raw.normalizer === 'object' ? raw.normalizer : {};
227
+ const normalizerOptions = {
228
+ lowercase: normalizer.lowercase === true || raw?.tokenizer_config?.do_lower_case === true,
229
+ stripAccents: normalizer.strip_accents === true
230
+ || (normalizer.strip_accents == null && normalizer.lowercase === true),
231
+ handleChineseChars: normalizer.handle_chinese_chars !== false,
232
+ };
233
+ const clsToken = added.has('[CLS]') ? '[CLS]' : '[CLS]';
234
+ const sepToken = added.has('[SEP]') ? '[SEP]' : '[SEP]';
235
+ const clsId = added.get('[CLS]') ?? vocab['[CLS]'];
236
+ const sepId = added.get('[SEP]') ?? vocab['[SEP]'];
237
+ const padId = added.get('[PAD]') ?? vocab['[PAD]'] ?? 0;
238
+ const unkToken = typeof model.unk_token === 'string' ? model.unk_token : '[UNK]';
239
+ const prefix = typeof model.continuing_subword_prefix === 'string' ? model.continuing_subword_prefix : '##';
240
+ const maxChars = Number.isInteger(model.max_input_chars_per_word) ? model.max_input_chars_per_word : 100;
241
+ if (!Number.isInteger(clsId) || !Number.isInteger(sepId)) {
242
+ throw embeddingError('E_EMBEDDING_TOKENIZER', 'tokenizer.json 缺少 [CLS]/[SEP] id');
243
+ }
244
+
245
+ return {
246
+ vocabSize: Object.keys(vocab).length,
247
+ padId,
248
+ clsId,
249
+ sepId,
250
+ encode(value, { maxLen = 512 } = {}) {
251
+ const normalized = bertBasicNormalize(value, normalizerOptions);
252
+ const words = bertPreTokenize(normalized);
253
+ const ids = [clsId];
254
+ for (const word of words) {
255
+ const pieces = wordPiece(word, vocab, { unkToken, prefix, maxChars });
256
+ for (const piece of pieces) {
257
+ const id = vocab[piece];
258
+ if (!Number.isInteger(id)) break;
259
+ ids.push(id);
260
+ if (ids.length >= maxLen - 1) break;
261
+ }
262
+ if (ids.length >= maxLen - 1) break;
263
+ }
264
+ ids.push(sepId);
265
+ // 不补齐到 maxLen:补齐会让每次推理都跑满 256 token(查询只有十几个字,
266
+ // 白烧 10 倍算力)。ONNX 图支持动态序列长度,真实长度反而更快。
267
+ return ids;
268
+ },
269
+ tokensOf(value) {
270
+ const normalized = bertBasicNormalize(value, normalizerOptions);
271
+ return bertPreTokenize(normalized).flatMap((word) => wordPiece(word, vocab, { unkToken, prefix, maxChars }));
272
+ },
273
+ decode(ids) {
274
+ return (Array.isArray(ids) ? ids : []).map((id) => idToToken[id] ?? '').filter(Boolean).join(' ');
275
+ },
276
+ };
277
+ }
278
+
279
+ /* ------------------------------------------------------------------ *
280
+ * 2. ONNX provider
281
+ * ------------------------------------------------------------------ */
282
+
283
+ /** Find `<modelPath>/onnx/model.onnx`, any `*.onnx`, or a direct file path. */
284
+ export function resolveOnnxModel(modelPath) {
285
+ const root = path.resolve(modelPath);
286
+ const candidates = [];
287
+ try {
288
+ if (fs.statSync(root).isFile()) candidates.push(root);
289
+ } catch {
290
+ /* not a file */
291
+ }
292
+ candidates.push(
293
+ path.join(root, 'onnx', 'model.onnx'),
294
+ path.join(root, 'onnx', 'model_quantized.onnx'),
295
+ path.join(root, 'model.onnx'),
296
+ path.join(root, 'model_quantized.onnx'),
297
+ );
298
+ for (const file of candidates) {
299
+ try {
300
+ if (fs.statSync(file).isFile()) return file;
301
+ } catch {
302
+ /* keep looking */
303
+ }
304
+ }
305
+ return null;
306
+ }
307
+
308
+ function tensorFromIds(ort, ids) {
309
+ return new ort.Tensor('int64', BigInt64Array.from(ids.map((n) => BigInt(n))), [1, ids.length]);
310
+ }
311
+
312
+ async function loadOrt() {
313
+ try {
314
+ const mod = await import('onnxruntime-node');
315
+ const ort = mod?.default && typeof mod.default.InferenceSession === 'function' ? mod.default : mod;
316
+ if (!ort?.InferenceSession) throw embeddingError('E_EMBEDDING_DEPS', 'onnxruntime-node 没有导出 InferenceSession');
317
+ return ort;
318
+ } catch (error) {
319
+ if (error?.code === 'E_EMBEDDING_DEPS') throw error;
320
+ throw embeddingError(
321
+ 'E_EMBEDDING_DEPS',
322
+ `onnxruntime-node 未安装或加载失败(可选依赖,未装 profile 时请手动安装):${error?.message ?? error}`,
323
+ );
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Create an ONNX-backed embedder.
329
+ * @returns {Promise<{dim:number, modelFingerprint:string, embed(text:string):Promise<Float32Array>, embedMany(texts:string[]):Promise<Float32Array[]>, dispose():Promise<void>}>}
330
+ */
331
+ export async function createOnnxEmbedder(config) {
332
+ const modelPath = path.resolve(String(config.modelPath));
333
+ const onnxPath = resolveOnnxModel(modelPath);
334
+ if (!onnxPath) {
335
+ throw embeddingError('E_EMBEDDING_MODEL_MISSING', `模型目录里没有 .onnx:${modelPath}`);
336
+ }
337
+ const tokenizerPath = path.join(modelPath, 'tokenizer.json');
338
+ const tokenizer = loadTokenizer(tokenizerPath);
339
+ const ort = await loadOrt();
340
+ let session;
341
+ try {
342
+ session = await ort.InferenceSession.create(onnxPath, {
343
+ executionProviders: ['cpu'],
344
+ graphOptimizationLevel: 'all',
345
+ });
346
+ } catch (error) {
347
+ throw embeddingError('E_EMBEDDING_RUNTIME', `ONNX 模型加载失败(${onnxPath}):${error?.message ?? error}`);
348
+ }
349
+
350
+ const statOf = (file) => {
351
+ try {
352
+ const s = fs.statSync(file);
353
+ return { size: s.size, mtimeMs: Math.round(s.mtimeMs) };
354
+ } catch {
355
+ return null;
356
+ }
357
+ };
358
+ const modelStat = statOf(onnxPath);
359
+ const tokenizerStat = statOf(tokenizerPath);
360
+ const fingerprint = digest(JSON.stringify({
361
+ version: EMBEDDING_VERSION,
362
+ onnx: path.basename(onnxPath),
363
+ modelStat,
364
+ tokenizerStat,
365
+ maxSeqLen: config.maxSeqLen,
366
+ instruction: config.queryInstruction,
367
+ pooling: 'cls',
368
+ }));
369
+
370
+ const embedOne = async (value) => {
371
+ const ids = tokenizer.encode(value, { maxLen: config.maxSeqLen });
372
+ const mask = ids.map((id) => (id === tokenizer.padId ? 0 : 1));
373
+ const feeds = {
374
+ input_ids: tensorFromIds(ort, ids),
375
+ attention_mask: tensorFromIds(ort, mask),
376
+ token_type_ids: tensorFromIds(ort, ids.map(() => 0)),
377
+ };
378
+ let output;
379
+ try {
380
+ output = await session.run(feeds);
381
+ } catch (error) {
382
+ throw embeddingError('E_EMBEDDING_RUNTIME', `ONNX 推理失败:${error?.message ?? error}`);
383
+ }
384
+ const tensor = output?.last_hidden_state ?? output?.[Object.keys(output ?? {})[0]];
385
+ if (!tensor?.data || !Array.isArray(tensor.dims) || tensor.dims.length !== 3) {
386
+ throw embeddingError('E_EMBEDDING_RUNTIME', 'ONNX 输出不是 [1, seq, hidden] 的 last_hidden_state');
387
+ }
388
+ const dim = Number(tensor.dims[2]);
389
+ const vector = new Float32Array(dim);
390
+ let norm = 0;
391
+ for (let i = 0; i < dim; i += 1) {
392
+ const valueAt = Number(tensor.data[i]); // CLS pooling: position 0
393
+ vector[i] = valueAt;
394
+ norm += valueAt * valueAt;
395
+ }
396
+ norm = Math.sqrt(norm);
397
+ if (norm > 0) for (let i = 0; i < dim; i += 1) vector[i] /= norm;
398
+ return vector;
399
+ };
400
+
401
+ return {
402
+ dim: 0,
403
+ modelFingerprint: `onnx:${fingerprint}`,
404
+ tokenizer,
405
+ async embed(value) {
406
+ const vector = await embedOne(value);
407
+ this.dim = vector.length;
408
+ return vector;
409
+ },
410
+ async embedMany(texts) {
411
+ const out = [];
412
+ for (const value of texts) out.push(await this.embed(value));
413
+ return out;
414
+ },
415
+ async dispose() {
416
+ try {
417
+ await session?.release?.();
418
+ } catch {
419
+ /* provider teardown is best effort */
420
+ }
421
+ },
422
+ };
423
+ }
424
+
425
+ /** Provider selection: test embedder first, ONNX second, error otherwise. */
426
+ export async function createEmbedder(config) {
427
+ if (config.embedder) {
428
+ const test = config.embedder;
429
+ return {
430
+ dim: Number(test.dim) || 0,
431
+ modelFingerprint: String(test.modelFingerprint ?? 'test-embedder'),
432
+ embed: async (value) => test.embedQuery(String(value)),
433
+ embedMany: async (texts) => Promise.all(texts.map((value) => test.embedDocument(String(value)))),
434
+ };
435
+ }
436
+ return createOnnxEmbedder(config);
437
+ }
438
+
439
+ /* ------------------------------------------------------------------ *
440
+ * 3. Chunking + vector index (incremental, atomic)
441
+ * ------------------------------------------------------------------ */
442
+
443
+ /** Split a card body into a handful of character-bounded chunks. */
444
+ export function chunkText(value, { maxChars = 400, maxChunks = 6 } = {}) {
445
+ const source = String(value ?? '').replace(/\r\n?/g, '\n').trim();
446
+ if (source === '') return [];
447
+ const paragraphs = source.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
448
+ const chunks = [];
449
+ let current = '';
450
+ for (const paragraph of paragraphs) {
451
+ if (current !== '' && current.length + paragraph.length + 1 > maxChars) {
452
+ chunks.push(current);
453
+ current = '';
454
+ }
455
+ if (paragraph.length > maxChars) {
456
+ if (current !== '') { chunks.push(current); current = ''; }
457
+ for (let at = 0; at < paragraph.length; at += maxChars) {
458
+ chunks.push(paragraph.slice(at, at + maxChars));
459
+ }
460
+ } else {
461
+ current = current === '' ? paragraph : `${current}\n${paragraph}`;
462
+ }
463
+ }
464
+ if (current !== '') chunks.push(current);
465
+ if (chunks.length <= maxChunks) return chunks;
466
+ // Keep the first chunk (title/abstract) and sample the rest evenly: a long
467
+ // card must not push every other card out of the index.
468
+ const kept = [chunks[0]];
469
+ const rest = chunks.length - 1;
470
+ for (let i = 1; i < maxChunks; i += 1) {
471
+ kept.push(chunks[Math.round((i * rest) / (maxChunks - 1))]);
472
+ }
473
+ return [...new Set(kept)];
474
+ }
475
+
476
+ /**
477
+ * Text actually embedded for one card chunk.
478
+ *
479
+ * 实测对比(30 条查询,见 REPORT):只嵌 title+body 时 top1 21/30;把
480
+ * scope_in/aliases 的关键词也写进被嵌文本后 top1 27/30。原因:这张卡的
481
+ * 「检索面」本来就是作者手写的 scope 词表,不该只拿给关键词打分用。
482
+ */
483
+ export function cardChunkTexts(card, config) {
484
+ const title = String(card?.title ?? '').trim();
485
+ const vocab = [
486
+ ...(Array.isArray(card?.scopeIn) ? card.scopeIn : []),
487
+ ...(Array.isArray(card?.aliases) ? card.aliases : []),
488
+ ].map((x) => String(x).trim()).filter(Boolean).join(' ');
489
+ const chunks = chunkText(card?.body ?? card?.summary ?? '', {
490
+ maxChars: config.maxChunkChars,
491
+ maxChunks: config.maxChunksPerCard,
492
+ });
493
+ if (chunks.length === 0) chunks.push('');
494
+ return chunks
495
+ .map((chunk) => `【标题】${title}\n【关键词】${vocab}\n【正文】${chunk}`)
496
+ .filter((t) => t.trim() !== '');
497
+ }
498
+
499
+ /** Content the vector index depends on: change any of it → re-embed that card. */
500
+ export function cardDigest(card) {
501
+ return digest(JSON.stringify({
502
+ title: String(card?.title ?? ''),
503
+ body: String(card?.body ?? card?.summary ?? ''),
504
+ scopeIn: Array.isArray(card?.scopeIn) ? card.scopeIn : [],
505
+ aliases: Array.isArray(card?.aliases) ? card.aliases : [],
506
+ }));
507
+ }
508
+
509
+ export function cosineSimilarity(left, right) {
510
+ if (!left || !right || left.length !== right.length) return 0;
511
+ let dot = 0;
512
+ let a = 0;
513
+ let b = 0;
514
+ for (let i = 0; i < left.length; i += 1) {
515
+ dot += left[i] * right[i];
516
+ a += left[i] * left[i];
517
+ b += right[i] * right[i];
518
+ }
519
+ if (a === 0 || b === 0) return 0;
520
+ return dot / Math.sqrt(a * b);
521
+ }
522
+
523
+ /** Max cosine over a card's chunks (one chunk in the common case). */
524
+ export function maxSimilarity(queryVector, vectors) {
525
+ let best = 0;
526
+ for (const vector of Array.isArray(vectors) ? vectors : []) {
527
+ const score = cosineSimilarity(queryVector, vector);
528
+ if (score > best) best = score;
529
+ }
530
+ return best;
531
+ }
532
+
533
+ function readCache(cachePath) {
534
+ try {
535
+ const raw = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
536
+ if (!raw || raw.version !== EMBEDDING_VERSION || typeof raw.cards !== 'object' || raw.cards === null) return null;
537
+ return raw;
538
+ } catch {
539
+ return null;
540
+ }
541
+ }
542
+
543
+ function writeCacheAtomic(cachePath, payload) {
544
+ const dir = path.dirname(cachePath);
545
+ fs.mkdirSync(dir, { recursive: true });
546
+ const tmp = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
547
+ fs.writeFileSync(tmp, `${JSON.stringify(payload)}\n`, 'utf8');
548
+ fs.renameSync(tmp, cachePath);
549
+ }
550
+
551
+ /**
552
+ * Build (or incrementally refresh) the vector index for `cards`.
553
+ *
554
+ * The cache lives at `<cacheDir>/index.json` and is keyed by model fingerprint
555
+ * + per-card content digest. A failed write never fails recall: the in-memory
556
+ * vectors are returned regardless, the next call simply rebuilds.
557
+ *
558
+ * @returns {Promise<{cardVectors:Map<string,Float32Array[]>, stats:object}>}
559
+ */
560
+ export async function buildVectorIndex({ cards, config, embedder, cachePath }) {
561
+ const started = Date.now();
562
+ const cache = cachePath ? readCache(cachePath) : null;
563
+ const cachedCards = cache && cache.modelFingerprint === embedder.modelFingerprint && cache.cards
564
+ ? cache.cards
565
+ : {};
566
+ const nextCards = {};
567
+ const cardVectors = new Map();
568
+ const stats = { cards: 0, chunks: 0, reusedCards: 0, embeddedCards: 0, embeddedChunks: 0, cacheHit: Boolean(cache), changed: false };
569
+
570
+ for (const card of cards) {
571
+ if (!card || typeof card.path !== 'string') continue;
572
+ const hash = cardDigest(card);
573
+ const cached = cachedCards[card.path];
574
+ stats.cards += 1;
575
+ if (cached && cached.hash === hash && Array.isArray(cached.chunks) && cached.chunks.length > 0) {
576
+ const vectors = cached.chunks.map((chunk) => Float32Array.from(chunk));
577
+ cardVectors.set(card.path, vectors);
578
+ nextCards[card.path] = { hash, chunks: cached.chunks };
579
+ stats.chunks += vectors.length;
580
+ stats.reusedCards += 1;
581
+ continue;
582
+ }
583
+ const texts = cardChunkTexts(card, config);
584
+ const vectors = await embedder.embedMany(texts);
585
+ const normalized = vectors.map((vector) => (vector instanceof Float32Array ? vector : Float32Array.from(vector)));
586
+ cardVectors.set(card.path, normalized);
587
+ nextCards[card.path] = { hash, chunks: normalized.map((vector) => Array.from(vector, (n) => Math.round(n * 1e6) / 1e6)) };
588
+ stats.chunks += normalized.length;
589
+ stats.embeddedCards += 1;
590
+ stats.embeddedChunks += normalized.length;
591
+ stats.changed = true;
592
+ }
593
+
594
+ if (cachePath) {
595
+ const sameShape = cache && Object.keys(nextCards).length === Object.keys(cache.cards ?? {}).length
596
+ && Object.entries(nextCards).every(([key, value]) => cache.cards?.[key]?.hash === value.hash);
597
+ if (stats.changed || !sameShape) {
598
+ try {
599
+ writeCacheAtomic(cachePath, {
600
+ version: EMBEDDING_VERSION,
601
+ generatedAt: new Date().toISOString(),
602
+ modelFingerprint: embedder.modelFingerprint,
603
+ dim: embedder.dim || (cardVectors.values().next().value?.[0]?.length ?? 0),
604
+ cards: nextCards,
605
+ });
606
+ stats.written = true;
607
+ } catch (error) {
608
+ stats.writeError = error?.code ?? error?.message ?? String(error);
609
+ }
610
+ }
611
+ }
612
+ stats.ms = Date.now() - started;
613
+ return { cardVectors, stats };
614
+ }
615
+
616
+ /* ------------------------------------------------------------------ *
617
+ * 4. Runtime facade used by autoRecall / memory_recall
618
+ * ------------------------------------------------------------------ */
619
+
620
+ /**
621
+ * A lazy engine: nothing loads until `ensure()` is called with the current
622
+ * card list. Failures are returned as `{ok:false, code, message}` so callers
623
+ * can fall back instead of throwing into the host's pre-step waterfall.
624
+ */
625
+ export function createEmbeddingRuntime(input, { memoryRoot = null, warn = null } = {}) {
626
+ const config = normalizeEmbeddingConfig(input, { memoryRoot });
627
+ const cachePath = config.cacheDir ? path.join(config.cacheDir, 'index.json') : '';
628
+ let state = null; // {ok, embedder, vectors, stats, signature} | {ok:false, code, message}
629
+ let loading = null;
630
+
631
+ const load = async (cards) => {
632
+ if (!config.enabled) return { ok: false, code: 'E_EMBEDDING_DISABLED', message: 'embedding.enabled=false' };
633
+ if (!config.modelPath && !config.embedder) {
634
+ return { ok: false, code: 'E_EMBEDDING_MODEL_MISSING', message: 'embedding.modelPath 未配置' };
635
+ }
636
+ let embedder;
637
+ try {
638
+ embedder = await createEmbedder(config);
639
+ } catch (error) {
640
+ return { ok: false, code: error?.code ?? 'E_EMBEDDING_RUNTIME', message: String(error?.message ?? error) };
641
+ }
642
+ let index;
643
+ try {
644
+ index = await buildVectorIndex({ cards, config, embedder, cachePath });
645
+ } catch (error) {
646
+ return { ok: false, code: error?.code ?? 'E_EMBEDDING_RUNTIME', message: String(error?.message ?? error) };
647
+ }
648
+ return { ok: true, embedder, ...index };
649
+ };
650
+
651
+ return {
652
+ config,
653
+ get enabled() {
654
+ return config.enabled;
655
+ },
656
+ /** Build/refresh once; a changed card signature rebuilds the in-memory index. */
657
+ async ensure(cards, { refresh = false, signature = undefined } = {}) {
658
+ if (state?.ok && !refresh && (signature === undefined || signature === state.signature)) return state;
659
+ if (loading) return loading;
660
+ loading = load(cards).then((value) => {
661
+ state = { ...value, signature };
662
+ if (!value.ok && typeof warn === 'function') {
663
+ warn(`[embedding] ${value.code}: ${value.message} — 回退关键词召回`);
664
+ }
665
+ return state;
666
+ }).finally(() => {
667
+ loading = null;
668
+ });
669
+ return loading;
670
+ },
671
+ async embedQuery(value) {
672
+ const current = await this.ensure([]);
673
+ if (!current.ok) throw embeddingError(current.code, current.message);
674
+ return current.embedder.embed(`${config.queryInstruction}${String(value ?? '')}`);
675
+ },
676
+ /** One-shot convenience used by the evaluation script. */
677
+ async query(value) {
678
+ const current = await this.ensure([]);
679
+ if (!current.ok) throw embeddingError(current.code, current.message);
680
+ return current.embedder.embed(`${config.queryInstruction}${String(value ?? '')}`);
681
+ },
682
+ dispose() {
683
+ const current = state;
684
+ state = null;
685
+ if (current?.ok) {
686
+ Promise.resolve(current.embedder.dispose?.()).catch(() => {});
687
+ }
688
+ },
689
+ _state: () => state,
690
+ };
691
+ }
692
+
693
+ /** Does this card have a vector entry? Used by tests and diagnostics. */
694
+ export function vectorCount(cardVectors) {
695
+ return cardVectors instanceof Map ? cardVectors.size : 0;
696
+ }
697
+
698
+ export { fsp };