@mastra/lance 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-trace-timeline-update-20251121092347

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.js CHANGED
@@ -1,132 +1,17 @@
1
1
  import { connect, Index } from '@lancedb/lancedb';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
- import { MastraStorage, StoreOperations, LegacyEvalsStorage, TABLE_EVALS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage, TABLE_SCORERS, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate } from '@mastra/core/storage';
3
+ import { MastraStorage, StoreOperations, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, normalizePerPage, calculatePagination, TABLE_RESOURCES, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate } from '@mastra/core/storage';
4
4
  import { MessageList } from '@mastra/core/agent';
5
5
  import { Utf8, Float64, Binary, Float32, Int32, Field, Schema } from 'apache-arrow';
6
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
6
7
  import { MastraVector } from '@mastra/core/vector';
7
8
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
8
9
 
9
10
  // src/storage/index.ts
10
- var StoreLegacyEvalsLance = class extends LegacyEvalsStorage {
11
- client;
12
- constructor({ client }) {
13
- super();
14
- this.client = client;
15
- }
16
- async getEvalsByAgentName(agentName, type) {
17
- try {
18
- const table = await this.client.openTable(TABLE_EVALS);
19
- const query = table.query().where(`agent_name = '${agentName}'`);
20
- const records = await query.toArray();
21
- let filteredRecords = records;
22
- if (type === "live") {
23
- filteredRecords = records.filter((record) => record.test_info === null);
24
- } else if (type === "test") {
25
- filteredRecords = records.filter((record) => record.test_info !== null);
26
- }
27
- return filteredRecords.map((record) => {
28
- return {
29
- id: record.id,
30
- input: record.input,
31
- output: record.output,
32
- agentName: record.agent_name,
33
- metricName: record.metric_name,
34
- result: JSON.parse(record.result),
35
- instructions: record.instructions,
36
- testInfo: record.test_info ? JSON.parse(record.test_info) : null,
37
- globalRunId: record.global_run_id,
38
- runId: record.run_id,
39
- createdAt: new Date(record.created_at).toString()
40
- };
41
- });
42
- } catch (error) {
43
- throw new MastraError(
44
- {
45
- id: "LANCE_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
46
- domain: ErrorDomain.STORAGE,
47
- category: ErrorCategory.THIRD_PARTY,
48
- details: { agentName }
49
- },
50
- error
51
- );
52
- }
53
- }
54
- async getEvals(options) {
55
- try {
56
- const table = await this.client.openTable(TABLE_EVALS);
57
- const conditions = [];
58
- if (options.agentName) {
59
- conditions.push(`agent_name = '${options.agentName}'`);
60
- }
61
- if (options.type === "live") {
62
- conditions.push("length(test_info) = 0");
63
- } else if (options.type === "test") {
64
- conditions.push("length(test_info) > 0");
65
- }
66
- const startDate = options.dateRange?.start || options.fromDate;
67
- const endDate = options.dateRange?.end || options.toDate;
68
- if (startDate) {
69
- conditions.push(`\`created_at\` >= ${startDate.getTime()}`);
70
- }
71
- if (endDate) {
72
- conditions.push(`\`created_at\` <= ${endDate.getTime()}`);
73
- }
74
- let total = 0;
75
- if (conditions.length > 0) {
76
- total = await table.countRows(conditions.join(" AND "));
77
- } else {
78
- total = await table.countRows();
79
- }
80
- const query = table.query();
81
- if (conditions.length > 0) {
82
- const whereClause = conditions.join(" AND ");
83
- query.where(whereClause);
84
- }
85
- const records = await query.toArray();
86
- const evals = records.sort((a, b) => b.created_at - a.created_at).map((record) => {
87
- return {
88
- id: record.id,
89
- input: record.input,
90
- output: record.output,
91
- agentName: record.agent_name,
92
- metricName: record.metric_name,
93
- result: JSON.parse(record.result),
94
- instructions: record.instructions,
95
- testInfo: record.test_info ? JSON.parse(record.test_info) : null,
96
- globalRunId: record.global_run_id,
97
- runId: record.run_id,
98
- createdAt: new Date(record.created_at).toISOString()
99
- };
100
- });
101
- const page = options.page || 0;
102
- const perPage = options.perPage || 10;
103
- const pagedEvals = evals.slice(page * perPage, (page + 1) * perPage);
104
- return {
105
- evals: pagedEvals,
106
- total,
107
- page,
108
- perPage,
109
- hasMore: total > (page + 1) * perPage
110
- };
111
- } catch (error) {
112
- throw new MastraError(
113
- {
114
- id: "LANCE_STORE_GET_EVALS_FAILED",
115
- domain: ErrorDomain.STORAGE,
116
- category: ErrorCategory.THIRD_PARTY,
117
- details: { agentName: options.agentName ?? "" }
118
- },
119
- error
120
- );
121
- }
122
- }
123
- };
124
11
  function getPrimaryKeys(tableName) {
125
12
  let primaryId = ["id"];
126
13
  if (tableName === TABLE_WORKFLOW_SNAPSHOT) {
127
14
  primaryId = ["workflow_name", "run_id"];
128
- } else if (tableName === TABLE_EVALS) {
129
- primaryId = ["agent_name", "metric_name", "run_id"];
130
15
  }
131
16
  return primaryId;
132
17
  }
@@ -187,7 +72,6 @@ function processResultWithTypeConversion(rawResult, tableSchema) {
187
72
  } else if (fieldTypeStr.includes("float64") && ["createdAt", "updatedAt"].includes(key)) {
188
73
  processedResult[key] = new Date(processedResult[key]);
189
74
  }
190
- console.log(key, "processedResult", processedResult);
191
75
  }
192
76
  return processedResult;
193
77
  }
@@ -247,6 +131,10 @@ var StoreMemoryLance = class extends MemoryStorage {
247
131
  this.client = client;
248
132
  this.operations = operations;
249
133
  }
