@mastra/lance 0.0.0-iterate-traces-ui-again-20250912091900 → 0.0.0-main-test-20251105183450

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 CHANGED
@@ -5,130 +5,15 @@ var error = require('@mastra/core/error');
5
5
  var storage = require('@mastra/core/storage');
6
6
  var agent = require('@mastra/core/agent');
7
7
  var apacheArrow = require('apache-arrow');
8
+ var evals = require('@mastra/core/evals');
8
9
  var vector = require('@mastra/core/vector');
9
10
  var filter = require('@mastra/core/vector/filter');
10
11
 
11
12
  // 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
13
  function getPrimaryKeys(tableName) {
127
14
  let primaryId = ["id"];
128
15
  if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
129
16
  primaryId = ["workflow_name", "run_id"];
130
- } else if (tableName === storage.TABLE_EVALS) {
131
- primaryId = ["agent_name", "metric_name", "run_id"];
132
17
  }
133
18
  return primaryId;
134
19
  }
@@ -189,7 +74,6 @@ function processResultWithTypeConversion(rawResult, tableSchema) {
189
74
  } else if (fieldTypeStr.includes("float64") && ["createdAt", "updatedAt"].includes(key)) {
190
75
  processedResult[key] = new Date(processedResult[key]);
191
76
  }
192
- console.log(key, "processedResult", processedResult);
193
77
  }
194
78
  return processedResult;
195
79
  }
@@ -249,6 +133,10 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
249
133
  this.client = client;
250
134
  this.operations = operations;
251
135
  }
