@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.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
  }
@@ -1816,6 +1539,7 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1816
1539
  async persistWorkflowSnapshot({
1817
1540
  workflowName,
1818
1541
  runId,
1542
+ resourceId,
1819
1543
  snapshot
1820
1544
  }) {
1821
1545
  try {
@@ -1832,6 +1556,7 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1832
1556
  const record = {
1833
1557
  workflow_name: workflowName,
1834
1558
  run_id: runId,
1559
+ resourceId,
1835
1560
  snapshot: JSON.stringify(snapshot),
1836
1561
  createdAt,
1837
1562
  updatedAt: now
@@ -1894,7 +1619,7 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1894
1619
  );
1895
1620
  }
1896
1621
  }
1897
- async getWorkflowRuns(args) {
1622
+ async listWorkflowRuns(args) {
1898
1623
  try {
1899
1624
  const table = await this.client.openTable(TABLE_WORKFLOW_SNAPSHOT);
1900
1625
  let query = table.query();
@@ -1918,11 +1643,22 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1918
1643
  } else {
1919
1644
  total = await table.countRows();
1920
1645
  }
1921
- if (args?.limit) {
1922
- query.limit(args.limit);
1923
- }
1924
- if (args?.offset) {
1925
- query.offset(args.offset);
1646
+ if (args?.perPage !== void 0 && args?.page !== void 0) {
1647
+ const normalizedPerPage = normalizePerPage(args.perPage, Number.MAX_SAFE_INTEGER);
1648
+ if (args.page < 0 || !Number.isInteger(args.page)) {
1649
+ throw new MastraError(
1650
+ {
1651
+ id: "LANCE_STORE_INVALID_PAGINATION_PARAMS",
1652
+ domain: ErrorDomain.STORAGE,
1653
+ category: ErrorCategory.USER,
1654
+ details: { page: args.page, perPage: args.perPage }
1655
+ },
1656
+ new Error(`Invalid pagination parameters: page=${args.page}, perPage=${args.perPage}`)
1657
+ );
1658
+ }
1659
+ const offset = args.page * normalizedPerPage;
1660
+ query.limit(normalizedPerPage);
1661
+ query.offset(offset);
1926
1662
  }
1927
1663
  const records = await query.toArray();
1928
1664
  return {
@@ -1932,10 +1668,10 @@ var StoreWorkflowsLance = class extends WorkflowsStorage {
1932
1668
  } catch (error) {
1933
1669
  throw new MastraError(
1934
1670
  {
1935
- id: "LANCE_STORE_GET_WORKFLOW_RUNS_FAILED",
1671
+ id: "LANCE_STORE_LIST_WORKFLOW_RUNS_FAILED",
1936
1672
  domain: ErrorDomain.STORAGE,
1937
1673
  category: ErrorCategory.THIRD_PARTY,
1938
- details: { namespace: args?.namespace ?? "", workflowName: args?.workflowName ?? "" }
1674
+ details: { resourceId: args?.resourceId ?? "", workflowName: args?.workflowName ?? "" }
1939
1675
  },
1940
1676
  error
1941
1677
  );
@@ -1977,10 +1713,8 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
1977
1713
  instance.stores = {
1978
1714
  operations: new StoreOperationsLance({ client: instance.lanceClient }),
1979
1715
  workflows: new StoreWorkflowsLance({ client: instance.lanceClient }),
1980
- traces: new StoreTracesLance({ client: instance.lanceClient, operations }),
1981
1716
  scores: new StoreScoresLance({ client: instance.lanceClient }),
1982
- memory: new StoreMemoryLance({ client: instance.lanceClient, operations }),
1983
- legacyEvals: new StoreLegacyEvalsLance({ client: instance.lanceClient })
1717
+ memory: new StoreMemoryLance({ client: instance.lanceClient, operations })
1984
1718
  };
1985
1719
  return instance;
1986
1720
  } catch (e) {
@@ -2006,9 +1740,7 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2006
1740
  this.stores = {
2007
1741
  operations: new StoreOperationsLance({ client: this.lanceClient }),
2008
1742
  workflows: new StoreWorkflowsLance({ client: this.lanceClient }),
2009
- traces: new StoreTracesLance({ client: this.lanceClient, operations }),
2010
1743
  scores: new StoreScoresLance({ client: this.lanceClient }),
2011
- legacyEvals: new StoreLegacyEvalsLance({ client: this.lanceClient }),
2012
1744
  memory: new StoreMemoryLance({ client: this.lanceClient, operations })
2013
1745
  };
2014
1746
  }
@@ -2043,9 +1775,6 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2043
1775
  async getThreadById({ threadId }) {
2044
1776
  return this.stores.memory.getThreadById({ threadId });
2045
1777
  }
2046
- async getThreadsByResourceId({ resourceId }) {
2047
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2048
- }
2049
1778
  /**
2050
1779
  * Saves a thread to the database. This function doesn't overwrite existing threads.
2051
1780
  * @param thread - The thread to save
@@ -2070,7 +1799,8 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2070
1799
  resourceWorkingMemory: true,
2071
1800
  hasColumn: true,
2072
1801
  createTable: true,
2073
- deleteMessages: false
1802
+ deleteMessages: false,
1803
+ listScoresBySpan: true
2074
1804
  };
2075
1805
  }
2076
1806
  async getResourceById({ resourceId }) {
@@ -2134,50 +1864,17 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2134
1864
  });
2135
1865
  return Array.from(allIndices).sort((a, b) => a - b).map((index) => records[index]);
2136
1866
  }
2137
- async getMessages({
2138
- threadId,
2139
- resourceId,
2140
- selectBy,
2141
- format,
2142
- threadConfig
2143
- }) {
2144
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format, threadConfig });
2145
- }
2146
- async getMessagesById({
2147
- messageIds,
2148
- format
2149
- }) {
2150
- return this.stores.memory.getMessagesById({ messageIds, format });
1867
+ async listMessagesById({ messageIds }) {
1868
+ return this.stores.memory.listMessagesById({ messageIds });
2151
1869
  }
2152
1870
  async saveMessages(args) {
2153
1871
  return this.stores.memory.saveMessages(args);
2154
1872
  }
2155
- async getThreadsByResourceIdPaginated(args) {
2156
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2157
- }
2158
- async getMessagesPaginated(args) {
2159
- return this.stores.memory.getMessagesPaginated(args);
2160
- }
2161
1873
  async updateMessages(_args) {
2162
1874
  return this.stores.memory.updateMessages(_args);
2163
1875
  }
2164
- async getTraceById(args) {
2165
- return this.stores.traces.getTraceById(args);
2166
- }
2167
- async getTraces(args) {
2168
- return this.stores.traces.getTraces(args);
2169
- }
2170
- async getTracesPaginated(args) {
2171
- return this.stores.traces.getTracesPaginated(args);
2172
- }
2173
- async getEvalsByAgentName(agentName, type) {
2174
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2175
- }
2176
- async getEvals(options) {
2177
- return this.stores.legacyEvals.getEvals(options);
2178
- }
2179
- async getWorkflowRuns(args) {
2180
- return this.stores.workflows.getWorkflowRuns(args);
1876
+ async listWorkflowRuns(args) {
1877
+ return this.stores.workflows.listWorkflowRuns(args);
2181
1878
  }
2182
1879
  async getWorkflowRunById(args) {
2183
1880
  return this.stores.workflows.getWorkflowRunById(args);
@@ -2187,9 +1884,9 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2187
1884
  runId,
2188
1885
  stepId,
2189
1886
  result,
2190
- runtimeContext
1887
+ requestContext
2191
1888
  }) {
2192
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
1889
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2193
1890
  }
2194
1891
  async updateWorkflowState({
2195
1892
  workflowName,
@@ -2201,9 +1898,10 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2201
1898
  async persistWorkflowSnapshot({
2202
1899
  workflowName,
2203
1900
  runId,
1901
+ resourceId,
2204
1902
  snapshot
2205
1903
  }) {
2206
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
1904
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2207
1905
  }
2208
1906
  async loadWorkflowSnapshot({
2209
1907
  workflowName,
@@ -2214,30 +1912,37 @@ var LanceStorage = class _LanceStorage extends MastraStorage {
2214
1912
  async getScoreById({ id: _id }) {
2215
1913
  return this.stores.scores.getScoreById({ id: _id });
2216
1914
  }
2217
- async getScoresByScorerId({
1915
+ async listScoresByScorerId({
2218
1916
  scorerId,
2219
1917
  source,
2220
1918
  entityId,
2221
1919
  entityType,
2222
1920
  pagination
2223
1921
  }) {
2224
- return this.stores.scores.getScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
1922
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, pagination, entityId, entityType });
2225
1923
  }
2226
1924
  async saveScore(_score) {
2227
1925
  return this.stores.scores.saveScore(_score);
2228
1926
  }
2229
- async getScoresByRunId({
1927
+ async listScoresByRunId({
2230
1928
  runId,
2231
1929
  pagination
2232
1930
  }) {
2233
- return this.stores.scores.getScoresByRunId({ runId, pagination });
1931
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2234
1932
  }
2235
- async getScoresByEntityId({
1933
+ async listScoresByEntityId({
2236
1934
  entityId,
2237
1935
  entityType,
2238
1936
  pagination
2239
1937
  }) {
2240
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
1938
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
1939
+ }
1940
+ async listScoresBySpan({
1941
+ traceId,
1942
+ spanId,
1943
+ pagination
1944
+ }) {
1945
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2241
1946
  }
2242
1947
  };
2243
1948
  var LanceFilterTranslator = class extends BaseFilterTranslator {