134
+ // Utility to escape single quotes in SQL strings
135
+ escapeSql(str) {
136
+ return str.replace(/'/g, "''");
137
+ }
250
138
  async getThreadById({ threadId }) {
251
139
  try {
252
140
  const thread = await this.operations.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
@@ -269,26 +157,6 @@ var StoreMemoryLance = class extends MemoryStorage {
269
157
  );
270
158
  }
271
159
  }
272
- async getThreadsByResourceId({ resourceId }) {
273
- try {
274
- const table = await this.client.openTable(TABLE_THREADS);
275
- const query = table.query().where(`\`resourceId\` = '${resourceId}'`);
276
- const records = await query.toArray();
277
- return processResultWithTypeConversion(
278
- records,
279
- await getTableSchema({ tableName: TABLE_THREADS, client: this.client })
280
- );
281
- } catch (error) {
282
- throw new MastraError(
283
- {
284
- id: "LANCE_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
285
- domain: ErrorDomain.STORAGE,
286
- category: ErrorCategory.THIRD_PARTY
287
- },
288
- error
289
- );
290
- }
291
- }
292
160
  /**
293
161
  * Saves a thread to the database. This function doesn't overwrite existing threads.
294
162
  * @param thread - The thread to save
@@ -393,100 +261,174 @@ var StoreMemoryLance = class extends MemoryStorage {
393
261
  })() : message.content
394
262
  };
395
263
  }
396
- async getMessages({
397
- threadId,
398
- resourceId,
399
- selectBy,
400
- format,
401
- threadConfig
402
- }) {
264
+ async listMessagesById({ messageIds }) {
265
+ if (messageIds.length === 0) return { messages: [] };
403
266
  try {
404
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
405
- if (threadConfig) {
406
- throw new Error("ThreadConfig is not supported by LanceDB storage");
407
- }
408
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
409
267
  const table = await this.client.openTable(TABLE_MESSAGES);
410
- let allRecords = [];
411
- if (selectBy?.include && selectBy.include.length > 0) {
412
- const threadIds = [...new Set(selectBy.include.map((item) => item.threadId))];
413
- for (const threadId2 of threadIds) {
414
- const threadQuery = table.query().where(`thread_id = '${threadId2}'`);
415
- let threadRecords = await threadQuery.toArray();
416
- allRecords.push(...threadRecords);
417
- }
418
- } else {
419
- let query = table.query().where(`\`thread_id\` = '${threadId}'`);
420
- allRecords = await query.toArray();
421
- }
422
- allRecords.sort((a, b) => {
423
- const dateA = new Date(a.createdAt).getTime();
424
- const dateB = new Date(b.createdAt).getTime();
425
- return dateA - dateB;
426
- });
427
- if (selectBy?.include && selectBy.include.length > 0) {
428
- allRecords = this.processMessagesWithContext(allRecords, selectBy.include);
429
- }
430
- if (limit !== Number.MAX_SAFE_INTEGER) {
431
- allRecords = allRecords.slice(-limit);
432
- }
268
+ const quotedIds = messageIds.map((id) => `'${id}'`).join(", ");
269
+ const allRecords = await table.query().where(`id IN (${quotedIds})`).toArray();
433
270
  const messages = processResultWithTypeConversion(
434
271
  allRecords,
435
272
  await getTableSchema({ tableName: TABLE_MESSAGES, client: this.client })
436
273
  );
437
- const list = new MessageList({ threadId, resourceId }).add(messages.map(this.normalizeMessage), "memory");
438
- if (format === "v2") return list.get.all.v2();
439
- return list.get.all.v1();
274
+ const list = new MessageList().add(
275
+ messages.map(this.normalizeMessage),
276
+ "memory"
277
+ );
278
+ return { messages: list.get.all.db() };
440
279
  } catch (error) {
441
280
  throw new MastraError(
442
281
  {
443
- id: "LANCE_STORE_GET_MESSAGES_FAILED",
282
+ id: "LANCE_STORE_LIST_MESSAGES_BY_ID_FAILED",
444
283
  domain: ErrorDomain.STORAGE,
445
284
  category: ErrorCategory.THIRD_PARTY,
446
285
  details: {
447
- threadId,
448
- resourceId: resourceId ?? ""
286
+ messageIds: JSON.stringify(messageIds)
449
287
  }
450
288
  },
451
289
  error
452
290
  );
453
291
  }
454
292
  }
455
- async getMessagesById({
456
- messageIds,
457
- format
458
- }) {
459
- if (messageIds.length === 0) return [];
293
+ async listMessages(args) {
294
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
295
+ if (!threadId.trim()) {
296
+ throw new MastraError(
297
+ {
298
+ id: "STORAGE_LANCE_LIST_MESSAGES_INVALID_THREAD_ID",
299
+ domain: ErrorDomain.STORAGE,
300
+ category: ErrorCategory.THIRD_PARTY,
301
+ details: { threadId }
302
+ },
303
+ new Error("threadId must be a non-empty string")
304
+ );
305
+ }
306
+ const perPage = normalizePerPage(perPageInput, 40);
307
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
460
308
  try {
309
+ if (page < 0) {
310
+ throw new MastraError(
311
+ {
312
+ id: "STORAGE_LANCE_LIST_MESSAGES_INVALID_PAGE",
313
+ domain: ErrorDomain.STORAGE,
314
+ category: ErrorCategory.USER,
315
+ details: { page }
316
+ },
317
+ new Error("page must be >= 0")
318
+ );
319
+ }
320
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
461
321
  const table = await this.client.openTable(TABLE_MESSAGES);
462
- const quotedIds = messageIds.map((id) => `'${id}'`).join(", ");
463
- const allRecords = await table.query().where(`id IN (${quotedIds})`).toArray();
464
- const messages = processResultWithTypeConversion(
465
- allRecords,
466
- await getTableSchema({ tableName: TABLE_MESSAGES, client: this.client })
467
- );
468
- const list = new MessageList().add(messages.map(this.normalizeMessage), "memory");
469
- if (format === `v1`) return list.get.all.v1();
470
- return list.get.all.v2();
322
+ const conditions = [`thread_id = '${this.escapeSql(threadId)}'`];
323
+ if (resourceId) {
324
+ conditions.push(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
325
+ }
326
+ if (filter?.dateRange?.start) {
327
+ const startTime = filter.dateRange.start instanceof Date ? filter.dateRange.start.getTime() : new Date(filter.dateRange.start).getTime();
328
+ conditions.push(`\`createdAt\` >= ${startTime}`);
329
+ }
330
+ if (filter?.dateRange?.end) {
331
+ const endTime = filter.dateRange.end instanceof Date ? filter.dateRange.end.getTime() : new Date(filter.dateRange.end).getTime();
332
+ conditions.push(`\`createdAt\` <= ${endTime}`);
333
+ }
334
+ const whereClause = conditions.join(" AND ");
335
+ const total = await table.countRows(whereClause);
336
+ const query = table.query().where(whereClause);
337
+ let allRecords = await query.toArray();
338
+ allRecords.sort((a, b) => {
339
+ const aValue = field === "createdAt" ? a.createdAt : a[field];
340
+ const bValue = field === "createdAt" ? b.createdAt : b[field];
341
+ if (aValue == null && bValue == null) return 0;
342
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
343
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
344
+ if (typeof aValue === "string" && typeof bValue === "string") {
345
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
346
+ }
347
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
348
+ });
349
+ const paginatedRecords = allRecords.slice(offset, offset + perPage);
350
+ const messages = paginatedRecords.map((row) => this.normalizeMessage(row));
351
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
352
+ return {
353
+ messages: [],
354
+ total: 0,
355
+ page,
356
+ perPage: perPageForResponse,
357
+ hasMore: false
358
+ };
359
+ }
360
+ const messageIds = new Set(messages.map((m) => m.id));
361
+ if (include && include.length > 0) {
362
+ const threadIds = [...new Set(include.map((item) => item.threadId || threadId))];
363
+ const allThreadMessages = [];
364
+ for (const tid of threadIds) {
365
+ const threadQuery = table.query().where(`thread_id = '${tid}'`);
366
+ let threadRecords = await threadQuery.toArray();
367
+ allThreadMessages.push(...threadRecords);
368
+ }
369
+ allThreadMessages.sort((a, b) => a.createdAt - b.createdAt);
370
+ const contextMessages = this.processMessagesWithContext(allThreadMessages, include);
371
+ const includedMessages = contextMessages.map((row) => this.normalizeMessage(row));
372
+ for (const includeMsg of includedMessages) {
373
+ if (!messageIds.has(includeMsg.id)) {
374
+ messages.push(includeMsg);
375
+ messageIds.add(includeMsg.id);
376
+ }
377
+ }
378
+ }
379
+ const list = new MessageList().add(messages, "memory");
380
+ let finalMessages = list.get.all.db();
381
+ finalMessages = finalMessages.sort((a, b) => {
382
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
383
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
384
+ if (aValue == null && bValue == null) return 0;
385
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
386
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
387
+ if (typeof aValue === "string" && typeof bValue === "string") {
388
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
389
+ }
390
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
391
+ });
392
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
393
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
394
+ const fetchedAll = perPageInput === false || allThreadMessagesReturned;
395
+ const hasMore = !fetchedAll && offset + perPage < total;
396
+ return {
397
+ messages: finalMessages,
398
+ total,
399
+ page,
400
+ perPage: perPageForResponse,
401
+ hasMore
402
+ };
471
403
  } catch (error) {
472
- throw new MastraError(
404
+ const mastraError = new MastraError(
473
405
  {
474
- id: "LANCE_STORE_GET_MESSAGES_BY_ID_FAILED",
406
+ id: "LANCE_STORE_LIST_MESSAGES_FAILED",
475
407
  domain: ErrorDomain.STORAGE,
476
408
  category: ErrorCategory.THIRD_PARTY,
477
409
  details: {
478
- messageIds: JSON.stringify(messageIds)
410
+ threadId,
411
+ resourceId: resourceId ?? ""
479
412
  }
480
413
  },
481
414
  error
482
415
  );
416
+ this.logger?.error?.(mastraError.toString());
417
+ this.logger?.trackException?.(mastraError);
418
+ return {
419
+ messages: [],
420
+ total: 0,
421
+ page,
422
+ perPage: perPageForResponse,
423
+ hasMore: false
424
+ };
483
425
  }
484
426
  }
485
427
  async saveMessages(args) {
486
428
  try {
487
- const { messages, format = "v1" } = args;
429
+ const { messages } = args;
488
430
  if (messages.length === 0) {
489
- return [];
431
+ return { messages: [] };
490
432
  }
491
433
  const threadId = messages[0]?.threadId;
492
434
  if (!threadId) {
@@ -522,8 +464,7 @@ var StoreMemoryLance = class extends MemoryStorage {
522
464
  const updateRecord = { id: threadId, updatedAt: currentTime };
523
465
  await threadsTable.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([updateRecord]);
524
466
  const list = new MessageList().add(messages, "memory");
525
- if (format === `v2`) return list.get.all.v2();
526
- return list.get.all.v1();
467
+ return { messages: list.get.all.db() };
527
468
  } catch (error) {
528
469
  throw new MastraError(
529
470
  {
@@ -535,32 +476,54 @@ var StoreMemoryLance = class extends MemoryStorage {
535
476
  );
536
477
  }
537
478
  }
538
- async getThreadsByResourceIdPaginated(args) {
479
+ async listThreadsByResourceId(args) {
539
480
  try {
540
- const { resourceId, page = 0, perPage = 10 } = args;
541
- const table = await this.client.openTable(TABLE_THREADS);
542
- const total = await table.countRows(`\`resourceId\` = '${resourceId}'`);
543
- const query = table.query().where(`\`resourceId\` = '${resourceId}'`);
544
- const offset = page * perPage;
545
- query.limit(perPage);
546
- if (offset > 0) {
547
- query.offset(offset);
481
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
482
+ const perPage = normalizePerPage(perPageInput, 100);
483
+ if (page < 0) {
484
+ throw new MastraError(
485
+ {
486
+ id: "STORAGE_LANCE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
487
+ domain: ErrorDomain.STORAGE,
488
+ category: ErrorCategory.USER,
489
+ details: { page }
490
+ },
491
+ new Error("page must be >= 0")
492
+ );
548
493
  }
494
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
495
+ const { field, direction } = this.parseOrderBy(orderBy);
496
+ const table = await this.client.openTable(TABLE_THREADS);
497
+ const total = await table.countRows(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
498
+ const query = table.query().where(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
549
499
  const records = await query.toArray();
550
- records.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
500
+ records.sort((a, b) => {
501
+ const aValue = ["createdAt", "updatedAt"].includes(field) ? new Date(a[field]).getTime() : a[field];
502
+ const bValue = ["createdAt", "updatedAt"].includes(field) ? new Date(b[field]).getTime() : b[field];
503
+ if (aValue == null && bValue == null) return 0;
504
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
505
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
506
+ if (typeof aValue === "string" && typeof bValue === "string") {
507
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
508
+ }
509
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
510
+ });
511
+ const paginatedRecords = records.slice(offset, offset + perPage);
551
512
  const schema = await getTableSchema({ tableName: TABLE_THREADS, client: this.client });
552
- const threads = records.map((record) => processResultWithTypeConversion(record, schema));
513
+ const threads = paginatedRecords.map(
514
+ (record) => processResultWithTypeConversion(record, schema)
515
+ );
553
516
  return {
554
517
  threads,
555
518
  total,
556
519
  page,
557
- perPage,
558
- hasMore: total > (page + 1) * perPage
520
+ perPage: perPageForResponse,
521
+ hasMore: offset + perPage < total
559
522
  };
560
523
  } catch (error) {
561
524
  throw new MastraError(
562
525
  {
563
- id: "LANCE_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
526
+ id: "LANCE_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
564
527
  domain: ErrorDomain.STORAGE,
565
528
  category: ErrorCategory.THIRD_PARTY
566
529
  },
@@ -616,132 +579,8 @@ var StoreMemoryLance = class extends MemoryStorage {
616
579
  });
617
580
  return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
618
581
  }
619
- async getMessagesPaginated(args) {
620
- const { threadId, resourceId, selectBy, format = "v1" } = args;
621
- const page = selectBy?.pagination?.page ?? 0;
622
- const perPage = selectBy?.pagination?.perPage ?? 10;
623
- try {
624
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
625
- const dateRange = selectBy?.pagination?.dateRange;
626
- const fromDate = dateRange?.start;
627
- const toDate = dateRange?.end;
628
- const table = await this.client.openTable(TABLE_MESSAGES);
629
- const messages = [];
630
- if (selectBy?.include && Array.isArray(selectBy.include)) {
631
- const threadIds = [...new Set(selectBy.include.map((item) => item.threadId))];
632
- const allThreadMessages = [];
633
- for (const threadId2 of threadIds) {
634
- const threadQuery = table.query().where(`thread_id = '${threadId2}'`);
635
- let threadRecords = await threadQuery.toArray();
636
- if (fromDate) threadRecords = threadRecords.filter((m) => m.createdAt >= fromDate.getTime());
637
- if (toDate) threadRecords = threadRecords.filter((m) => m.createdAt <= toDate.getTime());
638
- allThreadMessages.push(...threadRecords);
639
- }
640
- allThreadMessages.sort((a, b) => a.createdAt - b.createdAt);
641
- const contextMessages = this.processMessagesWithContext(allThreadMessages, selectBy.include);
642
- messages.push(...contextMessages);
643
- }
644
- const conditions = [`thread_id = '${threadId}'`];
645
- if (resourceId) {
646
- conditions.push(`\`resourceId\` = '${resourceId}'`);
647
- }
648
- if (fromDate) {
649
- conditions.push(`\`createdAt\` >= ${fromDate.getTime()}`);
650
- }
651
- if (toDate) {
652
- conditions.push(`\`createdAt\` <= ${toDate.getTime()}`);
653
- }
654
- let total = 0;
655
- if (conditions.length > 0) {
656
- total = await table.countRows(conditions.join(" AND "));
657
- } else {
658
- total = await table.countRows();
659
- }
660
- if (total === 0 && messages.length === 0) {
661
- return {
662
- messages: [],
663
- total: 0,
664
- page,
665
- perPage,
666
- hasMore: false
667
- };
668
- }
669
- const excludeIds = messages.map((m) => m.id);
670
- let selectedMessages = [];
671
- if (selectBy?.last && selectBy.last > 0) {
672
- const query = table.query();
673
- if (conditions.length > 0) {
674
- query.where(conditions.join(" AND "));
675
- }
676
- let records = await query.toArray();
677
- records = records.sort((a, b) => a.createdAt - b.createdAt);
678
- if (excludeIds.length > 0) {
679
- records = records.filter((m) => !excludeIds.includes(m.id));
680
- }
681
- selectedMessages = records.slice(-selectBy.last);
682
- } else {
683
- const query = table.query();
684
- if (conditions.length > 0) {
685
- query.where(conditions.join(" AND "));
686
- }
687
- let records = await query.toArray();
688
- records = records.sort((a, b) => a.createdAt - b.createdAt);
689
- if (excludeIds.length > 0) {
690
- records = records.filter((m) => !excludeIds.includes(m.id));
691
- }
692
- selectedMessages = records.slice(page * perPage, (page + 1) * perPage);
693
- }
694
- const allMessages = [...messages, ...selectedMessages];
695
- const seen = /* @__PURE__ */ new Set();
696
- const dedupedMessages = allMessages.filter((m) => {
697
- const key = `${m.id}:${m.thread_id}`;
698
- if (seen.has(key)) return false;
699
- seen.add(key);
700
- return true;
701
- });
702
- const formattedMessages = dedupedMessages.map((msg) => {
703
- const { thread_id, ...rest } = msg;
704
- return {
705
- ...rest,
706
- threadId: thread_id,
707
- content: typeof msg.content === "string" ? (() => {
708
- try {
709
- return JSON.parse(msg.content);
710
- } catch {
711
- return msg.content;
712
- }
713
- })() : msg.content
714
- };
715
- });
716
- const list = new MessageList().add(formattedMessages, "memory");
717
- return {
718
- messages: format === "v2" ? list.get.all.v2() : list.get.all.v1(),
719
- total,
720
- // Total should be the count of messages matching the filters
721
- page,
722
- perPage,
723
- hasMore: total > (page + 1) * perPage
724
- };
725
- } catch (error) {
726
- const mastraError = new MastraError(
727
- {
728
- id: "LANCE_STORE_GET_MESSAGES_PAGINATED_FAILED",
729
- domain: ErrorDomain.STORAGE,
730
- category: ErrorCategory.THIRD_PARTY,
731
- details: {
732
- threadId,
733
- resourceId: resourceId ?? ""
734
- }
735
- },
736
- error
737
- );
738
- this.logger?.trackException?.(mastraError);
739
- this.logger?.error?.(mastraError.toString());
740
- return { messages: [], total: 0, page, perPage, hasMore: false };
741
- }
742
- }
743
582
  /**
744
- * Parse message data from LanceDB record format to MastraMessageV2 format
583
+ * Parse message data from LanceDB record format to MastraDBMessage format
745
584
  */