136
+ // Utility to escape single quotes in SQL strings
137
+ escapeSql(str) {
138
+ return str.replace(/'/g, "''");
139
+ }
252
140
  async getThreadById({ threadId }) {
253
141
  try {
254
142
  const thread = await this.operations.load({ tableName: storage.TABLE_THREADS, keys: { id: threadId } });
@@ -271,26 +159,6 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
271
159
  );
272
160
  }
273
161
  }
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
162
  /**
295
163
  * Saves a thread to the database. This function doesn't overwrite existing threads.
296
164
  * @param thread - The thread to save
@@ -395,100 +263,174 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
395
263
  })() : message.content
396
264
  };
397
265
  }
398
- async getMessages({
399
- threadId,
400
- resourceId,
401
- selectBy,
402
- format,
403
- threadConfig
404
- }) {
266
+ async listMessagesById({ messageIds }) {
267
+ if (messageIds.length === 0) return { messages: [] };
405
268
  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
269
  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
- }
270
+ const quotedIds = messageIds.map((id) => `'${id}'`).join(", ");
271
+ const allRecords = await table.query().where(`id IN (${quotedIds})`).toArray();
435
272
  const messages = processResultWithTypeConversion(
436
273
  allRecords,
437
274
  await getTableSchema({ tableName: storage.TABLE_MESSAGES, client: this.client })
438
275
  );
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();
276
+ const list = new agent.MessageList().add(
277
+ messages.map(this.normalizeMessage),
278
+ "memory"
279
+ );
280
+ return { messages: list.get.all.db() };
442
281
  } catch (error$1) {
443
282
  throw new error.MastraError(
444
283
  {
445
- id: "LANCE_STORE_GET_MESSAGES_FAILED",
284
+ id: "LANCE_STORE_LIST_MESSAGES_BY_ID_FAILED",
446
285
  domain: error.ErrorDomain.STORAGE,
447
286
  category: error.ErrorCategory.THIRD_PARTY,
448
287
  details: {
449
- threadId,
450
- resourceId: resourceId ?? ""
288
+ messageIds: JSON.stringify(messageIds)
451
289
  }
452
290
  },
453
291
  error$1
454
292
  );
455
293
  }
456
294
  }
457
- async getMessagesById({
458
- messageIds,
459
- format
460
- }) {
461
- if (messageIds.length === 0) return [];
295
+ async listMessages(args) {
296
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
297
+ if (!threadId.trim()) {
298
+ throw new error.MastraError(
299
+ {
300
+ id: "STORAGE_LANCE_LIST_MESSAGES_INVALID_THREAD_ID",
301
+ domain: error.ErrorDomain.STORAGE,
302
+ category: error.ErrorCategory.THIRD_PARTY,
303
+ details: { threadId }
304
+ },
305
+ new Error("threadId must be a non-empty string")
306
+ );
307
+ }
308
+ const perPage = storage.normalizePerPage(perPageInput, 40);
309
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
462
310
  try {
311
+ if (page < 0) {
312
+ throw new error.MastraError(
313
+ {
314
+ id: "STORAGE_LANCE_LIST_MESSAGES_INVALID_PAGE",
315
+ domain: error.ErrorDomain.STORAGE,
316
+ category: error.ErrorCategory.USER,
317
+ details: { page }
318
+ },
319
+ new Error("page must be >= 0")
320
+ );
321
+ }
322
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
463
323
  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();
324
+ const conditions = [`thread_id = '${this.escapeSql(threadId)}'`];
325
+ if (resourceId) {
326
+ conditions.push(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
327
+ }
328
+ if (filter?.dateRange?.start) {
329
+ const startTime = filter.dateRange.start instanceof Date ? filter.dateRange.start.getTime() : new Date(filter.dateRange.start).getTime();
330
+ conditions.push(`\`createdAt\` >= ${startTime}`);
331
+ }
332
+ if (filter?.dateRange?.end) {
333
+ const endTime = filter.dateRange.end instanceof Date ? filter.dateRange.end.getTime() : new Date(filter.dateRange.end).getTime();
334
+ conditions.push(`\`createdAt\` <= ${endTime}`);
335
+ }
336
+ const whereClause = conditions.join(" AND ");
337
+ const total = await table.countRows(whereClause);
338
+ const query = table.query().where(whereClause);
339
+ let allRecords = await query.toArray();
340
+ allRecords.sort((a, b) => {
341
+ const aValue = field === "createdAt" ? a.createdAt : a[field];
342
+ const bValue = field === "createdAt" ? b.createdAt : b[field];
343
+ if (aValue == null && bValue == null) return 0;
344
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
345
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
346
+ if (typeof aValue === "string" && typeof bValue === "string") {
347
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
348
+ }
349
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
350
+ });
351
+ const paginatedRecords = allRecords.slice(offset, offset + perPage);
352
+ const messages = paginatedRecords.map((row) => this.normalizeMessage(row));
353
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
354
+ return {
355
+ messages: [],
356
+ total: 0,
357
+ page,
358
+ perPage: perPageForResponse,
359
+ hasMore: false
360
+ };
361
+ }
362
+ const messageIds = new Set(messages.map((m) => m.id));
363
+ if (include && include.length > 0) {
364
+ const threadIds = [...new Set(include.map((item) => item.threadId || threadId))];
365
+ const allThreadMessages = [];
366
+ for (const tid of threadIds) {
367
+ const threadQuery = table.query().where(`thread_id = '${tid}'`);
368
+ let threadRecords = await threadQuery.toArray();
369
+ allThreadMessages.push(...threadRecords);
370
+ }
371
+ allThreadMessages.sort((a, b) => a.createdAt - b.createdAt);
372
+ const contextMessages = this.processMessagesWithContext(allThreadMessages, include);
373
+ const includedMessages = contextMessages.map((row) => this.normalizeMessage(row));
374
+ for (const includeMsg of includedMessages) {
375
+ if (!messageIds.has(includeMsg.id)) {
376
+ messages.push(includeMsg);
377
+ messageIds.add(includeMsg.id);
378
+ }
379
+ }
380
+ }
381
+ const list = new agent.MessageList().add(messages, "memory");
382
+ let finalMessages = list.get.all.db();
383
+ finalMessages = finalMessages.sort((a, b) => {
384
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
385
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
386
+ if (aValue == null && bValue == null) return 0;
387
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
388
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
389
+ if (typeof aValue === "string" && typeof bValue === "string") {
390
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
391
+ }
392
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
393
+ });
394
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
395
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
396
+ const fetchedAll = perPageInput === false || allThreadMessagesReturned;
397
+ const hasMore = !fetchedAll && offset + perPage < total;
398
+ return {
399
+ messages: finalMessages,
400
+ total,
401
+ page,
402
+ perPage: perPageForResponse,
403
+ hasMore
404
+ };
473
405
  } catch (error$1) {
474
- throw new error.MastraError(
406
+ const mastraError = new error.MastraError(
475
407
  {
476
- id: "LANCE_STORE_GET_MESSAGES_BY_ID_FAILED",
408
+ id: "LANCE_STORE_LIST_MESSAGES_FAILED",
477
409
  domain: error.ErrorDomain.STORAGE,
478
410
  category: error.ErrorCategory.THIRD_PARTY,
479
411
  details: {
480
- messageIds: JSON.stringify(messageIds)
412
+ threadId,
413
+ resourceId: resourceId ?? ""
481
414
  }
482
415
  },
483
416
  error$1
484
417
  );
418
+ this.logger?.error?.(mastraError.toString());
419
+ this.logger?.trackException?.(mastraError);
420
+ return {
421
+ messages: [],
422
+ total: 0,
423
+ page,
424
+ perPage: perPageForResponse,
425
+ hasMore: false
426
+ };
485
427
  }
486
428
  }
487
429
  async saveMessages(args) {
488
430
  try {
489
- const { messages, format = "v1" } = args;
431
+ const { messages } = args;
490
432
  if (messages.length === 0) {
491
- return [];
433
+ return { messages: [] };
492
434
  }
493
435
  const threadId = messages[0]?.threadId;
494
436
  if (!threadId) {
@@ -524,8 +466,7 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
524
466
  const updateRecord = { id: threadId, updatedAt: currentTime };
525
467
  await threadsTable.mergeInsert("id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([updateRecord]);
526
468
  const list = new agent.MessageList().add(messages, "memory");
527
- if (format === `v2`) return list.get.all.v2();
528
- return list.get.all.v1();
469
+ return { messages: list.get.all.db() };
529
470
  } catch (error$1) {
530
471
  throw new error.MastraError(
531
472
  {
@@ -537,32 +478,54 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
537
478
  );
538
479
  }
539
480
  }
540
- async getThreadsByResourceIdPaginated(args) {
481
+ async listThreadsByResourceId(args) {
541
482
  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);
483
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
484
+ const perPage = storage.normalizePerPage(perPageInput, 100);
485
+ if (page < 0) {
486
+ throw new error.MastraError(
487
+ {
488
+ id: "STORAGE_LANCE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
489
+ domain: error.ErrorDomain.STORAGE,
490
+ category: error.ErrorCategory.USER,
491
+ details: { page }
492
+ },
493
+ new Error("page must be >= 0")
494
+ );
550
495
  }
496
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
497
+ const { field, direction } = this.parseOrderBy(orderBy);
498
+ const table = await this.client.openTable(storage.TABLE_THREADS);
499
+ const total = await table.countRows(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
500
+ const query = table.query().where(`\`resourceId\` = '${this.escapeSql(resourceId)}'`);
551
501
  const records = await query.toArray();
552
- records.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
502
+ records.sort((a, b) => {
503
+ const aValue = ["createdAt", "updatedAt"].includes(field) ? new Date(a[field]).getTime() : a[field];
504
+ const bValue = ["createdAt", "updatedAt"].includes(field) ? new Date(b[field]).getTime() : b[field];
505
+ if (aValue == null && bValue == null) return 0;
506
+ if (aValue == null) return direction === "ASC" ? -1 : 1;
507
+ if (bValue == null) return direction === "ASC" ? 1 : -1;
508
+ if (typeof aValue === "string" && typeof bValue === "string") {
509
+ return direction === "ASC" ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
510
+ }
511
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
512
+ });
513
+ const paginatedRecords = records.slice(offset, offset + perPage);
553
514
  const schema = await getTableSchema({ tableName: storage.TABLE_THREADS, client: this.client });
554
- const threads = records.map((record) => processResultWithTypeConversion(record, schema));
515
+ const threads = paginatedRecords.map(
516
+ (record) => processResultWithTypeConversion(record, schema)
517
+ );
555
518
  return {
556
519
  threads,
557
520
  total,
558
521
  page,
559
- perPage,
560
- hasMore: total > (page + 1) * perPage
522
+ perPage: perPageForResponse,
523
+ hasMore: offset + perPage < total
561
524
  };
562
525
  } catch (error$1) {
563
526
  throw new error.MastraError(
564
527
  {
565
- id: "LANCE_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
528
+ id: "LANCE_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
566
529
  domain: error.ErrorDomain.STORAGE,
567
530
  category: error.ErrorCategory.THIRD_PARTY
568
531
  },
@@ -618,132 +581,8 @@ var StoreMemoryLance = class extends storage.MemoryStorage {
618
581
  });
619
582
  return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
620
583
  }
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
584
  /**
746
- * Parse message data from LanceDB record format to MastraMessageV2 format
585
+ * Parse message data from LanceDB record format to MastraDBMessage format
747
586
  */
