@totalreclaw/mcp-server 1.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 (86) hide show
  1. package/README.md +113 -0
  2. package/dist/cli/setup.d.ts +43 -0
  3. package/dist/cli/setup.d.ts.map +1 -0
  4. package/dist/cli/setup.js +276 -0
  5. package/dist/cli/setup.js.map +1 -0
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +700 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/prompts.d.ts +27 -0
  11. package/dist/prompts.d.ts.map +1 -0
  12. package/dist/prompts.js +219 -0
  13. package/dist/prompts.js.map +1 -0
  14. package/dist/resources/index.d.ts +2 -0
  15. package/dist/resources/index.d.ts.map +1 -0
  16. package/dist/resources/index.js +8 -0
  17. package/dist/resources/index.js.map +1 -0
  18. package/dist/resources/memory-context.d.ts +16 -0
  19. package/dist/resources/memory-context.d.ts.map +1 -0
  20. package/dist/resources/memory-context.js +111 -0
  21. package/dist/resources/memory-context.js.map +1 -0
  22. package/dist/server.d.ts +4 -0
  23. package/dist/server.d.ts.map +1 -0
  24. package/dist/server.js +25 -0
  25. package/dist/server.js.map +1 -0
  26. package/dist/subgraph/crypto.d.ts +106 -0
  27. package/dist/subgraph/crypto.d.ts.map +1 -0
  28. package/dist/subgraph/crypto.js +287 -0
  29. package/dist/subgraph/crypto.js.map +1 -0
  30. package/dist/subgraph/embedding.d.ts +47 -0
  31. package/dist/subgraph/embedding.d.ts.map +1 -0
  32. package/dist/subgraph/embedding.js +77 -0
  33. package/dist/subgraph/embedding.js.map +1 -0
  34. package/dist/subgraph/index.d.ts +7 -0
  35. package/dist/subgraph/index.d.ts.map +1 -0
  36. package/dist/subgraph/index.js +23 -0
  37. package/dist/subgraph/index.js.map +1 -0
  38. package/dist/subgraph/lsh.d.ts +95 -0
  39. package/dist/subgraph/lsh.d.ts.map +1 -0
  40. package/dist/subgraph/lsh.js +211 -0
  41. package/dist/subgraph/lsh.js.map +1 -0
  42. package/dist/subgraph/reranker.d.ts +157 -0
  43. package/dist/subgraph/reranker.d.ts.map +1 -0
  44. package/dist/subgraph/reranker.js +427 -0
  45. package/dist/subgraph/reranker.js.map +1 -0
  46. package/dist/subgraph/search.d.ts +62 -0
  47. package/dist/subgraph/search.d.ts.map +1 -0
  48. package/dist/subgraph/search.js +208 -0
  49. package/dist/subgraph/search.js.map +1 -0
  50. package/dist/subgraph/store.d.ts +97 -0
  51. package/dist/subgraph/store.d.ts.map +1 -0
  52. package/dist/subgraph/store.js +270 -0
  53. package/dist/subgraph/store.js.map +1 -0
  54. package/dist/tools/export.d.ts +48 -0
  55. package/dist/tools/export.d.ts.map +1 -0
  56. package/dist/tools/export.js +126 -0
  57. package/dist/tools/export.js.map +1 -0
  58. package/dist/tools/forget.d.ts +43 -0
  59. package/dist/tools/forget.d.ts.map +1 -0
  60. package/dist/tools/forget.js +96 -0
  61. package/dist/tools/forget.js.map +1 -0
  62. package/dist/tools/import.d.ts +73 -0
  63. package/dist/tools/import.d.ts.map +1 -0
  64. package/dist/tools/import.js +248 -0
  65. package/dist/tools/import.js.map +1 -0
  66. package/dist/tools/index.d.ts +8 -0
  67. package/dist/tools/index.d.ts.map +1 -0
  68. package/dist/tools/index.js +25 -0
  69. package/dist/tools/index.js.map +1 -0
  70. package/dist/tools/recall.d.ts +65 -0
  71. package/dist/tools/recall.d.ts.map +1 -0
  72. package/dist/tools/recall.js +113 -0
  73. package/dist/tools/recall.js.map +1 -0
  74. package/dist/tools/remember.d.ts +109 -0
  75. package/dist/tools/remember.d.ts.map +1 -0
  76. package/dist/tools/remember.js +227 -0
  77. package/dist/tools/remember.js.map +1 -0
  78. package/dist/tools/status.d.ts +43 -0
  79. package/dist/tools/status.d.ts.map +1 -0
  80. package/dist/tools/status.js +110 -0
  81. package/dist/tools/status.js.map +1 -0
  82. package/dist/tools/upgrade.d.ts +48 -0
  83. package/dist/tools/upgrade.d.ts.map +1 -0
  84. package/dist/tools/upgrade.js +122 -0
  85. package/dist/tools/upgrade.js.map +1 -0
  86. package/package.json +61 -0
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP - Crypto Operations
4
+ *
5
+ * All cryptographic primitives used by the MCP server. These must
6
+ * produce byte-for-byte identical output to the TotalReclaw client library
7
+ * (`client/src/crypto/`) so that memories written by one can be read by
8
+ * the other.
9
+ *
10
+ * Key derivation chain:
11
+ * master_password + salt
12
+ * -> Argon2id(t=3, m=65536, p=4, dkLen=32) -> masterKey
13
+ * -> HKDF-SHA256(masterKey, salt, "totalreclaw-auth-key-v1", 32) -> authKey
14
+ * -> HKDF-SHA256(masterKey, salt, "totalreclaw-encryption-key-v1", 32) -> encryptionKey
15
+ * -> HKDF-SHA256(masterKey, salt, "openmemory-dedup-v1", 32) -> dedupKey
16
+ *
17
+ * Encryption: AES-256-GCM (12-byte IV, 16-byte tag)
18
+ * Blind indices: SHA-256 of lowercase tokens
19
+ * Content fingerprint: HMAC-SHA256(dedupKey, normalizeText(plaintext))
20
+ */
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.deriveKeysFromMnemonic = deriveKeysFromMnemonic;
26
+ exports.deriveKeys = deriveKeys;
27
+ exports.deriveLshSeed = deriveLshSeed;
28
+ exports.computeAuthKeyHash = computeAuthKeyHash;
29
+ exports.encrypt = encrypt;
30
+ exports.decrypt = decrypt;
31
+ exports.generateBlindIndices = generateBlindIndices;
32
+ exports.generateContentFingerprint = generateContentFingerprint;
33
+ const argon2_js_1 = require("@noble/hashes/argon2.js");
34
+ const hkdf_js_1 = require("@noble/hashes/hkdf.js");
35
+ const sha2_js_1 = require("@noble/hashes/sha2.js");
36
+ const hmac_js_1 = require("@noble/hashes/hmac.js");
37
+ const bip39_1 = require("@scure/bip39");
38
+ const english_js_1 = require("@scure/bip39/wordlists/english.js");
39
+ const porter_stemmer_1 = require("porter-stemmer");
40
+ const node_crypto_1 = __importDefault(require("node:crypto"));
41
+ // ---------------------------------------------------------------------------
42
+ // Key Derivation
43
+ // ---------------------------------------------------------------------------
44
+ /** HKDF context strings -- must match client/src/crypto/kdf.ts exactly. */
45
+ const AUTH_KEY_INFO = 'totalreclaw-auth-key-v1';
46
+ const ENCRYPTION_KEY_INFO = 'totalreclaw-encryption-key-v1';
47
+ const DEDUP_KEY_INFO = 'openmemory-dedup-v1';
48
+ /** Argon2id parameters -- OWASP recommendations, matching client defaults. */
49
+ const ARGON2_TIME_COST = 3;
50
+ const ARGON2_MEMORY_COST = 65536; // 64 MB in KiB
51
+ const ARGON2_PARALLELISM = 4;
52
+ const ARGON2_DK_LEN = 32;
53
+ /** AES-256-GCM constants. */
54
+ const IV_LENGTH = 12;
55
+ const TAG_LENGTH = 16;
56
+ const KEY_LENGTH = 32;
57
+ /**
58
+ * Check if the input looks like a BIP-39 mnemonic (12 or 24 words from the BIP-39 English wordlist).
59
+ */
60
+ function isBip39Mnemonic(input) {
61
+ const words = input.trim().split(/\s+/);
62
+ if (words.length !== 12 && words.length !== 24)
63
+ return false;
64
+ return (0, bip39_1.validateMnemonic)(input.trim(), english_js_1.wordlist);
65
+ }
66
+ /**
67
+ * Derive encryption keys from a BIP-39 mnemonic.
68
+ * Uses the 512-bit BIP-39 seed as HKDF input (NOT the derived private key)
69
+ * for proper key separation from the Ethereum signing key.
70
+ */
71
+ function deriveKeysFromMnemonic(mnemonic) {
72
+ // BIP-39: mnemonic -> 512-bit seed via PBKDF2(mnemonic, "mnemonic", 2048 rounds)
73
+ const seed = (0, bip39_1.mnemonicToSeedSync)(mnemonic.trim());
74
+ // Use first 32 bytes of seed as deterministic salt for HKDF
75
+ // (BIP-39 mnemonics are self-salting via PBKDF2, no random salt needed)
76
+ const salt = Buffer.from(seed.slice(0, 32));
77
+ // HKDF-SHA256 from the full 512-bit seed, using distinct info strings
78
+ const enc = (s) => Buffer.from(s, 'utf8');
79
+ const seedBuf = Buffer.from(seed);
80
+ const authKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, seedBuf, salt, enc(AUTH_KEY_INFO), 32));
81
+ const encryptionKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, seedBuf, salt, enc(ENCRYPTION_KEY_INFO), 32));
82
+ const dedupKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, seedBuf, salt, enc(DEDUP_KEY_INFO), 32));
83
+ return { authKey, encryptionKey, dedupKey, salt };
84
+ }
85
+ /**
86
+ * Derive auth, encryption, and dedup keys from a master password.
87
+ *
88
+ * If the password is a valid BIP-39 mnemonic (12 or 24 words), keys are
89
+ * derived from the 512-bit BIP-39 seed via HKDF. Otherwise, the legacy
90
+ * Argon2id path is used.
91
+ *
92
+ * For the Argon2id path: if no salt is provided a fresh 32-byte random salt
93
+ * is generated. Pass an existing salt when restoring a previously-registered
94
+ * account so that the derived keys match the original registration.
95
+ *
96
+ * @returns Object containing authKey, encryptionKey, dedupKey, and salt (all Buffers).
97
+ */
98
+ function deriveKeys(password, existingSalt) {
99
+ // Auto-detect BIP-39 mnemonic vs arbitrary password
100
+ if (isBip39Mnemonic(password)) {
101
+ // BIP-39 path: mnemonic is self-salting, existingSalt is ignored for derivation
102
+ // but we still return the deterministic salt for server registration
103
+ return deriveKeysFromMnemonic(password);
104
+ }
105
+ // Legacy path: arbitrary password via Argon2id
106
+ const salt = existingSalt ?? node_crypto_1.default.randomBytes(32);
107
+ // Step 1 -- Argon2id to derive a 32-byte master key.
108
+ // @noble/hashes argon2id accepts Uint8Array for both password and salt.
109
+ const masterKey = (0, argon2_js_1.argon2id)(Buffer.from(password, 'utf8'), salt, { t: ARGON2_TIME_COST, m: ARGON2_MEMORY_COST, p: ARGON2_PARALLELISM, dkLen: ARGON2_DK_LEN });
110
+ // Step 2 -- HKDF-SHA256 for each sub-key using distinct info strings.
111
+ // @noble/hashes v2 requires Uint8Array for info param.
112
+ const enc = (s) => Buffer.from(s, 'utf8');
113
+ const authKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, masterKey, salt, enc(AUTH_KEY_INFO), 32));
114
+ const encryptionKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, masterKey, salt, enc(ENCRYPTION_KEY_INFO), 32));
115
+ const dedupKey = Buffer.from((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, masterKey, salt, enc(DEDUP_KEY_INFO), 32));
116
+ return { authKey, encryptionKey, dedupKey, salt: Buffer.from(salt) };
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // LSH Seed Derivation
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * HKDF context string for LSH seed derivation.
123
+ *
124
+ * The LSH hasher needs a deterministic seed so that the same master key
125
+ * always generates the same random hyperplane matrices. We derive this seed
126
+ * from the master key using HKDF with a unique info string.
127
+ *
128
+ * For the BIP-39 path the HKDF input is the 512-bit BIP-39 seed; for the
129
+ * Argon2id path it is the 32-byte master key.
130
+ */
131
+ const LSH_SEED_INFO = 'openmemory-lsh-seed-v1';
132
+ /**
133
+ * Derive a 32-byte seed for the LSH hasher from the master key derivation
134
+ * chain.
135
+ *
136
+ * Call this once during initialization and pass the result to `new LSHHasher(seed, dims)`.
137
+ *
138
+ * For the BIP-39 path we use the full 512-bit BIP-39 seed as IKM; for the
139
+ * Argon2id path we use the 32-byte Argon2id-derived master key. In both
140
+ * cases the salt from `deriveKeys()` is reused for domain separation.
141
+ */
142
+ function deriveLshSeed(password, salt) {
143
+ if (isBip39Mnemonic(password)) {
144
+ const seed = (0, bip39_1.mnemonicToSeedSync)(password.trim());
145
+ return new Uint8Array((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, Buffer.from(seed), salt, Buffer.from(LSH_SEED_INFO, 'utf8'), 32));
146
+ }
147
+ // Argon2id path: re-derive the master key, then HKDF with LSH info string.
148
+ const masterKey = (0, argon2_js_1.argon2id)(Buffer.from(password, 'utf8'), salt, { t: ARGON2_TIME_COST, m: ARGON2_MEMORY_COST, p: ARGON2_PARALLELISM, dkLen: ARGON2_DK_LEN });
149
+ return new Uint8Array((0, hkdf_js_1.hkdf)(sha2_js_1.sha256, masterKey, salt, Buffer.from(LSH_SEED_INFO, 'utf8'), 32));
150
+ }
151
+ // ---------------------------------------------------------------------------
152
+ // Auth Key Hash
153
+ // ---------------------------------------------------------------------------
154
+ /**
155
+ * Compute the SHA-256 hash of the auth key.
156
+ *
157
+ * The server stores SHA256(authKey) during registration and uses it to look
158
+ * up users on every request. The hex string returned here is what the plugin
159
+ * sends to `/v1/register` as `auth_key_hash`.
160
+ */
161
+ function computeAuthKeyHash(authKey) {
162
+ return Buffer.from((0, sha2_js_1.sha256)(authKey)).toString('hex');
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // AES-256-GCM Encrypt / Decrypt
166
+ // ---------------------------------------------------------------------------
167
+ /**
168
+ * Encrypt a UTF-8 plaintext string with AES-256-GCM.
169
+ *
170
+ * Wire format (base64-encoded):
171
+ * [iv: 12 bytes][tag: 16 bytes][ciphertext: variable]
172
+ *
173
+ * This matches `serializeEncryptedData` in `client/src/crypto/aes.ts`.
174
+ */
175
+ function encrypt(plaintext, encryptionKey) {
176
+ if (encryptionKey.length !== KEY_LENGTH) {
177
+ throw new Error(`Invalid key length: expected ${KEY_LENGTH}, got ${encryptionKey.length}`);
178
+ }
179
+ const iv = node_crypto_1.default.randomBytes(IV_LENGTH);
180
+ const cipher = node_crypto_1.default.createCipheriv('aes-256-gcm', encryptionKey, iv, {
181
+ authTagLength: TAG_LENGTH,
182
+ });
183
+ const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
184
+ const tag = cipher.getAuthTag();
185
+ // Combine: iv || tag || ciphertext (same order as client library)
186
+ const combined = Buffer.concat([iv, tag, ciphertext]);
187
+ return combined.toString('base64');
188
+ }
189
+ /**
190
+ * Decrypt a base64-encoded AES-256-GCM blob back to a UTF-8 string.
191
+ *
192
+ * Expects the wire format produced by `encrypt()` above.
193
+ */
194
+ function decrypt(encryptedBase64, encryptionKey) {
195
+ if (encryptionKey.length !== KEY_LENGTH) {
196
+ throw new Error(`Invalid key length: expected ${KEY_LENGTH}, got ${encryptionKey.length}`);
197
+ }
198
+ const combined = Buffer.from(encryptedBase64, 'base64');
199
+ if (combined.length < IV_LENGTH + TAG_LENGTH) {
200
+ throw new Error('Encrypted data too short');
201
+ }
202
+ const iv = combined.subarray(0, IV_LENGTH);
203
+ const tag = combined.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
204
+ const ciphertext = combined.subarray(IV_LENGTH + TAG_LENGTH);
205
+ const decipher = node_crypto_1.default.createDecipheriv('aes-256-gcm', encryptionKey, iv, {
206
+ authTagLength: TAG_LENGTH,
207
+ });
208
+ decipher.setAuthTag(tag);
209
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
210
+ return plaintext.toString('utf8');
211
+ }
212
+ // ---------------------------------------------------------------------------
213
+ // Blind Indices
214
+ // ---------------------------------------------------------------------------
215
+ /**
216
+ * Generate blind indices (SHA-256 hashes of tokens) for a text string.
217
+ *
218
+ * Tokenization rules (must match `client/src/crypto/blind.ts#tokenize`):
219
+ * 1. Lowercase
220
+ * 2. Remove punctuation (keep Unicode letters, numbers, whitespace)
221
+ * 3. Split on whitespace
222
+ * 4. Filter tokens shorter than 2 characters
223
+ *
224
+ * Each surviving token is SHA-256 hashed and returned as a hex string.
225
+ * The returned array is deduplicated.
226
+ */
227
+ function generateBlindIndices(text) {
228
+ const tokens = text
229
+ .toLowerCase()
230
+ .replace(/[^\p{L}\p{N}\s]/gu, ' ') // Remove punctuation, keep letters/numbers
231
+ .split(/\s+/)
232
+ .filter((t) => t.length >= 2);
233
+ const seen = new Set();
234
+ const indices = [];
235
+ for (const token of tokens) {
236
+ // Exact word hash (unchanged behavior).
237
+ const hash = Buffer.from((0, sha2_js_1.sha256)(Buffer.from(token, 'utf8'))).toString('hex');
238
+ if (!seen.has(hash)) {
239
+ seen.add(hash);
240
+ indices.push(hash);
241
+ }
242
+ // Stemmed word hash. The stem is prefixed with "stem:" before hashing
243
+ // to avoid collisions between a word that happens to equal another
244
+ // word's stem (e.g., the word "commun" vs the stem of "community").
245
+ const stem = (0, porter_stemmer_1.stemmer)(token);
246
+ if (stem.length >= 2 && stem !== token) {
247
+ const stemHash = Buffer.from((0, sha2_js_1.sha256)(Buffer.from(`stem:${stem}`, 'utf8'))).toString('hex');
248
+ if (!seen.has(stemHash)) {
249
+ seen.add(stemHash);
250
+ indices.push(stemHash);
251
+ }
252
+ }
253
+ }
254
+ return indices;
255
+ }
256
+ // ---------------------------------------------------------------------------
257
+ // Content Fingerprint (Dedup)
258
+ // ---------------------------------------------------------------------------
259
+ /**
260
+ * Normalize text for deterministic fingerprinting.
261
+ *
262
+ * Steps (matching `client/src/crypto/fingerprint.ts#normalizeText`):
263
+ * 1. Unicode NFC normalization
264
+ * 2. Lowercase
265
+ * 3. Collapse whitespace (spaces/tabs/newlines to single space)
266
+ * 4. Trim leading/trailing whitespace
267
+ */
268
+ function normalizeText(text) {
269
+ return text
270
+ .normalize('NFC')
271
+ .toLowerCase()
272
+ .replace(/\s+/g, ' ')
273
+ .trim();
274
+ }
275
+ /**
276
+ * Compute an HMAC-SHA256 content fingerprint for exact-duplicate detection.
277
+ *
278
+ * The server stores this fingerprint and uses it to reject duplicate writes
279
+ * without ever seeing the plaintext.
280
+ *
281
+ * @returns 64-character hex string.
282
+ */
283
+ function generateContentFingerprint(plaintext, dedupKey) {
284
+ const normalized = normalizeText(plaintext);
285
+ return Buffer.from((0, hmac_js_1.hmac)(sha2_js_1.sha256, dedupKey, Buffer.from(normalized, 'utf8'))).toString('hex');
286
+ }
287
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/subgraph/crypto.ts"],"names":[],"mappings":";AAAA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
+ * text embeddings locally. No API key needed, no data leaves the machine.
6
+ *
7
+ * This preserves the zero-knowledge guarantee: embeddings are generated
8
+ * CLIENT-SIDE before encryption, so no plaintext ever reaches an external API.
9
+ *
10
+ * Model details:
11
+ * - Quantized (int8) ONNX model: ~33.8MB download on first use
12
+ * - Cached in ~/.cache/huggingface/ after first download
13
+ * - Lazy initialization: first call ~2-3s (model load), subsequent ~15ms
14
+ * - Output: 384-dimensional normalized embedding vector
15
+ * - For retrieval, queries should be prefixed with an instruction string
16
+ * (documents/passages should NOT be prefixed)
17
+ *
18
+ * Dependencies: @huggingface/transformers (handles model download, WordPiece
19
+ * tokenization, ONNX inference, mean pooling, and normalization).
20
+ */
21
+ /**
22
+ * Generate a 384-dimensional embedding vector for the given text.
23
+ *
24
+ * On first call, downloads and loads the ONNX model (~33.8MB, cached).
25
+ * Subsequent calls reuse the loaded model and run in ~15ms.
26
+ *
27
+ * For bge-small-en-v1.5, queries should set `isQuery: true` to prepend the
28
+ * retrieval instruction prefix for improved retrieval accuracy (default: false).
29
+ *
30
+ * @param text - The text to embed.
31
+ * @param options - Optional settings.
32
+ * @param options.isQuery - If true, prepend the BGE query instruction prefix
33
+ * for improved retrieval accuracy (default: false).
34
+ * @returns 384-dimensional normalized embedding as a number array.
35
+ */
36
+ export declare function generateEmbedding(text: string, options?: {
37
+ isQuery?: boolean;
38
+ }): Promise<number[]>;
39
+ /**
40
+ * Get the embedding vector dimensionality.
41
+ *
42
+ * Always returns 384 (fixed for bge-small-en-v1.5).
43
+ * This is needed by downstream code (e.g. LSH hasher) to know the vector
44
+ * size without calling the embedding model.
45
+ */
46
+ export declare function getEmbeddingDims(): number;
47
+ //# sourceMappingURL=embedding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedding.d.ts","sourceRoot":"","sources":["../../src/subgraph/embedding.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAsBH;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAC9B,OAAO,CAAC,MAAM,EAAE,CAAC,CAYnB;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC"}
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP - Local Embedding via @huggingface/transformers
4
+ *
5
+ * Uses the Xenova/bge-small-en-v1.5 ONNX model to generate 384-dimensional
6
+ * text embeddings locally. No API key needed, no data leaves the machine.
7
+ *
8
+ * This preserves the zero-knowledge guarantee: embeddings are generated
9
+ * CLIENT-SIDE before encryption, so no plaintext ever reaches an external API.
10
+ *
11
+ * Model details:
12
+ * - Quantized (int8) ONNX model: ~33.8MB download on first use
13
+ * - Cached in ~/.cache/huggingface/ after first download
14
+ * - Lazy initialization: first call ~2-3s (model load), subsequent ~15ms
15
+ * - Output: 384-dimensional normalized embedding vector
16
+ * - For retrieval, queries should be prefixed with an instruction string
17
+ * (documents/passages should NOT be prefixed)
18
+ *
19
+ * Dependencies: @huggingface/transformers (handles model download, WordPiece
20
+ * tokenization, ONNX inference, mean pooling, and normalization).
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.generateEmbedding = generateEmbedding;
24
+ exports.getEmbeddingDims = getEmbeddingDims;
25
+ // @ts-ignore - @huggingface/transformers types may not be perfect
26
+ const transformers_1 = require("@huggingface/transformers");
27
+ /** ONNX-optimized bge-small-en-v1.5 from HuggingFace Hub. */
28
+ const MODEL_ID = 'Xenova/bge-small-en-v1.5';
29
+ /** Fixed output dimensionality for bge-small-en-v1.5. */
30
+ const EMBEDDING_DIM = 384;
31
+ /**
32
+ * Query instruction prefix for bge-small-en-v1.5 retrieval tasks.
33
+ *
34
+ * Per the BAAI model card: prepend this to short queries when searching
35
+ * for relevant passages. Do NOT prepend for documents/passages being stored.
36
+ */
37
+ const QUERY_PREFIX = 'Represent this sentence for searching relevant passages: ';
38
+ /** Lazily initialized feature extraction pipeline. */
39
+ let extractor = null;
40
+ /**
41
+ * Generate a 384-dimensional embedding vector for the given text.
42
+ *
43
+ * On first call, downloads and loads the ONNX model (~33.8MB, cached).
44
+ * Subsequent calls reuse the loaded model and run in ~15ms.
45
+ *
46
+ * For bge-small-en-v1.5, queries should set `isQuery: true` to prepend the
47
+ * retrieval instruction prefix for improved retrieval accuracy (default: false).
48
+ *
49
+ * @param text - The text to embed.
50
+ * @param options - Optional settings.
51
+ * @param options.isQuery - If true, prepend the BGE query instruction prefix
52
+ * for improved retrieval accuracy (default: false).
53
+ * @returns 384-dimensional normalized embedding as a number array.
54
+ */
55
+ async function generateEmbedding(text, options) {
56
+ if (!extractor) {
57
+ extractor = await (0, transformers_1.pipeline)('feature-extraction', MODEL_ID, {
58
+ // @ts-ignore - quantized option exists at runtime but not in type defs
59
+ quantized: true,
60
+ });
61
+ }
62
+ const input = options?.isQuery ? QUERY_PREFIX + text : text;
63
+ const output = await extractor(input, { pooling: 'mean', normalize: true });
64
+ // output.data is a Float32Array; convert to plain number[]
65
+ return Array.from(output.data);
66
+ }
67
+ /**
68
+ * Get the embedding vector dimensionality.
69
+ *
70
+ * Always returns 384 (fixed for bge-small-en-v1.5).
71
+ * This is needed by downstream code (e.g. LSH hasher) to know the vector
72
+ * size without calling the embedding model.
73
+ */
74
+ function getEmbeddingDims() {
75
+ return EMBEDDING_DIM;
76
+ }
77
+ //# sourceMappingURL=embedding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedding.js","sourceRoot":"","sources":["../../src/subgraph/embedding.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;AAqCH,8CAeC;AASD,4CAEC;AA7DD,kEAAkE;AAClE,4DAAqF;AAErF,6DAA6D;AAC7D,MAAM,QAAQ,GAAG,0BAA0B,CAAC;AAE5C,yDAAyD;AACzD,MAAM,aAAa,GAAG,GAAG,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,YAAY,GAAG,2DAA2D,CAAC;AAEjF,sDAAsD;AACtD,IAAI,SAAS,GAAqC,IAAI,CAAC;AAEvD;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,iBAAiB,CACrC,IAAY,EACZ,OAA+B;IAE/B,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,MAAM,IAAA,uBAAQ,EAAC,oBAAoB,EAAE,QAAQ,EAAE;YACzD,uEAAuE;YACvE,SAAS,EAAE,IAAI;SACT,CAAC,CAAC;IACZ,CAAC;IAED,MAAM,KAAK,GAAG,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5E,2DAA2D;IAC3D,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAoB,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB;IAC9B,OAAO,aAAa,CAAC;AACvB,CAAC"}
@@ -0,0 +1,7 @@
1
+ export * from './crypto.js';
2
+ export * from './lsh.js';
3
+ export * from './embedding.js';
4
+ export * from './reranker.js';
5
+ export * from './store.js';
6
+ export * from './search.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/subgraph/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./crypto.js"), exports);
18
+ __exportStar(require("./lsh.js"), exports);
19
+ __exportStar(require("./embedding.js"), exports);
20
+ __exportStar(require("./reranker.js"), exports);
21
+ __exportStar(require("./store.js"), exports);
22
+ __exportStar(require("./search.js"), exports);
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/subgraph/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,2CAAyB;AACzB,iDAA+B;AAC/B,gDAA8B;AAC9B,6CAA2B;AAC3B,8CAA4B"}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * TotalReclaw MCP - LSH Hasher (Locality-Sensitive Hashing)
3
+ *
4
+ * Pure TypeScript implementation of Random Hyperplane LSH for zero-knowledge
5
+ * semantic search. Generates deterministic hyperplane matrices from a seed
6
+ * derived from the user's master key, so the same embedding always hashes to
7
+ * the same buckets across sessions.
8
+ *
9
+ * Architecture overview:
10
+ * 1. Seed (32 bytes from HKDF) -> HKDF per table -> random bytes
11
+ * 2. Random bytes -> Box-Muller transform -> Gaussian-distributed hyperplanes
12
+ * 3. Embedding dot hyperplane -> sign bit -> N-bit signature per table
13
+ * 4. Signature -> `lsh_t{table}_{signature}` -> SHA-256 -> blind hash
14
+ *
15
+ * The blind hashes are merged with the existing blind word indices in the
16
+ * `blind_indices` array. The server never knows which hashes are word-based
17
+ * and which are LSH-based.
18
+ *
19
+ * Default parameters:
20
+ * - 32 bits per table (balanced discrimination vs. recall)
21
+ * - 20 tables (moderate table count for good coverage)
22
+ * - Middle ground between 64-bit x 12 (too strict) and 12-bit x 28 (too loose)
23
+ *
24
+ * Dependencies: @noble/hashes only (already in project).
25
+ */
26
+ /**
27
+ * Random Hyperplane LSH hasher.
28
+ *
29
+ * All state is deterministic from the seed -- no randomness at hash time.
30
+ * Construct once per session; call `hash()` for every store/search operation.
31
+ */
32
+ export declare class LSHHasher {
33
+ /**
34
+ * Flat hyperplane storage.
35
+ *
36
+ * `hyperplanes[t]` is a Float64Array of length `dims * nBits` containing the
37
+ * hyperplane matrix for table `t`. The hyperplane for bit `b` starts at
38
+ * offset `b * dims`.
39
+ */
40
+ private hyperplanes;
41
+ /** Embedding dimensionality. */
42
+ private readonly dims;
43
+ /** Number of independent hash tables. */
44
+ private readonly nTables;
45
+ /** Number of bits (hyperplanes) per table. */
46
+ private readonly nBits;
47
+ /**
48
+ * Create a new LSH hasher.
49
+ *
50
+ * @param seed - 32-byte seed from `deriveLshSeed()` in crypto.ts.
51
+ * @param dims - Embedding dimensionality (e.g. 1536 for text-embedding-3-small).
52
+ * @param nTables - Number of independent hash tables (default 20).
53
+ * @param nBits - Number of bits per table (default 32).
54
+ */
55
+ constructor(seed: Uint8Array, dims: number, nTables?: number, nBits?: number);
56
+ /**
57
+ * Generate the hyperplane matrix for a single table.
58
+ *
59
+ * Each table gets a unique HKDF-derived byte stream. We consume 8 bytes
60
+ * per Gaussian sample (Box-Muller uses two uniform uint32 values).
61
+ *
62
+ * The hyperplanes are NOT normalised to unit length. Normalisation is
63
+ * unnecessary because we only care about the sign of the dot product,
64
+ * which is scale-invariant.
65
+ */
66
+ private generateTableHyperplanes;
67
+ /**
68
+ * Derive `length` pseudo-random bytes from the seed using HKDF with
69
+ * chunked sub-blocks.
70
+ *
71
+ * A single HKDF-SHA256 call can output at most 255 * 32 = 8,160 bytes.
72
+ * For large embedding dimensions we need more, so we iterate over
73
+ * sub-block indices as part of the info string.
74
+ */
75
+ private deriveRandomBytes;
76
+ /**
77
+ * Hash an embedding vector to an array of blind-hashed bucket IDs.
78
+ *
79
+ * For each table:
80
+ * 1. Compute the 64-bit signature (sign of dot product with each hyperplane).
81
+ * 2. Build the bucket string: `lsh_t{tableIndex}_{binarySignature}`.
82
+ * 3. SHA-256 the bucket string to produce a blind hash (hex).
83
+ *
84
+ * @param embedding - The embedding vector (must have `dims` elements).
85
+ * @returns Array of `nTables` hex strings (one blind hash per table).
86
+ */
87
+ hash(embedding: number[]): string[];
88
+ /** Number of hash tables. */
89
+ get tables(): number;
90
+ /** Number of bits per table. */
91
+ get bits(): number;
92
+ /** Embedding dimensionality. */
93
+ get dimensions(): number;
94
+ }
95
+ //# sourceMappingURL=lsh.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lsh.d.ts","sourceRoot":"","sources":["../../src/subgraph/lsh.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAsBH;;;;;GAKG;AACH,qBAAa,SAAS;IACpB;;;;;;OAMG;IACH,OAAO,CAAC,WAAW,CAAiB;IAEpC,gCAAgC;IAChC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAE9B,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC,8CAA8C;IAC9C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B;;;;;;;OAOG;gBAED,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,MAAyB,EAClC,KAAK,GAAE,MAAuB;IA8BhC;;;;;;;;;OASG;IACH,OAAO,CAAC,wBAAwB;IAmChC;;;;;;;OAOG;IACH,OAAO,CAAC,iBAAiB;IA2BzB;;;;;;;;;;OAUG;IACH,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE;IAsCnC,6BAA6B;IAC7B,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,gCAAgC;IAChC,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,gCAAgC;IAChC,IAAI,UAAU,IAAI,MAAM,CAEvB;CACF"}