746
585
  parseMessageData(data) {
747
586
  const { thread_id, ...rest } = data;
@@ -1264,7 +1103,7 @@ var StoreOperationsLance = class extends StoreOperations {
1264
1103
  processedRecord[key] = JSON.stringify(processedRecord[key]);
1265
1104
  }
1266
1105
  }
1267
- console.log(await table.schema());
1106
+ console.info(await table.schema());
1268
1107
  await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([processedRecord]);
1269
1108
  } catch (error) {
1270
1109
  throw new MastraError(
@@ -1314,7 +1153,6 @@ var StoreOperationsLance = class extends StoreOperations {
1314
1153
  }
1315
1154
  return processedRecord;
1316
1155
  });
1317
- console.log(processedRecords);
1318
1156
  await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(processedRecords);
1319
1157
  } catch (error) {
1320
1158
  throw new MastraError(
@@ -1398,13 +1236,27 @@ var StoreScoresLance = class extends ScoresStorage {
1398
1236
  this.client = client;
1399
1237
  }
1400
1238
  async saveScore(score) {
1239
+ let validatedScore;
1240
+ try {
1241
+ validatedScore = saveScorePayloadSchema.parse(score);
1242
+ } catch (error) {
1243
+ throw new MastraError(
1244
+ {
1245
+ id: "LANCE_STORAGE_SAVE_SCORE_FAILED",
1246
+ text: "Failed to save score in LanceStorage",
1247
+ domain: ErrorDomain.STORAGE,
1248
+ category: ErrorCategory.THIRD_PARTY
1249
+ },
1250
+ error
1251
+ );
1252
+ }
1401
1253
  try {
1402
1254
  const id = crypto.randomUUID();
1403
1255
  const table = await this.client.openTable(TABLE_SCORERS);
1404
1256
  const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1405
1257
  const allowedFields = new Set(schema.fields.map((f) => f.name));
1406
1258
  const filteredScore = {};
1407
- Object.keys(score).forEach((key) => {
1259
+ Object.keys(validatedScore).forEach((key) => {
1408
1260
  if (allowedFields.has(key)) {
1409
1261
  filteredScore[key] = score[key];
1410
1262
  }
@@ -1451,7 +1303,7 @@ var StoreScoresLance = class extends ScoresStorage {
1451
1303
  );
1452
1304
  }
1453
1305
  }
1454
- async getScoresByScorerId({
1306
+ async listScoresByScorerId({
1455
1307
  scorerId,
1456
1308
  pagination,
1457
1309
  entityId,
@@ -1459,9 +1311,10 @@ var StoreScoresLance = class extends ScoresStorage {
1459
1311
  source
1460
1312
  }) {
1461
1313
  try {
1314
+ const { page, perPage: perPageInput } = pagination;
1315
+ const perPage = normalizePerPage(perPageInput, 100);
1316
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1462
1317
  const table = await this.client.openTable(TABLE_SCORERS);
1463
- const { page = 0, perPage = 10 } = pagination || {};
1464
- const offset = page * perPage;
1465
1318
  let query = table.query().where(`\`scorerId\` = '${scorerId}'`);
1466
1319
  if (source) {
1467
1320
  query = query.where(`\`source\` = '${source}'`);
@@ -1472,23 +1325,32 @@ var StoreScoresLance = class extends ScoresStorage {
1472
1325
  if (entityType) {
1473
1326
  query = query.where(`\`entityType\` = '${entityType}'`);
1474
1327
  }
1475
- query = query.limit(perPage);
1476
- if (offset > 0) query.offset(offset);
1477
- const records = await query.toArray();
1478
- const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1479
- const scores = processResultWithTypeConversion(records, schema);
1480
1328
  let totalQuery = table.query().where(`\`scorerId\` = '${scorerId}'`);
1481
1329
  if (source) {
1482
1330
  totalQuery = totalQuery.where(`\`source\` = '${source}'`);
1483
1331
  }
1332
+ if (entityId) {
1333
+ totalQuery = totalQuery.where(`\`entityId\` = '${entityId}'`);
1334
+ }
1335
+ if (entityType) {
1336
+ totalQuery = totalQuery.where(`\`entityType\` = '${entityType}'`);
1337
+ }
1484
1338
  const allRecords = await totalQuery.toArray();
1485
1339
  const total = allRecords.length;
1340
+ const end = perPageInput === false ? total : start + perPage;
1341
+ if (perPageInput !== false) {
1342
+ query = query.limit(perPage);
1343
+ if (start > 0) query = query.offset(start);
1344
+ }
1345
+ const records = await query.toArray();
1346
+ const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1347
+ const scores = processResultWithTypeConversion(records, schema);
1486
1348
  return {
1487
1349
  pagination: {
1488
1350
  page,
1489
- perPage,
1351
+ perPage: perPageForResponse,
1490
1352
  total,
1491
- hasMore: offset + scores.length < total
1353
+ hasMore: end < total
1492
1354
  },
1493
1355
  scores
1494
1356
  };
@@ -1505,27 +1367,32 @@ var StoreScoresLance = class extends ScoresStorage {
1505
1367
  );
1506
1368
  }
1507
1369
  }
1508
- async getScoresByRunId({
1370
+ async listScoresByRunId({
1509
1371
  runId,
1510
1372
  pagination
1511
1373
  }) {
1512
1374
  try {
1375
+ const { page, perPage: perPageInput } = pagination;
1376
+ const perPage = normalizePerPage(perPageInput, 100);
1377
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1513
1378
  const table = await this.client.openTable(TABLE_SCORERS);
1514
- const { page = 0, perPage = 10 } = pagination || {};
1515
- const offset = page * perPage;
1516
- const query = table.query().where(`\`runId\` = '${runId}'`).limit(perPage);
1517
- if (offset > 0) query.offset(offset);
1379
+ const allRecords = await table.query().where(`\`runId\` = '${runId}'`).toArray();
1380
+ const total = allRecords.length;
1381
+ const end = perPageInput === false ? total : start + perPage;
1382
+ let query = table.query().where(`\`runId\` = '${runId}'`);
1383
+ if (perPageInput !== false) {
1384
+ query = query.limit(perPage);
1385
+ if (start > 0) query = query.offset(start);
1386
+ }
1518
1387
  const records = await query.toArray();
1519
1388
  const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1520
1389
  const scores = processResultWithTypeConversion(records, schema);
1521
- const allRecords = await table.query().where(`\`runId\` = '${runId}'`).toArray();
1522
- const total = allRecords.length;
1523
1390
  return {
1524
1391
  pagination: {
1525
1392
  page,
1526
- perPage,
1393
+ perPage: perPageForResponse,
1527
1394
  total,
1528
- hasMore: offset + scores.length < total
1395
+ hasMore: end < total
1529
1396
  },
1530
1397
  scores
1531
1398
  };
@@ -1542,28 +1409,33 @@ var StoreScoresLance = class extends ScoresStorage {
1542
1409
  );
1543
1410
  }
1544
1411
  }
1545
- async getScoresByEntityId({
1412
+ async listScoresByEntityId({
1546
1413
  entityId,
1547
1414
  entityType,
1548
1415
  pagination
1549
1416
  }) {
1550
1417
  try {
1418
+ const { page, perPage: perPageInput } = pagination;
1419
+ const perPage = normalizePerPage(perPageInput, 100);
1420
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1551
1421
  const table = await this.client.openTable(TABLE_SCORERS);
1552
- const { page = 0, perPage = 10 } = pagination || {};
1553
- const offset = page * perPage;
1554
- const query = table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).limit(perPage);
1555
- if (offset > 0) query.offset(offset);
1422
+ const allRecords = await table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).toArray();
1423
+ const total = allRecords.length;
1424
+ const end = perPageInput === false ? total : start + perPage;
1425
+ let query = table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`);
1426
+ if (perPageInput !== false) {
1427
+ query = query.limit(perPage);
1428
+ if (start > 0) query = query.offset(start);
1429
+ }
1556
1430
  const records = await query.toArray();
1557
1431
  const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1558
1432
  const scores = processResultWithTypeConversion(records, schema);
1559
- const allRecords = await table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).toArray();
1560
- const total = allRecords.length;
1561
1433
  return {
1562
1434
  pagination: {
1563
1435
  page,
1564
- perPage,
1436
+ perPage: perPageForResponse,
1565
1437
  total,
1566
- hasMore: offset + scores.length < total
1438
+ hasMore: end < total
1567
1439
  },
1568
1440
  scores
1569
1441
  };
@@ -1580,198 +1452,49 @@ var StoreScoresLance = class extends ScoresStorage {
1580
1452
  );
1581
1453
  }
1582
1454
  }
1583
- };
1584
- var StoreTracesLance = class extends TracesStorage {
1585
- client;
1586
- operations;
1587
- constructor({ client, operations }) {
1588
- super();
1589
- this.client = client;
1590
- this.operations = operations;
1591
- }
1592
- async saveTrace({ trace }) {
1593
- try {
1594
- const table = await this.client.openTable(TABLE_TRACES);
1595
- const record = {
1596
- ...trace,
1597
- attributes: JSON.stringify(trace.attributes),
1598
- status: JSON.stringify(trace.status),
1599
- events: JSON.stringify(trace.events),
1600
- links: JSON.stringify(trace.links),
1601
- other: JSON.stringify(trace.other)
1602
- };
1603
- await table.add([record], { mode: "append" });
1604
- return trace;
1605
- } catch (error) {
1606
- throw new MastraError(
1607
- {
1608
- id: "LANCE_STORE_SAVE_TRACE_FAILED",
1609
- domain: ErrorDomain.STORAGE,
1610
- category: ErrorCategory.THIRD_PARTY
1611
- },
1612
- error
1613
- );
1614
- }
1615
- }
1616
- async getTraceById({ traceId }) {
1617
- try {
1618
- const table = await this.client.openTable(TABLE_TRACES);
1619
- const query = table.query().where(`id = '${traceId}'`);
1620
- const records = await query.toArray();
1621
- return records[0];
1622
- } catch (error) {
1623
- throw new MastraError(
1624
- {
1625
- id: "LANCE_STORE_GET_TRACE_BY_ID_FAILED",
1626
- domain: ErrorDomain.STORAGE,
1627
- category: ErrorCategory.THIRD_PARTY
1628
- },
1629
- error
1630
- );
1631
- }
1632
- }
1633
- async getTraces({
1634
- name,
1635
- scope,
1636
- page = 1,
1637
- perPage = 10,
1638
- attributes
1455
+ async listScoresBySpan({
1456
+ traceId,
1457
+ spanId,
1458
+ pagination
1639
1459
  }) {
1640
1460
  try {
1641
- const table = await this.client.openTable(TABLE_TRACES);
1642
- const query = table.query();
1643
- if (name) {
1644
- query.where(`name = '${name}'`);
1645
- }
1646
- if (scope) {
1647
- query.where(`scope = '${scope}'`);
1648
- }
1649
- if (attributes) {
1650
- query.where(`attributes = '${JSON.stringify(attributes)}'`);
1651
- }
1652
- const offset = (page - 1) * perPage;
1653
- query.limit(perPage);
1654
- if (offset > 0) {
1655
- query.offset(offset);
1656
- }
1657
- const records = await query.toArray();
1658
- return records.map((record) => {
1659
- const processed = {
1660
- ...record,
1661
- attributes: record.attributes ? JSON.parse(record.attributes) : {},
1662
- status: record.status ? JSON.parse(record.status) : {},
1663
- events: record.events ? JSON.parse(record.events) : [],
1664
- links: record.links ? JSON.parse(record.links) : [],
1665
- other: record.other ? JSON.parse(record.other) : {},
1666
- startTime: new Date(record.startTime),
1667
- endTime: new Date(record.endTime),
1668
- createdAt: new Date(record.createdAt)
1669
- };
1670
- if (processed.parentSpanId === null || processed.parentSpanId === void 0) {
1671
- processed.parentSpanId = "";
1672
- } else {
1673
- processed.parentSpanId = String(processed.parentSpanId);
1674
- }
1675
- return processed;
1676
- });
1677
- } catch (error) {
1678
- throw new MastraError(
1679
- {
1680
- id: "LANCE_STORE_GET_TRACES_FAILED",
1681
- domain: ErrorDomain.STORAGE,
1682
- category: ErrorCategory.THIRD_PARTY,
1683
- details: { name: name ?? "", scope: scope ?? "" }
1684
- },
1685
- error
1686
- );
1687
- }
1688
- }
1689
- async getTracesPaginated(args) {
1690
- try {
1691
- const table = await this.client.openTable(TABLE_TRACES);
1692
- const query = table.query();
1693
- const conditions = [];
1694
- if (args.name) {
1695
- conditions.push(`name = '${args.name}'`);
1696
- }
1697
- if (args.scope) {
1698
- conditions.push(`scope = '${args.scope}'`);
1699
- }
1700
- if (args.attributes) {
1701
- const attributesStr = JSON.stringify(args.attributes);
1702
- conditions.push(`attributes LIKE '%${attributesStr.replace(/"/g, '\\"')}%'`);
1703
- }
1704
- if (args.dateRange?.start) {
1705
- conditions.push(`\`createdAt\` >= ${args.dateRange.start.getTime()}`);
1706
- }
1707
- if (args.dateRange?.end) {
1708
- conditions.push(`\`createdAt\` <= ${args.dateRange.end.getTime()}`);
1709
- }
1710
- if (conditions.length > 0) {
1711
- const whereClause = conditions.join(" AND ");
1712
- query.where(whereClause);
1713
- }
1714
- let total = 0;
1715
- if (conditions.length > 0) {
1716
- const countQuery = table.query().where(conditions.join(" AND "));
1717
- const allRecords = await countQuery.toArray();
1718
- total = allRecords.length;
1719
- } else {
1720
- total = await table.countRows();
1721
- }
1722
- const page = args.page || 0;
1723
- const perPage = args.perPage || 10;
1724
- const offset = page * perPage;
1725
- query.limit(perPage);
1726
- if (offset > 0) {
1727
- query.offset(offset);
1461
+ const { page, perPage: perPageInput } = pagination;
1462
+ const perPage = normalizePerPage(perPageInput, 100);
1463
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1464
+ const table = await this.client.openTable(TABLE_SCORERS);
1465
+ const allRecords = await table.query().where(`\`traceId\` = '${traceId}' AND \`spanId\` = '${spanId}'`).toArray();
1466
+ const total = allRecords.length;
1467
+ const end = perPageInput === false ? total : start + perPage;
1468
+ let query = table.query().where(`\`traceId\` = '${traceId}' AND \`spanId\` = '${spanId}'`);
1469
+ if (perPageInput !== false) {
1470
+ query = query.limit(perPage);
1471
+ if (start > 0) query = query.offset(start);
1728
1472
  }
1729
1473
  const records = await query.toArray();
1730
- const traces = records.map((record) => {
1731
- const processed = {
1732
- ...record,
1733
- attributes: record.attributes ? JSON.parse(record.attributes) : {},
1734
- status: record.status ? JSON.parse(record.status) : {},
1735
- events: record.events ? JSON.parse(record.events) : [],
1736
- links: record.links ? JSON.parse(record.links) : [],
1737
- other: record.other ? JSON.parse(record.other) : {},
1738
- startTime: new Date(record.startTime),
1739
- endTime: new Date(record.endTime),
1740
- createdAt: new Date(record.createdAt)
1741
- };
1742
- if (processed.parentSpanId === null || processed.parentSpanId === void 0) {
1743
- processed.parentSpanId = "";
1744
- } else {
1745
- processed.parentSpanId = String(processed.parentSpanId);
1746
- }
1747
- return processed;
1748
- });
1474
+ const schema = await getTableSchema({ tableName: TABLE_SCORERS, client: this.client });
1475
+ const scores = processResultWithTypeConversion(records, schema);
1749
1476
  return {
1750
- traces,
1751
- total,
1752
- page,
1753
- perPage,
1754
- hasMore: total > (page + 1) * perPage
1477
+ pagination: {
1478
+ page,
1479
+ perPage: perPageForResponse,
1480
+ total,
1481
+ hasMore: end < total
1482
+ },
1483
+ scores
1755
1484
  };
1756
1485
  } catch (error) {
1757
1486
  throw new MastraError(
1758
1487
  {
1759
- id: "LANCE_STORE_GET_TRACES_PAGINATED_FAILED",
1488
+ id: "LANCE_STORAGE_GET_SCORES_BY_SPAN_FAILED",
1489
+ text: "Failed to get scores by traceId and spanId in LanceStorage",
1760
1490
  domain: ErrorDomain.STORAGE,
1761
1491
  category: ErrorCategory.THIRD_PARTY,
1762
- details: { name: args.name ?? "", scope: args.scope ?? "" }
1492
+ details: { error: error?.message }
1763
1493
  },
1764
1494
  error
1765
1495
  );
1766
1496
  }
1767
1497
  }
1768
- async batchTraceInsert({ records }) {
1769
- this.logger.debug("Batch inserting traces", { count: records.length });
1770
- await this.operations.batchInsert({
1771
- tableName: TABLE_TRACES,
1772
- records
1773
- });
1774
- }
1775
1498
  };
1776
1499
  function parseWorkflowRun(row) {
1777
1500
  let parsedSnapshot = row.snapshot;
@@ -1802,7 +1525,7 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1802
1525
  // runId,
1803
1526
  // stepId,
1804
1527
  // result,
1805
- // runtimeContext,
1528
+ // requestContext,
1806
1529
  }) {
1807
1530
  throw new Error("Method not implemented.");
1808
1531
  }
@@ -1830,11 +1553,13 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1830
1553
  } else {
1831
1554
  createdAt = now;
1832
1555
  }
1556
+ const { status, value, ...rest } = snapshot;
1833
1557
  const record = {
1834
1558
  workflow_name: workflowName,
1835
1559
  run_id: runId,
1836
1560
  resourceId,
1837
- snapshot: JSON.stringify(snapshot),
1561
+ snapshot: JSON.stringify({ status, value, ...rest }),
1562
+ // this is to ensure status is always just before value, for when querying the db by status
1838
1563
  createdAt,
1839
1564
  updatedAt: now
1840
1565
  };
@@ -1896,7 +1621,7 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1896
1621
  );
1897
1622
  }
1898
1623
  }
1899
- async getWorkflowRuns(args) {
1624
+ async listWorkflowRuns(args) {
1900
1625
  try {
1901
1626
  const table = await this.client.openTable(TABLE_WORKFLOW_SNAPSHOT);
1902
1627
  let query = table.query();
@@ -1904,6 +1629,10 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1904
1629
  if (args?.workflowName) {
1905
1630
  conditions.push(`workflow_name = '${args.workflowName.replace(/'/g, "''")}'`);
1906
1631
  }
1632
+ if (args?.status) {
1633
+ const escapedStatus = args.status.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/%/g, "\\%").replace(/_/g, "\\_");
1634
+ conditions.push(`\`snapshot\` LIKE '%"status":"${escapedStatus}","value"%'`);
1635
+ }
1907
1636
  if (args?.resourceId) {
1908
1637
  conditions.push(`\`resourceId\` = '${args.resourceId}'`);
1909
1638
  }
@@ -1920,11 +1649,22 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1920
1649
  } else {
1921
1650
  total = await table.countRows();
1922
1651
  }
1923
- if (args?.limit) {
1924
- query.limit(args.limit);
1925
- }
1926
- if (args?.offset) {
1927
- query.offset(args.offset);
1652
+ if (args?.perPage !== void 0 && args?.page !== void 0) {
1653
+ const normalizedPerPage = normalizePerPage(args.perPage, Number.MAX_SAFE_INTEGER);
1654
+ if (args.page < 0 || !Number.isInteger(args.page)) {
1655
+ throw new MastraError(
1656
+ {
1657
+ id: "LANCE_STORE_INVALID_PAGINATION_PARAMS",
1658
+ domain: ErrorDomain.STORAGE,
1659
+ category: ErrorCategory.USER,
1660
+ details: { page: args.page, perPage: args.perPage }
1661
+ },
1662
+ new Error(`Invalid pagination parameters: page=${args.page}, perPage=${args.perPage}`)
1663
+ );
1664
+ }
1665
+ const offset = args.page * normalizedPerPage;
1666
+ query.limit(normalizedPerPage);
1667
+ query.offset(offset);
1928
1668
  }
1929
1669
  const records = await query.toArray();
1930
1670
  return {
@@ -1934,10 +1674,10 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1934
1674
  } catch (error) {
1935
1675
  throw new MastraError(
1936
1676
  {
1937
- id: "LANCE_STORE_GET_WORKFLOW_RUNS_FAILED",
1677
+ id: "LANCE_STORE_LIST_WORKFLOW_RUNS_FAILED",
1938
1678
  domain: ErrorDomain.STORAGE,
1939
1679
  category: ErrorCategory.THIRD_PARTY,
1940
- details: { namespace: args?.namespace ?? "", workflowName: args?.workflowName ?? "" }
1680
+ details: { resourceId: args?.resourceId ?? "", workflowName: args?.workflowName ?? "" }
1941
1681
  },
1942
1682
  error
1943
1683
  );
@@ -1951,6 +1691,8 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
1951
1691
  lanceClient;
1952
1692
  /**
1953
1693
  * Creates a new instance of LanceStorage
1694
+ * @param id The unique identifier for this storage instance
1695
+ * @param name The name for this storage instance
1954
1696
  * @param uri The URI to connect to LanceDB
1955
1697
  * @param options connection options
1956
1698
  *
@@ -1958,31 +1700,29 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
1958
1700
  *
1959
1701
  * Connect to a local database
1960
1702
  * ```ts
1961
- * const store = await LanceStorage.create('/path/to/db');
1703
+ * const store = await LanceStorage.create('my-storage-id', 'MyStorage', '/path/to/db');
1962
1704
  * ```
1963
1705
  *
1964
1706
  * Connect to a LanceDB cloud database
1965
1707
  * ```ts
1966
- * const store = await LanceStorage.create('db://host:port');
1708
+ * const store = await LanceStorage.create('my-storage-id', 'MyStorage', 'db://host:port');
1967
1709
  * ```
1968
1710
  *
1969
1711
  * Connect to a cloud database
1970
1712
  * ```ts
1971
- * const store = await LanceStorage.create('s3://bucket/db', { storageOptions: { timeout: '60s' } });
1713
+ * const store = await LanceStorage.create('my-storage-id', 'MyStorage', 's3://bucket/db', { storageOptions: { timeout: '60s' } });
1972
1714
  * ```
1973
1715
  */
1974
- static async create(name, uri, options) {
1975
- const instance = new _LanceStorage(name);
1716
+ static async create(id, name, uri, options) {
1717
+ const instance = new _LanceStorage(id, name);
1976
1718
  try {
1977
1719
  instance.lanceClient = await connect(uri, options);
1978
1720
  const operations = new StoreOperationsLance({ client: instance.lanceClient });
1979
1721
  instance.stores = {
1980
1722
  operations: new StoreOperationsLance({ client: instance.lanceClient }),
1981
1723
  workflows: new StoreWorkflowsLance({ client: instance.lanceClient }),
1982
- traces: new StoreTracesLance({ client: instance.lanceClient, operations }),
1983
1724
  scores: new StoreScoresLance({ client: instance.lanceClient }),
1984
- memory: new StoreMemoryLance({ client: instance.lanceClient, operations }),
1985
- legacyEvals: new StoreLegacyEvalsLance({ client: instance.lanceClient })
1725
+ memory: new StoreMemoryLance({ client: instance.lanceClient, operations })
1986
1726
  };
1987
1727
  return instance;
1988
1728
  } catch (e) {
@@ -2002,15 +1742,13 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2002
1742
  * @internal
2003
1743
  * Private constructor to enforce using the create factory method
2004
1744
  */
2005
- constructor(name) {
2006
- super({ name });
1745
+ constructor(id, name) {
1746
+ super({ id, name });
2007
1747
  const operations = new StoreOperationsLance({ client: this.lanceClient });
2008
1748
  this.stores = {
2009
1749
  operations: new StoreOperationsLance({ client: this.lanceClient }),
2010
1750
  workflows: new StoreWorkflowsLance({ client: this.lanceClient }),
2011
- traces: new StoreTracesLance({ client: this.lanceClient, operations }),
2012
1751
  scores: new StoreScoresLance({ client: this.lanceClient }),
2013
- legacyEvals: new StoreLegacyEvalsLance({ client: this.lanceClient }),
2014
1752
  memory: new StoreMemoryLance({ client: this.lanceClient, operations })
2015
1753
  };
2016
1754
  }
@@ -2045,9 +1783,6 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2045
1783
  async getThreadById({ threadId }) {
2046
1784
  return this.stores.memory.getThreadById({ threadId });
2047
1785
  }
2048
- async getThreadsByResourceId({ resourceId }) {
2049
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2050
- }
2051
1786
  /**
2052
1787
  * Saves a thread to the database. This function doesn't overwrite existing threads.
2053
1788
  * @param thread - The thread to save
@@ -2072,7 +1807,8 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2072
1807
  resourceWorkingMemory: true,
2073
1808
  hasColumn: true,
2074
1809
  createTable: true,
2075
- deleteMessages: false
1810
+ deleteMessages: false,
1811
+ listScoresBySpan: true
2076
1812
  };
2077
1813
  }
2078
1814
  async getResourceById({ resourceId }) {
@@ -2136,50 +1872,17 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2136
1872
  });
2137
1873
  return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
2138
1874
  }
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 });
1875
+ async listMessagesById({ messageIds }) {
1876
+ return this.stores.memory.listMessagesById({ messageIds });
2153
1877
  }
2154
1878
  async saveMessages(args) {
2155
1879
  return this.stores.memory.saveMessages(args);
2156
1880
  }
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
1881
  async updateMessages(_args) {
2164
1882
  return this.stores.memory.updateMessages(_args);
2165
1883
  }
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);
1884
+ async listWorkflowRuns(args) {
1885
+ return this.stores.workflows.listWorkflowRuns(args);
2183
1886
  }
2184
1887
  async getWorkflowRunById(args) {
2185
1888
  return this.stores.workflows.getWorkflowRunById(args);
@@ -2189,9 +1892,9 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2189
1892
  runId,
2190
1893
  stepId,
2191
1894
  result,
2192
- runtimeContext
1895
+ requestContext
2193
1896
  }) {
2194
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
1897
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2195
1898
  }
2196
1899
  async updateWorkflowState({
2197
1900
  workflowName,
@@ -2217,30 +1920,37 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2217
1920
  async getScoreById({ id: _id }) {
2218
1921
  return this.stores.scores.getScoreById({ id: _id });
2219
1922
  }
2220
- async getScoresByScorerId({
1923
+ async listScoresByScorerId({
2221
1924
  scorerId,
2222
1925
  source,
2223
1926
  entityId,
2224
1927
  entityType,
2225
1928
  pagination
2226
1929
  }) {
2227
- return this.stores.scores.getScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
1930
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
2228
1931
  }
2229
1932
  async saveScore(_score) {
2230
1933
  return this.stores.scores.saveScore(_score);
2231
1934
  }
2232
- async getScoresByRunId({
1935
+ async listScoresByRunId({
2233
1936
  runId,
2234
1937
  pagination
2235
1938
  }) {
2236
- return this.stores.scores.getScoresByRunId({ runId, pagination });
1939
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2237
1940
  }
2238
- async getScoresByEntityId({
1941
+ async listScoresByEntityId({
2239
1942
  entityId,
2240
1943
  entityType,
2241
1944
  pagination
2242
1945
  }) {
2243
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
1946
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
1947
+ }
1948
+ async listScoresBySpan({
1949
+ traceId,
1950
+ spanId,
1951
+ pagination
1952
+ }) {
1953
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2244
1954
  }
2245
1955
  };
2246
1956
  var LanceFilterTranslator = class extends BaseFilterTranslator {
@@ -2589,7 +2299,7 @@ var LanceVectorStore = class _LanceVectorStore extends MastraVector {
2589
2299
  * ```
2590
2300
  */
2591
2301
  static async create(uri, options) {
2592
- const instance = new _LanceVectorStore();
2302
+ const instance = new _LanceVectorStore(options?.id || crypto.randomUUID());
2593
2303
  try {
2594
2304
  instance.lanceClient = await connect(uri, options);
2595
2305
  return instance;
@@ -2609,8 +2319,8 @@ var LanceVectorStore = class _LanceVectorStore extends MastraVector {
2609
2319
  * @internal
2610
2320
  * Private constructor to enforce using the create factory method
2611
2321
  */
2612
- constructor() {
2613
- super();
2322
+ constructor(id) {
2323
+ super({ id });
2614
2324
  }
2615
2325
  close() {
2616
2326
  if (this.lanceClient) {