@mastra/lance 0.0.0-add-libsql-changeset-20250910154739

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/index.cjs ADDED
@@ -0,0 +1,3303 @@
1
+ 'use strict';
2
+
3
+ var lancedb = require('@lancedb/lancedb');
4
+ var error = require('@mastra/core/error');
5
+ var storage = require('@mastra/core/storage');
6
+ var agent = require('@mastra/core/agent');
7
+ var apacheArrow = require('apache-arrow');
8
+ var vector = require('@mastra/core/vector');
9
+ var filter = require('@mastra/core/vector/filter');
10
+
11
+ // src/storage/index.ts
12
+ var StoreLegacyEvalsLance = class extends storage.LegacyEvalsStorage {
13
+ client;
14
+ constructor({ client }) {
15
+ super();
16
+ this.client = client;
17
+ }
18
+ async getEvalsByAgentName(agentName, type) {
19
+ try {
20
+ const table = await this.client.openTable(storage.TABLE_EVALS);
21
+ const query = table.query().where(`agent_name = '${agentName}'`);
22
+ const records = await query.toArray();
23
+ let filteredRecords = records;
24
+ if (type === "live") {
25
+ filteredRecords = records.filter((record) => record.test_info === null);
26
+ } else if (type === "test") {
27
+ filteredRecords = records.filter((record) => record.test_info !== null);
28
+ }
29
+ return filteredRecords.map((record) => {
30
+ return {
31
+ id: record.id,
32
+ input: record.input,
33
+ output: record.output,
34
+ agentName: record.agent_name,
35
+ metricName: record.metric_name,
36
+ result: JSON.parse(record.result),
37
+ instructions: record.instructions,
38
+ testInfo: record.test_info ? JSON.parse(record.test_info) : null,
39
+ globalRunId: record.global_run_id,
40
+ runId: record.run_id,
41
+ createdAt: new Date(record.created_at).toString()
42
+ };
43
+ });
44
+ } catch (error$1) {
45
+ throw new error.MastraError(
46
+ {
47
+ id: "LANCE_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
48
+ domain: error.ErrorDomain.STORAGE,
49
+ category: error.ErrorCategory.THIRD_PARTY,
50
+ details: { agentName }
51
+ },
52
+ error$1
53
+ );
54
+ }
55
+ }
56
+ async getEvals(options) {
57
+ try {
58
+ const table = await this.client.openTable(storage.TABLE_EVALS);
59
+ const conditions = [];
60
+ if (options.agentName) {
61
+ conditions.push(`agent_name = '${options.agentName}'`);
62
+ }
63
+ if (options.type === "live") {
64
+ conditions.push("length(test_info) = 0");
65
+ } else if (options.type === "test") {
66
+ conditions.push("length(test_info) > 0");
67
+ }
68
+ const startDate = options.dateRange?.start || options.fromDate;
69
+ const endDate = options.dateRange?.end || options.toDate;
70
+ if (startDate) {
71
+ conditions.push(`\`created_at\` >= ${startDate.getTime()}`);
72
+ }
73
+ if (endDate) {
74
+ conditions.push(`\`created_at\` <= ${endDate.getTime()}`);
75
+ }
76
+ let total = 0;
77
+ if (conditions.length > 0) {
78
+ total = await table.countRows(conditions.join(" AND "));
79
+ } else {
80
+ total = await table.countRows();
81
+ }
82
+ const query = table.query();
83
+ if (conditions.length > 0) {
84
+ const whereClause = conditions.join(" AND ");
85
+ query.where(whereClause);
86
+ }
87
+ const records = await query.toArray();
88
+ const evals = records.sort((a, b) => b.created_at - a.created_at).map((record) => {
89
+ return {
90
+ id: record.id,
91
+ input: record.input,
92
+ output: record.output,
93
+ agentName: record.agent_name,
94
+ metricName: record.metric_name,
95
+ result: JSON.parse(record.result),
96
+ instructions: record.instructions,
97
+ testInfo: record.test_info ? JSON.parse(record.test_info) : null,
98
+ globalRunId: record.global_run_id,
99
+ runId: record.run_id,
100
+ createdAt: new Date(record.created_at).toISOString()
101
+ };
102
+ });
103
+ const page = options.page || 0;
104
+ const perPage = options.perPage || 10;
105
+ const pagedEvals = evals.slice(page * perPage, (page + 1) * perPage);
106
+ return {
107
+ evals: pagedEvals,
108
+ total,
109
+ page,
110
+ perPage,
111
+ hasMore: total > (page + 1) * perPage
112
+ };
113
+ } catch (error$1) {
114
+ throw new error.MastraError(
115
+ {
116
+ id: "LANCE_STORE_GET_EVALS_FAILED",
117
+ domain: error.ErrorDomain.STORAGE,
118
+ category: error.ErrorCategory.THIRD_PARTY,
119
+ details: { agentName: options.agentName ?? "" }
120
+ },
121
+ error$1
122
+ );
123
+ }
124
+ }
125
+ };
126
+ function getPrimaryKeys(tableName) {
127
+ let primaryId = ["id"];
128
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
129
+ primaryId = ["workflow_name", "run_id"];
130
+ } else if (tableName === storage.TABLE_EVALS) {
131
+ primaryId = ["agent_name", "metric_name", "run_id"];
132
+ }
133
+ return primaryId;
134
+ }
135
+ function validateKeyTypes(keys, tableSchema) {
136
+ const fieldTypes = new Map(
137
+ tableSchema.fields.map((field) => [field.name, field.type?.toString().toLowerCase()])
138
+ );
139
+ for (const [key, value] of Object.entries(keys)) {
140
+ const fieldType = fieldTypes.get(key);
141
+ if (!fieldType) {
142
+ throw new Error(`Field '${key}' does not exist in table schema`);
143
+ }
144
+ if (value !== null) {
145
+ if ((fieldType.includes("int") || fieldType.includes("bigint")) && typeof value !== "number") {
146
+ throw new Error(`Expected numeric value for field '${key}', got ${typeof value}`);
147
+ }
148
+ if (fieldType.includes("utf8") && typeof value !== "string") {
149
+ throw new Error(`Expected string value for field '${key}', got ${typeof value}`);
150
+ }
151
+ if (fieldType.includes("timestamp") && !(value instanceof Date) && typeof value !== "string") {
152
+ throw new Error(`Expected Date or string value for field '${key}', got ${typeof value}`);
153
+ }
154
+ }
155
+ }
156
+ }
157
+ function processResultWithTypeConversion(rawResult, tableSchema) {
158
+ const fieldTypeMap = /* @__PURE__ */ new Map();
159
+ tableSchema.fields.forEach((field) => {
160
+ const fieldName = field.name;
161
+ const fieldTypeStr = field.type.toString().toLowerCase();
162
+ fieldTypeMap.set(fieldName, fieldTypeStr);
163
+ });
164
+ if (Array.isArray(rawResult)) {
165
+ return rawResult.map((item) => processResultWithTypeConversion(item, tableSchema));
166
+ }
167
+ const processedResult = { ...rawResult };
168
+ for (const key in processedResult) {
169
+ const fieldTypeStr = fieldTypeMap.get(key);
170
+ if (!fieldTypeStr) continue;
171
+ if (typeof processedResult[key] === "string") {
172
+ if (fieldTypeStr.includes("int32") || fieldTypeStr.includes("float32")) {
173
+ if (!isNaN(Number(processedResult[key]))) {
174
+ processedResult[key] = Number(processedResult[key]);
175
+ }
176
+ } else if (fieldTypeStr.includes("int64")) {
177
+ processedResult[key] = Number(processedResult[key]);
178
+ } else if (fieldTypeStr.includes("utf8") && key !== "id") {
179
+ try {
180
+ const parsed = JSON.parse(processedResult[key]);
181
+ if (typeof parsed === "object") {
182
+ processedResult[key] = JSON.parse(processedResult[key]);
183
+ }
184
+ } catch {
185
+ }
186
+ }
187
+ } else if (typeof processedResult[key] === "bigint") {
188
+ processedResult[key] = Number(processedResult[key]);
189
+ } else if (fieldTypeStr.includes("float64") && ["createdAt", "updatedAt"].includes(key)) {
190
+ processedResult[key] = new Date(processedResult[key]);
191
+ }
192
+ console.log(key, "processedResult", processedResult);
193
+ }
194
+ return processedResult;
195
+ }
196
+ async function getTableSchema({
197
+ tableName,
198
+ client
199
+ }) {
200
+ try {
201
+ if (!client) {
202
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
203
+ }
204
+ if (!tableName) {
205
+ throw new Error("tableName is required for getTableSchema.");
206
+ }
207
+ } catch (validationError) {
208
+ throw new error.MastraError(
209
+ {
210
+ id: "STORAGE_LANCE_STORAGE_GET_TABLE_SCHEMA_INVALID_ARGS",
211
+ domain: error.ErrorDomain.STORAGE,
212
+ category: error.ErrorCategory.USER,
213
+ text: validationError.message,
214
+ details: { tableName }
215
+ },
216
+ validationError
217
+ );
218
+ }
219
+ try {
220
+ const table = await client.openTable(tableName);
221
+ const rawSchema = await table.schema();
222
+ const fields = rawSchema.fields;
223
+ return {
224
+ fields,
225
+ metadata: /* @__PURE__ */ new Map(),
226
+ get names() {
227
+ return fields.map((field) => field.name);
228
+ }
229
+ };
230
+ } catch (error$1) {
231
+ throw new error.MastraError(
232
+ {
233
+ id: "STORAGE_LANCE_STORAGE_GET_TABLE_SCHEMA_FAILED",
234
+ domain: error.ErrorDomain.STORAGE,
235
+ category: error.ErrorCategory.THIRD_PARTY,
236
+ details: { tableName }
237
+ },
238
+ error$1
239
+ );
240
+ }
241
+ }
242
+
243
+ // src/storage/domains/memory/index.ts
244
+ var StoreMemoryLance = class extends storage.MemoryStorage {
245
+ client;
246
+ operations;
247
+ constructor({ client, operations }) {
248
+ super();
249
+ this.client = client;
250
+ this.operations = operations;
251
+ }
252
+ async getThreadById({ threadId }) {
253
+ try {
254
+ const thread = await this.operations.load({ tableName: storage.TABLE_THREADS, keys: { id: threadId } });
255
+ if (!thread) {
256
+ return null;
257
+ }
258
+ return {
259
+ ...thread,
260
+ createdAt: new Date(thread.createdAt),
261
+ updatedAt: new Date(thread.updatedAt)
262
+ };
263
+ } catch (error$1) {
264
+ throw new error.MastraError(
265
+ {
266
+ id: "LANCE_STORE_GET_THREAD_BY_ID_FAILED",
267
+ domain: error.ErrorDomain.STORAGE,
268
+ category: error.ErrorCategory.THIRD_PARTY
269
+ },
270
+ error$1
271
+ );
272
+ }
273
+ }
274
+ async getThreadsByResourceId({ resourceId }) {
275
+ try {
276
+ const table = await this.client.openTable(storage.TABLE_THREADS);
277
+ const query = table.query().where(`\`resourceId\` = '${resourceId}'`);
278
+ const records = await query.toArray();
279
+ return processResultWithTypeConversion(
280
+ records,
281
+ await getTableSchema({ tableName: storage.TABLE_THREADS, client: this.client })
282
+ );
283
+ } catch (error$1) {
284
+ throw new error.MastraError(
285
+ {
286
+ id: "LANCE_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
287
+ domain: error.ErrorDomain.STORAGE,
288
+ category: error.ErrorCategory.THIRD_PARTY
289
+ },
290
+ error$1
291
+ );
292
+ }
293
+ }
294
+ /**
295
+ * Saves a thread to the database. This function doesn't overwrite existing threads.
296
+ * @param thread - The thread to save
297
+ * @returns The saved thread
298
+ */
299
+ async saveThread({ thread }) {
300
+ try {
301
+ const record = { ...thread, metadata: JSON.stringify(thread.metadata) };
302
+ const table = await this.client.openTable(storage.TABLE_THREADS);
303
+ await table.add([record], { mode: "append" });
304
+ return thread;
305
+ } catch (error$1) {
306
+ throw new error.MastraError(
307
+ {
308
+ id: "LANCE_STORE_SAVE_THREAD_FAILED",
309
+ domain: error.ErrorDomain.STORAGE,
310
+ category: error.ErrorCategory.THIRD_PARTY
311
+ },
312
+ error$1
313
+ );
314
+ }
315
+ }
316
+ async updateThread({
317
+ id,
318
+ title,
319
+ metadata
320
+ }) {
321
+ const maxRetries = 5;
322
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
323
+ try {
324
+ const current = await this.getThreadById({ threadId: id });
325
+ if (!current) {
326
+ throw new Error(`Thread with id ${id} not found`);
327
+ }
328
+ const mergedMetadata = { ...current.metadata, ...metadata };
329
+ const record = {
330
+ id,
331
+ title,
332
+ metadata: JSON.stringify(mergedMetadata),
333
+ updatedAt: (/* @__PURE__ */ new Date()).getTime()
334
+ };
335
+ const table = await this.client.openTable(storage.TABLE_THREADS);
336
+ await table.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([record]);
337
+ const updatedThread = await this.getThreadById({ threadId: id });
338
+ if (!updatedThread) {
339
+ throw new Error(`Failed to retrieve updated thread ${id}`);
340
+ }
341
+ return updatedThread;
342
+ } catch (error$1) {
343
+ if (error$1.message?.includes("Commit conflict") && attempt < maxRetries - 1) {
344
+ const delay = Math.pow(2, attempt) * 10;
345
+ await new Promise((resolve) => setTimeout(resolve, delay));
346
+ continue;
347
+ }
348
+ throw new error.MastraError(
349
+ {
350
+ id: "LANCE_STORE_UPDATE_THREAD_FAILED",
351
+ domain: error.ErrorDomain.STORAGE,
352
+ category: error.ErrorCategory.THIRD_PARTY
353
+ },
354
+ error$1
355
+ );
356
+ }
357
+ }
358
+ throw new error.MastraError(
359
+ {
360
+ id: "LANCE_STORE_UPDATE_THREAD_FAILED",
361
+ domain: error.ErrorDomain.STORAGE,
362
+ category: error.ErrorCategory.THIRD_PARTY
363
+ },
364
+ new Error("All retries exhausted")
365
+ );
366
+ }
367
+ async deleteThread({ threadId }) {
368
+ try {
369
+ const table = await this.client.openTable(storage.TABLE_THREADS);
370
+ await table.delete(`id = '${threadId}'`);
371
+ const messagesTable = await this.client.openTable(storage.TABLE_MESSAGES);
372
+ await messagesTable.delete(`thread_id = '${threadId}'`);
373
+ } catch (error$1) {
374
+ throw new error.MastraError(
375
+ {
376
+ id: "LANCE_STORE_DELETE_THREAD_FAILED",
377
+ domain: error.ErrorDomain.STORAGE,
378
+ category: error.ErrorCategory.THIRD_PARTY
379
+ },
380
+ error$1
381
+ );
382
+ }
383
+ }
384
+ normalizeMessage(message) {
385
+ const { thread_id, ...rest } = message;
386
+ return {
387
+ ...rest,
388
+ threadId: thread_id,
389
+ content: typeof message.content === "string" ? (() => {
390
+ try {
391
+ return JSON.parse(message.content);
392
+ } catch {
393
+ return message.content;
394
+ }
395
+ })() : message.content
396
+ };
397
+ }
398
+ async getMessages({
399
+ threadId,
400
+ resourceId,
401
+ selectBy,
402
+ format,
403
+ threadConfig
404
+ }) {
405
+ try {
406
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
407
+ if (threadConfig) {
408
+ throw new Error("ThreadConfig is not supported by LanceDB storage");
409
+ }
410
+ const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
411
+ const table = await this.client.openTable(storage.TABLE_MESSAGES);
412
+ let allRecords = [];
413
+ if (selectBy?.include && selectBy.include.length > 0) {
414
+ const threadIds = [...new Set(selectBy.include.map((item) => item.threadId))];
415
+ for (const threadId2 of threadIds) {
416
+ const threadQuery = table.query().where(`thread_id = '${threadId2}'`);
417
+ let threadRecords = await threadQuery.toArray();
418
+ allRecords.push(...threadRecords);
419
+ }
420
+ } else {
421
+ let query = table.query().where(`\`thread_id\` = '${threadId}'`);
422
+ allRecords = await query.toArray();
423
+ }
424
+ allRecords.sort((a, b) => {
425
+ const dateA = new Date(a.createdAt).getTime();
426
+ const dateB = new Date(b.createdAt).getTime();
427
+ return dateA - dateB;
428
+ });
429
+ if (selectBy?.include && selectBy.include.length > 0) {
430
+ allRecords = this.processMessagesWithContext(allRecords, selectBy.include);
431
+ }
432
+ if (limit !== Number.MAX_SAFE_INTEGER) {
433
+ allRecords = allRecords.slice(-limit);
434
+ }
435
+ const messages = processResultWithTypeConversion(
436
+ allRecords,
437
+ await getTableSchema({ tableName: storage.TABLE_MESSAGES, client: this.client })
438
+ );
439
+ const list = new agent.MessageList({ threadId, resourceId }).add(messages.map(this.normalizeMessage), "memory");
440
+ if (format === "v2") return list.get.all.v2();
441
+ return list.get.all.v1();
442
+ } catch (error$1) {
443
+ throw new error.MastraError(
444
+ {
445
+ id: "LANCE_STORE_GET_MESSAGES_FAILED",
446
+ domain: error.ErrorDomain.STORAGE,
447
+ category: error.ErrorCategory.THIRD_PARTY,
448
+ details: {
449
+ threadId,
450
+ resourceId: resourceId ?? ""
451
+ }
452
+ },
453
+ error$1
454
+ );
455
+ }
456
+ }
457
+ async getMessagesById({
458
+ messageIds,
459
+ format
460
+ }) {
461
+ if (messageIds.length === 0) return [];
462
+ try {
463
+ const table = await this.client.openTable(storage.TABLE_MESSAGES);
464
+ const quotedIds = messageIds.map((id) => `'${id}'`).join(", ");
465
+ const allRecords = await table.query().where(`id IN (${quotedIds})`).toArray();
466
+ const messages = processResultWithTypeConversion(
467
+ allRecords,
468
+ await getTableSchema({ tableName: storage.TABLE_MESSAGES, client: this.client })
469
+ );
470
+ const list = new agent.MessageList().add(messages.map(this.normalizeMessage), "memory");
471
+ if (format === `v1`) return list.get.all.v1();
472
+ return list.get.all.v2();
473
+ } catch (error$1) {
474
+ throw new error.MastraError(
475
+ {
476
+ id: "LANCE_STORE_GET_MESSAGES_BY_ID_FAILED",
477
+ domain: error.ErrorDomain.STORAGE,
478
+ category: error.ErrorCategory.THIRD_PARTY,
479
+ details: {
480
+ messageIds: JSON.stringify(messageIds)
481
+ }
482
+ },
483
+ error$1
484
+ );
485
+ }
486
+ }
487
+ async saveMessages(args) {
488
+ try {
489
+ const { messages, format = "v1" } = args;
490
+ if (messages.length === 0) {
491
+ return [];
492
+ }
493
+ const threadId = messages[0]?.threadId;
494
+ if (!threadId) {
495
+ throw new Error("Thread ID is required");
496
+ }
497
+ for (const message of messages) {
498
+ if (!message.id) {
499
+ throw new Error("Message ID is required");
500
+ }
501
+ if (!message.threadId) {
502
+ throw new Error("Thread ID is required for all messages");
503
+ }
504
+ if (message.resourceId === null || message.resourceId === void 0) {
505
+ throw new Error("Resource ID cannot be null or undefined");
506
+ }
507
+ if (!message.content) {
508
+ throw new Error("Message content is required");
509
+ }
510
+ }
511
+ const transformedMessages = messages.map((message) => {
512
+ const { threadId: threadId2, type, ...rest } = message;
513
+ return {
514
+ ...rest,
515
+ thread_id: threadId2,
516
+ type: type ?? "v2",
517
+ content: JSON.stringify(message.content)
518
+ };
519
+ });
520
+ const table = await this.client.openTable(storage.TABLE_MESSAGES);
521
+ await table.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(transformedMessages);
522
+ const threadsTable = await this.client.openTable(storage.TABLE_THREADS);
523
+ const currentTime = (/* @__PURE__ */ new Date()).getTime();
524
+ const updateRecord = { id: threadId, updatedAt: currentTime };
525
+ await threadsTable.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([updateRecord]);
526
+ const list = new agent.MessageList().add(messages, "memory");
527
+ if (format === `v2`) return list.get.all.v2();
528
+ return list.get.all.v1();
529
+ } catch (error$1) {
530
+ throw new error.MastraError(
531
+ {
532
+ id: "LANCE_STORE_SAVE_MESSAGES_FAILED",
533
+ domain: error.ErrorDomain.STORAGE,
534
+ category: error.ErrorCategory.THIRD_PARTY
535
+ },
536
+ error$1
537
+ );
538
+ }
539
+ }
540
+ async getThreadsByResourceIdPaginated(args) {
541
+ try {
542
+ const { resourceId, page = 0, perPage = 10 } = args;
543
+ const table = await this.client.openTable(storage.TABLE_THREADS);
544
+ const total = await table.countRows(`\`resourceId\` = '${resourceId}'`);
545
+ const query = table.query().where(`\`resourceId\` = '${resourceId}'`);
546
+ const offset = page * perPage;
547
+ query.limit(perPage);
548
+ if (offset > 0) {
549
+ query.offset(offset);
550
+ }
551
+ const records = await query.toArray();
552
+ records.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
553
+ const schema = await getTableSchema({ tableName: storage.TABLE_THREADS, client: this.client });
554
+ const threads = records.map((record) => processResultWithTypeConversion(record, schema));
555
+ return {
556
+ threads,
557
+ total,
558
+ page,
559
+ perPage,
560
+ hasMore: total > (page + 1) * perPage
561
+ };
562
+ } catch (error$1) {
563
+ throw new error.MastraError(
564
+ {
565
+ id: "LANCE_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
566
+ domain: error.ErrorDomain.STORAGE,
567
+ category: error.ErrorCategory.THIRD_PARTY
568
+ },
569
+ error$1
570
+ );
571
+ }
572
+ }
573
+ /**
574
+ * Processes messages to include context messages based on withPreviousMessages and withNextMessages
575
+ * @param records - The sorted array of records to process
576
+ * @param include - The array of include specifications with context parameters
577
+ * @returns The processed array with context messages included
578
+ */
579
+ processMessagesWithContext(records, include) {
580
+ const messagesWithContext = include.filter((item) => item.withPreviousMessages || item.withNextMessages);
581
+ if (messagesWithContext.length === 0) {
582
+ return records;
583
+ }
584
+ const messageIndexMap = /* @__PURE__ */ new Map();
585
+ records.forEach((message, index) => {
586
+ messageIndexMap.set(message.id, index);
587
+ });
588
+ const additionalIndices = /* @__PURE__ */ new Set();
589
+ for (const item of messagesWithContext) {
590
+ const messageIndex = messageIndexMap.get(item.id);
591
+ if (messageIndex !== void 0) {
592
+ if (item.withPreviousMessages) {
593
+ const startIdx = Math.max(0, messageIndex - item.withPreviousMessages);
594
+ for (let i = startIdx; i < messageIndex; i++) {
595
+ additionalIndices.add(i);
596
+ }
597
+ }
598
+ if (item.withNextMessages) {
599
+ const endIdx = Math.min(records.length - 1, messageIndex + item.withNextMessages);
600
+ for (let i = messageIndex + 1; i <= endIdx; i++) {
601
+ additionalIndices.add(i);
602
+ }
603
+ }
604
+ }
605
+ }
606
+ if (additionalIndices.size === 0) {
607
+ return records;
608
+ }
609
+ const originalMatchIds = new Set(include.map((item) => item.id));
610
+ const allIndices = /* @__PURE__ */ new Set();
611
+ records.forEach((record, index) => {
612
+ if (originalMatchIds.has(record.id)) {
613
+ allIndices.add(index);
614
+ }
615
+ });
616
+ additionalIndices.forEach((index) => {
617
+ allIndices.add(index);
618
+ });
619
+ return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
620
+ }
621
+ async getMessagesPaginated(args) {
622
+ const { threadId, resourceId, selectBy, format = "v1" } = args;
623
+ const page = selectBy?.pagination?.page ?? 0;
624
+ const perPage = selectBy?.pagination?.perPage ?? 10;
625
+ try {
626
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
627
+ const dateRange = selectBy?.pagination?.dateRange;
628
+ const fromDate = dateRange?.start;
629
+ const toDate = dateRange?.end;
630
+ const table = await this.client.openTable(storage.TABLE_MESSAGES);
631
+ const messages = [];
632
+ if (selectBy?.include && Array.isArray(selectBy.include)) {
633
+ const threadIds = [...new Set(selectBy.include.map((item) => item.threadId))];
634
+ const allThreadMessages = [];
635
+ for (const threadId2 of threadIds) {
636
+ const threadQuery = table.query().where(`thread_id = '${threadId2}'`);
637
+ let threadRecords = await threadQuery.toArray();
638
+ if (fromDate) threadRecords = threadRecords.filter((m) => m.createdAt >= fromDate.getTime());
639
+ if (toDate) threadRecords = threadRecords.filter((m) => m.createdAt <= toDate.getTime());
640
+ allThreadMessages.push(...threadRecords);
641
+ }
642
+ allThreadMessages.sort((a, b) => a.createdAt - b.createdAt);
643
+ const contextMessages = this.processMessagesWithContext(allThreadMessages, selectBy.include);
644
+ messages.push(...contextMessages);
645
+ }
646
+ const conditions = [`thread_id = '${threadId}'`];
647
+ if (resourceId) {
648
+ conditions.push(`\`resourceId\` = '${resourceId}'`);
649
+ }
650
+ if (fromDate) {
651
+ conditions.push(`\`createdAt\` >= ${fromDate.getTime()}`);
652
+ }
653
+ if (toDate) {
654
+ conditions.push(`\`createdAt\` <= ${toDate.getTime()}`);
655
+ }
656
+ let total = 0;
657
+ if (conditions.length > 0) {
658
+ total = await table.countRows(conditions.join(" AND "));
659
+ } else {
660
+ total = await table.countRows();
661
+ }
662
+ if (total === 0 && messages.length === 0) {
663
+ return {
664
+ messages: [],
665
+ total: 0,
666
+ page,
667
+ perPage,
668
+ hasMore: false
669
+ };
670
+ }
671
+ const excludeIds = messages.map((m) => m.id);
672
+ let selectedMessages = [];
673
+ if (selectBy?.last && selectBy.last > 0) {
674
+ const query = table.query();
675
+ if (conditions.length > 0) {
676
+ query.where(conditions.join(" AND "));
677
+ }
678
+ let records = await query.toArray();
679
+ records = records.sort((a, b) => a.createdAt - b.createdAt);
680
+ if (excludeIds.length > 0) {
681
+ records = records.filter((m) => !excludeIds.includes(m.id));
682
+ }
683
+ selectedMessages = records.slice(-selectBy.last);
684
+ } else {
685
+ const query = table.query();
686
+ if (conditions.length > 0) {
687
+ query.where(conditions.join(" AND "));
688
+ }
689
+ let records = await query.toArray();
690
+ records = records.sort((a, b) => a.createdAt - b.createdAt);
691
+ if (excludeIds.length > 0) {
692
+ records = records.filter((m) => !excludeIds.includes(m.id));
693
+ }
694
+ selectedMessages = records.slice(page * perPage, (page + 1) * perPage);
695
+ }
696
+ const allMessages = [...messages, ...selectedMessages];
697
+ const seen = /* @__PURE__ */ new Set();
698
+ const dedupedMessages = allMessages.filter((m) => {
699
+ const key = `${m.id}:${m.thread_id}`;
700
+ if (seen.has(key)) return false;
701
+ seen.add(key);
702
+ return true;
703
+ });
704
+ const formattedMessages = dedupedMessages.map((msg) => {
705
+ const { thread_id, ...rest } = msg;
706
+ return {
707
+ ...rest,
708
+ threadId: thread_id,
709
+ content: typeof msg.content === "string" ? (() => {
710
+ try {
711
+ return JSON.parse(msg.content);
712
+ } catch {
713
+ return msg.content;
714
+ }
715
+ })() : msg.content
716
+ };
717
+ });
718
+ const list = new agent.MessageList().add(formattedMessages, "memory");
719
+ return {
720
+ messages: format === "v2" ? list.get.all.v2() : list.get.all.v1(),
721
+ total,
722
+ // Total should be the count of messages matching the filters
723
+ page,
724
+ perPage,
725
+ hasMore: total > (page + 1) * perPage
726
+ };
727
+ } catch (error$1) {
728
+ const mastraError = new error.MastraError(
729
+ {
730
+ id: "LANCE_STORE_GET_MESSAGES_PAGINATED_FAILED",
731
+ domain: error.ErrorDomain.STORAGE,
732
+ category: error.ErrorCategory.THIRD_PARTY,
733
+ details: {
734
+ threadId,
735
+ resourceId: resourceId ?? ""
736
+ }
737
+ },
738
+ error$1
739
+ );
740
+ this.logger?.trackException?.(mastraError);
741
+ this.logger?.error?.(mastraError.toString());
742
+ return { messages: [], total: 0, page, perPage, hasMore: false };
743
+ }
744
+ }
745
+ /**
746
+ * Parse message data from LanceDB record format to MastraMessageV2 format
747
+ */
748
+ parseMessageData(data) {
749
+ const { thread_id, ...rest } = data;
750
+ return {
751
+ ...rest,
752
+ threadId: thread_id,
753
+ content: typeof data.content === "string" ? (() => {
754
+ try {
755
+ return JSON.parse(data.content);
756
+ } catch {
757
+ return data.content;
758
+ }
759
+ })() : data.content,
760
+ createdAt: new Date(data.createdAt),
761
+ updatedAt: new Date(data.updatedAt)
762
+ };
763
+ }
764
+ async updateMessages(args) {
765
+ const { messages } = args;
766
+ this.logger.debug("Updating messages", { count: messages.length });
767
+ if (!messages.length) {
768
+ return [];
769
+ }
770
+ const updatedMessages = [];
771
+ const affectedThreadIds = /* @__PURE__ */ new Set();
772
+ try {
773
+ for (const updateData of messages) {
774
+ const { id, ...updates } = updateData;
775
+ const existingMessage = await this.operations.load({ tableName: storage.TABLE_MESSAGES, keys: { id } });
776
+ if (!existingMessage) {
777
+ this.logger.warn("Message not found for update", { id });
778
+ continue;
779
+ }
780
+ const existingMsg = this.parseMessageData(existingMessage);
781
+ const originalThreadId = existingMsg.threadId;
782
+ affectedThreadIds.add(originalThreadId);
783
+ const updatePayload = {};
784
+ if ("role" in updates && updates.role !== void 0) updatePayload.role = updates.role;
785
+ if ("type" in updates && updates.type !== void 0) updatePayload.type = updates.type;
786
+ if ("resourceId" in updates && updates.resourceId !== void 0) updatePayload.resourceId = updates.resourceId;
787
+ if ("threadId" in updates && updates.threadId !== void 0 && updates.threadId !== null) {
788
+ updatePayload.thread_id = updates.threadId;
789
+ affectedThreadIds.add(updates.threadId);
790
+ }
791
+ if (updates.content) {
792
+ const existingContent = existingMsg.content;
793
+ let newContent = { ...existingContent };
794
+ if (updates.content.metadata !== void 0) {
795
+ newContent.metadata = {
796
+ ...existingContent.metadata || {},
797
+ ...updates.content.metadata || {}
798
+ };
799
+ }
800
+ if (updates.content.content !== void 0) {
801
+ newContent.content = updates.content.content;
802
+ }
803
+ if ("parts" in updates.content && updates.content.parts !== void 0) {
804
+ newContent.parts = updates.content.parts;
805
+ }
806
+ updatePayload.content = JSON.stringify(newContent);
807
+ }
808
+ await this.operations.insert({ tableName: storage.TABLE_MESSAGES, record: { id, ...updatePayload } });
809
+ const updatedMessage = await this.operations.load({ tableName: storage.TABLE_MESSAGES, keys: { id } });
810
+ if (updatedMessage) {
811
+ updatedMessages.push(this.parseMessageData(updatedMessage));
812
+ }
813
+ }
814
+ for (const threadId of affectedThreadIds) {
815
+ await this.operations.insert({
816
+ tableName: storage.TABLE_THREADS,
817
+ record: { id: threadId, updatedAt: Date.now() }
818
+ });
819
+ }
820
+ return updatedMessages;
821
+ } catch (error$1) {
822
+ throw new error.MastraError(
823
+ {
824
+ id: "LANCE_STORE_UPDATE_MESSAGES_FAILED",
825
+ domain: error.ErrorDomain.STORAGE,
826
+ category: error.ErrorCategory.THIRD_PARTY,
827
+ details: { count: messages.length }
828
+ },
829
+ error$1
830
+ );
831
+ }
832
+ }
833
+ async getResourceById({ resourceId }) {
834
+ try {
835
+ const resource = await this.operations.load({ tableName: storage.TABLE_RESOURCES, keys: { id: resourceId } });
836
+ if (!resource) {
837
+ return null;
838
+ }
839
+ let createdAt;
840
+ let updatedAt;
841
+ try {
842
+ if (resource.createdAt instanceof Date) {
843
+ createdAt = resource.createdAt;
844
+ } else if (typeof resource.createdAt === "string") {
845
+ createdAt = new Date(resource.createdAt);
846
+ } else if (typeof resource.createdAt === "number") {
847
+ createdAt = new Date(resource.createdAt);
848
+ } else {
849
+ createdAt = /* @__PURE__ */ new Date();
850
+ }
851
+ if (isNaN(createdAt.getTime())) {
852
+ createdAt = /* @__PURE__ */ new Date();
853
+ }
854
+ } catch {
855
+ createdAt = /* @__PURE__ */ new Date();
856
+ }
857
+ try {
858
+ if (resource.updatedAt instanceof Date) {
859
+ updatedAt = resource.updatedAt;
860
+ } else if (typeof resource.updatedAt === "string") {
861
+ updatedAt = new Date(resource.updatedAt);
862
+ } else if (typeof resource.updatedAt === "number") {
863
+ updatedAt = new Date(resource.updatedAt);
864
+ } else {
865
+ updatedAt = /* @__PURE__ */ new Date();
866
+ }
867
+ if (isNaN(updatedAt.getTime())) {
868
+ updatedAt = /* @__PURE__ */ new Date();
869
+ }
870
+ } catch {
871
+ updatedAt = /* @__PURE__ */ new Date();
872
+ }
873
+ let workingMemory = resource.workingMemory;
874
+ if (workingMemory === null || workingMemory === void 0) {
875
+ workingMemory = void 0;
876
+ } else if (workingMemory === "") {
877
+ workingMemory = "";
878
+ } else if (typeof workingMemory === "object") {
879
+ workingMemory = JSON.stringify(workingMemory);
880
+ }
881
+ let metadata = resource.metadata;
882
+ if (metadata === "" || metadata === null || metadata === void 0) {
883
+ metadata = void 0;
884
+ } else if (typeof metadata === "string") {
885
+ try {
886
+ metadata = JSON.parse(metadata);
887
+ } catch {
888
+ metadata = metadata;
889
+ }
890
+ }
891
+ return {
892
+ ...resource,
893
+ createdAt,
894
+ updatedAt,
895
+ workingMemory,
896
+ metadata
897
+ };
898
+ } catch (error$1) {
899
+ throw new error.MastraError(
900
+ {
901
+ id: "LANCE_STORE_GET_RESOURCE_BY_ID_FAILED",
902
+ domain: error.ErrorDomain.STORAGE,
903
+ category: error.ErrorCategory.THIRD_PARTY
904
+ },
905
+ error$1
906
+ );
907
+ }
908
+ }
909
+ async saveResource({ resource }) {
910
+ try {
911
+ const record = {
912
+ ...resource,
913
+ metadata: resource.metadata ? JSON.stringify(resource.metadata) : "",
914
+ createdAt: resource.createdAt.getTime(),
915
+ // Store as timestamp (milliseconds)
916
+ updatedAt: resource.updatedAt.getTime()
917
+ // Store as timestamp (milliseconds)
918
+ };
919
+ const table = await this.client.openTable(storage.TABLE_RESOURCES);
920
+ await table.add([record], { mode: "append" });
921
+ return resource;
922
+ } catch (error$1) {
923
+ throw new error.MastraError(
924
+ {
925
+ id: "LANCE_STORE_SAVE_RESOURCE_FAILED",
926
+ domain: error.ErrorDomain.STORAGE,
927
+ category: error.ErrorCategory.THIRD_PARTY
928
+ },
929
+ error$1
930
+ );
931
+ }
932
+ }
933
+ async updateResource({
934
+ resourceId,
935
+ workingMemory,
936
+ metadata
937
+ }) {
938
+ const maxRetries = 3;
939
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
940
+ try {
941
+ const existingResource = await this.getResourceById({ resourceId });
942
+ if (!existingResource) {
943
+ const newResource = {
944
+ id: resourceId,
945
+ workingMemory,
946
+ metadata: metadata || {},
947
+ createdAt: /* @__PURE__ */ new Date(),
948
+ updatedAt: /* @__PURE__ */ new Date()
949
+ };
950
+ return this.saveResource({ resource: newResource });
951
+ }
952
+ const updatedResource = {
953
+ ...existingResource,
954
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
955
+ metadata: {
956
+ ...existingResource.metadata,
957
+ ...metadata
958
+ },
959
+ updatedAt: /* @__PURE__ */ new Date()
960
+ };
961
+ const record = {
962
+ id: resourceId,
963
+ workingMemory: updatedResource.workingMemory || "",
964
+ metadata: updatedResource.metadata ? JSON.stringify(updatedResource.metadata) : "",
965
+ updatedAt: updatedResource.updatedAt.getTime()
966
+ // Store as timestamp (milliseconds)
967
+ };
968
+ const table = await this.client.openTable(storage.TABLE_RESOURCES);
969
+ await table.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([record]);
970
+ return updatedResource;
971
+ } catch (error$1) {
972
+ if (error$1.message?.includes("Commit conflict") && attempt < maxRetries - 1) {
973
+ const delay = Math.pow(2, attempt) * 10;
974
+ await new Promise((resolve) => setTimeout(resolve, delay));
975
+ continue;
976
+ }
977
+ throw new error.MastraError(
978
+ {
979
+ id: "LANCE_STORE_UPDATE_RESOURCE_FAILED",
980
+ domain: error.ErrorDomain.STORAGE,
981
+ category: error.ErrorCategory.THIRD_PARTY
982
+ },
983
+ error$1
984
+ );
985
+ }
986
+ }
987
+ throw new Error("Unexpected end of retry loop");
988
+ }
989
+ };
990
+ var StoreOperationsLance = class extends storage.StoreOperations {
991
+ client;
992
+ constructor({ client }) {
993
+ super();
994
+ this.client = client;
995
+ }
996
+ getDefaultValue(type) {
997
+ switch (type) {
998
+ case "text":
999
+ return "''";
1000
+ case "timestamp":
1001
+ return "CURRENT_TIMESTAMP";
1002
+ case "integer":
1003
+ case "bigint":
1004
+ return "0";
1005
+ case "jsonb":
1006
+ return "'{}'";
1007
+ case "uuid":
1008
+ return "''";
1009
+ default:
1010
+ return super.getDefaultValue(type);
1011
+ }
1012
+ }
1013
+ async hasColumn(tableName, columnName) {
1014
+ const table = await this.client.openTable(tableName);
1015
+ const schema = await table.schema();
1016
+ return schema.fields.some((field) => field.name === columnName);
1017
+ }
1018
+ translateSchema(schema) {
1019
+ const fields = Object.entries(schema).map(([name, column]) => {
1020
+ let arrowType;
1021
+ switch (column.type.toLowerCase()) {
1022
+ case "text":
1023
+ case "uuid":
1024
+ arrowType = new apacheArrow.Utf8();
1025
+ break;
1026
+ case "int":
1027
+ case "integer":
1028
+ arrowType = new apacheArrow.Int32();
1029
+ break;
1030
+ case "bigint":
1031
+ arrowType = new apacheArrow.Float64();
1032
+ break;
1033
+ case "float":
1034
+ arrowType = new apacheArrow.Float32();
1035
+ break;
1036
+ case "jsonb":
1037
+ case "json":
1038
+ arrowType = new apacheArrow.Utf8();
1039
+ break;
1040
+ case "binary":
1041
+ arrowType = new apacheArrow.Binary();
1042
+ break;
1043
+ case "timestamp":
1044
+ arrowType = new apacheArrow.Float64();
1045
+ break;
1046
+ default:
1047
+ arrowType = new apacheArrow.Utf8();
1048
+ }
1049
+ return new apacheArrow.Field(name, arrowType, column.nullable ?? true);
1050
+ });
1051
+ return new apacheArrow.Schema(fields);
1052
+ }
1053
+ async createTable({
1054
+ tableName,
1055
+ schema
1056
+ }) {
1057
+ try {
1058
+ if (!this.client) {
1059
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1060
+ }
1061
+ if (!tableName) {
1062
+ throw new Error("tableName is required for createTable.");
1063
+ }
1064
+ if (!schema) {
1065
+ throw new Error("schema is required for createTable.");
1066
+ }
1067
+ } catch (error$1) {
1068
+ throw new error.MastraError(
1069
+ {
1070
+ id: "STORAGE_LANCE_STORAGE_CREATE_TABLE_INVALID_ARGS",
1071
+ domain: error.ErrorDomain.STORAGE,
1072
+ category: error.ErrorCategory.USER,
1073
+ details: { tableName }
1074
+ },
1075
+ error$1
1076
+ );
1077
+ }
1078
+ try {
1079
+ const arrowSchema = this.translateSchema(schema);
1080
+ await this.client.createEmptyTable(tableName, arrowSchema);
1081
+ } catch (error$1) {
1082
+ if (error$1.message?.includes("already exists")) {
1083
+ this.logger.debug(`Table '${tableName}' already exists, skipping create`);
1084
+ return;
1085
+ }
1086
+ throw new error.MastraError(
1087
+ {
1088
+ id: "STORAGE_LANCE_STORAGE_CREATE_TABLE_FAILED",
1089
+ domain: error.ErrorDomain.STORAGE,
1090
+ category: error.ErrorCategory.THIRD_PARTY,
1091
+ details: { tableName }
1092
+ },
1093
+ error$1
1094
+ );
1095
+ }
1096
+ }
1097
+ async dropTable({ tableName }) {
1098
+ try {
1099
+ if (!this.client) {
1100
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1101
+ }
1102
+ if (!tableName) {
1103
+ throw new Error("tableName is required for dropTable.");
1104
+ }
1105
+ } catch (validationError) {
1106
+ throw new error.MastraError(
1107
+ {
1108
+ id: "STORAGE_LANCE_STORAGE_DROP_TABLE_INVALID_ARGS",
1109
+ domain: error.ErrorDomain.STORAGE,
1110
+ category: error.ErrorCategory.USER,
1111
+ text: validationError.message,
1112
+ details: { tableName }
1113
+ },
1114
+ validationError
1115
+ );
1116
+ }
1117
+ try {
1118
+ await this.client.dropTable(tableName);
1119
+ } catch (error$1) {
1120
+ if (error$1.toString().includes("was not found") || error$1.message?.includes("Table not found")) {
1121
+ this.logger.debug(`Table '${tableName}' does not exist, skipping drop`);
1122
+ return;
1123
+ }
1124
+ throw new error.MastraError(
1125
+ {
1126
+ id: "STORAGE_LANCE_STORAGE_DROP_TABLE_FAILED",
1127
+ domain: error.ErrorDomain.STORAGE,
1128
+ category: error.ErrorCategory.THIRD_PARTY,
1129
+ details: { tableName }
1130
+ },
1131
+ error$1
1132
+ );
1133
+ }
1134
+ }
1135
+ async alterTable({
1136
+ tableName,
1137
+ schema,
1138
+ ifNotExists
1139
+ }) {
1140
+ try {
1141
+ if (!this.client) {
1142
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1143
+ }
1144
+ if (!tableName) {
1145
+ throw new Error("tableName is required for alterTable.");
1146
+ }
1147
+ if (!schema) {
1148
+ throw new Error("schema is required for alterTable.");
1149
+ }
1150
+ if (!ifNotExists || ifNotExists.length === 0) {
1151
+ this.logger.debug("No columns specified to add in alterTable, skipping.");
1152
+ return;
1153
+ }
1154
+ } catch (validationError) {
1155
+ throw new error.MastraError(
1156
+ {
1157
+ id: "STORAGE_LANCE_STORAGE_ALTER_TABLE_INVALID_ARGS",
1158
+ domain: error.ErrorDomain.STORAGE,
1159
+ category: error.ErrorCategory.USER,
1160
+ text: validationError.message,
1161
+ details: { tableName }
1162
+ },
1163
+ validationError
1164
+ );
1165
+ }
1166
+ try {
1167
+ const table = await this.client.openTable(tableName);
1168
+ const currentSchema = await table.schema();
1169
+ const existingFields = new Set(currentSchema.fields.map((f) => f.name));
1170
+ const typeMap = {
1171
+ text: "string",
1172
+ integer: "int",
1173
+ bigint: "bigint",
1174
+ timestamp: "timestamp",
1175
+ jsonb: "string",
1176
+ uuid: "string"
1177
+ };
1178
+ const columnsToAdd = ifNotExists.filter((col) => schema[col] && !existingFields.has(col)).map((col) => {
1179
+ const colDef = schema[col];
1180
+ return {
1181
+ name: col,
1182
+ valueSql: colDef?.nullable ? `cast(NULL as ${typeMap[colDef.type ?? "text"]})` : `cast(${this.getDefaultValue(colDef?.type ?? "text")} as ${typeMap[colDef?.type ?? "text"]})`
1183
+ };
1184
+ });
1185
+ if (columnsToAdd.length > 0) {
1186
+ await table.addColumns(columnsToAdd);
1187
+ this.logger?.info?.(`Added columns [${columnsToAdd.map((c) => c.name).join(", ")}] to table ${tableName}`);
1188
+ }
1189
+ } catch (error$1) {
1190
+ throw new error.MastraError(
1191
+ {
1192
+ id: "STORAGE_LANCE_STORAGE_ALTER_TABLE_FAILED",
1193
+ domain: error.ErrorDomain.STORAGE,
1194
+ category: error.ErrorCategory.THIRD_PARTY,
1195
+ details: { tableName }
1196
+ },
1197
+ error$1
1198
+ );
1199
+ }
1200
+ }
1201
+ async clearTable({ tableName }) {
1202
+ try {
1203
+ if (!this.client) {
1204
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1205
+ }
1206
+ if (!tableName) {
1207
+ throw new Error("tableName is required for clearTable.");
1208
+ }
1209
+ } catch (validationError) {
1210
+ throw new error.MastraError(
1211
+ {
1212
+ id: "STORAGE_LANCE_STORAGE_CLEAR_TABLE_INVALID_ARGS",
1213
+ domain: error.ErrorDomain.STORAGE,
1214
+ category: error.ErrorCategory.USER,
1215
+ text: validationError.message,
1216
+ details: { tableName }
1217
+ },
1218
+ validationError
1219
+ );
1220
+ }
1221
+ try {
1222
+ const table = await this.client.openTable(tableName);
1223
+ await table.delete("1=1");
1224
+ } catch (error$1) {
1225
+ throw new error.MastraError(
1226
+ {
1227
+ id: "STORAGE_LANCE_STORAGE_CLEAR_TABLE_FAILED",
1228
+ domain: error.ErrorDomain.STORAGE,
1229
+ category: error.ErrorCategory.THIRD_PARTY,
1230
+ details: { tableName }
1231
+ },
1232
+ error$1
1233
+ );
1234
+ }
1235
+ }
1236
+ async insert({ tableName, record }) {
1237
+ try {
1238
+ if (!this.client) {
1239
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1240
+ }
1241
+ if (!tableName) {
1242
+ throw new Error("tableName is required for insert.");
1243
+ }
1244
+ if (!record || Object.keys(record).length === 0) {
1245
+ throw new Error("record is required and cannot be empty for insert.");
1246
+ }
1247
+ } catch (validationError) {
1248
+ throw new error.MastraError(
1249
+ {
1250
+ id: "STORAGE_LANCE_STORAGE_INSERT_INVALID_ARGS",
1251
+ domain: error.ErrorDomain.STORAGE,
1252
+ category: error.ErrorCategory.USER,
1253
+ text: validationError.message,
1254
+ details: { tableName }
1255
+ },
1256
+ validationError
1257
+ );
1258
+ }
1259
+ try {
1260
+ const table = await this.client.openTable(tableName);
1261
+ const primaryId = getPrimaryKeys(tableName);
1262
+ const processedRecord = { ...record };
1263
+ for (const key in processedRecord) {
1264
+ if (processedRecord[key] !== null && typeof processedRecord[key] === "object" && !(processedRecord[key] instanceof Date)) {
1265
+ this.logger.debug("Converting object to JSON string: ", processedRecord[key]);
1266
+ processedRecord[key] = JSON.stringify(processedRecord[key]);
1267
+ }
1268
+ }
1269
+ console.log(await table.schema());
1270
+ await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([processedRecord]);
1271
+ } catch (error$1) {
1272
+ throw new error.MastraError(
1273
+ {
1274
+ id: "STORAGE_LANCE_STORAGE_INSERT_FAILED",
1275
+ domain: error.ErrorDomain.STORAGE,
1276
+ category: error.ErrorCategory.THIRD_PARTY,
1277
+ details: { tableName }
1278
+ },
1279
+ error$1
1280
+ );
1281
+ }
1282
+ }
1283
+ async batchInsert({ tableName, records }) {
1284
+ try {
1285
+ if (!this.client) {
1286
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1287
+ }
1288
+ if (!tableName) {
1289
+ throw new Error("tableName is required for batchInsert.");
1290
+ }
1291
+ if (!records || records.length === 0) {
1292
+ throw new Error("records array is required and cannot be empty for batchInsert.");
1293
+ }
1294
+ } catch (validationError) {
1295
+ throw new error.MastraError(
1296
+ {
1297
+ id: "STORAGE_LANCE_STORAGE_BATCH_INSERT_INVALID_ARGS",
1298
+ domain: error.ErrorDomain.STORAGE,
1299
+ category: error.ErrorCategory.USER,
1300
+ text: validationError.message,
1301
+ details: { tableName }
1302
+ },
1303
+ validationError
1304
+ );
1305
+ }
1306
+ try {
1307
+ const table = await this.client.openTable(tableName);
1308
+ const primaryId = getPrimaryKeys(tableName);
1309
+ const processedRecords = records.map((record) => {
1310
+ const processedRecord = { ...record };
1311
+ for (const key in processedRecord) {
1312
+ if (processedRecord[key] == null) continue;
1313
+ if (processedRecord[key] !== null && typeof processedRecord[key] === "object" && !(processedRecord[key] instanceof Date)) {
1314
+ processedRecord[key] = JSON.stringify(processedRecord[key]);
1315
+ }
1316
+ }
1317
+ return processedRecord;
1318
+ });
1319
+ console.log(processedRecords);
1320
+ await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(processedRecords);
1321
+ } catch (error$1) {
1322
+ throw new error.MastraError(
1323
+ {
1324
+ id: "STORAGE_LANCE_STORAGE_BATCH_INSERT_FAILED",
1325
+ domain: error.ErrorDomain.STORAGE,
1326
+ category: error.ErrorCategory.THIRD_PARTY,
1327
+ details: { tableName }
1328
+ },
1329
+ error$1
1330
+ );
1331
+ }
1332
+ }
1333
+ async load({ tableName, keys }) {
1334
+ try {
1335
+ if (!this.client) {
1336
+ throw new Error("LanceDB client not initialized. Call LanceStorage.create() first.");
1337
+ }
1338
+ if (!tableName) {
1339
+ throw new Error("tableName is required for load.");
1340
+ }
1341
+ if (!keys || Object.keys(keys).length === 0) {
1342
+ throw new Error("keys are required and cannot be empty for load.");
1343
+ }
1344
+ } catch (validationError) {
1345
+ throw new error.MastraError(
1346
+ {
1347
+ id: "STORAGE_LANCE_STORAGE_LOAD_INVALID_ARGS",
1348
+ domain: error.ErrorDomain.STORAGE,
1349
+ category: error.ErrorCategory.USER,
1350
+ text: validationError.message,
1351
+ details: { tableName }
1352
+ },
1353
+ validationError
1354
+ );
1355
+ }
1356
+ try {
1357
+ const table = await this.client.openTable(tableName);
1358
+ const tableSchema = await getTableSchema({ tableName, client: this.client });
1359
+ const query = table.query();
1360
+ if (Object.keys(keys).length > 0) {
1361
+ validateKeyTypes(keys, tableSchema);
1362
+ const filterConditions = Object.entries(keys).map(([key, value]) => {
1363
+ const isCamelCase = /^[a-z][a-zA-Z]*$/.test(key) && /[A-Z]/.test(key);
1364
+ const quotedKey = isCamelCase ? `\`${key}\`` : key;
1365
+ if (typeof value === "string") {
1366
+ return `${quotedKey} = '${value}'`;
1367
+ } else if (value === null) {
1368
+ return `${quotedKey} IS NULL`;
1369
+ } else {
1370
+ return `${quotedKey} = ${value}`;
1371
+ }
1372
+ }).join(" AND ");
1373
+ this.logger.debug("where clause generated: " + filterConditions);
1374
+ query.where(filterConditions);
1375
+ }
1376
+ const result = await query.limit(1).toArray();
1377
+ if (result.length === 0) {
1378
+ this.logger.debug("No record found");
1379
+ return null;
1380
+ }
1381
+ return processResultWithTypeConversion(result[0], tableSchema);
1382
+ } catch (error$1) {
1383
+ if (error$1 instanceof error.MastraError) throw error$1;
1384
+ throw new error.MastraError(
1385
+ {
1386
+ id: "STORAGE_LANCE_STORAGE_LOAD_FAILED",
1387
+ domain: error.ErrorDomain.STORAGE,
1388
+ category: error.ErrorCategory.THIRD_PARTY,
1389
+ details: { tableName, keyCount: Object.keys(keys).length, firstKey: Object.keys(keys)[0] ?? "" }
1390
+ },
1391
+ error$1
1392
+ );
1393
+ }
1394
+ }
1395
+ };
1396
+ var StoreScoresLance = class extends storage.ScoresStorage {
1397
+ client;
1398
+ constructor({ client }) {
1399
+ super();
1400
+ this.client = client;
1401
+ }
1402
+ async saveScore(score) {
1403
+ try {
1404
+ const id = crypto.randomUUID();
1405
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1406
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1407
+ const allowedFields = new Set(schema.fields.map((f) => f.name));
1408
+ const filteredScore = {};
1409
+ Object.keys(score).forEach((key) => {
1410
+ if (allowedFields.has(key)) {
1411
+ filteredScore[key] = score[key];
1412
+ }
1413
+ });
1414
+ for (const key in filteredScore) {
1415
+ if (filteredScore[key] !== null && typeof filteredScore[key] === "object" && !(filteredScore[key] instanceof Date)) {
1416
+ filteredScore[key] = JSON.stringify(filteredScore[key]);
1417
+ }
1418
+ }
1419
+ filteredScore.id = id;
1420
+ await table.add([filteredScore], { mode: "append" });
1421
+ return { score };
1422
+ } catch (error$1) {
1423
+ throw new error.MastraError(
1424
+ {
1425
+ id: "LANCE_STORAGE_SAVE_SCORE_FAILED",
1426
+ text: "Failed to save score in LanceStorage",
1427
+ domain: error.ErrorDomain.STORAGE,
1428
+ category: error.ErrorCategory.THIRD_PARTY,
1429
+ details: { error: error$1?.message }
1430
+ },
1431
+ error$1
1432
+ );
1433
+ }
1434
+ }
1435
+ async getScoreById({ id }) {
1436
+ try {
1437
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1438
+ const query = table.query().where(`id = '${id}'`).limit(1);
1439
+ const records = await query.toArray();
1440
+ if (records.length === 0) return null;
1441
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1442
+ return processResultWithTypeConversion(records[0], schema);
1443
+ } catch (error$1) {
1444
+ throw new error.MastraError(
1445
+ {
1446
+ id: "LANCE_STORAGE_GET_SCORE_BY_ID_FAILED",
1447
+ text: "Failed to get score by id in LanceStorage",
1448
+ domain: error.ErrorDomain.STORAGE,
1449
+ category: error.ErrorCategory.THIRD_PARTY,
1450
+ details: { error: error$1?.message }
1451
+ },
1452
+ error$1
1453
+ );
1454
+ }
1455
+ }
1456
+ async getScoresByScorerId({
1457
+ scorerId,
1458
+ pagination,
1459
+ entityId,
1460
+ entityType,
1461
+ source
1462
+ }) {
1463
+ try {
1464
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1465
+ const { page = 0, perPage = 10 } = pagination || {};
1466
+ const offset = page * perPage;
1467
+ let query = table.query().where(`\`scorerId\` = '${scorerId}'`);
1468
+ if (source) {
1469
+ query = query.where(`\`source\` = '${source}'`);
1470
+ }
1471
+ if (entityId) {
1472
+ query = query.where(`\`entityId\` = '${entityId}'`);
1473
+ }
1474
+ if (entityType) {
1475
+ query = query.where(`\`entityType\` = '${entityType}'`);
1476
+ }
1477
+ query = query.limit(perPage);
1478
+ if (offset > 0) query.offset(offset);
1479
+ const records = await query.toArray();
1480
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1481
+ const scores = processResultWithTypeConversion(records, schema);
1482
+ let totalQuery = table.query().where(`\`scorerId\` = '${scorerId}'`);
1483
+ if (source) {
1484
+ totalQuery = totalQuery.where(`\`source\` = '${source}'`);
1485
+ }
1486
+ const allRecords = await totalQuery.toArray();
1487
+ const total = allRecords.length;
1488
+ return {
1489
+ pagination: {
1490
+ page,
1491
+ perPage,
1492
+ total,
1493
+ hasMore: offset + scores.length < total
1494
+ },
1495
+ scores
1496
+ };
1497
+ } catch (error$1) {
1498
+ throw new error.MastraError(
1499
+ {
1500
+ id: "LANCE_STORAGE_GET_SCORES_BY_SCORER_ID_FAILED",
1501
+ text: "Failed to get scores by scorerId in LanceStorage",
1502
+ domain: error.ErrorDomain.STORAGE,
1503
+ category: error.ErrorCategory.THIRD_PARTY,
1504
+ details: { error: error$1?.message }
1505
+ },
1506
+ error$1
1507
+ );
1508
+ }
1509
+ }
1510
+ async getScoresByRunId({
1511
+ runId,
1512
+ pagination
1513
+ }) {
1514
+ try {
1515
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1516
+ const { page = 0, perPage = 10 } = pagination || {};
1517
+ const offset = page * perPage;
1518
+ const query = table.query().where(`\`runId\` = '${runId}'`).limit(perPage);
1519
+ if (offset > 0) query.offset(offset);
1520
+ const records = await query.toArray();
1521
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1522
+ const scores = processResultWithTypeConversion(records, schema);
1523
+ const allRecords = await table.query().where(`\`runId\` = '${runId}'`).toArray();
1524
+ const total = allRecords.length;
1525
+ return {
1526
+ pagination: {
1527
+ page,
1528
+ perPage,
1529
+ total,
1530
+ hasMore: offset + scores.length < total
1531
+ },
1532
+ scores
1533
+ };
1534
+ } catch (error$1) {
1535
+ throw new error.MastraError(
1536
+ {
1537
+ id: "LANCE_STORAGE_GET_SCORES_BY_RUN_ID_FAILED",
1538
+ text: "Failed to get scores by runId in LanceStorage",
1539
+ domain: error.ErrorDomain.STORAGE,
1540
+ category: error.ErrorCategory.THIRD_PARTY,
1541
+ details: { error: error$1?.message }
1542
+ },
1543
+ error$1
1544
+ );
1545
+ }
1546
+ }
1547
+ async getScoresByEntityId({
1548
+ entityId,
1549
+ entityType,
1550
+ pagination
1551
+ }) {
1552
+ try {
1553
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1554
+ const { page = 0, perPage = 10 } = pagination || {};
1555
+ const offset = page * perPage;
1556
+ const query = table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).limit(perPage);
1557
+ if (offset > 0) query.offset(offset);
1558
+ const records = await query.toArray();
1559
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1560
+ const scores = processResultWithTypeConversion(records, schema);
1561
+ const allRecords = await table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).toArray();
1562
+ const total = allRecords.length;
1563
+ return {
1564
+ pagination: {
1565
+ page,
1566
+ perPage,
1567
+ total,
1568
+ hasMore: offset + scores.length < total
1569
+ },
1570
+ scores
1571
+ };
1572
+ } catch (error$1) {
1573
+ throw new error.MastraError(
1574
+ {
1575
+ id: "LANCE_STORAGE_GET_SCORES_BY_ENTITY_ID_FAILED",
1576
+ text: "Failed to get scores by entityId and entityType in LanceStorage",
1577
+ domain: error.ErrorDomain.STORAGE,
1578
+ category: error.ErrorCategory.THIRD_PARTY,
1579
+ details: { error: error$1?.message }
1580
+ },
1581
+ error$1
1582
+ );
1583
+ }
1584
+ }
1585
+ };
1586
+ var StoreTracesLance = class extends storage.TracesStorage {
1587
+ client;
1588
+ operations;
1589
+ constructor({ client, operations }) {
1590
+ super();
1591
+ this.client = client;
1592
+ this.operations = operations;
1593
+ }
1594
+ async saveTrace({ trace }) {
1595
+ try {
1596
+ const table = await this.client.openTable(storage.TABLE_TRACES);
1597
+ const record = {
1598
+ ...trace,
1599
+ attributes: JSON.stringify(trace.attributes),
1600
+ status: JSON.stringify(trace.status),
1601
+ events: JSON.stringify(trace.events),
1602
+ links: JSON.stringify(trace.links),
1603
+ other: JSON.stringify(trace.other)
1604
+ };
1605
+ await table.add([record], { mode: "append" });
1606
+ return trace;
1607
+ } catch (error$1) {
1608
+ throw new error.MastraError(
1609
+ {
1610
+ id: "LANCE_STORE_SAVE_TRACE_FAILED",
1611
+ domain: error.ErrorDomain.STORAGE,
1612
+ category: error.ErrorCategory.THIRD_PARTY
1613
+ },
1614
+ error$1
1615
+ );
1616
+ }
1617
+ }
1618
+ async getTraceById({ traceId }) {
1619
+ try {
1620
+ const table = await this.client.openTable(storage.TABLE_TRACES);
1621
+ const query = table.query().where(`id = '${traceId}'`);
1622
+ const records = await query.toArray();
1623
+ return records[0];
1624
+ } catch (error$1) {
1625
+ throw new error.MastraError(
1626
+ {
1627
+ id: "LANCE_STORE_GET_TRACE_BY_ID_FAILED",
1628
+ domain: error.ErrorDomain.STORAGE,
1629
+ category: error.ErrorCategory.THIRD_PARTY
1630
+ },
1631
+ error$1
1632
+ );
1633
+ }
1634
+ }
1635
+ async getTraces({
1636
+ name,
1637
+ scope,
1638
+ page = 1,
1639
+ perPage = 10,
1640
+ attributes
1641
+ }) {
1642
+ try {
1643
+ const table = await this.client.openTable(storage.TABLE_TRACES);
1644
+ const query = table.query();
1645
+ if (name) {
1646
+ query.where(`name = '${name}'`);
1647
+ }
1648
+ if (scope) {
1649
+ query.where(`scope = '${scope}'`);
1650
+ }
1651
+ if (attributes) {
1652
+ query.where(`attributes = '${JSON.stringify(attributes)}'`);
1653
+ }
1654
+ const offset = (page - 1) * perPage;
1655
+ query.limit(perPage);
1656
+ if (offset > 0) {
1657
+ query.offset(offset);
1658
+ }
1659
+ const records = await query.toArray();
1660
+ return records.map((record) => {
1661
+ const processed = {
1662
+ ...record,
1663
+ attributes: record.attributes ? JSON.parse(record.attributes) : {},
1664
+ status: record.status ? JSON.parse(record.status) : {},
1665
+ events: record.events ? JSON.parse(record.events) : [],
1666
+ links: record.links ? JSON.parse(record.links) : [],
1667
+ other: record.other ? JSON.parse(record.other) : {},
1668
+ startTime: new Date(record.startTime),
1669
+ endTime: new Date(record.endTime),
1670
+ createdAt: new Date(record.createdAt)
1671
+ };
1672
+ if (processed.parentSpanId === null || processed.parentSpanId === void 0) {
1673
+ processed.parentSpanId = "";
1674
+ } else {
1675
+ processed.parentSpanId = String(processed.parentSpanId);
1676
+ }
1677
+ return processed;
1678
+ });
1679
+ } catch (error$1) {
1680
+ throw new error.MastraError(
1681
+ {
1682
+ id: "LANCE_STORE_GET_TRACES_FAILED",
1683
+ domain: error.ErrorDomain.STORAGE,
1684
+ category: error.ErrorCategory.THIRD_PARTY,
1685
+ details: { name: name ?? "", scope: scope ?? "" }
1686
+ },
1687
+ error$1
1688
+ );
1689
+ }
1690
+ }
1691
+ async getTracesPaginated(args) {
1692
+ try {
1693
+ const table = await this.client.openTable(storage.TABLE_TRACES);
1694
+ const query = table.query();
1695
+ const conditions = [];
1696
+ if (args.name) {
1697
+ conditions.push(`name = '${args.name}'`);
1698
+ }
1699
+ if (args.scope) {
1700
+ conditions.push(`scope = '${args.scope}'`);
1701
+ }
1702
+ if (args.attributes) {
1703
+ const attributesStr = JSON.stringify(args.attributes);
1704
+ conditions.push(`attributes LIKE '%${attributesStr.replace(/"/g, '\\"')}%'`);
1705
+ }
1706
+ if (args.dateRange?.start) {
1707
+ conditions.push(`\`createdAt\` >= ${args.dateRange.start.getTime()}`);
1708
+ }
1709
+ if (args.dateRange?.end) {
1710
+ conditions.push(`\`createdAt\` <= ${args.dateRange.end.getTime()}`);
1711
+ }
1712
+ if (conditions.length > 0) {
1713
+ const whereClause = conditions.join(" AND ");
1714
+ query.where(whereClause);
1715
+ }
1716
+ let total = 0;
1717
+ if (conditions.length > 0) {
1718
+ const countQuery = table.query().where(conditions.join(" AND "));
1719
+ const allRecords = await countQuery.toArray();
1720
+ total = allRecords.length;
1721
+ } else {
1722
+ total = await table.countRows();
1723
+ }
1724
+ const page = args.page || 0;
1725
+ const perPage = args.perPage || 10;
1726
+ const offset = page * perPage;
1727
+ query.limit(perPage);
1728
+ if (offset > 0) {
1729
+ query.offset(offset);
1730
+ }
1731
+ const records = await query.toArray();
1732
+ const traces = records.map((record) => {
1733
+ const processed = {
1734
+ ...record,
1735
+ attributes: record.attributes ? JSON.parse(record.attributes) : {},
1736
+ status: record.status ? JSON.parse(record.status) : {},
1737
+ events: record.events ? JSON.parse(record.events) : [],
1738
+ links: record.links ? JSON.parse(record.links) : [],
1739
+ other: record.other ? JSON.parse(record.other) : {},
1740
+ startTime: new Date(record.startTime),
1741
+ endTime: new Date(record.endTime),
1742
+ createdAt: new Date(record.createdAt)
1743
+ };
1744
+ if (processed.parentSpanId === null || processed.parentSpanId === void 0) {
1745
+ processed.parentSpanId = "";
1746
+ } else {
1747
+ processed.parentSpanId = String(processed.parentSpanId);
1748
+ }
1749
+ return processed;
1750
+ });
1751
+ return {
1752
+ traces,
1753
+ total,
1754
+ page,
1755
+ perPage,
1756
+ hasMore: total > (page + 1) * perPage
1757
+ };
1758
+ } catch (error$1) {
1759
+ throw new error.MastraError(
1760
+ {
1761
+ id: "LANCE_STORE_GET_TRACES_PAGINATED_FAILED",
1762
+ domain: error.ErrorDomain.STORAGE,
1763
+ category: error.ErrorCategory.THIRD_PARTY,
1764
+ details: { name: args.name ?? "", scope: args.scope ?? "" }
1765
+ },
1766
+ error$1
1767
+ );
1768
+ }
1769
+ }
1770
+ async batchTraceInsert({ records }) {
1771
+ this.logger.debug("Batch inserting traces", { count: records.length });
1772
+ await this.operations.batchInsert({
1773
+ tableName: storage.TABLE_TRACES,
1774
+ records
1775
+ });
1776
+ }
1777
+ };
1778
+ function parseWorkflowRun(row) {
1779
+ let parsedSnapshot = row.snapshot;
1780
+ if (typeof parsedSnapshot === "string") {
1781
+ try {
1782
+ parsedSnapshot = JSON.parse(row.snapshot);
1783
+ } catch (e) {
1784
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1785
+ }
1786
+ }
1787
+ return {
1788
+ workflowName: row.workflow_name,
1789
+ runId: row.run_id,
1790
+ snapshot: parsedSnapshot,
1791
+ createdAt: storage.ensureDate(row.createdAt),
1792
+ updatedAt: storage.ensureDate(row.updatedAt),
1793
+ resourceId: row.resourceId
1794
+ };
1795
+ }
1796
+ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1797
+ client;
1798
+ constructor({ client }) {
1799
+ super();
1800
+ this.client = client;
1801
+ }
1802
+ updateWorkflowResults({
1803
+ // workflowName,
1804
+ // runId,
1805
+ // stepId,
1806
+ // result,
1807
+ // runtimeContext,
1808
+ }) {
1809
+ throw new Error("Method not implemented.");
1810
+ }
1811
+ updateWorkflowState({
1812
+ // workflowName,
1813
+ // runId,
1814
+ // opts,
1815
+ }) {
1816
+ throw new Error("Method not implemented.");
1817
+ }
1818
+ async persistWorkflowSnapshot({
1819
+ workflowName,
1820
+ runId,
1821
+ snapshot
1822
+ }) {
1823
+ try {
1824
+ const table = await this.client.openTable(storage.TABLE_WORKFLOW_SNAPSHOT);
1825
+ const query = table.query().where(`workflow_name = '${workflowName}' AND run_id = '${runId}'`);
1826
+ const records = await query.toArray();
1827
+ let createdAt;
1828
+ const now = Date.now();
1829
+ if (records.length > 0) {
1830
+ createdAt = records[0].createdAt ?? now;
1831
+ } else {
1832
+ createdAt = now;
1833
+ }
1834
+ const record = {
1835
+ workflow_name: workflowName,
1836
+ run_id: runId,
1837
+ snapshot: JSON.stringify(snapshot),
1838
+ createdAt,
1839
+ updatedAt: now
1840
+ };
1841
+ await table.mergeInsert(["workflow_name", "run_id"]).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([record]);
1842
+ } catch (error$1) {
1843
+ throw new error.MastraError(
1844
+ {
1845
+ id: "LANCE_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1846
+ domain: error.ErrorDomain.STORAGE,
1847
+ category: error.ErrorCategory.THIRD_PARTY,
1848
+ details: { workflowName, runId }
1849
+ },
1850
+ error$1
1851
+ );
1852
+ }
1853
+ }
1854
+ async loadWorkflowSnapshot({
1855
+ workflowName,
1856
+ runId
1857
+ }) {
1858
+ try {
1859
+ const table = await this.client.openTable(storage.TABLE_WORKFLOW_SNAPSHOT);
1860
+ const query = table.query().where(`workflow_name = '${workflowName}' AND run_id = '${runId}'`);
1861
+ const records = await query.toArray();
1862
+ return records.length > 0 ? JSON.parse(records[0].snapshot) : null;
1863
+ } catch (error$1) {
1864
+ throw new error.MastraError(
1865
+ {
1866
+ id: "LANCE_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1867
+ domain: error.ErrorDomain.STORAGE,
1868
+ category: error.ErrorCategory.THIRD_PARTY,
1869
+ details: { workflowName, runId }
1870
+ },
1871
+ error$1
1872
+ );
1873
+ }
1874
+ }
1875
+ async getWorkflowRunById(args) {
1876
+ try {
1877
+ const table = await this.client.openTable(storage.TABLE_WORKFLOW_SNAPSHOT);
1878
+ let whereClause = `run_id = '${args.runId}'`;
1879
+ if (args.workflowName) {
1880
+ whereClause += ` AND workflow_name = '${args.workflowName}'`;
1881
+ }
1882
+ const query = table.query().where(whereClause);
1883
+ const records = await query.toArray();
1884
+ if (records.length === 0) return null;
1885
+ const record = records[0];
1886
+ return parseWorkflowRun(record);
1887
+ } catch (error$1) {
1888
+ throw new error.MastraError(
1889
+ {
1890
+ id: "LANCE_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1891
+ domain: error.ErrorDomain.STORAGE,
1892
+ category: error.ErrorCategory.THIRD_PARTY,
1893
+ details: { runId: args.runId, workflowName: args.workflowName ?? "" }
1894
+ },
1895
+ error$1
1896
+ );
1897
+ }
1898
+ }
1899
+ async getWorkflowRuns(args) {
1900
+ try {
1901
+ const table = await this.client.openTable(storage.TABLE_WORKFLOW_SNAPSHOT);
1902
+ let query = table.query();
1903
+ const conditions = [];
1904
+ if (args?.workflowName) {
1905
+ conditions.push(`workflow_name = '${args.workflowName.replace(/'/g, "''")}'`);
1906
+ }
1907
+ if (args?.resourceId) {
1908
+ conditions.push(`\`resourceId\` = '${args.resourceId}'`);
1909
+ }
1910
+ if (args?.fromDate instanceof Date) {
1911
+ conditions.push(`\`createdAt\` >= ${args.fromDate.getTime()}`);
1912
+ }
1913
+ if (args?.toDate instanceof Date) {
1914
+ conditions.push(`\`createdAt\` <= ${args.toDate.getTime()}`);
1915
+ }
1916
+ let total = 0;
1917
+ if (conditions.length > 0) {
1918
+ query = query.where(conditions.join(" AND "));
1919
+ total = await table.countRows(conditions.join(" AND "));
1920
+ } else {
1921
+ total = await table.countRows();
1922
+ }
1923
+ if (args?.limit) {
1924
+ query.limit(args.limit);
1925
+ }
1926
+ if (args?.offset) {
1927
+ query.offset(args.offset);
1928
+ }
1929
+ const records = await query.toArray();
1930
+ return {
1931
+ runs: records.map((record) => parseWorkflowRun(record)),
1932
+ total: total || records.length
1933
+ };
1934
+ } catch (error$1) {
1935
+ throw new error.MastraError(
1936
+ {
1937
+ id: "LANCE_STORE_GET_WORKFLOW_RUNS_FAILED",
1938
+ domain: error.ErrorDomain.STORAGE,
1939
+ category: error.ErrorCategory.THIRD_PARTY,
1940
+ details: { namespace: args?.namespace ?? "", workflowName: args?.workflowName ?? "" }
1941
+ },
1942
+ error$1
1943
+ );
1944
+ }
1945
+ }
1946
+ };
1947
+
1948
+ // src/storage/index.ts
1949
+ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
1950
+ stores;
1951
+ lanceClient;
1952
+ /**
1953
+ * Creates a new instance of LanceStorage
1954
+ * @param uri The URI to connect to LanceDB
1955
+ * @param options connection options
1956
+ *
1957
+ * Usage:
1958
+ *
1959
+ * Connect to a local database
1960
+ * ```ts
1961
+ * const store = await LanceStorage.create('/path/to/db');
1962
+ * ```
1963
+ *
1964
+ * Connect to a LanceDB cloud database
1965
+ * ```ts
1966
+ * const store = await LanceStorage.create('db://host:port');
1967
+ * ```
1968
+ *
1969
+ * Connect to a cloud database
1970
+ * ```ts
1971
+ * const store = await LanceStorage.create('s3://bucket/db', { storageOptions: { timeout: '60s' } });
1972
+ * ```
1973
+ */
1974
+ static async create(name, uri, options) {
1975
+ const instance = new _LanceStorage(name);
1976
+ try {
1977
+ instance.lanceClient = await lancedb.connect(uri, options);
1978
+ const operations = new StoreOperationsLance({ client: instance.lanceClient });
1979
+ instance.stores = {
1980
+ operations: new StoreOperationsLance({ client: instance.lanceClient }),
1981
+ workflows: new StoreWorkflowsLance({ client: instance.lanceClient }),
1982
+ traces: new StoreTracesLance({ client: instance.lanceClient, operations }),
1983
+ scores: new StoreScoresLance({ client: instance.lanceClient }),
1984
+ memory: new StoreMemoryLance({ client: instance.lanceClient, operations }),
1985
+ legacyEvals: new StoreLegacyEvalsLance({ client: instance.lanceClient })
1986
+ };
1987
+ return instance;
1988
+ } catch (e) {
1989
+ throw new error.MastraError(
1990
+ {
1991
+ id: "STORAGE_LANCE_STORAGE_CONNECT_FAILED",
1992
+ domain: error.ErrorDomain.STORAGE,
1993
+ category: error.ErrorCategory.THIRD_PARTY,
1994
+ text: `Failed to connect to LanceDB: ${e.message || e}`,
1995
+ details: { uri, optionsProvided: !!options }
1996
+ },
1997
+ e
1998
+ );
1999
+ }
2000
+ }
2001
+ /**
2002
+ * @internal
2003
+ * Private constructor to enforce using the create factory method
2004
+ */
2005
+ constructor(name) {
2006
+ super({ name });
2007
+ const operations = new StoreOperationsLance({ client: this.lanceClient });
2008
+ this.stores = {
2009
+ operations: new StoreOperationsLance({ client: this.lanceClient }),
2010
+ workflows: new StoreWorkflowsLance({ client: this.lanceClient }),
2011
+ traces: new StoreTracesLance({ client: this.lanceClient, operations }),
2012
+ scores: new StoreScoresLance({ client: this.lanceClient }),
2013
+ legacyEvals: new StoreLegacyEvalsLance({ client: this.lanceClient }),
2014
+ memory: new StoreMemoryLance({ client: this.lanceClient, operations })
2015
+ };
2016
+ }
2017
+ async createTable({
2018
+ tableName,
2019
+ schema
2020
+ }) {
2021
+ return this.stores.operations.createTable({ tableName, schema });
2022
+ }
2023
+ async dropTable({ tableName }) {
2024
+ return this.stores.operations.dropTable({ tableName });
2025
+ }
2026
+ async alterTable({
2027
+ tableName,
2028
+ schema,
2029
+ ifNotExists
2030
+ }) {
2031
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2032
+ }
2033
+ async clearTable({ tableName }) {
2034
+ return this.stores.operations.clearTable({ tableName });
2035
+ }
2036
+ async insert({ tableName, record }) {
2037
+ return this.stores.operations.insert({ tableName, record });
2038
+ }
2039
+ async batchInsert({ tableName, records }) {
2040
+ return this.stores.operations.batchInsert({ tableName, records });
2041
+ }
2042
+ async load({ tableName, keys }) {
2043
+ return this.stores.operations.load({ tableName, keys });
2044
+ }
2045
+ async getThreadById({ threadId }) {
2046
+ return this.stores.memory.getThreadById({ threadId });
2047
+ }
2048
+ async getThreadsByResourceId({ resourceId }) {
2049
+ return this.stores.memory.getThreadsByResourceId({ resourceId });
2050
+ }
2051
+ /**
2052
+ * Saves a thread to the database. This function doesn't overwrite existing threads.
2053
+ * @param thread - The thread to save
2054
+ * @returns The saved thread
2055
+ */
2056
+ async saveThread({ thread }) {
2057
+ return this.stores.memory.saveThread({ thread });
2058
+ }
2059
+ async updateThread({
2060
+ id,
2061
+ title,
2062
+ metadata
2063
+ }) {
2064
+ return this.stores.memory.updateThread({ id, title, metadata });
2065
+ }
2066
+ async deleteThread({ threadId }) {
2067
+ return this.stores.memory.deleteThread({ threadId });
2068
+ }
2069
+ get supports() {
2070
+ return {
2071
+ selectByIncludeResourceScope: true,
2072
+ resourceWorkingMemory: true,
2073
+ hasColumn: true,
2074
+ createTable: true,
2075
+ deleteMessages: false
2076
+ };
2077
+ }
2078
+ async getResourceById({ resourceId }) {
2079
+ return this.stores.memory.getResourceById({ resourceId });
2080
+ }
2081
+ async saveResource({ resource }) {
2082
+ return this.stores.memory.saveResource({ resource });
2083
+ }
2084
+ async updateResource({
2085
+ resourceId,
2086
+ workingMemory,
2087
+ metadata
2088
+ }) {
2089
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2090
+ }
2091
+ /**
2092
+ * Processes messages to include context messages based on withPreviousMessages and withNextMessages
2093
+ * @param records - The sorted array of records to process
2094
+ * @param include - The array of include specifications with context parameters
2095
+ * @returns The processed array with context messages included
2096
+ */
2097
+ processMessagesWithContext(records, include) {
2098
+ const messagesWithContext = include.filter((item) => item.withPreviousMessages || item.withNextMessages);
2099
+ if (messagesWithContext.length === 0) {
2100
+ return records;
2101
+ }
2102
+ const messageIndexMap = /* @__PURE__ */ new Map();
2103
+ records.forEach((message, index) => {
2104
+ messageIndexMap.set(message.id, index);
2105
+ });
2106
+ const additionalIndices = /* @__PURE__ */ new Set();
2107
+ for (const item of messagesWithContext) {
2108
+ const messageIndex = messageIndexMap.get(item.id);
2109
+ if (messageIndex !== void 0) {
2110
+ if (item.withPreviousMessages) {
2111
+ const startIdx = Math.max(0, messageIndex - item.withPreviousMessages);
2112
+ for (let i = startIdx; i < messageIndex; i++) {
2113
+ additionalIndices.add(i);
2114
+ }
2115
+ }
2116
+ if (item.withNextMessages) {
2117
+ const endIdx = Math.min(records.length - 1, messageIndex + item.withNextMessages);
2118
+ for (let i = messageIndex + 1; i <= endIdx; i++) {
2119
+ additionalIndices.add(i);
2120
+ }
2121
+ }
2122
+ }
2123
+ }
2124
+ if (additionalIndices.size === 0) {
2125
+ return records;
2126
+ }
2127
+ const originalMatchIds = new Set(include.map((item) => item.id));
2128
+ const allIndices = /* @__PURE__ */ new Set();
2129
+ records.forEach((record, index) => {
2130
+ if (originalMatchIds.has(record.id)) {
2131
+ allIndices.add(index);
2132
+ }
2133
+ });
2134
+ additionalIndices.forEach((index) => {
2135
+ allIndices.add(index);
2136
+ });
2137
+ return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
2138
+ }
2139
+ async getMessages({
2140
+ threadId,
2141
+ resourceId,
2142
+ selectBy,
2143
+ format,
2144
+ threadConfig
2145
+ }) {
2146
+ return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format, threadConfig });
2147
+ }
2148
+ async getMessagesById({
2149
+ messageIds,
2150
+ format
2151
+ }) {
2152
+ return this.stores.memory.getMessagesById({ messageIds, format });
2153
+ }
2154
+ async saveMessages(args) {
2155
+ return this.stores.memory.saveMessages(args);
2156
+ }
2157
+ async getThreadsByResourceIdPaginated(args) {
2158
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2159
+ }
2160
+ async getMessagesPaginated(args) {
2161
+ return this.stores.memory.getMessagesPaginated(args);
2162
+ }
2163
+ async updateMessages(_args) {
2164
+ return this.stores.memory.updateMessages(_args);
2165
+ }
2166
+ async getTraceById(args) {
2167
+ return this.stores.traces.getTraceById(args);
2168
+ }
2169
+ async getTraces(args) {
2170
+ return this.stores.traces.getTraces(args);
2171
+ }
2172
+ async getTracesPaginated(args) {
2173
+ return this.stores.traces.getTracesPaginated(args);
2174
+ }
2175
+ async getEvalsByAgentName(agentName, type) {
2176
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2177
+ }
2178
+ async getEvals(options) {
2179
+ return this.stores.legacyEvals.getEvals(options);
2180
+ }
2181
+ async getWorkflowRuns(args) {
2182
+ return this.stores.workflows.getWorkflowRuns(args);
2183
+ }
2184
+ async getWorkflowRunById(args) {
2185
+ return this.stores.workflows.getWorkflowRunById(args);
2186
+ }
2187
+ async updateWorkflowResults({
2188
+ workflowName,
2189
+ runId,
2190
+ stepId,
2191
+ result,
2192
+ runtimeContext
2193
+ }) {
2194
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2195
+ }
2196
+ async updateWorkflowState({
2197
+ workflowName,
2198
+ runId,
2199
+ opts
2200
+ }) {
2201
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2202
+ }
2203
+ async persistWorkflowSnapshot({
2204
+ workflowName,
2205
+ runId,
2206
+ snapshot
2207
+ }) {
2208
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2209
+ }
2210
+ async loadWorkflowSnapshot({
2211
+ workflowName,
2212
+ runId
2213
+ }) {
2214
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2215
+ }
2216
+ async getScoreById({ id: _id }) {
2217
+ return this.stores.scores.getScoreById({ id: _id });
2218
+ }
2219
+ async getScoresByScorerId({
2220
+ scorerId,
2221
+ source,
2222
+ entityId,
2223
+ entityType,
2224
+ pagination
2225
+ }) {
2226
+ return this.stores.scores.getScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
2227
+ }
2228
+ async saveScore(_score) {
2229
+ return this.stores.scores.saveScore(_score);
2230
+ }
2231
+ async getScoresByRunId({
2232
+ runId,
2233
+ pagination
2234
+ }) {
2235
+ return this.stores.scores.getScoresByRunId({ runId, pagination });
2236
+ }
2237
+ async getScoresByEntityId({
2238
+ entityId,
2239
+ entityType,
2240
+ pagination
2241
+ }) {
2242
+ return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2243
+ }
2244
+ };
2245
+ var LanceFilterTranslator = class extends filter.BaseFilterTranslator {
2246
+ translate(filter) {
2247
+ if (!filter || Object.keys(filter).length === 0) {
2248
+ return "";
2249
+ }
2250
+ if (typeof filter === "object" && filter !== null) {
2251
+ const keys = Object.keys(filter);
2252
+ for (const key of keys) {
2253
+ if (key.includes(".") && !this.isNormalNestedField(key)) {
2254
+ throw new Error(`Field names containing periods (.) are not supported: ${key}`);
2255
+ }
2256
+ }
2257
+ }
2258
+ return this.processFilter(filter);
2259
+ }
2260
+ processFilter(filter$1, parentPath = "") {
2261
+ if (filter$1 === null) {
2262
+ return `${parentPath} IS NULL`;
2263
+ }
2264
+ if (filter$1 instanceof Date) {
2265
+ return `${parentPath} = ${this.formatValue(filter$1)}`;
2266
+ }
2267
+ if (typeof filter$1 === "object" && filter$1 !== null) {
2268
+ const obj = filter$1;
2269
+ const keys = Object.keys(obj);
2270
+ if (keys.length === 1 && this.isOperator(keys[0])) {
2271
+ const operator = keys[0];
2272
+ const operatorValue = obj[operator];
2273
+ if (this.isLogicalOperator(operator)) {
2274
+ if (operator === "$and" || operator === "$or") {
2275
+ return this.processLogicalOperator(operator, operatorValue);
2276
+ }
2277
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(operator));
2278
+ }
2279
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.INVALID_TOP_LEVEL_OPERATOR(operator));
2280
+ }
2281
+ for (const key of keys) {
2282
+ if (key.includes(".") && !this.isNormalNestedField(key)) {
2283
+ throw new Error(`Field names containing periods (.) are not supported: ${key}`);
2284
+ }
2285
+ }
2286
+ if (keys.length > 1) {
2287
+ const conditions = keys.map((key) => {
2288
+ const value = obj[key];
2289
+ if (this.isNestedObject(value) && !this.isDateObject(value)) {
2290
+ return this.processNestedObject(key, value);
2291
+ } else {
2292
+ return this.processField(key, value);
2293
+ }
2294
+ });
2295
+ return conditions.join(" AND ");
2296
+ }
2297
+ if (keys.length === 1) {
2298
+ const key = keys[0];
2299
+ const value = obj[key];
2300
+ if (this.isNestedObject(value) && !this.isDateObject(value)) {
2301
+ return this.processNestedObject(key, value);
2302
+ } else {
2303
+ return this.processField(key, value);
2304
+ }
2305
+ }
2306
+ }
2307
+ return "";
2308
+ }
2309
+ processLogicalOperator(operator, conditions) {
2310
+ if (!Array.isArray(conditions)) {
2311
+ throw new Error(`Logical operator ${operator} must have an array value`);
2312
+ }
2313
+ if (conditions.length === 0) {
2314
+ return operator === "$and" ? "true" : "false";
2315
+ }
2316
+ const sqlOperator = operator === "$and" ? "AND" : "OR";
2317
+ const processedConditions = conditions.map((condition) => {
2318
+ if (typeof condition !== "object" || condition === null) {
2319
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.INVALID_LOGICAL_OPERATOR_CONTENT(operator));
2320
+ }
2321
+ const condObj = condition;
2322
+ const keys = Object.keys(condObj);
2323
+ if (keys.length === 1 && this.isOperator(keys[0])) {
2324
+ if (this.isLogicalOperator(keys[0])) {
2325
+ return `(${this.processLogicalOperator(keys[0], condObj[keys[0]])})`;
2326
+ } else {
2327
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(keys[0]));
2328
+ }
2329
+ }
2330
+ if (keys.length > 1) {
2331
+ return `(${this.processFilter(condition)})`;
2332
+ }
2333
+ return this.processFilter(condition);
2334
+ });
2335
+ return processedConditions.join(` ${sqlOperator} `);
2336
+ }
2337
+ processNestedObject(path, value) {
2338
+ if (typeof value !== "object" || value === null) {
2339
+ throw new Error(`Expected object for nested path ${path}`);
2340
+ }
2341
+ const obj = value;
2342
+ const keys = Object.keys(obj);
2343
+ if (keys.length === 0) {
2344
+ return `${path} = {}`;
2345
+ }
2346
+ if (keys.every((k) => this.isOperator(k))) {
2347
+ return this.processOperators(path, obj);
2348
+ }
2349
+ const conditions = keys.map((key) => {
2350
+ const nestedPath = key.includes(".") ? `${path}.${key}` : `${path}.${key}`;
2351
+ if (this.isNestedObject(obj[key]) && !this.isDateObject(obj[key])) {
2352
+ return this.processNestedObject(nestedPath, obj[key]);
2353
+ } else {
2354
+ return this.processField(nestedPath, obj[key]);
2355
+ }
2356
+ });
2357
+ return conditions.join(" AND ");
2358
+ }
2359
+ processField(field, value) {
2360
+ if (field.includes(".") && !this.isNormalNestedField(field)) {
2361
+ throw new Error(`Field names containing periods (.) are not supported: ${field}`);
2362
+ }
2363
+ const escapedField = this.escapeFieldName(field);
2364
+ if (value === null) {
2365
+ return `${escapedField} IS NULL`;
2366
+ }
2367
+ if (value instanceof Date) {
2368
+ return `${escapedField} = ${this.formatValue(value)}`;
2369
+ }
2370
+ if (Array.isArray(value)) {
2371
+ if (value.length === 0) {
2372
+ return "false";
2373
+ }
2374
+ const normalizedValues = this.normalizeArrayValues(value);
2375
+ return `${escapedField} IN (${this.formatArrayValues(normalizedValues)})`;
2376
+ }
2377
+ if (this.isOperatorObject(value)) {
2378
+ return this.processOperators(field, value);
2379
+ }
2380
+ return `${escapedField} = ${this.formatValue(this.normalizeComparisonValue(value))}`;
2381
+ }
2382
+ processOperators(field, operators) {
2383
+ const escapedField = this.escapeFieldName(field);
2384
+ const operatorKeys = Object.keys(operators);
2385
+ if (operatorKeys.some((op) => this.isLogicalOperator(op))) {
2386
+ const logicalOp = operatorKeys.find((op) => this.isLogicalOperator(op)) || "";
2387
+ throw new Error(`Unsupported operator: ${logicalOp} cannot be used at field level`);
2388
+ }
2389
+ return operatorKeys.map((op) => {
2390
+ const value = operators[op];
2391
+ if (!this.isFieldOperator(op) && !this.isCustomOperator(op)) {
2392
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(op));
2393
+ }
2394
+ switch (op) {
2395
+ case "$eq":
2396
+ if (value === null) {
2397
+ return `${escapedField} IS NULL`;
2398
+ }
2399
+ return `${escapedField} = ${this.formatValue(this.normalizeComparisonValue(value))}`;
2400
+ case "$ne":
2401
+ if (value === null) {
2402
+ return `${escapedField} IS NOT NULL`;
2403
+ }
2404
+ return `${escapedField} != ${this.formatValue(this.normalizeComparisonValue(value))}`;
2405
+ case "$gt":
2406
+ return `${escapedField} > ${this.formatValue(this.normalizeComparisonValue(value))}`;
2407
+ case "$gte":
2408
+ return `${escapedField} >= ${this.formatValue(this.normalizeComparisonValue(value))}`;
2409
+ case "$lt":
2410
+ return `${escapedField} < ${this.formatValue(this.normalizeComparisonValue(value))}`;
2411
+ case "$lte":
2412
+ return `${escapedField} <= ${this.formatValue(this.normalizeComparisonValue(value))}`;
2413
+ case "$in":
2414
+ if (!Array.isArray(value)) {
2415
+ throw new Error(`$in operator requires array value for field: ${field}`);
2416
+ }
2417
+ if (value.length === 0) {
2418
+ return "false";
2419
+ }
2420
+ const normalizedValues = this.normalizeArrayValues(value);
2421
+ return `${escapedField} IN (${this.formatArrayValues(normalizedValues)})`;
2422
+ case "$like":
2423
+ return `${escapedField} LIKE ${this.formatValue(value)}`;
2424
+ case "$notLike":
2425
+ return `${escapedField} NOT LIKE ${this.formatValue(value)}`;
2426
+ case "$regex":
2427
+ return `regexp_match(${escapedField}, ${this.formatValue(value)})`;
2428
+ default:
2429
+ throw new Error(filter.BaseFilterTranslator.ErrorMessages.UNSUPPORTED_OPERATOR(op));
2430
+ }
2431
+ }).join(" AND ");
2432
+ }
2433
+ formatValue(value) {
2434
+ if (value === null) {
2435
+ return "NULL";
2436
+ }
2437
+ if (typeof value === "string") {
2438
+ return `'${value.replace(/'/g, "''")}'`;
2439
+ }
2440
+ if (typeof value === "number") {
2441
+ return value.toString();
2442
+ }
2443
+ if (typeof value === "boolean") {
2444
+ return value ? "true" : "false";
2445
+ }
2446
+ if (value instanceof Date) {
2447
+ return `timestamp '${value.toISOString()}'`;
2448
+ }
2449
+ if (typeof value === "object") {
2450
+ if (value instanceof Date) {
2451
+ return `timestamp '${value.toISOString()}'`;
2452
+ }
2453
+ return JSON.stringify(value);
2454
+ }
2455
+ return String(value);
2456
+ }
2457
+ formatArrayValues(array) {
2458
+ return array.map((item) => this.formatValue(item)).join(", ");
2459
+ }
2460
+ normalizeArrayValues(array) {
2461
+ return array.map((item) => {
2462
+ if (item instanceof Date) {
2463
+ return item;
2464
+ }
2465
+ return this.normalizeComparisonValue(item);
2466
+ });
2467
+ }
2468
+ normalizeComparisonValue(value) {
2469
+ if (value instanceof Date) {
2470
+ return value;
2471
+ }
2472
+ return super.normalizeComparisonValue(value);
2473
+ }
2474
+ isOperatorObject(value) {
2475
+ if (typeof value !== "object" || value === null) {
2476
+ return false;
2477
+ }
2478
+ const obj = value;
2479
+ const keys = Object.keys(obj);
2480
+ return keys.length > 0 && keys.some((key) => this.isOperator(key));
2481
+ }
2482
+ isNestedObject(value) {
2483
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2484
+ }
2485
+ isNormalNestedField(field) {
2486
+ const parts = field.split(".");
2487
+ return !field.startsWith(".") && !field.endsWith(".") && parts.every((part) => part.trim().length > 0);
2488
+ }
2489
+ escapeFieldName(field) {
2490
+ if (field.includes(" ") || field.includes("-") || /^[A-Z]+$/.test(field) || this.isSqlKeyword(field)) {
2491
+ if (field.includes(".")) {
2492
+ return field.split(".").map((part) => `\`${part}\``).join(".");
2493
+ }
2494
+ return `\`${field}\``;
2495
+ }
2496
+ return field;
2497
+ }
2498
+ isSqlKeyword(str) {
2499
+ const sqlKeywords = [
2500
+ "SELECT",
2501
+ "FROM",
2502
+ "WHERE",
2503
+ "AND",
2504
+ "OR",
2505
+ "NOT",
2506
+ "INSERT",
2507
+ "UPDATE",
2508
+ "DELETE",
2509
+ "CREATE",
2510
+ "ALTER",
2511
+ "DROP",
2512
+ "TABLE",
2513
+ "VIEW",
2514
+ "INDEX",
2515
+ "JOIN",
2516
+ "INNER",
2517
+ "OUTER",
2518
+ "LEFT",
2519
+ "RIGHT",
2520
+ "FULL",
2521
+ "UNION",
2522
+ "ALL",
2523
+ "DISTINCT",
2524
+ "AS",
2525
+ "ON",
2526
+ "BETWEEN",
2527
+ "LIKE",
2528
+ "IN",
2529
+ "IS",
2530
+ "NULL",
2531
+ "TRUE",
2532
+ "FALSE",
2533
+ "ASC",
2534
+ "DESC",
2535
+ "GROUP",
2536
+ "ORDER",
2537
+ "BY",
2538
+ "HAVING",
2539
+ "LIMIT",
2540
+ "OFFSET",
2541
+ "CASE",
2542
+ "WHEN",
2543
+ "THEN",
2544
+ "ELSE",
2545
+ "END",
2546
+ "CAST",
2547
+ "CUBE"
2548
+ ];
2549
+ return sqlKeywords.includes(str.toUpperCase());
2550
+ }
2551
+ isDateObject(value) {
2552
+ return value instanceof Date;
2553
+ }
2554
+ /**
2555
+ * Override getSupportedOperators to add custom operators for LanceDB
2556
+ */
2557
+ getSupportedOperators() {
2558
+ return {
2559
+ ...filter.BaseFilterTranslator.DEFAULT_OPERATORS,
2560
+ custom: ["$like", "$notLike", "$regex"]
2561
+ };
2562
+ }
2563
+ };
2564
+
2565
+ // src/vector/index.ts
2566
+ var LanceVectorStore = class _LanceVectorStore extends vector.MastraVector {
2567
+ lanceClient;
2568
+ /**
2569
+ * Creates a new instance of LanceVectorStore
2570
+ * @param uri The URI to connect to LanceDB
2571
+ * @param options connection options
2572
+ *
2573
+ * Usage:
2574
+ *
2575
+ * Connect to a local database
2576
+ * ```ts
2577
+ * const store = await LanceVectorStore.create('/path/to/db');
2578
+ * ```
2579
+ *
2580
+ * Connect to a LanceDB cloud database
2581
+ * ```ts
2582
+ * const store = await LanceVectorStore.create('db://host:port');
2583
+ * ```
2584
+ *
2585
+ * Connect to a cloud database
2586
+ * ```ts
2587
+ * const store = await LanceVectorStore.create('s3://bucket/db', { storageOptions: { timeout: '60s' } });
2588
+ * ```
2589
+ */
2590
+ static async create(uri, options) {
2591
+ const instance = new _LanceVectorStore();
2592
+ try {
2593
+ instance.lanceClient = await lancedb.connect(uri, options);
2594
+ return instance;
2595
+ } catch (e) {
2596
+ throw new error.MastraError(
2597
+ {
2598
+ id: "STORAGE_LANCE_VECTOR_CONNECT_FAILED",
2599
+ domain: error.ErrorDomain.STORAGE,
2600
+ category: error.ErrorCategory.THIRD_PARTY,
2601
+ details: { uri }
2602
+ },
2603
+ e
2604
+ );
2605
+ }
2606
+ }
2607
+ /**
2608
+ * @internal
2609
+ * Private constructor to enforce using the create factory method
2610
+ */
2611
+ constructor() {
2612
+ super();
2613
+ }
2614
+ close() {
2615
+ if (this.lanceClient) {
2616
+ this.lanceClient.close();
2617
+ }
2618
+ }
2619
+ async query({
2620
+ tableName,
2621
+ queryVector,
2622
+ filter,
2623
+ includeVector = false,
2624
+ topK = 10,
2625
+ columns = [],
2626
+ includeAllColumns = false
2627
+ }) {
2628
+ try {
2629
+ if (!this.lanceClient) {
2630
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
2631
+ }
2632
+ if (!tableName) {
2633
+ throw new Error("tableName is required");
2634
+ }
2635
+ if (!queryVector) {
2636
+ throw new Error("queryVector is required");
2637
+ }
2638
+ } catch (error$1) {
2639
+ throw new error.MastraError(
2640
+ {
2641
+ id: "STORAGE_LANCE_VECTOR_QUERY_FAILED_INVALID_ARGS",
2642
+ domain: error.ErrorDomain.STORAGE,
2643
+ category: error.ErrorCategory.USER,
2644
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2645
+ details: { tableName }
2646
+ },
2647
+ error$1
2648
+ );
2649
+ }
2650
+ try {
2651
+ const table = await this.lanceClient.openTable(tableName);
2652
+ const selectColumns = [...columns];
2653
+ if (!selectColumns.includes("id")) {
2654
+ selectColumns.push("id");
2655
+ }
2656
+ let query = table.search(queryVector);
2657
+ if (filter && Object.keys(filter).length > 0) {
2658
+ const whereClause = this.filterTranslator(filter);
2659
+ this.logger.debug(`Where clause generated: ${whereClause}`);
2660
+ query = query.where(whereClause);
2661
+ }
2662
+ if (!includeAllColumns && selectColumns.length > 0) {
2663
+ query = query.select(selectColumns);
2664
+ }
2665
+ query = query.limit(topK);
2666
+ const results = await query.toArray();
2667
+ return results.map((result) => {
2668
+ const flatMetadata = {};
2669
+ Object.keys(result).forEach((key) => {
2670
+ if (key !== "id" && key !== "score" && key !== "vector" && key !== "_distance") {
2671
+ if (key.startsWith("metadata_")) {
2672
+ const metadataKey = key.substring("metadata_".length);
2673
+ flatMetadata[metadataKey] = result[key];
2674
+ }
2675
+ }
2676
+ });
2677
+ const metadata = this.unflattenObject(flatMetadata);
2678
+ return {
2679
+ id: String(result.id || ""),
2680
+ metadata,
2681
+ vector: includeVector && result.vector ? Array.isArray(result.vector) ? result.vector : Array.from(result.vector) : void 0,
2682
+ document: result.document,
2683
+ score: result._distance
2684
+ };
2685
+ });
2686
+ } catch (error$1) {
2687
+ throw new error.MastraError(
2688
+ {
2689
+ id: "STORAGE_LANCE_VECTOR_QUERY_FAILED",
2690
+ domain: error.ErrorDomain.STORAGE,
2691
+ category: error.ErrorCategory.THIRD_PARTY,
2692
+ details: { tableName, includeVector, columnsCount: columns?.length, includeAllColumns }
2693
+ },
2694
+ error$1
2695
+ );
2696
+ }
2697
+ }
2698
+ filterTranslator(filter) {
2699
+ const processFilterKeys = (filterObj) => {
2700
+ const result = {};
2701
+ Object.entries(filterObj).forEach(([key, value]) => {
2702
+ if (key === "$or" || key === "$and" || key === "$not" || key === "$in") {
2703
+ if (Array.isArray(value)) {
2704
+ result[key] = value.map(
2705
+ (item) => typeof item === "object" && item !== null ? processFilterKeys(item) : item
2706
+ );
2707
+ } else {
2708
+ result[key] = value;
2709
+ }
2710
+ } else if (key.startsWith("metadata_")) {
2711
+ result[key] = value;
2712
+ } else {
2713
+ if (key.includes(".")) {
2714
+ const convertedKey = `metadata_${key.replace(/\./g, "_")}`;
2715
+ result[convertedKey] = value;
2716
+ } else {
2717
+ result[`metadata_${key}`] = value;
2718
+ }
2719
+ }
2720
+ });
2721
+ return result;
2722
+ };
2723
+ const prefixedFilter = filter && typeof filter === "object" ? processFilterKeys(filter) : {};
2724
+ const translator = new LanceFilterTranslator();
2725
+ return translator.translate(prefixedFilter);
2726
+ }
2727
+ async upsert({ tableName, vectors, metadata = [], ids = [] }) {
2728
+ try {
2729
+ if (!this.lanceClient) {
2730
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
2731
+ }
2732
+ if (!tableName) {
2733
+ throw new Error("tableName is required");
2734
+ }
2735
+ if (!vectors || !Array.isArray(vectors) || vectors.length === 0) {
2736
+ throw new Error("vectors array is required and must not be empty");
2737
+ }
2738
+ } catch (error$1) {
2739
+ throw new error.MastraError(
2740
+ {
2741
+ id: "STORAGE_LANCE_VECTOR_UPSERT_FAILED_INVALID_ARGS",
2742
+ domain: error.ErrorDomain.STORAGE,
2743
+ category: error.ErrorCategory.USER,
2744
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2745
+ details: { tableName }
2746
+ },
2747
+ error$1
2748
+ );
2749
+ }
2750
+ try {
2751
+ const tables = await this.lanceClient.tableNames();
2752
+ if (!tables.includes(tableName)) {
2753
+ throw new Error(`Table ${tableName} does not exist`);
2754
+ }
2755
+ const table = await this.lanceClient.openTable(tableName);
2756
+ const vectorIds = ids.length === vectors.length ? ids : vectors.map((_, i) => ids[i] || crypto.randomUUID());
2757
+ const data = vectors.map((vector, i) => {
2758
+ const id = String(vectorIds[i]);
2759
+ const metadataItem = metadata[i] || {};
2760
+ const rowData = {
2761
+ id,
2762
+ vector
2763
+ };
2764
+ if (Object.keys(metadataItem).length > 0) {
2765
+ const flattenedMetadata = this.flattenObject(metadataItem, "metadata");
2766
+ Object.entries(flattenedMetadata).forEach(([key, value]) => {
2767
+ rowData[key] = value;
2768
+ });
2769
+ }
2770
+ return rowData;
2771
+ });
2772
+ await table.add(data, { mode: "overwrite" });
2773
+ return vectorIds;
2774
+ } catch (error$1) {
2775
+ throw new error.MastraError(
2776
+ {
2777
+ id: "STORAGE_LANCE_VECTOR_UPSERT_FAILED",
2778
+ domain: error.ErrorDomain.STORAGE,
2779
+ category: error.ErrorCategory.THIRD_PARTY,
2780
+ details: { tableName, vectorCount: vectors.length, metadataCount: metadata.length, idsCount: ids.length }
2781
+ },
2782
+ error$1
2783
+ );
2784
+ }
2785
+ }
2786
+ /**
2787
+ * Flattens a nested object, creating new keys with underscores for nested properties.
2788
+ * Example: { metadata: { text: 'test' } } → { metadata_text: 'test' }
2789
+ */
2790
+ flattenObject(obj, prefix = "") {
2791
+ return Object.keys(obj).reduce((acc, k) => {
2792
+ const pre = prefix.length ? `${prefix}_` : "";
2793
+ if (typeof obj[k] === "object" && obj[k] !== null && !Array.isArray(obj[k])) {
2794
+ Object.assign(acc, this.flattenObject(obj[k], pre + k));
2795
+ } else {
2796
+ acc[pre + k] = obj[k];
2797
+ }
2798
+ return acc;
2799
+ }, {});
2800
+ }
2801
+ async createTable(tableName, data, options) {
2802
+ if (!this.lanceClient) {
2803
+ throw new error.MastraError({
2804
+ id: "STORAGE_LANCE_VECTOR_CREATE_TABLE_FAILED_INVALID_ARGS",
2805
+ domain: error.ErrorDomain.STORAGE,
2806
+ category: error.ErrorCategory.USER,
2807
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2808
+ details: { tableName }
2809
+ });
2810
+ }
2811
+ if (Array.isArray(data)) {
2812
+ data = data.map((record) => this.flattenObject(record));
2813
+ }
2814
+ try {
2815
+ return await this.lanceClient.createTable(tableName, data, options);
2816
+ } catch (error$1) {
2817
+ throw new error.MastraError(
2818
+ {
2819
+ id: "STORAGE_LANCE_VECTOR_CREATE_TABLE_FAILED",
2820
+ domain: error.ErrorDomain.STORAGE,
2821
+ category: error.ErrorCategory.THIRD_PARTY,
2822
+ details: { tableName }
2823
+ },
2824
+ error$1
2825
+ );
2826
+ }
2827
+ }
2828
+ async listTables() {
2829
+ if (!this.lanceClient) {
2830
+ throw new error.MastraError({
2831
+ id: "STORAGE_LANCE_VECTOR_LIST_TABLES_FAILED_INVALID_ARGS",
2832
+ domain: error.ErrorDomain.STORAGE,
2833
+ category: error.ErrorCategory.USER,
2834
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2835
+ details: { methodName: "listTables" }
2836
+ });
2837
+ }
2838
+ try {
2839
+ return await this.lanceClient.tableNames();
2840
+ } catch (error$1) {
2841
+ throw new error.MastraError(
2842
+ {
2843
+ id: "STORAGE_LANCE_VECTOR_LIST_TABLES_FAILED",
2844
+ domain: error.ErrorDomain.STORAGE,
2845
+ category: error.ErrorCategory.THIRD_PARTY
2846
+ },
2847
+ error$1
2848
+ );
2849
+ }
2850
+ }
2851
+ async getTableSchema(tableName) {
2852
+ if (!this.lanceClient) {
2853
+ throw new error.MastraError({
2854
+ id: "STORAGE_LANCE_VECTOR_GET_TABLE_SCHEMA_FAILED_INVALID_ARGS",
2855
+ domain: error.ErrorDomain.STORAGE,
2856
+ category: error.ErrorCategory.USER,
2857
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2858
+ details: { tableName }
2859
+ });
2860
+ }
2861
+ try {
2862
+ const table = await this.lanceClient.openTable(tableName);
2863
+ return await table.schema();
2864
+ } catch (error$1) {
2865
+ throw new error.MastraError(
2866
+ {
2867
+ id: "STORAGE_LANCE_VECTOR_GET_TABLE_SCHEMA_FAILED",
2868
+ domain: error.ErrorDomain.STORAGE,
2869
+ category: error.ErrorCategory.THIRD_PARTY,
2870
+ details: { tableName }
2871
+ },
2872
+ error$1
2873
+ );
2874
+ }
2875
+ }
2876
+ /**
2877
+ * indexName is actually a column name in a table in lanceDB
2878
+ */
2879
+ async createIndex({
2880
+ tableName,
2881
+ indexName,
2882
+ dimension,
2883
+ metric = "cosine",
2884
+ indexConfig = {}
2885
+ }) {
2886
+ try {
2887
+ if (!this.lanceClient) {
2888
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
2889
+ }
2890
+ if (!tableName) {
2891
+ throw new Error("tableName is required");
2892
+ }
2893
+ if (!indexName) {
2894
+ throw new Error("indexName is required");
2895
+ }
2896
+ if (typeof dimension !== "number" || dimension <= 0) {
2897
+ throw new Error("dimension must be a positive number");
2898
+ }
2899
+ } catch (err) {
2900
+ throw new error.MastraError(
2901
+ {
2902
+ id: "STORAGE_LANCE_VECTOR_CREATE_INDEX_FAILED_INVALID_ARGS",
2903
+ domain: error.ErrorDomain.STORAGE,
2904
+ category: error.ErrorCategory.USER,
2905
+ details: { tableName: tableName || "", indexName, dimension, metric }
2906
+ },
2907
+ err
2908
+ );
2909
+ }
2910
+ try {
2911
+ const tables = await this.lanceClient.tableNames();
2912
+ if (!tables.includes(tableName)) {
2913
+ throw new Error(
2914
+ `Table ${tableName} does not exist. Please create the table first by calling createTable() method.`
2915
+ );
2916
+ }
2917
+ const table = await this.lanceClient.openTable(tableName);
2918
+ let metricType;
2919
+ if (metric === "euclidean") {
2920
+ metricType = "l2";
2921
+ } else if (metric === "dotproduct") {
2922
+ metricType = "dot";
2923
+ } else if (metric === "cosine") {
2924
+ metricType = "cosine";
2925
+ }
2926
+ if (indexConfig.type === "ivfflat") {
2927
+ await table.createIndex(indexName, {
2928
+ config: lancedb.Index.ivfPq({
2929
+ numPartitions: indexConfig.numPartitions || 128,
2930
+ numSubVectors: indexConfig.numSubVectors || 16,
2931
+ distanceType: metricType
2932
+ })
2933
+ });
2934
+ } else {
2935
+ this.logger.debug("Creating HNSW PQ index with config:", indexConfig);
2936
+ await table.createIndex(indexName, {
2937
+ config: lancedb.Index.hnswPq({
2938
+ m: indexConfig?.hnsw?.m || 16,
2939
+ efConstruction: indexConfig?.hnsw?.efConstruction || 100,
2940
+ distanceType: metricType
2941
+ })
2942
+ });
2943
+ }
2944
+ } catch (error$1) {
2945
+ throw new error.MastraError(
2946
+ {
2947
+ id: "STORAGE_LANCE_VECTOR_CREATE_INDEX_FAILED",
2948
+ domain: error.ErrorDomain.STORAGE,
2949
+ category: error.ErrorCategory.THIRD_PARTY,
2950
+ details: { tableName: tableName || "", indexName, dimension }
2951
+ },
2952
+ error$1
2953
+ );
2954
+ }
2955
+ }
2956
+ async listIndexes() {
2957
+ if (!this.lanceClient) {
2958
+ throw new error.MastraError({
2959
+ id: "STORAGE_LANCE_VECTOR_LIST_INDEXES_FAILED_INVALID_ARGS",
2960
+ domain: error.ErrorDomain.STORAGE,
2961
+ category: error.ErrorCategory.USER,
2962
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance",
2963
+ details: { methodName: "listIndexes" }
2964
+ });
2965
+ }
2966
+ try {
2967
+ const tables = await this.lanceClient.tableNames();
2968
+ const allIndices = [];
2969
+ for (const tableName of tables) {
2970
+ const table = await this.lanceClient.openTable(tableName);
2971
+ const tableIndices = await table.listIndices();
2972
+ allIndices.push(...tableIndices.map((index) => index.name));
2973
+ }
2974
+ return allIndices;
2975
+ } catch (error$1) {
2976
+ throw new error.MastraError(
2977
+ {
2978
+ id: "STORAGE_LANCE_VECTOR_LIST_INDEXES_FAILED",
2979
+ domain: error.ErrorDomain.STORAGE,
2980
+ category: error.ErrorCategory.THIRD_PARTY
2981
+ },
2982
+ error$1
2983
+ );
2984
+ }
2985
+ }
2986
+ async describeIndex({ indexName }) {
2987
+ try {
2988
+ if (!this.lanceClient) {
2989
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
2990
+ }
2991
+ if (!indexName) {
2992
+ throw new Error("indexName is required");
2993
+ }
2994
+ } catch (err) {
2995
+ throw new error.MastraError(
2996
+ {
2997
+ id: "STORAGE_LANCE_VECTOR_DESCRIBE_INDEX_FAILED_INVALID_ARGS",
2998
+ domain: error.ErrorDomain.STORAGE,
2999
+ category: error.ErrorCategory.USER,
3000
+ details: { indexName }
3001
+ },
3002
+ err
3003
+ );
3004
+ }
3005
+ try {
3006
+ const tables = await this.lanceClient.tableNames();
3007
+ for (const tableName of tables) {
3008
+ this.logger.debug("Checking table:" + tableName);
3009
+ const table = await this.lanceClient.openTable(tableName);
3010
+ const tableIndices = await table.listIndices();
3011
+ const foundIndex = tableIndices.find((index) => index.name === indexName);
3012
+ if (foundIndex) {
3013
+ const stats = await table.indexStats(foundIndex.name);
3014
+ if (!stats) {
3015
+ throw new Error(`Index stats not found for index: ${indexName}`);
3016
+ }
3017
+ const schema = await table.schema();
3018
+ const vectorCol = foundIndex.columns[0] || "vector";
3019
+ const vectorField = schema.fields.find((field) => field.name === vectorCol);
3020
+ const dimension = vectorField?.type?.["listSize"] || 0;
3021
+ return {
3022
+ dimension,
3023
+ metric: stats.distanceType,
3024
+ count: stats.numIndexedRows
3025
+ };
3026
+ }
3027
+ }
3028
+ throw new Error(`IndexName: ${indexName} not found`);
3029
+ } catch (error$1) {
3030
+ throw new error.MastraError(
3031
+ {
3032
+ id: "STORAGE_LANCE_VECTOR_DESCRIBE_INDEX_FAILED",
3033
+ domain: error.ErrorDomain.STORAGE,
3034
+ category: error.ErrorCategory.THIRD_PARTY,
3035
+ details: { indexName }
3036
+ },
3037
+ error$1
3038
+ );
3039
+ }
3040
+ }
3041
+ async deleteIndex({ indexName }) {
3042
+ try {
3043
+ if (!this.lanceClient) {
3044
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
3045
+ }
3046
+ if (!indexName) {
3047
+ throw new Error("indexName is required");
3048
+ }
3049
+ } catch (err) {
3050
+ throw new error.MastraError(
3051
+ {
3052
+ id: "STORAGE_LANCE_VECTOR_DELETE_INDEX_FAILED_INVALID_ARGS",
3053
+ domain: error.ErrorDomain.STORAGE,
3054
+ category: error.ErrorCategory.USER,
3055
+ details: { indexName }
3056
+ },
3057
+ err
3058
+ );
3059
+ }
3060
+ try {
3061
+ const tables = await this.lanceClient.tableNames();
3062
+ for (const tableName of tables) {
3063
+ const table = await this.lanceClient.openTable(tableName);
3064
+ const tableIndices = await table.listIndices();
3065
+ const foundIndex = tableIndices.find((index) => index.name === indexName);
3066
+ if (foundIndex) {
3067
+ await table.dropIndex(indexName);
3068
+ return;
3069
+ }
3070
+ }
3071
+ throw new Error(`Index ${indexName} not found`);
3072
+ } catch (error$1) {
3073
+ throw new error.MastraError(
3074
+ {
3075
+ id: "STORAGE_LANCE_VECTOR_DELETE_INDEX_FAILED",
3076
+ domain: error.ErrorDomain.STORAGE,
3077
+ category: error.ErrorCategory.THIRD_PARTY,
3078
+ details: { indexName }
3079
+ },
3080
+ error$1
3081
+ );
3082
+ }
3083
+ }
3084
+ /**
3085
+ * Deletes all tables in the database
3086
+ */
3087
+ async deleteAllTables() {
3088
+ if (!this.lanceClient) {
3089
+ throw new error.MastraError({
3090
+ id: "STORAGE_LANCE_VECTOR_DELETE_ALL_TABLES_FAILED_INVALID_ARGS",
3091
+ domain: error.ErrorDomain.STORAGE,
3092
+ category: error.ErrorCategory.USER,
3093
+ details: { methodName: "deleteAllTables" },
3094
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance"
3095
+ });
3096
+ }
3097
+ try {
3098
+ await this.lanceClient.dropAllTables();
3099
+ } catch (error$1) {
3100
+ throw new error.MastraError(
3101
+ {
3102
+ id: "STORAGE_LANCE_VECTOR_DELETE_ALL_TABLES_FAILED",
3103
+ domain: error.ErrorDomain.STORAGE,
3104
+ category: error.ErrorCategory.THIRD_PARTY,
3105
+ details: { methodName: "deleteAllTables" }
3106
+ },
3107
+ error$1
3108
+ );
3109
+ }
3110
+ }
3111
+ async deleteTable(tableName) {
3112
+ if (!this.lanceClient) {
3113
+ throw new error.MastraError({
3114
+ id: "STORAGE_LANCE_VECTOR_DELETE_TABLE_FAILED_INVALID_ARGS",
3115
+ domain: error.ErrorDomain.STORAGE,
3116
+ category: error.ErrorCategory.USER,
3117
+ details: { tableName },
3118
+ text: "LanceDB client not initialized. Use LanceVectorStore.create() to create an instance"
3119
+ });
3120
+ }
3121
+ try {
3122
+ await this.lanceClient.dropTable(tableName);
3123
+ } catch (error$1) {
3124
+ throw new error.MastraError(
3125
+ {
3126
+ id: "STORAGE_LANCE_VECTOR_DELETE_TABLE_FAILED",
3127
+ domain: error.ErrorDomain.STORAGE,
3128
+ category: error.ErrorCategory.THIRD_PARTY,
3129
+ details: { tableName }
3130
+ },
3131
+ error$1
3132
+ );
3133
+ }
3134
+ }
3135
+ async updateVector({ indexName, id, update }) {
3136
+ try {
3137
+ if (!this.lanceClient) {
3138
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
3139
+ }
3140
+ if (!indexName) {
3141
+ throw new Error("indexName is required");
3142
+ }
3143
+ if (!id) {
3144
+ throw new Error("id is required");
3145
+ }
3146
+ } catch (err) {
3147
+ throw new error.MastraError(
3148
+ {
3149
+ id: "STORAGE_LANCE_VECTOR_UPDATE_VECTOR_FAILED_INVALID_ARGS",
3150
+ domain: error.ErrorDomain.STORAGE,
3151
+ category: error.ErrorCategory.USER,
3152
+ details: { indexName, id }
3153
+ },
3154
+ err
3155
+ );
3156
+ }
3157
+ try {
3158
+ const tables = await this.lanceClient.tableNames();
3159
+ for (const tableName of tables) {
3160
+ this.logger.debug("Checking table:" + tableName);
3161
+ const table = await this.lanceClient.openTable(tableName);
3162
+ try {
3163
+ const schema = await table.schema();
3164
+ const hasColumn = schema.fields.some((field) => field.name === indexName);
3165
+ if (hasColumn) {
3166
+ this.logger.debug(`Found column ${indexName} in table ${tableName}`);
3167
+ const existingRecord = await table.query().where(`id = '${id}'`).select(schema.fields.map((field) => field.name)).limit(1).toArray();
3168
+ if (existingRecord.length === 0) {
3169
+ throw new Error(`Record with id '${id}' not found in table ${tableName}`);
3170
+ }
3171
+ const rowData = {
3172
+ id
3173
+ };
3174
+ Object.entries(existingRecord[0]).forEach(([key, value]) => {
3175
+ if (key !== "id" && key !== "_distance") {
3176
+ if (key === indexName) {
3177
+ if (!update.vector) {
3178
+ if (Array.isArray(value)) {
3179
+ rowData[key] = [...value];
3180
+ } else if (typeof value === "object" && value !== null) {
3181
+ rowData[key] = Array.from(value);
3182
+ } else {
3183
+ rowData[key] = value;
3184
+ }
3185
+ }
3186
+ } else {
3187
+ rowData[key] = value;
3188
+ }
3189
+ }
3190
+ });
3191
+ if (update.vector) {
3192
+ rowData[indexName] = update.vector;
3193
+ }
3194
+ if (update.metadata) {
3195
+ Object.entries(update.metadata).forEach(([key, value]) => {
3196
+ rowData[`metadata_${key}`] = value;
3197
+ });
3198
+ }
3199
+ await table.add([rowData], { mode: "overwrite" });
3200
+ return;
3201
+ }
3202
+ } catch (err) {
3203
+ this.logger.error(`Error checking schema for table ${tableName}:` + err);
3204
+ continue;
3205
+ }
3206
+ }
3207
+ throw new Error(`No table found with column/index '${indexName}'`);
3208
+ } catch (error$1) {
3209
+ throw new error.MastraError(
3210
+ {
3211
+ id: "STORAGE_LANCE_VECTOR_UPDATE_VECTOR_FAILED",
3212
+ domain: error.ErrorDomain.STORAGE,
3213
+ category: error.ErrorCategory.THIRD_PARTY,
3214
+ details: { indexName, id, hasVector: !!update.vector, hasMetadata: !!update.metadata }
3215
+ },
3216
+ error$1
3217
+ );
3218
+ }
3219
+ }
3220
+ async deleteVector({ indexName, id }) {
3221
+ try {
3222
+ if (!this.lanceClient) {
3223
+ throw new Error("LanceDB client not initialized. Use LanceVectorStore.create() to create an instance");
3224
+ }
3225
+ if (!indexName) {
3226
+ throw new Error("indexName is required");
3227
+ }
3228
+ if (!id) {
3229
+ throw new Error("id is required");
3230
+ }
3231
+ } catch (err) {
3232
+ throw new error.MastraError(
3233
+ {
3234
+ id: "STORAGE_LANCE_VECTOR_DELETE_VECTOR_FAILED_INVALID_ARGS",
3235
+ domain: error.ErrorDomain.STORAGE,
3236
+ category: error.ErrorCategory.USER,
3237
+ details: { indexName, id }
3238
+ },
3239
+ err
3240
+ );
3241
+ }
3242
+ try {
3243
+ const tables = await this.lanceClient.tableNames();
3244
+ for (const tableName of tables) {
3245
+ this.logger.debug("Checking table:" + tableName);
3246
+ const table = await this.lanceClient.openTable(tableName);
3247
+ try {
3248
+ const schema = await table.schema();
3249
+ const hasColumn = schema.fields.some((field) => field.name === indexName);
3250
+ if (hasColumn) {
3251
+ this.logger.debug(`Found column ${indexName} in table ${tableName}`);
3252
+ await table.delete(`id = '${id}'`);
3253
+ return;
3254
+ }
3255
+ } catch (err) {
3256
+ this.logger.error(`Error checking schema for table ${tableName}:` + err);
3257
+ continue;
3258
+ }
3259
+ }
3260
+ throw new Error(`No table found with column/index '${indexName}'`);
3261
+ } catch (error$1) {
3262
+ throw new error.MastraError(
3263
+ {
3264
+ id: "STORAGE_LANCE_VECTOR_DELETE_VECTOR_FAILED",
3265
+ domain: error.ErrorDomain.STORAGE,
3266
+ category: error.ErrorCategory.THIRD_PARTY,
3267
+ details: { indexName, id }
3268
+ },
3269
+ error$1
3270
+ );
3271
+ }
3272
+ }
3273
+ /**
3274
+ * Converts a flattened object with keys using underscore notation back to a nested object.
3275
+ * Example: { name: 'test', details_text: 'test' } → { name: 'test', details: { text: 'test' } }
3276
+ */
3277
+ unflattenObject(obj) {
3278
+ const result = {};
3279
+ Object.keys(obj).forEach((key) => {
3280
+ const value = obj[key];
3281
+ const parts = key.split("_");
3282
+ let current = result;
3283
+ for (let i = 0; i < parts.length - 1; i++) {
3284
+ const part = parts[i];
3285
+ if (!part) continue;
3286
+ if (!current[part] || typeof current[part] !== "object") {
3287
+ current[part] = {};
3288
+ }
3289
+ current = current[part];
3290
+ }
3291
+ const lastPart = parts[parts.length - 1];
3292
+ if (lastPart) {
3293
+ current[lastPart] = value;
3294
+ }
3295
+ });
3296
+ return result;
3297
+ }
3298
+ };
3299
+
3300
+ exports.LanceStorage = LanceStorage;
3301
+ exports.LanceVectorStore = LanceVectorStore;
3302
+ //# sourceMappingURL=index.cjs.map
3303
+ //# sourceMappingURL=index.cjs.map