748
587
  parseMessageData(data) {
749
588
  const { thread_id, ...rest } = data;
@@ -1266,7 +1105,7 @@ var StoreOperationsLance = class extends storage.StoreOperations {
1266
1105
  processedRecord[key] = JSON.stringify(processedRecord[key]);
1267
1106
  }
1268
1107
  }
1269
- console.log(await table.schema());
1108
+ console.info(await table.schema());
1270
1109
  await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([processedRecord]);
1271
1110
  } catch (error$1) {
1272
1111
  throw new error.MastraError(
@@ -1316,7 +1155,6 @@ var StoreOperationsLance = class extends storage.StoreOperations {
1316
1155
  }
1317
1156
  return processedRecord;
1318
1157
  });
1319
- console.log(processedRecords);
1320
1158
  await table.mergeInsert(primaryId).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(processedRecords);
1321
1159
  } catch (error$1) {
1322
1160
  throw new error.MastraError(
@@ -1400,13 +1238,27 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1400
1238
  this.client = client;
1401
1239
  }
1402
1240
  async saveScore(score) {
1241
+ let validatedScore;
1242
+ try {
1243
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
1244
+ } catch (error$1) {
1245
+ throw new error.MastraError(
1246
+ {
1247
+ id: "LANCE_STORAGE_SAVE_SCORE_FAILED",
1248
+ text: "Failed to save score in LanceStorage",
1249
+ domain: error.ErrorDomain.STORAGE,
1250
+ category: error.ErrorCategory.THIRD_PARTY
1251
+ },
1252
+ error$1
1253
+ );
1254
+ }
1403
1255
  try {
1404
1256
  const id = crypto.randomUUID();
1405
1257
  const table = await this.client.openTable(storage.TABLE_SCORERS);
1406
1258
  const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1407
1259
  const allowedFields = new Set(schema.fields.map((f) => f.name));
1408
1260
  const filteredScore = {};
1409
- Object.keys(score).forEach((key) => {
1261
+ Object.keys(validatedScore).forEach((key) => {
1410
1262
  if (allowedFields.has(key)) {
1411
1263
  filteredScore[key] = score[key];
1412
1264
  }
@@ -1453,7 +1305,7 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1453
1305
  );
1454
1306
  }
1455
1307
  }
1456
- async getScoresByScorerId({
1308
+ async listScoresByScorerId({
1457
1309
  scorerId,
1458
1310
  pagination,
1459
1311
  entityId,
@@ -1461,9 +1313,10 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1461
1313
  source
1462
1314
  }) {
1463
1315
  try {
1316
+ const { page, perPage: perPageInput } = pagination;
1317
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1318
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1464
1319
  const table = await this.client.openTable(storage.TABLE_SCORERS);
1465
- const { page = 0, perPage = 10 } = pagination || {};
1466
- const offset = page * perPage;
1467
1320
  let query = table.query().where(`\`scorerId\` = '${scorerId}'`);
1468
1321
  if (source) {
1469
1322
  query = query.where(`\`source\` = '${source}'`);
@@ -1474,23 +1327,32 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1474
1327
  if (entityType) {
1475
1328
  query = query.where(`\`entityType\` = '${entityType}'`);
1476
1329
  }
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
1330
  let totalQuery = table.query().where(`\`scorerId\` = '${scorerId}'`);
1483
1331
  if (source) {
1484
1332
  totalQuery = totalQuery.where(`\`source\` = '${source}'`);
1485
1333
  }
1334
+ if (entityId) {
1335
+ totalQuery = totalQuery.where(`\`entityId\` = '${entityId}'`);
1336
+ }
1337
+ if (entityType) {
1338
+ totalQuery = totalQuery.where(`\`entityType\` = '${entityType}'`);
1339
+ }
1486
1340
  const allRecords = await totalQuery.toArray();
1487
1341
  const total = allRecords.length;
1342
+ const end = perPageInput === false ? total : start + perPage;
1343
+ if (perPageInput !== false) {
1344
+ query = query.limit(perPage);
1345
+ if (start > 0) query = query.offset(start);
1346
+ }
1347
+ const records = await query.toArray();
1348
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1349
+ const scores = processResultWithTypeConversion(records, schema);
1488
1350
  return {
1489
1351
  pagination: {
1490
1352
  page,
1491
- perPage,
1353
+ perPage: perPageForResponse,
1492
1354
  total,
1493
- hasMore: offset + scores.length < total
1355
+ hasMore: end < total
1494
1356
  },
1495
1357
  scores
1496
1358
  };
@@ -1507,27 +1369,32 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1507
1369
  );
1508
1370
  }
1509
1371
  }
1510
- async getScoresByRunId({
1372
+ async listScoresByRunId({
1511
1373
  runId,
1512
1374
  pagination
1513
1375
  }) {
1514
1376
  try {
1377
+ const { page, perPage: perPageInput } = pagination;
1378
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1379
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1515
1380
  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);
1381
+ const allRecords = await table.query().where(`\`runId\` = '${runId}'`).toArray();
1382
+ const total = allRecords.length;
1383
+ const end = perPageInput === false ? total : start + perPage;
1384
+ let query = table.query().where(`\`runId\` = '${runId}'`);
1385
+ if (perPageInput !== false) {
1386
+ query = query.limit(perPage);
1387
+ if (start > 0) query = query.offset(start);
1388
+ }
1520
1389
  const records = await query.toArray();
1521
1390
  const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1522
1391
  const scores = processResultWithTypeConversion(records, schema);
1523
- const allRecords = await table.query().where(`\`runId\` = '${runId}'`).toArray();
1524
- const total = allRecords.length;
1525
1392
  return {
1526
1393
  pagination: {
1527
1394
  page,
1528
- perPage,
1395
+ perPage: perPageForResponse,
1529
1396
  total,
1530
- hasMore: offset + scores.length < total
1397
+ hasMore: end < total
1531
1398
  },
1532
1399
  scores
1533
1400
  };
@@ -1544,28 +1411,33 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1544
1411
  );
1545
1412
  }
1546
1413
  }
1547
- async getScoresByEntityId({
1414
+ async listScoresByEntityId({
1548
1415
  entityId,
1549
1416
  entityType,
1550
1417
  pagination
1551
1418
  }) {
1552
1419
  try {
1420
+ const { page, perPage: perPageInput } = pagination;
1421
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1422
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1553
1423
  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);
1424
+ const allRecords = await table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).toArray();
1425
+ const total = allRecords.length;
1426
+ const end = perPageInput === false ? total : start + perPage;
1427
+ let query = table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`);
1428
+ if (perPageInput !== false) {
1429
+ query = query.limit(perPage);
1430
+ if (start > 0) query = query.offset(start);
1431
+ }
1558
1432
  const records = await query.toArray();
1559
1433
  const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1560
1434
  const scores = processResultWithTypeConversion(records, schema);
1561
- const allRecords = await table.query().where(`\`entityId\` = '${entityId}' AND \`entityType\` = '${entityType}'`).toArray();
1562
- const total = allRecords.length;
1563
1435
  return {
1564
1436
  pagination: {
1565
1437
  page,
1566
- perPage,
1438
+ perPage: perPageForResponse,
1567
1439
  total,
1568
- hasMore: offset + scores.length < total
1440
+ hasMore: end < total
1569
1441
  },
1570
1442
  scores
1571
1443
  };
@@ -1582,198 +1454,49 @@ var StoreScoresLance = class extends storage.ScoresStorage {
1582
1454
  );
1583
1455
  }
1584
1456
  }
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
1457
+ async listScoresBySpan({
1458
+ traceId,
1459
+ spanId,
1460
+ pagination
1641
1461
  }) {
1642
1462
  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);
1463
+ const { page, perPage: perPageInput } = pagination;
1464
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1465
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1466
+ const table = await this.client.openTable(storage.TABLE_SCORERS);
1467
+ const allRecords = await table.query().where(`\`traceId\` = '${traceId}' AND \`spanId\` = '${spanId}'`).toArray();
1468
+ const total = allRecords.length;
1469
+ const end = perPageInput === false ? total : start + perPage;
1470
+ let query = table.query().where(`\`traceId\` = '${traceId}' AND \`spanId\` = '${spanId}'`);
1471
+ if (perPageInput !== false) {
1472
+ query = query.limit(perPage);
1473
+ if (start > 0) query = query.offset(start);
1730
1474
  }
1731
1475
  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
- });
1476
+ const schema = await getTableSchema({ tableName: storage.TABLE_SCORERS, client: this.client });
1477
+ const scores = processResultWithTypeConversion(records, schema);
1751
1478
  return {
1752
- traces,
1753
- total,
1754
- page,
1755
- perPage,
1756
- hasMore: total > (page + 1) * perPage
1479
+ pagination: {
1480
+ page,
1481
+ perPage: perPageForResponse,
1482
+ total,
1483
+ hasMore: end < total
1484
+ },
1485
+ scores
1757
1486
  };
1758
1487
  } catch (error$1) {
1759
1488
  throw new error.MastraError(
1760
1489
  {
1761
- id: "LANCE_STORE_GET_TRACES_PAGINATED_FAILED",
1490
+ id: "LANCE_STORAGE_GET_SCORES_BY_SPAN_FAILED",
1491
+ text: "Failed to get scores by traceId and spanId in LanceStorage",
1762
1492
  domain: error.ErrorDomain.STORAGE,
1763
1493
  category: error.ErrorCategory.THIRD_PARTY,
1764
- details: { name: args.name ?? "", scope: args.scope ?? "" }
1494
+ details: { error: error$1?.message }
1765
1495
  },
1766
1496
  error$1
1767
1497
  );
1768
1498
  }
1769
1499
  }
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
1500
  };
