@cmdoss/memwal-sdk 0.6.1 → 0.7.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.
- package/dist/ai-sdk/PDWVectorStore.d.ts.map +1 -1
- package/dist/ai-sdk/PDWVectorStore.js +4 -1
- package/dist/ai-sdk/PDWVectorStore.js.map +1 -1
- package/dist/ai-sdk/tools.d.ts +2 -2
- package/dist/ai-sdk/tools.js +2 -2
- package/dist/browser.d.ts +5 -6
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +7 -6
- package/dist/browser.js.map +1 -1
- package/dist/client/ClientMemoryManager.d.ts +1 -0
- package/dist/client/ClientMemoryManager.d.ts.map +1 -1
- package/dist/client/ClientMemoryManager.js +5 -1
- package/dist/client/ClientMemoryManager.js.map +1 -1
- package/dist/client/SimplePDWClient.d.ts +24 -1
- package/dist/client/SimplePDWClient.d.ts.map +1 -1
- package/dist/client/SimplePDWClient.js +31 -9
- package/dist/client/SimplePDWClient.js.map +1 -1
- package/dist/client/namespaces/EmbeddingsNamespace.d.ts +1 -1
- package/dist/client/namespaces/EmbeddingsNamespace.js +1 -1
- package/dist/client/namespaces/IndexNamespace.d.ts +38 -9
- package/dist/client/namespaces/IndexNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/IndexNamespace.js +77 -10
- package/dist/client/namespaces/IndexNamespace.js.map +1 -1
- package/dist/client/namespaces/MemoryNamespace.d.ts +27 -0
- package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/MemoryNamespace.js +104 -0
- package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
- package/dist/client/namespaces/SearchNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/SearchNamespace.js +25 -14
- package/dist/client/namespaces/SearchNamespace.js.map +1 -1
- package/dist/client/namespaces/consolidated/AINamespace.d.ts +2 -2
- package/dist/client/namespaces/consolidated/AINamespace.js +2 -2
- package/dist/client/namespaces/consolidated/BlockchainNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/consolidated/BlockchainNamespace.js +69 -1
- package/dist/client/namespaces/consolidated/BlockchainNamespace.js.map +1 -1
- package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +46 -0
- package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/consolidated/StorageNamespace.js +34 -0
- package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
- package/dist/graph/GraphService.js +2 -2
- package/dist/graph/GraphService.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/permissions/ConsentRepository.browser.d.ts +56 -0
- package/dist/permissions/ConsentRepository.browser.d.ts.map +1 -0
- package/dist/permissions/ConsentRepository.browser.js +198 -0
- package/dist/permissions/ConsentRepository.browser.js.map +1 -0
- package/dist/retrieval/MemoryRetrievalService.d.ts +31 -0
- package/dist/retrieval/MemoryRetrievalService.d.ts.map +1 -1
- package/dist/retrieval/MemoryRetrievalService.js +44 -4
- package/dist/retrieval/MemoryRetrievalService.js.map +1 -1
- package/dist/services/EmbeddingService.d.ts +28 -1
- package/dist/services/EmbeddingService.d.ts.map +1 -1
- package/dist/services/EmbeddingService.js +54 -0
- package/dist/services/EmbeddingService.js.map +1 -1
- package/dist/services/GeminiAIService.d.ts.map +1 -1
- package/dist/services/GeminiAIService.js +283 -27
- package/dist/services/GeminiAIService.js.map +1 -1
- package/dist/services/IndexManager.d.ts +5 -1
- package/dist/services/IndexManager.d.ts.map +1 -1
- package/dist/services/IndexManager.js +17 -40
- package/dist/services/IndexManager.js.map +1 -1
- package/dist/services/MemoryIndexService.d.ts +31 -2
- package/dist/services/MemoryIndexService.d.ts.map +1 -1
- package/dist/services/MemoryIndexService.js +75 -3
- package/dist/services/MemoryIndexService.js.map +1 -1
- package/dist/services/QueryService.js +1 -1
- package/dist/services/QueryService.js.map +1 -1
- package/dist/services/StorageService.d.ts +10 -0
- package/dist/services/StorageService.d.ts.map +1 -1
- package/dist/services/StorageService.js +13 -0
- package/dist/services/StorageService.js.map +1 -1
- package/dist/services/storage/QuiltBatchManager.d.ts +111 -4
- package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
- package/dist/services/storage/QuiltBatchManager.js +450 -38
- package/dist/services/storage/QuiltBatchManager.js.map +1 -1
- package/dist/services/storage/index.d.ts +1 -1
- package/dist/services/storage/index.d.ts.map +1 -1
- package/dist/services/storage/index.js.map +1 -1
- package/dist/utils/LRUCache.d.ts +106 -0
- package/dist/utils/LRUCache.d.ts.map +1 -0
- package/dist/utils/LRUCache.js +281 -0
- package/dist/utils/LRUCache.js.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/memoryIndexOnChain.d.ts +212 -0
- package/dist/utils/memoryIndexOnChain.d.ts.map +1 -0
- package/dist/utils/memoryIndexOnChain.js +312 -0
- package/dist/utils/memoryIndexOnChain.js.map +1 -0
- package/dist/utils/rebuildIndexNode.d.ts +29 -0
- package/dist/utils/rebuildIndexNode.d.ts.map +1 -1
- package/dist/utils/rebuildIndexNode.js +387 -45
- package/dist/utils/rebuildIndexNode.js.map +1 -1
- package/dist/vector/HnswWasmService.d.ts +20 -5
- package/dist/vector/HnswWasmService.d.ts.map +1 -1
- package/dist/vector/HnswWasmService.js +73 -40
- package/dist/vector/HnswWasmService.js.map +1 -1
- package/dist/vector/IHnswService.d.ts +10 -1
- package/dist/vector/IHnswService.d.ts.map +1 -1
- package/dist/vector/IHnswService.js.map +1 -1
- package/dist/vector/NodeHnswService.d.ts +16 -0
- package/dist/vector/NodeHnswService.d.ts.map +1 -1
- package/dist/vector/NodeHnswService.js +108 -10
- package/dist/vector/NodeHnswService.js.map +1 -1
- package/dist/vector/createHnswService.d.ts +1 -1
- package/dist/vector/createHnswService.js +1 -1
- package/dist/vector/index.d.ts +1 -1
- package/dist/vector/index.js +1 -1
- package/package.json +157 -157
- package/src/ai-sdk/PDWVectorStore.ts +4 -1
- package/src/ai-sdk/tools.ts +2 -2
- package/src/browser.ts +15 -10
- package/src/client/ClientMemoryManager.ts +6 -1
- package/src/client/SimplePDWClient.ts +63 -10
- package/src/client/namespaces/EmbeddingsNamespace.ts +1 -1
- package/src/client/namespaces/IndexNamespace.ts +89 -11
- package/src/client/namespaces/MemoryNamespace.ts +137 -0
- package/src/client/namespaces/SearchNamespace.ts +27 -14
- package/src/client/namespaces/consolidated/AINamespace.ts +2 -2
- package/src/client/namespaces/consolidated/BlockchainNamespace.ts +73 -1
- package/src/client/namespaces/consolidated/StorageNamespace.ts +57 -0
- package/src/core/types/index.ts +1 -1
- package/src/generated/pdw/capability.ts +319 -319
- package/src/graph/GraphService.ts +2 -2
- package/src/index.ts +25 -1
- package/src/permissions/ConsentRepository.browser.ts +249 -0
- package/src/retrieval/MemoryRetrievalService.ts +78 -4
- package/src/services/EmbeddingService.ts +66 -1
- package/src/services/GeminiAIService.ts +283 -27
- package/src/services/IndexManager.ts +18 -45
- package/src/services/MemoryIndexService.ts +85 -3
- package/src/services/QueryService.ts +1 -1
- package/src/services/StorageService.ts +15 -0
- package/src/services/storage/QuiltBatchManager.ts +538 -42
- package/src/services/storage/index.ts +6 -1
- package/src/utils/LRUCache.ts +378 -0
- package/src/utils/index.ts +8 -0
- package/src/utils/memoryIndexOnChain.ts +507 -0
- package/src/utils/rebuildIndexNode.ts +482 -52
- package/src/vector/HnswWasmService.ts +95 -43
- package/src/vector/IHnswService.ts +10 -1
- package/src/vector/NodeHnswService.ts +130 -10
- package/src/vector/createHnswService.ts +1 -1
- package/src/vector/index.ts +1 -1
|
@@ -87,30 +87,64 @@ export class QuiltBatchManager {
|
|
|
87
87
|
let totalSize = 0;
|
|
88
88
|
console.log(`📦 Uploading batch of ${memories.length} memories as Quilt (writeFilesFlow)...`);
|
|
89
89
|
try {
|
|
90
|
-
// Create WalrusFile for each memory
|
|
90
|
+
// Create WalrusFile for each memory as JSON package
|
|
91
|
+
// This format is consistent with regular memory storage
|
|
91
92
|
const files = memories.map((memory, index) => {
|
|
92
93
|
const identifier = memory.id
|
|
93
94
|
? `memory-${memory.id}.json`
|
|
94
95
|
: `memory-${Date.now()}-${index}-${Math.random().toString(36).slice(2, 9)}.json`;
|
|
95
|
-
|
|
96
|
+
const isEncrypted = !!memory.encryptedContent && memory.encryptedContent.length > 0;
|
|
97
|
+
const timestamp = Date.now();
|
|
98
|
+
// Create memory package (JSON format - consistent with regular storage)
|
|
99
|
+
const memoryPackage = {
|
|
100
|
+
// Content: plaintext if not encrypted, empty if encrypted
|
|
101
|
+
content: isEncrypted ? '' : memory.content,
|
|
102
|
+
embedding: memory.embedding,
|
|
103
|
+
metadata: {
|
|
104
|
+
category: memory.category,
|
|
105
|
+
importance: memory.importance,
|
|
106
|
+
topic: memory.topic,
|
|
107
|
+
...(memory.summary ? { summary: memory.summary } : {}),
|
|
108
|
+
...(memory.id ? { memoryId: memory.id } : {})
|
|
109
|
+
},
|
|
110
|
+
timestamp,
|
|
111
|
+
version: '2.0.0', // Quilt JSON package version
|
|
112
|
+
encrypted: isEncrypted,
|
|
113
|
+
// Store encrypted content as base64 for JSON compatibility
|
|
114
|
+
...(isEncrypted && memory.encryptedContent ? {
|
|
115
|
+
encryptedContent: this.uint8ArrayToBase64(memory.encryptedContent)
|
|
116
|
+
} : {})
|
|
117
|
+
};
|
|
118
|
+
// Serialize to JSON and encode as bytes
|
|
119
|
+
const jsonString = JSON.stringify(memoryPackage);
|
|
120
|
+
const contents = new TextEncoder().encode(jsonString);
|
|
121
|
+
totalSize += contents.length;
|
|
122
|
+
// Diagnostic logging for debugging Quilt corruption issues
|
|
123
|
+
console.log(` 📝 File ${index}: identifier=${identifier}`);
|
|
124
|
+
console.log(` JSON string length: ${jsonString.length} chars`);
|
|
125
|
+
console.log(` Encoded bytes: ${contents.length} bytes`);
|
|
126
|
+
console.log(` Last 50 chars of JSON: ...${jsonString.slice(-50)}`);
|
|
127
|
+
console.log(` Last 10 bytes (hex): ${Array.from(contents.slice(-10)).map(b => b.toString(16).padStart(2, '0')).join(' ')}`);
|
|
96
128
|
return WalrusFile.from({
|
|
97
|
-
contents
|
|
129
|
+
contents,
|
|
98
130
|
identifier,
|
|
99
131
|
tags: {
|
|
100
|
-
// Core metadata (plaintext for filtering)
|
|
132
|
+
// Core metadata (plaintext for filtering without decryption)
|
|
133
|
+
'content-type': 'application/json',
|
|
101
134
|
'category': memory.category,
|
|
102
135
|
'importance': memory.importance.toString(),
|
|
103
136
|
'topic': memory.topic,
|
|
104
|
-
'timestamp': new Date().toISOString(),
|
|
105
|
-
'created_at': new Date().toISOString(),
|
|
137
|
+
'timestamp': new Date(timestamp).toISOString(),
|
|
138
|
+
'created_at': new Date(timestamp).toISOString(),
|
|
106
139
|
// Encryption info
|
|
107
|
-
'encrypted': 'true',
|
|
108
|
-
'encryption_type': 'seal',
|
|
140
|
+
'encrypted': isEncrypted ? 'true' : 'false',
|
|
141
|
+
...(isEncrypted ? { 'encryption_type': 'seal' } : {}),
|
|
109
142
|
// Owner
|
|
110
143
|
'owner': options.userAddress,
|
|
111
144
|
// Content info
|
|
112
|
-
'content_size':
|
|
145
|
+
'content_size': contents.length.toString(),
|
|
113
146
|
'embedding_dimensions': memory.embedding.length.toString(),
|
|
147
|
+
'package_version': '2.0.0',
|
|
114
148
|
// Optional rich metadata
|
|
115
149
|
...(memory.summary ? { 'summary': memory.summary } : {}),
|
|
116
150
|
...(memory.id ? { 'memory_id': memory.id } : {})
|
|
@@ -163,22 +197,25 @@ export class QuiltBatchManager {
|
|
|
163
197
|
console.log(` Upload time: ${uploadTimeMs.toFixed(1)}ms`);
|
|
164
198
|
console.log(` Gas saved: ${gasSaved} vs individual uploads`);
|
|
165
199
|
// Build file results using original WalrusFile objects for metadata
|
|
166
|
-
//
|
|
200
|
+
// Use shared quiltId as blobId - SDK can only read via getBlob(quiltId).files()
|
|
201
|
+
// Match files by identifier when reading
|
|
202
|
+
const quiltId = uploadedFilesInfo[0]?.blobId || '';
|
|
167
203
|
const fileResults = await Promise.all(files.map(async (originalFile, i) => {
|
|
168
204
|
const identifier = await originalFile.getIdentifier() || `file-${i}`;
|
|
169
205
|
const tags = await originalFile.getTags() || {};
|
|
170
|
-
|
|
171
|
-
|
|
206
|
+
const fileInfo = uploadedFilesInfo[i];
|
|
207
|
+
// quiltPatchId is stored for reference but not used for retrieval
|
|
208
|
+
const quiltPatchId = fileInfo?.id || '';
|
|
209
|
+
console.log(` File ${i}: identifier=${identifier}, quiltId=${quiltId.substring(0, 20)}...`);
|
|
172
210
|
return {
|
|
173
211
|
identifier,
|
|
174
|
-
blobId
|
|
175
|
-
|
|
212
|
+
// Use shared quiltId as blobId - read via getBlob(quiltId).files()
|
|
213
|
+
blobId: quiltId,
|
|
214
|
+
quiltPatchId,
|
|
176
215
|
tags: Object.fromEntries(Object.entries(tags).map(([k, v]) => [k, String(v)])),
|
|
177
|
-
size: memories[i]?.encryptedContent
|
|
216
|
+
size: memories[i]?.encryptedContent?.length || memories[i]?.content?.length || 0
|
|
178
217
|
};
|
|
179
218
|
}));
|
|
180
|
-
// Get quiltId from first uploaded file
|
|
181
|
-
const quiltId = uploadedFilesInfo[0]?.blobId || '';
|
|
182
219
|
return {
|
|
183
220
|
quiltId,
|
|
184
221
|
blobObjectId: undefined, // Not available from flow
|
|
@@ -263,22 +300,25 @@ export class QuiltBatchManager {
|
|
|
263
300
|
console.log(` Files uploaded: ${uploadedFilesInfo.length}`);
|
|
264
301
|
console.log(` Upload time: ${uploadTimeMs.toFixed(1)}ms`);
|
|
265
302
|
// Build file results using original WalrusFile objects for metadata
|
|
266
|
-
//
|
|
303
|
+
// Use shared quiltId as blobId - SDK can only read via getBlob(quiltId).files()
|
|
304
|
+
// Match files by identifier when reading
|
|
305
|
+
const quiltId = uploadedFilesInfo[0]?.blobId || '';
|
|
267
306
|
const fileResults = await Promise.all(walrusFiles.map(async (originalFile, i) => {
|
|
268
307
|
const identifier = await originalFile.getIdentifier() || files[i]?.identifier || `file-${i}`;
|
|
269
308
|
const tags = await originalFile.getTags() || {};
|
|
270
|
-
|
|
271
|
-
|
|
309
|
+
const fileInfo = uploadedFilesInfo[i];
|
|
310
|
+
// quiltPatchId is stored for reference but not used for retrieval
|
|
311
|
+
const quiltPatchId = fileInfo?.id || '';
|
|
312
|
+
console.log(` File ${i}: identifier=${identifier}, quiltId=${quiltId.substring(0, 20)}...`);
|
|
272
313
|
return {
|
|
273
314
|
identifier,
|
|
274
|
-
blobId
|
|
275
|
-
|
|
315
|
+
// Use shared quiltId as blobId - read via getBlob(quiltId).files()
|
|
316
|
+
blobId: quiltId,
|
|
317
|
+
quiltPatchId,
|
|
276
318
|
tags: Object.fromEntries(Object.entries(tags).map(([k, v]) => [k, String(v)])),
|
|
277
319
|
size: files[i]?.data.length || 0
|
|
278
320
|
};
|
|
279
321
|
}));
|
|
280
|
-
// Get quiltId from first uploaded file
|
|
281
|
-
const quiltId = uploadedFilesInfo[0]?.blobId || '';
|
|
282
322
|
return {
|
|
283
323
|
quiltId,
|
|
284
324
|
blobObjectId: undefined, // Not available from flow
|
|
@@ -299,14 +339,29 @@ export class QuiltBatchManager {
|
|
|
299
339
|
/**
|
|
300
340
|
* Retrieve all files from a Quilt
|
|
301
341
|
*
|
|
302
|
-
*
|
|
342
|
+
* Uses getBlob().files() pattern which correctly parses Quilt structure
|
|
343
|
+
* and returns individual files with their identifiers and tags.
|
|
344
|
+
*
|
|
345
|
+
* @param quiltId - The Quilt blob ID (shared blobId)
|
|
303
346
|
* @returns Array of WalrusFile objects
|
|
304
347
|
*/
|
|
305
348
|
async getQuiltFiles(quiltId) {
|
|
306
349
|
try {
|
|
307
350
|
console.log(`📂 Retrieving files from Quilt ${quiltId}...`);
|
|
308
|
-
|
|
309
|
-
|
|
351
|
+
// Try to parse as Quilt first (getBlob().files() returns ALL files in Quilt)
|
|
352
|
+
// Fall back to getFiles() for regular blobs
|
|
353
|
+
let files;
|
|
354
|
+
try {
|
|
355
|
+
const blob = await this.suiClient.walrus.getBlob({ blobId: quiltId });
|
|
356
|
+
files = await blob.files();
|
|
357
|
+
console.log(`✅ Retrieved ${files.length} files from Quilt`);
|
|
358
|
+
}
|
|
359
|
+
catch (quiltError) {
|
|
360
|
+
// Not a Quilt - try as regular blob
|
|
361
|
+
console.log(`📄 Not a Quilt format, fetching as regular blob...`);
|
|
362
|
+
files = await this.suiClient.walrus.getFiles({ ids: [quiltId] });
|
|
363
|
+
console.log(`✅ Retrieved ${files.length} file(s) as regular blob`);
|
|
364
|
+
}
|
|
310
365
|
return files;
|
|
311
366
|
}
|
|
312
367
|
catch (error) {
|
|
@@ -317,7 +372,9 @@ export class QuiltBatchManager {
|
|
|
317
372
|
/**
|
|
318
373
|
* Retrieve a specific file by identifier from a Quilt
|
|
319
374
|
*
|
|
320
|
-
*
|
|
375
|
+
* Uses getBlob().files() to get all files then matches by identifier.
|
|
376
|
+
*
|
|
377
|
+
* @param quiltId - The Quilt blob ID (shared blobId)
|
|
321
378
|
* @param identifier - The file identifier within the quilt
|
|
322
379
|
* @returns QuiltRetrieveResult with content and metadata
|
|
323
380
|
*/
|
|
@@ -325,18 +382,22 @@ export class QuiltBatchManager {
|
|
|
325
382
|
const startTime = performance.now();
|
|
326
383
|
try {
|
|
327
384
|
console.log(`📄 Retrieving file "${identifier}" from Quilt ${quiltId}...`);
|
|
328
|
-
// Get all files from
|
|
329
|
-
const files = await this.
|
|
385
|
+
// Get all files from the blob (Quilt or regular)
|
|
386
|
+
const files = await this.getQuiltFiles(quiltId);
|
|
330
387
|
// Find file by identifier
|
|
331
|
-
|
|
388
|
+
let matchingFile;
|
|
389
|
+
for (const f of files) {
|
|
332
390
|
const fileIdentifier = await f.getIdentifier();
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
391
|
+
if (fileIdentifier === identifier) {
|
|
392
|
+
matchingFile = f;
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (!matchingFile) {
|
|
336
397
|
throw new Error(`File "${identifier}" not found in Quilt`);
|
|
337
398
|
}
|
|
338
|
-
const content = await
|
|
339
|
-
const tags = await
|
|
399
|
+
const content = await matchingFile.bytes();
|
|
400
|
+
const tags = await matchingFile.getTags();
|
|
340
401
|
const retrievalTimeMs = performance.now() - startTime;
|
|
341
402
|
console.log(`✅ Retrieved file "${identifier}" (${content.length} bytes)`);
|
|
342
403
|
return {
|
|
@@ -354,13 +415,16 @@ export class QuiltBatchManager {
|
|
|
354
415
|
/**
|
|
355
416
|
* List all patches in a Quilt with their metadata
|
|
356
417
|
*
|
|
357
|
-
*
|
|
418
|
+
* Uses getBlob().files() to correctly parse Quilt structure.
|
|
419
|
+
*
|
|
420
|
+
* @param quiltId - The Quilt blob ID (shared blobId)
|
|
358
421
|
* @returns Array of QuiltListResult with identifiers and tags
|
|
359
422
|
*/
|
|
360
423
|
async listQuiltPatches(quiltId) {
|
|
361
424
|
try {
|
|
362
425
|
console.log(`📋 Listing patches in Quilt ${quiltId}...`);
|
|
363
|
-
|
|
426
|
+
// Get all files from the blob (Quilt or regular)
|
|
427
|
+
const files = await this.getQuiltFiles(quiltId);
|
|
364
428
|
const results = await Promise.all(files.map(async (file) => {
|
|
365
429
|
const identifier = await file.getIdentifier() || 'unknown';
|
|
366
430
|
const tags = await file.getTags();
|
|
@@ -445,8 +509,347 @@ export class QuiltBatchManager {
|
|
|
445
509
|
return matchingFiles;
|
|
446
510
|
}
|
|
447
511
|
// ==========================================================================
|
|
512
|
+
// JSON Memory Package Retrieval
|
|
513
|
+
// ==========================================================================
|
|
514
|
+
/**
|
|
515
|
+
* Retrieve a memory package as JSON from a Quilt
|
|
516
|
+
*
|
|
517
|
+
* Uses file.json() for efficient parsing (SDK handles it)
|
|
518
|
+
*
|
|
519
|
+
* @param quiltId - The Quilt blob ID
|
|
520
|
+
* @param identifier - The file identifier within the quilt
|
|
521
|
+
* @returns QuiltMemoryRetrieveResult with parsed memory package
|
|
522
|
+
*/
|
|
523
|
+
async getMemoryPackage(quiltId, identifier) {
|
|
524
|
+
const startTime = performance.now();
|
|
525
|
+
try {
|
|
526
|
+
console.log(`📄 Retrieving memory package "${identifier}" from Quilt ${quiltId}...`);
|
|
527
|
+
// Get all files from the blob
|
|
528
|
+
const files = await this.getQuiltFiles(quiltId);
|
|
529
|
+
// Find file by identifier
|
|
530
|
+
let matchingFile;
|
|
531
|
+
for (const f of files) {
|
|
532
|
+
const fileIdentifier = await f.getIdentifier();
|
|
533
|
+
if (fileIdentifier === identifier) {
|
|
534
|
+
matchingFile = f;
|
|
535
|
+
break;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (!matchingFile) {
|
|
539
|
+
throw new Error(`File "${identifier}" not found in Quilt`);
|
|
540
|
+
}
|
|
541
|
+
const tags = await matchingFile.getTags();
|
|
542
|
+
let memoryPackage;
|
|
543
|
+
try {
|
|
544
|
+
// Parse directly as JSON (SDK handles it!)
|
|
545
|
+
memoryPackage = await matchingFile.json();
|
|
546
|
+
}
|
|
547
|
+
catch (parseError) {
|
|
548
|
+
// Try partial recovery for truncated JSON
|
|
549
|
+
console.warn(`⚠️ JSON parse failed for "${identifier}", attempting recovery...`);
|
|
550
|
+
const bytes = await matchingFile.bytes();
|
|
551
|
+
const recovered = this.tryRecoverTruncatedPackage(bytes);
|
|
552
|
+
if (recovered) {
|
|
553
|
+
console.log(`🔧 Partially recovered "${identifier}" (encryptedContent may be corrupted)`);
|
|
554
|
+
memoryPackage = recovered;
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
throw parseError;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
const retrievalTimeMs = performance.now() - startTime;
|
|
561
|
+
console.log(`✅ Retrieved memory package "${identifier}" (${retrievalTimeMs.toFixed(1)}ms)`);
|
|
562
|
+
return {
|
|
563
|
+
identifier,
|
|
564
|
+
memoryPackage,
|
|
565
|
+
tags,
|
|
566
|
+
retrievalTimeMs
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
catch (error) {
|
|
570
|
+
console.error(`❌ Failed to retrieve memory package:`, error);
|
|
571
|
+
throw new Error(`Failed to retrieve memory package "${identifier}": ${error}`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Retrieve all memory packages from a Quilt as JSON
|
|
576
|
+
*
|
|
577
|
+
* @param quiltId - The Quilt blob ID
|
|
578
|
+
* @returns Array of memory packages with metadata
|
|
579
|
+
*/
|
|
580
|
+
async getAllMemoryPackages(quiltId) {
|
|
581
|
+
const startTime = performance.now();
|
|
582
|
+
try {
|
|
583
|
+
console.log(`📂 Retrieving all memory packages from Quilt ${quiltId}...`);
|
|
584
|
+
const files = await this.getQuiltFiles(quiltId);
|
|
585
|
+
const results = [];
|
|
586
|
+
for (const file of files) {
|
|
587
|
+
const identifier = await file.getIdentifier() || 'unknown';
|
|
588
|
+
const tags = await file.getTags();
|
|
589
|
+
try {
|
|
590
|
+
// Parse as JSON
|
|
591
|
+
const memoryPackage = await file.json();
|
|
592
|
+
results.push({
|
|
593
|
+
identifier,
|
|
594
|
+
memoryPackage,
|
|
595
|
+
tags,
|
|
596
|
+
retrievalTimeMs: 0 // Individual timing not tracked in batch
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
catch (parseError) {
|
|
600
|
+
console.warn(`⚠️ Failed to parse "${identifier}" as JSON:`, parseError);
|
|
601
|
+
// Try partial recovery for truncated JSON
|
|
602
|
+
try {
|
|
603
|
+
const bytes = await file.bytes();
|
|
604
|
+
const recoveredPackage = this.tryRecoverTruncatedPackage(bytes);
|
|
605
|
+
if (recoveredPackage) {
|
|
606
|
+
console.log(`🔧 Partially recovered "${identifier}" (encryptedContent truncated)`);
|
|
607
|
+
results.push({
|
|
608
|
+
identifier,
|
|
609
|
+
memoryPackage: recoveredPackage,
|
|
610
|
+
tags,
|
|
611
|
+
retrievalTimeMs: 0
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
catch {
|
|
616
|
+
// Skip files that can't be recovered
|
|
617
|
+
console.warn(`❌ Could not recover "${identifier}"`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const totalTimeMs = performance.now() - startTime;
|
|
622
|
+
console.log(`✅ Retrieved ${results.length} memory packages (${totalTimeMs.toFixed(1)}ms)`);
|
|
623
|
+
return results;
|
|
624
|
+
}
|
|
625
|
+
catch (error) {
|
|
626
|
+
console.error(`❌ Failed to retrieve memory packages:`, error);
|
|
627
|
+
throw new Error(`Failed to retrieve memory packages from Quilt ${quiltId}: ${error}`);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Find a specific memory in a Quilt using multiple matching strategies
|
|
632
|
+
*
|
|
633
|
+
* Strategies (in order of priority):
|
|
634
|
+
* 1. Match by tags['memory_id'] === memoryId
|
|
635
|
+
* 2. Match by identifier === `memory-${memoryId}.json`
|
|
636
|
+
* 3. Match by JSON metadata.memoryId === memoryId
|
|
637
|
+
* 4. Fallback to index-based matching (if fileIndex provided)
|
|
638
|
+
*
|
|
639
|
+
* @param quiltId - The Quilt blob ID
|
|
640
|
+
* @param memoryId - The memory ID (usually vectorId) to find
|
|
641
|
+
* @param fileIndex - Optional fallback index if other strategies fail
|
|
642
|
+
* @returns The matching memory package result, or null if not found
|
|
643
|
+
*/
|
|
644
|
+
async findMemoryInQuilt(quiltId, memoryId, fileIndex) {
|
|
645
|
+
const startTime = performance.now();
|
|
646
|
+
try {
|
|
647
|
+
console.log(`🔍 Finding memory "${memoryId}" in Quilt ${quiltId.substring(0, 20)}...`);
|
|
648
|
+
const files = await this.getQuiltFiles(quiltId);
|
|
649
|
+
let matchedFile;
|
|
650
|
+
let matchStrategy = '';
|
|
651
|
+
// Strategy 1: Match by tags['memory_id']
|
|
652
|
+
for (const f of files) {
|
|
653
|
+
const tags = await f.getTags();
|
|
654
|
+
if (tags?.['memory_id'] === memoryId) {
|
|
655
|
+
matchedFile = f;
|
|
656
|
+
matchStrategy = 'memory_id tag';
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
// Strategy 2: Match by identifier pattern "memory-{memoryId}.json"
|
|
661
|
+
if (!matchedFile) {
|
|
662
|
+
for (const f of files) {
|
|
663
|
+
const identifier = await f.getIdentifier();
|
|
664
|
+
if (identifier === `memory-${memoryId}.json`) {
|
|
665
|
+
matchedFile = f;
|
|
666
|
+
matchStrategy = 'identifier pattern';
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
// Strategy 3: Parse JSON to find matching metadata.memoryId
|
|
672
|
+
if (!matchedFile) {
|
|
673
|
+
for (const f of files) {
|
|
674
|
+
try {
|
|
675
|
+
const json = await f.json();
|
|
676
|
+
if (json?.metadata?.memoryId === memoryId) {
|
|
677
|
+
matchedFile = f;
|
|
678
|
+
matchStrategy = 'JSON metadata.memoryId';
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
catch {
|
|
683
|
+
// Not valid JSON, continue
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
// Strategy 4: Fallback to index-based matching
|
|
688
|
+
if (!matchedFile && fileIndex !== undefined && fileIndex < files.length) {
|
|
689
|
+
matchedFile = files[fileIndex];
|
|
690
|
+
matchStrategy = `index fallback (${fileIndex})`;
|
|
691
|
+
}
|
|
692
|
+
if (!matchedFile) {
|
|
693
|
+
console.log(`❌ Memory "${memoryId}" not found in Quilt (${files.length} files)`);
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
696
|
+
const identifier = await matchedFile.getIdentifier() || 'unknown';
|
|
697
|
+
const tags = await matchedFile.getTags();
|
|
698
|
+
let memoryPackage;
|
|
699
|
+
try {
|
|
700
|
+
memoryPackage = await matchedFile.json();
|
|
701
|
+
}
|
|
702
|
+
catch (parseError) {
|
|
703
|
+
// Try recovery for truncated JSON
|
|
704
|
+
const bytes = await matchedFile.bytes();
|
|
705
|
+
const recovered = this.tryRecoverTruncatedPackage(bytes);
|
|
706
|
+
if (recovered) {
|
|
707
|
+
memoryPackage = recovered;
|
|
708
|
+
}
|
|
709
|
+
else {
|
|
710
|
+
throw parseError;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
const retrievalTimeMs = performance.now() - startTime;
|
|
714
|
+
console.log(`✅ Found memory "${memoryId}" via ${matchStrategy} (${identifier}) in ${retrievalTimeMs.toFixed(1)}ms`);
|
|
715
|
+
return {
|
|
716
|
+
identifier,
|
|
717
|
+
memoryPackage,
|
|
718
|
+
tags,
|
|
719
|
+
retrievalTimeMs
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
console.error(`❌ Failed to find memory in Quilt:`, error);
|
|
724
|
+
throw new Error(`Failed to find memory "${memoryId}" in Quilt ${quiltId}: ${error}`);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Get memory content from a Quilt file
|
|
729
|
+
*
|
|
730
|
+
* Handles both encrypted and unencrypted content:
|
|
731
|
+
* - Unencrypted: Returns content directly from package
|
|
732
|
+
* - Encrypted: Returns decrypted content if sessionKey provided, otherwise throws
|
|
733
|
+
*
|
|
734
|
+
* @param quiltId - The Quilt blob ID
|
|
735
|
+
* @param identifier - The file identifier
|
|
736
|
+
* @param sessionKey - Optional session key for encrypted content
|
|
737
|
+
* @returns Memory content as string
|
|
738
|
+
*/
|
|
739
|
+
async getMemoryContent(quiltId, identifier, decryptFn) {
|
|
740
|
+
const result = await this.getMemoryPackage(quiltId, identifier);
|
|
741
|
+
const pkg = result.memoryPackage;
|
|
742
|
+
if (!pkg.encrypted) {
|
|
743
|
+
// Not encrypted - return content directly
|
|
744
|
+
return pkg.content;
|
|
745
|
+
}
|
|
746
|
+
if (!pkg.encryptedContent) {
|
|
747
|
+
throw new Error('Memory is marked as encrypted but no encrypted content found');
|
|
748
|
+
}
|
|
749
|
+
if (!decryptFn) {
|
|
750
|
+
throw new Error('Memory is encrypted. Provide decryptFn to decrypt content.');
|
|
751
|
+
}
|
|
752
|
+
// Decrypt using provided function
|
|
753
|
+
return await decryptFn(pkg.encryptedContent);
|
|
754
|
+
}
|
|
755
|
+
// ==========================================================================
|
|
448
756
|
// Utility Methods
|
|
449
757
|
// ==========================================================================
|
|
758
|
+
/**
|
|
759
|
+
* Try to recover a partially truncated memory package
|
|
760
|
+
*
|
|
761
|
+
* Handles cases where JSON was truncated (e.g., in the middle of encryptedContent)
|
|
762
|
+
* by extracting metadata and marking the encrypted content as corrupted.
|
|
763
|
+
*
|
|
764
|
+
* @param bytes - Raw bytes of the file
|
|
765
|
+
* @returns Recovered QuiltMemoryPackage or null if recovery fails
|
|
766
|
+
*/
|
|
767
|
+
tryRecoverTruncatedPackage(bytes) {
|
|
768
|
+
try {
|
|
769
|
+
const rawString = new TextDecoder().decode(bytes);
|
|
770
|
+
// Find and trim trailing null bytes
|
|
771
|
+
let lastValidIndex = rawString.length - 1;
|
|
772
|
+
while (lastValidIndex >= 0 && rawString.charCodeAt(lastValidIndex) === 0) {
|
|
773
|
+
lastValidIndex--;
|
|
774
|
+
}
|
|
775
|
+
const trimmedString = rawString.slice(0, lastValidIndex + 1);
|
|
776
|
+
// First try to parse as-is (maybe nulls were the only issue)
|
|
777
|
+
try {
|
|
778
|
+
return JSON.parse(trimmedString);
|
|
779
|
+
}
|
|
780
|
+
catch {
|
|
781
|
+
// Continue to partial recovery
|
|
782
|
+
}
|
|
783
|
+
// Look for encryptedContent field - data likely truncated there
|
|
784
|
+
const encryptedIdx = trimmedString.indexOf('"encryptedContent":"');
|
|
785
|
+
if (encryptedIdx > 0) {
|
|
786
|
+
// Extract everything before encryptedContent
|
|
787
|
+
const beforeEncrypted = trimmedString.slice(0, encryptedIdx);
|
|
788
|
+
// Remove trailing comma and close the object
|
|
789
|
+
const cleanedJson = beforeEncrypted.replace(/,\s*$/, '') + '}';
|
|
790
|
+
try {
|
|
791
|
+
const partialPackage = JSON.parse(cleanedJson);
|
|
792
|
+
return {
|
|
793
|
+
...partialPackage,
|
|
794
|
+
encrypted: true,
|
|
795
|
+
encryptedContent: '[CORRUPTED - data truncated during storage]'
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
// Partial extraction failed
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
// Try to find the last complete JSON object by looking for closing brace
|
|
803
|
+
// This handles cases where truncation happened elsewhere
|
|
804
|
+
for (let i = trimmedString.length - 1; i >= 0; i--) {
|
|
805
|
+
if (trimmedString[i] === '}') {
|
|
806
|
+
try {
|
|
807
|
+
const candidate = trimmedString.slice(0, i + 1);
|
|
808
|
+
return JSON.parse(candidate);
|
|
809
|
+
}
|
|
810
|
+
catch {
|
|
811
|
+
// This position doesn't form valid JSON, try earlier
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
return null;
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
return null;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Convert Uint8Array to base64 string
|
|
824
|
+
*/
|
|
825
|
+
uint8ArrayToBase64(bytes) {
|
|
826
|
+
// Use Buffer in Node.js, btoa in browser
|
|
827
|
+
if (typeof Buffer !== 'undefined') {
|
|
828
|
+
return Buffer.from(bytes).toString('base64');
|
|
829
|
+
}
|
|
830
|
+
// Browser fallback
|
|
831
|
+
let binary = '';
|
|
832
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
833
|
+
binary += String.fromCharCode(bytes[i]);
|
|
834
|
+
}
|
|
835
|
+
return btoa(binary);
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Convert base64 string to Uint8Array
|
|
839
|
+
*/
|
|
840
|
+
base64ToUint8Array(base64) {
|
|
841
|
+
// Use Buffer in Node.js, atob in browser
|
|
842
|
+
if (typeof Buffer !== 'undefined') {
|
|
843
|
+
return new Uint8Array(Buffer.from(base64, 'base64'));
|
|
844
|
+
}
|
|
845
|
+
// Browser fallback
|
|
846
|
+
const binary = atob(base64);
|
|
847
|
+
const bytes = new Uint8Array(binary.length);
|
|
848
|
+
for (let i = 0; i < binary.length; i++) {
|
|
849
|
+
bytes[i] = binary.charCodeAt(i);
|
|
850
|
+
}
|
|
851
|
+
return bytes;
|
|
852
|
+
}
|
|
450
853
|
/**
|
|
451
854
|
* Get statistics
|
|
452
855
|
*/
|
|
@@ -464,5 +867,14 @@ export class QuiltBatchManager {
|
|
|
464
867
|
? this.walrusWithRelay
|
|
465
868
|
: this.walrusWithoutRelay;
|
|
466
869
|
}
|
|
870
|
+
/**
|
|
871
|
+
* Get base64 converter (for external use)
|
|
872
|
+
*/
|
|
873
|
+
getBase64Utils() {
|
|
874
|
+
return {
|
|
875
|
+
encode: this.uint8ArrayToBase64.bind(this),
|
|
876
|
+
decode: this.base64ToUint8Array.bind(this)
|
|
877
|
+
};
|
|
878
|
+
}
|
|
467
879
|
}
|
|
468
880
|
//# sourceMappingURL=QuiltBatchManager.js.map
|