1778
1501
  function parseWorkflowRun(row) {
1779
1502
  let parsedSnapshot = row.snapshot;
@@ -1804,7 +1527,7 @@ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1804
1527
  // runId,
1805
1528
  // stepId,
1806
1529
  // result,
1807
- // runtimeContext,
1530
+ // requestContext,
1808
1531
  }) {
1809
1532
  throw new Error("Method not implemented.");
1810
1533
  }
@@ -1818,6 +1541,7 @@ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1818
1541
  async persistWorkflowSnapshot({
1819
1542
  workflowName,
1820
1543
  runId,
1544
+ resourceId,
1821
1545
  snapshot
1822
1546
  }) {
1823
1547
  try {
@@ -1834,6 +1558,7 @@ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1834
1558
  const record = {
1835
1559
  workflow_name: workflowName,
1836
1560
  run_id: runId,
1561
+ resourceId,
1837
1562
  snapshot: JSON.stringify(snapshot),
1838
1563
  createdAt,
1839
1564
  updatedAt: now
@@ -1896,7 +1621,7 @@ var StoreWorkflowsLance = class extends storage.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(storage.TABLE_WORKFLOW_SNAPSHOT);
1902
1627
  let query = table.query();
@@ -1920,11 +1645,22 @@ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1920
1645
  } else {
1921
1646
  total = await table.countRows();
1922
1647
  }
1923
- if (args?.limit) {
1924
- query.limit(args.limit);
1925
- }
1926
- if (args?.offset) {
1927
- query.offset(args.offset);
1648
+ if (args?.perPage !== void 0 && args?.page !== void 0) {
1649
+ const normalizedPerPage = storage.normalizePerPage(args.perPage, Number.MAX_SAFE_INTEGER);
1650
+ if (args.page < 0 || !Number.isInteger(args.page)) {
1651
+ throw new error.MastraError(
1652
+ {
1653
+ id: "LANCE_STORE_INVALID_PAGINATION_PARAMS",
1654
+ domain: error.ErrorDomain.STORAGE,
1655
+ category: error.ErrorCategory.USER,
1656
+ details: { page: args.page, perPage: args.perPage }
1657
+ },
1658
+ new Error(`Invalid pagination parameters: page=${args.page}, perPage=${args.perPage}`)
1659
+ );
1660
+ }
1661
+ const offset = args.page * normalizedPerPage;
1662
+ query.limit(normalizedPerPage);
1663
+ query.offset(offset);
1928
1664
  }
1929
1665
  const records = await query.toArray();
1930
1666
  return {
@@ -1934,10 +1670,10 @@ var StoreWorkflowsLance = class extends storage.WorkflowsStorage {
1934
1670
  } catch (error$1) {
1935
1671
  throw new error.MastraError(
1936
1672
  {
1937
- id: "LANCE_STORE_GET_WORKFLOW_RUNS_FAILED",
1673
+ id: "LANCE_STORE_LIST_WORKFLOW_RUNS_FAILED",
1938
1674
  domain: error.ErrorDomain.STORAGE,
1939
1675
  category: error.ErrorCategory.THIRD_PARTY,
1940
- details: { namespace: args?.namespace ?? "", workflowName: args?.workflowName ?? "" }
1676
+ details: { resourceId: args?.resourceId ?? "", workflowName: args?.workflowName ?? "" }
1941
1677
  },
1942
1678
  error$1
1943
1679
  );
@@ -1979,10 +1715,8 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
1979
1715
  instance.stores = {
1980
1716
  operations: new StoreOperationsLance({ client: instance.lanceClient }),
1981
1717
  workflows: new StoreWorkflowsLance({ client: instance.lanceClient }),
1982
- traces: new StoreTracesLance({ client: instance.lanceClient, operations }),
1983
1718
  scores: new StoreScoresLance({ client: instance.lanceClient }),
1984
- memory: new StoreMemoryLance({ client: instance.lanceClient, operations }),
1985
- legacyEvals: new StoreLegacyEvalsLance({ client: instance.lanceClient })
1719
+ memory: new StoreMemoryLance({ client: instance.lanceClient, operations })
1986
1720
  };
1987
1721
  return instance;
1988
1722
  } catch (e) {
@@ -2008,9 +1742,7 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2008
1742
  this.stores = {
2009
1743
  operations: new StoreOperationsLance({ client: this.lanceClient }),
2010
1744
  workflows: new StoreWorkflowsLance({ client: this.lanceClient }),
2011
- traces: new StoreTracesLance({ client: this.lanceClient, operations }),
2012
1745
  scores: new StoreScoresLance({ client: this.lanceClient }),
2013
- legacyEvals: new StoreLegacyEvalsLance({ client: this.lanceClient }),
2014
1746
  memory: new StoreMemoryLance({ client: this.lanceClient, operations })
2015
1747
  };
2016
1748
  }
@@ -2045,9 +1777,6 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2045
1777
  async getThreadById({ threadId }) {
2046
1778
  return this.stores.memory.getThreadById({ threadId });
2047
1779
  }
2048
- async getThreadsByResourceId({ resourceId }) {
2049
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2050
- }
2051
1780
  /**
2052
1781
  * Saves a thread to the database. This function doesn't overwrite existing threads.
2053
1782
  * @param thread - The thread to save
@@ -2072,7 +1801,8 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2072
1801
  resourceWorkingMemory: true,
2073
1802
  hasColumn: true,
2074
1803
  createTable: true,
2075
- deleteMessages: false
1804
+ deleteMessages: false,
1805
+ listScoresBySpan: true
2076
1806
  };
2077
1807
  }
2078
1808
  async getResourceById({ resourceId }) {
@@ -2136,50 +1866,17 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2136
1866
  });
2137
1867
  return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
2138
1868
  }
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 });
1869
+ async listMessagesById({ messageIds }) {
1870
+ return this.stores.memory.listMessagesById({ messageIds });
2153
1871
  }
2154
1872
  async saveMessages(args) {
2155
1873
  return this.stores.memory.saveMessages(args);
2156
1874
  }
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
1875
  async updateMessages(_args) {
2164
1876
  return this.stores.memory.updateMessages(_args);
2165
1877
  }
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);
1878
+ async listWorkflowRuns(args) {
1879
+ return this.stores.workflows.listWorkflowRuns(args);
2183
1880
  }
2184
1881
  async getWorkflowRunById(args) {
2185
1882
  return this.stores.workflows.getWorkflowRunById(args);
@@ -2189,9 +1886,9 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2189
1886
  runId,
2190
1887
  stepId,
2191
1888
  result,
2192
- runtimeContext
1889
+ requestContext
2193
1890
  }) {
2194
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
1891
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2195
1892
  }
2196
1893
  async updateWorkflowState({
2197
1894
  workflowName,
@@ -2203,9 +1900,10 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2203
1900
  async persistWorkflowSnapshot({
2204
1901
  workflowName,
2205
1902
  runId,
1903
+ resourceId,
2206
1904
  snapshot
2207
1905
  }) {
2208
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
1906
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2209
1907
  }
2210
1908
  async loadWorkflowSnapshot({
2211
1909
  workflowName,
@@ -2216,30 +1914,37 @@ var LanceStorage = class _LanceStorage extends storage.MastraStorage {
2216
1914
  async getScoreById({ id: _id }) {
2217
1915
  return this.stores.scores.getScoreById({ id: _id });
2218
1916
  }
2219
- async getScoresByScorerId({
1917
+ async listScoresByScorerId({
2220
1918
  scorerId,
2221
1919
  source,
2222
1920
  entityId,
2223
1921
  entityType,
2224
1922
  pagination
2225
1923
  }) {
2226
- return this.stores.scores.getScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
1924
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
2227
1925
  }
2228
1926
  async saveScore(_score) {
2229
1927
  return this.stores.scores.saveScore(_score);
2230
1928
  }
2231
- async getScoresByRunId({
1929
+ async listScoresByRunId({
2232
1930
  runId,
2233
1931
  pagination
2234
1932
  }) {
2235
- return this.stores.scores.getScoresByRunId({ runId, pagination });
1933
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2236
1934
  }
2237
- async getScoresByEntityId({
1935
+ async listScoresByEntityId({
2238
1936
  entityId,
2239
1937
  entityType,
2240
1938
  pagination
2241
1939
  }) {
2242
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
1940
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
1941
+ }
1942
+ async listScoresBySpan({
1943
+ traceId,
1944
+ spanId,
1945
+ pagination
1946
+ }) {
1947
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2243
1948
  }
2244
1949
  };
2245
1950
  var LanceFilterTranslator = class extends filter.BaseFilterTranslator {