@mastra/libsql 0.16.2 → 1.0.0-beta.1

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
@@ -7,7 +7,7 @@ var vector = require('@mastra/core/vector');
7
7
  var filter = require('@mastra/core/vector/filter');
8
8
  var storage = require('@mastra/core/storage');
9
9
  var agent = require('@mastra/core/agent');
10
- var scores = require('@mastra/core/scores');
10
+ var evals = require('@mastra/core/evals');
11
11
 
12
12
  // src/vector/index.ts
13
13
  var LibSQLFilterTranslator = class extends filter.BaseFilterTranslator {
@@ -507,9 +507,10 @@ var LibSQLVector = class extends vector.MastraVector {
507
507
  syncUrl,
508
508
  syncInterval,
509
509
  maxRetries = 5,
510
- initialBackoffMs = 100
510
+ initialBackoffMs = 100,
511
+ id
511
512
  }) {
512
- super();
513
+ super({ id });
513
514
  this.turso = client.createClient({
514
515
  url: connectionUrl,
515
516
  syncUrl,
@@ -920,120 +921,6 @@ var LibSQLVector = class extends vector.MastraVector {
920
921
  });
921
922
  }
922
923
  };
923
- function transformEvalRow(row) {
924
- const resultValue = JSON.parse(row.result);
925
- const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
926
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
927
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
928
- }
929
- return {
930
- input: row.input,
931
- output: row.output,
932
- result: resultValue,
933
- agentName: row.agent_name,
934
- metricName: row.metric_name,
935
- instructions: row.instructions,
936
- testInfo: testInfoValue,
937
- globalRunId: row.global_run_id,
938
- runId: row.run_id,
939
- createdAt: row.created_at
940
- };
941
- }
942
- var LegacyEvalsLibSQL = class extends storage.LegacyEvalsStorage {
943
- client;
944
- constructor({ client }) {
945
- super();
946
- this.client = client;
947
- }
948
- /** @deprecated use getEvals instead */
949
- async getEvalsByAgentName(agentName, type) {
950
- try {
951
- const baseQuery = `SELECT * FROM ${storage.TABLE_EVALS} WHERE agent_name = ?`;
952
- const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
953
- const result = await this.client.execute({
954
- sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
955
- args: [agentName]
956
- });
957
- return result.rows?.map((row) => transformEvalRow(row)) ?? [];
958
- } catch (error$1) {
959
- if (error$1 instanceof Error && error$1.message.includes("no such table")) {
960
- return [];
961
- }
962
- throw new error.MastraError(
963
- {
964
- id: "LIBSQL_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
965
- domain: error.ErrorDomain.STORAGE,
966
- category: error.ErrorCategory.THIRD_PARTY,
967
- details: { agentName }
968
- },
969
- error$1
970
- );
971
- }
972
- }
973
- async getEvals(options = {}) {
974
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
975
- const fromDate = dateRange?.start;
976
- const toDate = dateRange?.end;
977
- const conditions = [];
978
- const queryParams = [];
979
- if (agentName) {
980
- conditions.push(`agent_name = ?`);
981
- queryParams.push(agentName);
982
- }
983
- if (type === "test") {
984
- conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
985
- } else if (type === "live") {
986
- conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
987
- }
988
- if (fromDate) {
989
- conditions.push(`created_at >= ?`);
990
- queryParams.push(fromDate.toISOString());
991
- }
992
- if (toDate) {
993
- conditions.push(`created_at <= ?`);
994
- queryParams.push(toDate.toISOString());
995
- }
996
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
997
- try {
998
- const countResult = await this.client.execute({
999
- sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
1000
- args: queryParams
1001
- });
1002
- const total = Number(countResult.rows?.[0]?.count ?? 0);
1003
- const currentOffset = page * perPage;
1004
- const hasMore = currentOffset + perPage < total;
1005
- if (total === 0) {
1006
- return {
1007
- evals: [],
1008
- total: 0,
1009
- page,
1010
- perPage,
1011
- hasMore: false
1012
- };
1013
- }
1014
- const dataResult = await this.client.execute({
1015
- sql: `SELECT * FROM ${storage.TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
1016
- args: [...queryParams, perPage, currentOffset]
1017
- });
1018
- return {
1019
- evals: dataResult.rows?.map((row) => transformEvalRow(row)) ?? [],
1020
- total,
1021
- page,
1022
- perPage,
1023
- hasMore
1024
- };
1025
- } catch (error$1) {
1026
- throw new error.MastraError(
1027
- {
1028
- id: "LIBSQL_STORE_GET_EVALS_FAILED",
1029
- domain: error.ErrorDomain.STORAGE,
1030
- category: error.ErrorCategory.THIRD_PARTY
1031
- },
1032
- error$1
1033
- );
1034
- }
1035
- }
1036
- };
1037
924
  var MemoryLibSQL = class extends storage.MemoryStorage {
1038
925
  client;
1039
926
  operations;
@@ -1061,10 +948,9 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1061
948
  }
1062
949
  async _getIncludedMessages({
1063
950
  threadId,
1064
- selectBy
951
+ include
1065
952
  }) {
1066
953
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1067
- const include = selectBy?.include;
1068
954
  if (!include) return null;
1069
955
  const unionQueries = [];
1070
956
  const params = [];
@@ -1107,24 +993,10 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1107
993
  });
1108
994
  return dedupedRows;
1109
995
  }
1110
- async getMessages({
1111
- threadId,
1112
- resourceId,
1113
- selectBy,
1114
- format
1115
- }) {
996
+ async listMessagesById({ messageIds }) {
997
+ if (messageIds.length === 0) return { messages: [] };
1116
998
  try {
1117
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1118
- const messages = [];
1119
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1120
- if (selectBy?.include?.length) {
1121
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1122
- if (includeMessages) {
1123
- messages.push(...includeMessages);
1124
- }
1125
- }
1126
- const excludeIds = messages.map((m) => m.id);
1127
- const remainingSql = `
999
+ const sql = `
1128
1000
  SELECT
1129
1001
  id,
1130
1002
  content,
@@ -1134,105 +1006,71 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1134
1006
  thread_id,
1135
1007
  "resourceId"
1136
1008
  FROM "${storage.TABLE_MESSAGES}"
1137
- WHERE thread_id = ?
1138
- ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
1009
+ WHERE id IN (${messageIds.map(() => "?").join(", ")})
1139
1010
  ORDER BY "createdAt" DESC
1140
- LIMIT ?
1141
1011
  `;
1142
- const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
1143
- const remainingResult = await this.client.execute({ sql: remainingSql, args: remainingArgs });
1144
- if (remainingResult.rows) {
1145
- messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
1146
- }
1147
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
1148
- const list = new agent.MessageList().add(messages, "memory");
1149
- if (format === `v2`) return list.get.all.v2();
1150
- return list.get.all.v1();
1012
+ const result = await this.client.execute({ sql, args: messageIds });
1013
+ if (!result.rows) return { messages: [] };
1014
+ const list = new agent.MessageList().add(result.rows.map(this.parseRow), "memory");
1015
+ return { messages: list.get.all.db() };
1151
1016
  } catch (error$1) {
1152
1017
  throw new error.MastraError(
1153
1018
  {
1154
- id: "LIBSQL_STORE_GET_MESSAGES_FAILED",
1019
+ id: "LIBSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
1155
1020
  domain: error.ErrorDomain.STORAGE,
1156
1021
  category: error.ErrorCategory.THIRD_PARTY,
1157
- details: { threadId, resourceId: resourceId ?? "" }
1022
+ details: { messageIds: JSON.stringify(messageIds) }
1158
1023
  },
1159
1024
  error$1
1160
1025
  );
1161
1026
  }
1162
1027
  }
1163
- async getMessagesById({
1164
- messageIds,
1165
- format
1166
- }) {
1167
- if (messageIds.length === 0) return [];
1168
- try {
1169
- const sql = `
1170
- SELECT
1171
- id,
1172
- content,
1173
- role,
1174
- type,
1175
- "createdAt",
1176
- thread_id,
1177
- "resourceId"
1178
- FROM "${storage.TABLE_MESSAGES}"
1179
- WHERE id IN (${messageIds.map(() => "?").join(", ")})
1180
- ORDER BY "createdAt" DESC
1181
- `;
1182
- const result = await this.client.execute({ sql, args: messageIds });
1183
- if (!result.rows) return [];
1184
- const list = new agent.MessageList().add(result.rows.map(this.parseRow), "memory");
1185
- if (format === `v1`) return list.get.all.v1();
1186
- return list.get.all.v2();
1187
- } catch (error$1) {
1028
+ async listMessages(args) {
1029
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1030
+ if (!threadId.trim()) {
1188
1031
  throw new error.MastraError(
1189
1032
  {
1190
- id: "LIBSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
1033
+ id: "STORAGE_LIBSQL_LIST_MESSAGES_INVALID_THREAD_ID",
1191
1034
  domain: error.ErrorDomain.STORAGE,
1192
1035
  category: error.ErrorCategory.THIRD_PARTY,
1193
- details: { messageIds: JSON.stringify(messageIds) }
1036
+ details: { threadId }
1194
1037
  },
1195
- error$1
1038
+ new Error("threadId must be a non-empty string")
1196
1039
  );
1197
1040
  }
1198
- }
1199
- async getMessagesPaginated(args) {
1200
- const { threadId, format, selectBy } = args;
1201
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
1202
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1203
- const fromDate = dateRange?.start;
1204
- const toDate = dateRange?.end;
1205
- const messages = [];
1206
- if (selectBy?.include?.length) {
1207
- try {
1208
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1209
- if (includeMessages) {
1210
- messages.push(...includeMessages);
1211
- }
1212
- } catch (error$1) {
1213
- throw new error.MastraError(
1214
- {
1215
- id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_GET_INCLUDE_MESSAGES_FAILED",
1216
- domain: error.ErrorDomain.STORAGE,
1217
- category: error.ErrorCategory.THIRD_PARTY,
1218
- details: { threadId }
1219
- },
1220
- error$1
1221
- );
1222
- }
1041
+ if (page < 0) {
1042
+ throw new error.MastraError(
1043
+ {
1044
+ id: "LIBSQL_STORE_LIST_MESSAGES_INVALID_PAGE",
1045
+ domain: error.ErrorDomain.STORAGE,
1046
+ category: error.ErrorCategory.USER,
1047
+ details: { page }
1048
+ },
1049
+ new Error("page must be >= 0")
1050
+ );
1223
1051
  }
1052
+ const perPage = storage.normalizePerPage(perPageInput, 40);
1053
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1224
1054
  try {
1225
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1226
- const currentOffset = page * perPage;
1055
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1056
+ const orderByStatement = `ORDER BY "${field}" ${direction}`;
1227
1057
  const conditions = [`thread_id = ?`];
1228
1058
  const queryParams = [threadId];
1229
- if (fromDate) {
1059
+ if (resourceId) {
1060
+ conditions.push(`"resourceId" = ?`);
1061
+ queryParams.push(resourceId);
1062
+ }
1063
+ if (filter?.dateRange?.start) {
1230
1064
  conditions.push(`"createdAt" >= ?`);
1231
- queryParams.push(fromDate.toISOString());
1065
+ queryParams.push(
1066
+ filter.dateRange.start instanceof Date ? filter.dateRange.start.toISOString() : filter.dateRange.start
1067
+ );
1232
1068
  }
1233
- if (toDate) {
1069
+ if (filter?.dateRange?.end) {
1234
1070
  conditions.push(`"createdAt" <= ?`);
1235
- queryParams.push(toDate.toISOString());
1071
+ queryParams.push(
1072
+ filter.dateRange.end instanceof Date ? filter.dateRange.end.toISOString() : filter.dateRange.end
1073
+ );
1236
1074
  }
1237
1075
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1238
1076
  const countResult = await this.client.execute({
@@ -1240,50 +1078,80 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1240
1078
  args: queryParams
1241
1079
  });
1242
1080
  const total = Number(countResult.rows?.[0]?.count ?? 0);
1243
- if (total === 0 && messages.length === 0) {
1081
+ const limitValue = perPageInput === false ? total : perPage;
1082
+ const dataResult = await this.client.execute({
1083
+ sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${storage.TABLE_MESSAGES} ${whereClause} ${orderByStatement} LIMIT ? OFFSET ?`,
1084
+ args: [...queryParams, limitValue, offset]
1085
+ });
1086
+ const messages = (dataResult.rows || []).map((row) => this.parseRow(row));
1087
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
1244
1088
  return {
1245
1089
  messages: [],
1246
1090
  total: 0,
1247
1091
  page,
1248
- perPage,
1092
+ perPage: perPageForResponse,
1249
1093
  hasMore: false
1250
1094
  };
1251
1095
  }
1252
- const excludeIds = messages.map((m) => m.id);
1253
- const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + queryParams.length + 1}`).join(", ");
1254
- const dataResult = await this.client.execute({
1255
- sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${storage.TABLE_MESSAGES} ${whereClause} ${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""} ORDER BY "createdAt" DESC LIMIT ? OFFSET ?`,
1256
- args: [...queryParams, ...excludeIds, perPage, currentOffset]
1096
+ const messageIds = new Set(messages.map((m) => m.id));
1097
+ if (include && include.length > 0) {
1098
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
1099
+ if (includeMessages) {
1100
+ for (const includeMsg of includeMessages) {
1101
+ if (!messageIds.has(includeMsg.id)) {
1102
+ messages.push(includeMsg);
1103
+ messageIds.add(includeMsg.id);
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+ const list = new agent.MessageList().add(messages, "memory");
1109
+ let finalMessages = list.get.all.db();
1110
+ finalMessages = finalMessages.sort((a, b) => {
1111
+ const isDateField = field === "createdAt" || field === "updatedAt";
1112
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
1113
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
1114
+ if (typeof aValue === "number" && typeof bValue === "number") {
1115
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1116
+ }
1117
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1257
1118
  });
1258
- messages.push(...(dataResult.rows || []).map((row) => this.parseRow(row)));
1259
- const messagesToReturn = format === "v1" ? new agent.MessageList().add(messages, "memory").get.all.v1() : new agent.MessageList().add(messages, "memory").get.all.v2();
1119
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1120
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1121
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
1260
1122
  return {
1261
- messages: messagesToReturn,
1123
+ messages: finalMessages,
1262
1124
  total,
1263
1125
  page,
1264
- perPage,
1265
- hasMore: currentOffset + messages.length < total
1126
+ perPage: perPageForResponse,
1127
+ hasMore
1266
1128
  };
1267
1129
  } catch (error$1) {
1268
1130
  const mastraError = new error.MastraError(
1269
1131
  {
1270
- id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
1132
+ id: "LIBSQL_STORE_LIST_MESSAGES_FAILED",
1271
1133
  domain: error.ErrorDomain.STORAGE,
1272
1134
  category: error.ErrorCategory.THIRD_PARTY,
1273
- details: { threadId }
1135
+ details: {
1136
+ threadId,
1137
+ resourceId: resourceId ?? ""
1138
+ }
1274
1139
  },
1275
1140
  error$1
1276
1141
  );
1277
- this.logger?.trackException?.(mastraError);
1278
1142
  this.logger?.error?.(mastraError.toString());
1279
- return { messages: [], total: 0, page, perPage, hasMore: false };
1143
+ this.logger?.trackException?.(mastraError);
1144
+ return {
1145
+ messages: [],
1146
+ total: 0,
1147
+ page,
1148
+ perPage: perPageForResponse,
1149
+ hasMore: false
1150
+ };
1280
1151
  }
1281
1152
  }
1282
- async saveMessages({
1283
- messages,
1284
- format
1285
- }) {
1286
- if (messages.length === 0) return messages;
1153
+ async saveMessages({ messages }) {
1154
+ if (messages.length === 0) return { messages };
1287
1155
  try {
1288
1156
  const threadId = messages[0]?.threadId;
1289
1157
  if (!threadId) {
@@ -1340,8 +1208,7 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1340
1208
  await this.client.execute(threadUpdateStatement);
1341
1209
  }
1342
1210
  const list = new agent.MessageList().add(messages, "memory");
1343
- if (format === `v2`) return list.get.all.v2();
1344
- return list.get.all.v1();
1211
+ return { messages: list.get.all.db() };
1345
1212
  } catch (error$1) {
1346
1213
  throw new error.MastraError(
1347
1214
  {
@@ -1580,53 +1447,22 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1580
1447
  );
1581
1448
  }
1582
1449
  }
1583
- /**
1584
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1585
- */
1586
- async getThreadsByResourceId(args) {
1587
- const resourceId = args.resourceId;
1588
- const orderBy = this.castThreadOrderBy(args.orderBy);
1589
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1590
- try {
1591
- const baseQuery = `FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`;
1592
- const queryParams = [resourceId];
1593
- const mapRowToStorageThreadType = (row) => ({
1594
- id: row.id,
1595
- resourceId: row.resourceId,
1596
- title: row.title,
1597
- createdAt: new Date(row.createdAt),
1598
- // Convert string to Date
1599
- updatedAt: new Date(row.updatedAt),
1600
- // Convert string to Date
1601
- metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
1602
- });
1603
- const result = await this.client.execute({
1604
- sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection}`,
1605
- args: queryParams
1606
- });
1607
- if (!result.rows) {
1608
- return [];
1609
- }
1610
- return result.rows.map(mapRowToStorageThreadType);
1611
- } catch (error$1) {
1612
- const mastraError = new error.MastraError(
1450
+ async listThreadsByResourceId(args) {
1451
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1452
+ if (page < 0) {
1453
+ throw new error.MastraError(
1613
1454
  {
1614
- id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1455
+ id: "LIBSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
1615
1456
  domain: error.ErrorDomain.STORAGE,
1616
- category: error.ErrorCategory.THIRD_PARTY,
1617
- details: { resourceId }
1457
+ category: error.ErrorCategory.USER,
1458
+ details: { page }
1618
1459
  },
1619
- error$1
1460
+ new Error("page must be >= 0")
1620
1461
  );
1621
- this.logger?.trackException?.(mastraError);
1622
- this.logger?.error?.(mastraError.toString());
1623
- return [];
1624
1462
  }
1625
- }
1626
- async getThreadsByResourceIdPaginated(args) {
1627
- const { resourceId, page = 0, perPage = 100 } = args;
1628
- const orderBy = this.castThreadOrderBy(args.orderBy);
1629
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1463
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1464
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1465
+ const { field, direction } = this.parseOrderBy(orderBy);
1630
1466
  try {
1631
1467
  const baseQuery = `FROM ${storage.TABLE_THREADS} WHERE resourceId = ?`;
1632
1468
  const queryParams = [resourceId];
@@ -1640,7 +1476,6 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1640
1476
  // Convert string to Date
1641
1477
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
1642
1478
  });
1643
- const currentOffset = page * perPage;
1644
1479
  const countResult = await this.client.execute({
1645
1480
  sql: `SELECT COUNT(*) as count ${baseQuery}`,
1646
1481
  args: queryParams
@@ -1651,26 +1486,27 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1651
1486
  threads: [],
1652
1487
  total: 0,
1653
1488
  page,
1654
- perPage,
1489
+ perPage: perPageForResponse,
1655
1490
  hasMore: false
1656
1491
  };
1657
1492
  }
1493
+ const limitValue = perPageInput === false ? total : perPage;
1658
1494
  const dataResult = await this.client.execute({
1659
- sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection} LIMIT ? OFFSET ?`,
1660
- args: [...queryParams, perPage, currentOffset]
1495
+ sql: `SELECT * ${baseQuery} ORDER BY "${field}" ${direction} LIMIT ? OFFSET ?`,
1496
+ args: [...queryParams, limitValue, offset]
1661
1497
  });
1662
1498
  const threads = (dataResult.rows || []).map(mapRowToStorageThreadType);
1663
1499
  return {
1664
1500
  threads,
1665
1501
  total,
1666
1502
  page,
1667
- perPage,
1668
- hasMore: currentOffset + threads.length < total
1503
+ perPage: perPageForResponse,
1504
+ hasMore: perPageInput === false ? false : offset + perPage < total
1669
1505
  };
1670
1506
  } catch (error$1) {
1671
1507
  const mastraError = new error.MastraError(
1672
1508
  {
1673
- id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1509
+ id: "LIBSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1674
1510
  domain: error.ErrorDomain.STORAGE,
1675
1511
  category: error.ErrorCategory.THIRD_PARTY,
1676
1512
  details: { resourceId }
@@ -1679,7 +1515,13 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
1679
1515
  );
1680
1516
  this.logger?.trackException?.(mastraError);
1681
1517
  this.logger?.error?.(mastraError.toString());
1682
- return { threads: [], total: 0, page, perPage, hasMore: false };
1518
+ return {
1519
+ threads: [],
1520
+ total: 0,
1521
+ page,
1522
+ perPage: perPageForResponse,
1523
+ hasMore: false
1524
+ };
1683
1525
  }
1684
1526
  }
1685
1527
  async saveThread({ thread }) {
@@ -1950,7 +1792,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
1950
1792
  super();
1951
1793
  this.operations = operations;
1952
1794
  }
1953
- async createAISpan(span) {
1795
+ async createSpan(span) {
1954
1796
  try {
1955
1797
  const now = (/* @__PURE__ */ new Date()).toISOString();
1956
1798
  const record = {
@@ -1958,11 +1800,11 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
1958
1800
  createdAt: now,
1959
1801
  updatedAt: now
1960
1802
  };
1961
- return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1803
+ return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
1962
1804
  } catch (error$1) {
1963
1805
  throw new error.MastraError(
1964
1806
  {
1965
- id: "LIBSQL_STORE_CREATE_AI_SPAN_FAILED",
1807
+ id: "LIBSQL_STORE_CREATE_SPAN_FAILED",
1966
1808
  domain: error.ErrorDomain.STORAGE,
1967
1809
  category: error.ErrorCategory.USER,
1968
1810
  details: {
@@ -1976,10 +1818,10 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
1976
1818
  );
1977
1819
  }
1978
1820
  }
1979
- async getAITrace(traceId) {
1821
+ async getTrace(traceId) {
1980
1822
  try {
1981
1823
  const spans = await this.operations.loadMany({
1982
- tableName: storage.TABLE_AI_SPANS,
1824
+ tableName: storage.TABLE_SPANS,
1983
1825
  whereClause: { sql: " WHERE traceId = ?", args: [traceId] },
1984
1826
  orderBy: "startedAt DESC"
1985
1827
  });
@@ -1988,12 +1830,12 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
1988
1830
  }
1989
1831
  return {
1990
1832
  traceId,
1991
- spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_AI_SPANS, sqlRow: span }))
1833
+ spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: span }))
1992
1834
  };
1993
1835
  } catch (error$1) {
1994
1836
  throw new error.MastraError(
1995
1837
  {
1996
- id: "LIBSQL_STORE_GET_AI_TRACE_FAILED",
1838
+ id: "LIBSQL_STORE_GET_TRACE_FAILED",
1997
1839
  domain: error.ErrorDomain.STORAGE,
1998
1840
  category: error.ErrorCategory.USER,
1999
1841
  details: {
@@ -2004,21 +1846,21 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2004
1846
  );
2005
1847
  }
2006
1848
  }
2007
- async updateAISpan({
1849
+ async updateSpan({
2008
1850
  spanId,
2009
1851
  traceId,
2010
1852
  updates
2011
1853
  }) {
2012
1854
  try {
2013
1855
  await this.operations.update({
2014
- tableName: storage.TABLE_AI_SPANS,
1856
+ tableName: storage.TABLE_SPANS,
2015
1857
  keys: { spanId, traceId },
2016
1858
  data: { ...updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
2017
1859
  });
2018
1860
  } catch (error$1) {
2019
1861
  throw new error.MastraError(
2020
1862
  {
2021
- id: "LIBSQL_STORE_UPDATE_AI_SPAN_FAILED",
1863
+ id: "LIBSQL_STORE_UPDATE_SPAN_FAILED",
2022
1864
  domain: error.ErrorDomain.STORAGE,
2023
1865
  category: error.ErrorCategory.USER,
2024
1866
  details: {
@@ -2030,7 +1872,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2030
1872
  );
2031
1873
  }
2032
1874
  }
2033
- async getAITracesPaginated({
1875
+ async getTracesPaginated({
2034
1876
  filters,
2035
1877
  pagination
2036
1878
  }) {
@@ -2042,7 +1884,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2042
1884
  ...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
2043
1885
  parentSpanId: null
2044
1886
  };
2045
- const whereClause = prepareWhereClause(filtersWithDateRange, storage.AI_SPAN_SCHEMA);
1887
+ const whereClause = prepareWhereClause(filtersWithDateRange, storage.SPAN_SCHEMA);
2046
1888
  let actualWhereClause = whereClause.sql || "";
2047
1889
  if (entityId && entityType) {
2048
1890
  const statement = `name = ?`;
@@ -2053,7 +1895,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2053
1895
  name = `agent run: '${entityId}'`;
2054
1896
  } else {
2055
1897
  const error$1 = new error.MastraError({
2056
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1898
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2057
1899
  domain: error.ErrorDomain.STORAGE,
2058
1900
  category: error.ErrorCategory.USER,
2059
1901
  details: {
@@ -2075,13 +1917,13 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2075
1917
  let count = 0;
2076
1918
  try {
2077
1919
  count = await this.operations.loadTotalCount({
2078
- tableName: storage.TABLE_AI_SPANS,
1920
+ tableName: storage.TABLE_SPANS,
2079
1921
  whereClause: { sql: actualWhereClause, args: whereClause.args }
2080
1922
  });
2081
1923
  } catch (error$1) {
2082
1924
  throw new error.MastraError(
2083
1925
  {
2084
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_COUNT_FAILED",
1926
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_COUNT_FAILED",
2085
1927
  domain: error.ErrorDomain.STORAGE,
2086
1928
  category: error.ErrorCategory.USER
2087
1929
  },
@@ -2101,7 +1943,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2101
1943
  }
2102
1944
  try {
2103
1945
  const spans = await this.operations.loadMany({
2104
- tableName: storage.TABLE_AI_SPANS,
1946
+ tableName: storage.TABLE_SPANS,
2105
1947
  whereClause: {
2106
1948
  sql: actualWhereClause,
2107
1949
  args: whereClause.args
@@ -2117,12 +1959,12 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2117
1959
  perPage,
2118
1960
  hasMore: spans.length === perPage
2119
1961
  },
2120
- spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_AI_SPANS, sqlRow: span }))
1962
+ spans: spans.map((span) => transformFromSqlRow({ tableName: storage.TABLE_SPANS, sqlRow: span }))
2121
1963
  };
2122
1964
  } catch (error$1) {
2123
1965
  throw new error.MastraError(
2124
1966
  {
2125
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1967
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2126
1968
  domain: error.ErrorDomain.STORAGE,
2127
1969
  category: error.ErrorCategory.USER
2128
1970
  },
@@ -2130,11 +1972,11 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2130
1972
  );
2131
1973
  }
2132
1974
  }
2133
- async batchCreateAISpans(args) {
1975
+ async batchCreateSpans(args) {
2134
1976
  try {
2135
1977
  const now = (/* @__PURE__ */ new Date()).toISOString();
2136
1978
  return this.operations.batchInsert({
2137
- tableName: storage.TABLE_AI_SPANS,
1979
+ tableName: storage.TABLE_SPANS,
2138
1980
  records: args.records.map((record) => ({
2139
1981
  ...record,
2140
1982
  createdAt: now,
@@ -2144,7 +1986,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2144
1986
  } catch (error$1) {
2145
1987
  throw new error.MastraError(
2146
1988
  {
2147
- id: "LIBSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1989
+ id: "LIBSQL_STORE_BATCH_CREATE_SPANS_FAILED",
2148
1990
  domain: error.ErrorDomain.STORAGE,
2149
1991
  category: error.ErrorCategory.USER
2150
1992
  },
@@ -2152,10 +1994,10 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2152
1994
  );
2153
1995
  }
2154
1996
  }
2155
- async batchUpdateAISpans(args) {
1997
+ async batchUpdateSpans(args) {
2156
1998
  try {
2157
1999
  return this.operations.batchUpdate({
2158
- tableName: storage.TABLE_AI_SPANS,
2000
+ tableName: storage.TABLE_SPANS,
2159
2001
  updates: args.records.map((record) => ({
2160
2002
  keys: { spanId: record.spanId, traceId: record.traceId },
2161
2003
  data: { ...record.updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
@@ -2164,7 +2006,7 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2164
2006
  } catch (error$1) {
2165
2007
  throw new error.MastraError(
2166
2008
  {
2167
- id: "LIBSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
2009
+ id: "LIBSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
2168
2010
  domain: error.ErrorDomain.STORAGE,
2169
2011
  category: error.ErrorCategory.USER
2170
2012
  },
@@ -2172,17 +2014,17 @@ var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
2172
2014
  );
2173
2015
  }
2174
2016
  }
2175
- async batchDeleteAITraces(args) {
2017
+ async batchDeleteTraces(args) {
2176
2018
  try {
2177
2019
  const keys = args.traceIds.map((traceId) => ({ traceId }));
2178
2020
  return this.operations.batchDelete({
2179
- tableName: storage.TABLE_AI_SPANS,
2021
+ tableName: storage.TABLE_SPANS,
2180
2022
  keys
2181
2023
  });
2182
2024
  } catch (error$1) {
2183
2025
  throw new error.MastraError(
2184
2026
  {
2185
- id: "LIBSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
2027
+ id: "LIBSQL_STORE_BATCH_DELETE_TRACES_FAILED",
2186
2028
  domain: error.ErrorDomain.STORAGE,
2187
2029
  category: error.ErrorCategory.USER
2188
2030
  },
@@ -2238,7 +2080,7 @@ var StoreOperationsLibSQL = class extends storage.StoreOperations {
2238
2080
  )`;
2239
2081
  return stmnt;
2240
2082
  }
2241
- if (tableName === storage.TABLE_AI_SPANS) {
2083
+ if (tableName === storage.TABLE_SPANS) {
2242
2084
  const stmnt = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (
2243
2085
  ${columns.join(",\n")},
2244
2086
  PRIMARY KEY (traceId, spanId)
@@ -2586,22 +2428,44 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2586
2428
  this.operations = operations;
2587
2429
  this.client = client;
2588
2430
  }
2589
- async getScoresByRunId({
2431
+ async listScoresByRunId({
2590
2432
  runId,
2591
2433
  pagination
2592
2434
  }) {
2593
2435
  try {
2436
+ const { page, perPage: perPageInput } = pagination;
2437
+ const countResult = await this.client.execute({
2438
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE runId = ?`,
2439
+ args: [runId]
2440
+ });
2441
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2442
+ if (total === 0) {
2443
+ return {
2444
+ pagination: {
2445
+ total: 0,
2446
+ page,
2447
+ perPage: perPageInput,
2448
+ hasMore: false
2449
+ },
2450
+ scores: []
2451
+ };
2452
+ }
2453
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2454
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2455
+ const limitValue = perPageInput === false ? total : perPage;
2456
+ const end = perPageInput === false ? total : start + perPage;
2594
2457
  const result = await this.client.execute({
2595
2458
  sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE runId = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2596
- args: [runId, pagination.perPage + 1, pagination.page * pagination.perPage]
2459
+ args: [runId, limitValue, start]
2597
2460
  });
2461
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2598
2462
  return {
2599
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2463
+ scores,
2600
2464
  pagination: {
2601
- total: result.rows?.length ?? 0,
2602
- page: pagination.page,
2603
- perPage: pagination.perPage,
2604
- hasMore: result.rows?.length > pagination.perPage
2465
+ total,
2466
+ page,
2467
+ perPage: perPageForResponse,
2468
+ hasMore: end < total
2605
2469
  }
2606
2470
  };
2607
2471
  } catch (error$1) {
@@ -2615,7 +2479,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2615
2479
  );
2616
2480
  }
2617
2481
  }
2618
- async getScoresByScorerId({
2482
+ async listScoresByScorerId({
2619
2483
  scorerId,
2620
2484
  entityId,
2621
2485
  entityType,
@@ -2623,6 +2487,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2623
2487
  pagination
2624
2488
  }) {
2625
2489
  try {
2490
+ const { page, perPage: perPageInput } = pagination;
2626
2491
  const conditions = [];
2627
2492
  const queryParams = [];
2628
2493
  if (scorerId) {
@@ -2642,17 +2507,38 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2642
2507
  queryParams.push(source);
2643
2508
  }
2644
2509
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2510
+ const countResult = await this.client.execute({
2511
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} ${whereClause}`,
2512
+ args: queryParams
2513
+ });
2514
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2515
+ if (total === 0) {
2516
+ return {
2517
+ pagination: {
2518
+ total: 0,
2519
+ page,
2520
+ perPage: perPageInput,
2521
+ hasMore: false
2522
+ },
2523
+ scores: []
2524
+ };
2525
+ }
2526
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2527
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2528
+ const limitValue = perPageInput === false ? total : perPage;
2529
+ const end = perPageInput === false ? total : start + perPage;
2645
2530
  const result = await this.client.execute({
2646
2531
  sql: `SELECT * FROM ${storage.TABLE_SCORERS} ${whereClause} ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2647
- args: [...queryParams, pagination.perPage + 1, pagination.page * pagination.perPage]
2532
+ args: [...queryParams, limitValue, start]
2648
2533
  });
2534
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2649
2535
  return {
2650
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2536
+ scores,
2651
2537
  pagination: {
2652
- total: result.rows?.length ?? 0,
2653
- page: pagination.page,
2654
- perPage: pagination.perPage,
2655
- hasMore: result.rows?.length > pagination.perPage
2538
+ total,
2539
+ page,
2540
+ perPage: perPageForResponse,
2541
+ hasMore: end < total
2656
2542
  }
2657
2543
  };
2658
2544
  } catch (error$1) {
@@ -2671,7 +2557,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2671
2557
  const inputValue = storage.safelyParseJSON(row.input ?? "{}");
2672
2558
  const outputValue = storage.safelyParseJSON(row.output ?? "{}");
2673
2559
  const additionalLLMContextValue = row.additionalLLMContext ? storage.safelyParseJSON(row.additionalLLMContext) : null;
2674
- const runtimeContextValue = row.runtimeContext ? storage.safelyParseJSON(row.runtimeContext) : null;
2560
+ const requestContextValue = row.requestContext ? storage.safelyParseJSON(row.requestContext) : null;
2675
2561
  const metadataValue = row.metadata ? storage.safelyParseJSON(row.metadata) : null;
2676
2562
  const entityValue = row.entity ? storage.safelyParseJSON(row.entity) : null;
2677
2563
  const preprocessStepResultValue = row.preprocessStepResult ? storage.safelyParseJSON(row.preprocessStepResult) : null;
@@ -2694,7 +2580,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2694
2580
  input: inputValue,
2695
2581
  output: outputValue,
2696
2582
  additionalContext: additionalLLMContextValue,
2697
- runtimeContext: runtimeContextValue,
2583
+ requestContext: requestContextValue,
2698
2584
  entityType: row.entityType,
2699
2585
  entity: entityValue,
2700
2586
  entityId: row.entityId,
@@ -2716,7 +2602,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2716
2602
  async saveScore(score) {
2717
2603
  let parsedScore;
2718
2604
  try {
2719
- parsedScore = scores.saveScorePayloadSchema.parse(score);
2605
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
2720
2606
  } catch (error$1) {
2721
2607
  throw new error.MastraError(
2722
2608
  {
@@ -2724,7 +2610,7 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2724
2610
  domain: error.ErrorDomain.STORAGE,
2725
2611
  category: error.ErrorCategory.USER,
2726
2612
  details: {
2727
- scorer: score.scorer.name,
2613
+ scorer: score.scorer.id,
2728
2614
  entityId: score.entityId,
2729
2615
  entityType: score.entityType,
2730
2616
  traceId: score.traceId || "",
@@ -2758,23 +2644,45 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2758
2644
  );
2759
2645
  }
2760
2646
  }
2761
- async getScoresByEntityId({
2647
+ async listScoresByEntityId({
2762
2648
  entityId,
2763
2649
  entityType,
2764
2650
  pagination
2765
2651
  }) {
2766
2652
  try {
2653
+ const { page, perPage: perPageInput } = pagination;
2654
+ const countResult = await this.client.execute({
2655
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE entityId = ? AND entityType = ?`,
2656
+ args: [entityId, entityType]
2657
+ });
2658
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2659
+ if (total === 0) {
2660
+ return {
2661
+ pagination: {
2662
+ total: 0,
2663
+ page,
2664
+ perPage: perPageInput,
2665
+ hasMore: false
2666
+ },
2667
+ scores: []
2668
+ };
2669
+ }
2670
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2671
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2672
+ const limitValue = perPageInput === false ? total : perPage;
2673
+ const end = perPageInput === false ? total : start + perPage;
2767
2674
  const result = await this.client.execute({
2768
2675
  sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE entityId = ? AND entityType = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2769
- args: [entityId, entityType, pagination.perPage + 1, pagination.page * pagination.perPage]
2676
+ args: [entityId, entityType, limitValue, start]
2770
2677
  });
2678
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2771
2679
  return {
2772
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2680
+ scores,
2773
2681
  pagination: {
2774
- total: result.rows?.length ?? 0,
2775
- page: pagination.page,
2776
- perPage: pagination.perPage,
2777
- hasMore: result.rows?.length > pagination.perPage
2682
+ total,
2683
+ page,
2684
+ perPage: perPageForResponse,
2685
+ hasMore: end < total
2778
2686
  }
2779
2687
  };
2780
2688
  } catch (error$1) {
@@ -2788,30 +2696,34 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2788
2696
  );
2789
2697
  }
2790
2698
  }
2791
- async getScoresBySpan({
2699
+ async listScoresBySpan({
2792
2700
  traceId,
2793
2701
  spanId,
2794
2702
  pagination
2795
2703
  }) {
2796
2704
  try {
2705
+ const { page, perPage: perPageInput } = pagination;
2706
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2707
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2797
2708
  const countSQLResult = await this.client.execute({
2798
2709
  sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_SCORERS} WHERE traceId = ? AND spanId = ?`,
2799
2710
  args: [traceId, spanId]
2800
2711
  });
2801
2712
  const total = Number(countSQLResult.rows?.[0]?.count ?? 0);
2713
+ const limitValue = perPageInput === false ? total : perPage;
2714
+ const end = perPageInput === false ? total : start + perPage;
2802
2715
  const result = await this.client.execute({
2803
2716
  sql: `SELECT * FROM ${storage.TABLE_SCORERS} WHERE traceId = ? AND spanId = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2804
- args: [traceId, spanId, pagination.perPage + 1, pagination.page * pagination.perPage]
2717
+ args: [traceId, spanId, limitValue, start]
2805
2718
  });
2806
- const hasMore = result.rows?.length > pagination.perPage;
2807
- const scores = result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [];
2719
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2808
2720
  return {
2809
2721
  scores,
2810
2722
  pagination: {
2811
2723
  total,
2812
- page: pagination.page,
2813
- perPage: pagination.perPage,
2814
- hasMore
2724
+ page,
2725
+ perPage: perPageForResponse,
2726
+ hasMore: end < total
2815
2727
  }
2816
2728
  };
2817
2729
  } catch (error$1) {
@@ -2826,134 +2738,6 @@ var ScoresLibSQL = class extends storage.ScoresStorage {
2826
2738
  }
2827
2739
  }
2828
2740
  };
2829
- var TracesLibSQL = class extends storage.TracesStorage {
2830
- client;
2831
- operations;
2832
- constructor({ client, operations }) {
2833
- super();
2834
- this.client = client;
2835
- this.operations = operations;
2836
- }
2837
- async getTraces(args) {
2838
- if (args.fromDate || args.toDate) {
2839
- args.dateRange = {
2840
- start: args.fromDate,
2841
- end: args.toDate
2842
- };
2843
- }
2844
- try {
2845
- const result = await this.getTracesPaginated(args);
2846
- return result.traces;
2847
- } catch (error$1) {
2848
- throw new error.MastraError(
2849
- {
2850
- id: "LIBSQL_STORE_GET_TRACES_FAILED",
2851
- domain: error.ErrorDomain.STORAGE,
2852
- category: error.ErrorCategory.THIRD_PARTY
2853
- },
2854
- error$1
2855
- );
2856
- }
2857
- }
2858
- async getTracesPaginated(args) {
2859
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2860
- const fromDate = dateRange?.start;
2861
- const toDate = dateRange?.end;
2862
- const currentOffset = page * perPage;
2863
- const queryArgs = [];
2864
- const conditions = [];
2865
- if (name) {
2866
- conditions.push("name LIKE ?");
2867
- queryArgs.push(`${name}%`);
2868
- }
2869
- if (scope) {
2870
- conditions.push("scope = ?");
2871
- queryArgs.push(scope);
2872
- }
2873
- if (attributes) {
2874
- Object.entries(attributes).forEach(([key, value]) => {
2875
- conditions.push(`json_extract(attributes, '$.${key}') = ?`);
2876
- queryArgs.push(value);
2877
- });
2878
- }
2879
- if (filters) {
2880
- Object.entries(filters).forEach(([key, value]) => {
2881
- conditions.push(`${utils.parseSqlIdentifier(key, "filter key")} = ?`);
2882
- queryArgs.push(value);
2883
- });
2884
- }
2885
- if (fromDate) {
2886
- conditions.push("createdAt >= ?");
2887
- queryArgs.push(fromDate.toISOString());
2888
- }
2889
- if (toDate) {
2890
- conditions.push("createdAt <= ?");
2891
- queryArgs.push(toDate.toISOString());
2892
- }
2893
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2894
- try {
2895
- const countResult = await this.client.execute({
2896
- sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
2897
- args: queryArgs
2898
- });
2899
- const total = Number(countResult.rows?.[0]?.count ?? 0);
2900
- if (total === 0) {
2901
- return {
2902
- traces: [],
2903
- total: 0,
2904
- page,
2905
- perPage,
2906
- hasMore: false
2907
- };
2908
- }
2909
- const dataResult = await this.client.execute({
2910
- sql: `SELECT * FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
2911
- args: [...queryArgs, perPage, currentOffset]
2912
- });
2913
- const traces = dataResult.rows?.map(
2914
- (row) => ({
2915
- id: row.id,
2916
- parentSpanId: row.parentSpanId,
2917
- traceId: row.traceId,
2918
- name: row.name,
2919
- scope: row.scope,
2920
- kind: row.kind,
2921
- status: storage.safelyParseJSON(row.status),
2922
- events: storage.safelyParseJSON(row.events),
2923
- links: storage.safelyParseJSON(row.links),
2924
- attributes: storage.safelyParseJSON(row.attributes),
2925
- startTime: row.startTime,
2926
- endTime: row.endTime,
2927
- other: storage.safelyParseJSON(row.other),
2928
- createdAt: row.createdAt
2929
- })
2930
- ) ?? [];
2931
- return {
2932
- traces,
2933
- total,
2934
- page,
2935
- perPage,
2936
- hasMore: currentOffset + traces.length < total
2937
- };
2938
- } catch (error$1) {
2939
- throw new error.MastraError(
2940
- {
2941
- id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2942
- domain: error.ErrorDomain.STORAGE,
2943
- category: error.ErrorCategory.THIRD_PARTY
2944
- },
2945
- error$1
2946
- );
2947
- }
2948
- }
2949
- async batchTraceInsert({ records }) {
2950
- this.logger.debug("Batch inserting traces", { count: records.length });
2951
- await this.operations.batchInsert({
2952
- tableName: storage.TABLE_TRACES,
2953
- records
2954
- });
2955
- }
2956
- };
2957
2741
  function parseWorkflowRun(row) {
2958
2742
  let parsedSnapshot = row.snapshot;
2959
2743
  if (typeof parsedSnapshot === "string") {
@@ -3055,7 +2839,7 @@ var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
3055
2839
  runId,
3056
2840
  stepId,
3057
2841
  result,
3058
- runtimeContext
2842
+ requestContext
3059
2843
  }) {
3060
2844
  return this.executeWithRetry(async () => {
3061
2845
  const tx = await this.client.transaction("write");
@@ -3071,20 +2855,21 @@ var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
3071
2855
  activePaths: [],
3072
2856
  timestamp: Date.now(),
3073
2857
  suspendedPaths: {},
2858
+ activeStepsPath: {},
3074
2859
  resumeLabels: {},
3075
2860
  serializedStepGraph: [],
2861
+ status: "pending",
3076
2862
  value: {},
3077
2863
  waitingPaths: {},
3078
- status: "pending",
3079
2864
  runId,
3080
- runtimeContext: {}
2865
+ requestContext: {}
3081
2866
  };
3082
2867
  } else {
3083
2868
  const existingSnapshot = existingSnapshotResult.rows[0].snapshot;
3084
2869
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
3085
2870
  }
3086
2871
  snapshot.context[stepId] = result;
3087
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2872
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
3088
2873
  await tx.execute({
3089
2874
  sql: `UPDATE ${storage.TABLE_WORKFLOW_SNAPSHOT} SET snapshot = ? WHERE workflow_name = ? AND run_id = ?`,
3090
2875
  args: [JSON.stringify(snapshot), workflowName, runId]
@@ -3202,13 +2987,14 @@ var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
3202
2987
  );
3203
2988
  }
3204
2989
  }
3205
- async getWorkflowRuns({
2990
+ async listWorkflowRuns({
3206
2991
  workflowName,
3207
2992
  fromDate,
3208
2993
  toDate,
3209
- limit,
3210
- offset,
3211
- resourceId
2994
+ page,
2995
+ perPage,
2996
+ resourceId,
2997
+ status
3212
2998
  } = {}) {
3213
2999
  try {
3214
3000
  const conditions = [];
@@ -3217,6 +3003,10 @@ var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
3217
3003
  conditions.push("workflow_name = ?");
3218
3004
  args.push(workflowName);
3219
3005
  }
3006
+ if (status) {
3007
+ conditions.push("json_extract(snapshot, '$.status') = ?");
3008
+ args.push(status);
3009
+ }
3220
3010
  if (fromDate) {
3221
3011
  conditions.push("createdAt >= ?");
3222
3012
  args.push(fromDate.toISOString());
@@ -3236,23 +3026,26 @@ var WorkflowsLibSQL = class extends storage.WorkflowsStorage {
3236
3026
  }
3237
3027
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3238
3028
  let total = 0;
3239
- if (limit !== void 0 && offset !== void 0) {
3029
+ const usePagination = typeof perPage === "number" && typeof page === "number";
3030
+ if (usePagination) {
3240
3031
  const countResult = await this.client.execute({
3241
3032
  sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
3242
3033
  args
3243
3034
  });
3244
3035
  total = Number(countResult.rows?.[0]?.count ?? 0);
3245
3036
  }
3037
+ const normalizedPerPage = usePagination ? storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER) : 0;
3038
+ const offset = usePagination ? page * normalizedPerPage : 0;
3246
3039
  const result = await this.client.execute({
3247
- sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
3248
- args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
3040
+ sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${usePagination ? ` LIMIT ? OFFSET ?` : ""}`,
3041
+ args: usePagination ? [...args, normalizedPerPage, offset] : args
3249
3042
  });
3250
3043
  const runs = (result.rows || []).map((row) => parseWorkflowRun(row));
3251
3044
  return { runs, total: total || runs.length };
3252
3045
  } catch (error$1) {
3253
3046
  throw new error.MastraError(
3254
3047
  {
3255
- id: "LIBSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
3048
+ id: "LIBSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3256
3049
  domain: error.ErrorDomain.STORAGE,
3257
3050
  category: error.ErrorCategory.THIRD_PARTY
3258
3051
  },
@@ -3269,7 +3062,10 @@ var LibSQLStore = class extends storage.MastraStorage {
3269
3062
  initialBackoffMs;
3270
3063
  stores;
3271
3064
  constructor(config) {
3272
- super({ name: `LibSQLStore` });
3065
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
3066
+ throw new Error("LibSQLStore: id must be provided and cannot be empty.");
3067
+ }
3068
+ super({ id: config.id, name: `LibSQLStore` });
3273
3069
  this.maxRetries = config.maxRetries ?? 5;
3274
3070
  this.initialBackoffMs = config.initialBackoffMs ?? 100;
3275
3071
  if ("url" in config) {
@@ -3293,18 +3089,14 @@ var LibSQLStore = class extends storage.MastraStorage {
3293
3089
  initialBackoffMs: this.initialBackoffMs
3294
3090
  });
3295
3091
  const scores = new ScoresLibSQL({ client: this.client, operations });
3296
- const traces = new TracesLibSQL({ client: this.client, operations });
3297
3092
  const workflows = new WorkflowsLibSQL({ client: this.client, operations });
3298
3093
  const memory = new MemoryLibSQL({ client: this.client, operations });
3299
- const legacyEvals = new LegacyEvalsLibSQL({ client: this.client });
3300
3094
  const observability = new ObservabilityLibSQL({ operations });
3301
3095
  this.stores = {
3302
3096
  operations,
3303
3097
  scores,
3304
- traces,
3305
3098
  workflows,
3306
3099
  memory,
3307
- legacyEvals,
3308
3100
  observability
3309
3101
  };
3310
3102
  }
@@ -3315,8 +3107,8 @@ var LibSQLStore = class extends storage.MastraStorage {
3315
3107
  hasColumn: true,
3316
3108
  createTable: true,
3317
3109
  deleteMessages: true,
3318
- aiTracing: true,
3319
- getScoresBySpan: true
3110
+ observabilityInstance: true,
3111
+ listScoresBySpan: true
3320
3112
  };
3321
3113
  }
3322
3114
  async createTable({
@@ -3356,15 +3148,6 @@ var LibSQLStore = class extends storage.MastraStorage {
3356
3148
  async getThreadById({ threadId }) {
3357
3149
  return this.stores.memory.getThreadById({ threadId });
3358
3150
  }
3359
- /**
3360
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
3361
- */
3362
- async getThreadsByResourceId(args) {
3363
- return this.stores.memory.getThreadsByResourceId(args);
3364
- }
3365
- async getThreadsByResourceIdPaginated(args) {
3366
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3367
- }
3368
3151
  async saveThread({ thread }) {
3369
3152
  return this.stores.memory.saveThread({ thread });
3370
3153
  }
@@ -3378,24 +3161,12 @@ var LibSQLStore = class extends storage.MastraStorage {
3378
3161
  async deleteThread({ threadId }) {
3379
3162
  return this.stores.memory.deleteThread({ threadId });
3380
3163
  }
3381
- async getMessages({
3382
- threadId,
3383
- selectBy,
3384
- format
3385
- }) {
3386
- return this.stores.memory.getMessages({ threadId, selectBy, format });
3387
- }
3388
- async getMessagesById({
3389
- messageIds,
3390
- format
3391
- }) {
3392
- return this.stores.memory.getMessagesById({ messageIds, format });
3393
- }
3394
- async getMessagesPaginated(args) {
3395
- return this.stores.memory.getMessagesPaginated(args);
3164
+ async listMessagesById({ messageIds }) {
3165
+ return this.stores.memory.listMessagesById({ messageIds });
3396
3166
  }
3397
3167
  async saveMessages(args) {
3398
- return this.stores.memory.saveMessages(args);
3168
+ const result = await this.stores.memory.saveMessages({ messages: args.messages });
3169
+ return { messages: result.messages };
3399
3170
  }
3400
3171
  async updateMessages({
3401
3172
  messages
@@ -3405,55 +3176,33 @@ var LibSQLStore = class extends storage.MastraStorage {
3405
3176
  async deleteMessages(messageIds) {
3406
3177
  return this.stores.memory.deleteMessages(messageIds);
3407
3178
  }
3408
- /** @deprecated use getEvals instead */
3409
- async getEvalsByAgentName(agentName, type) {
3410
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3411
- }
3412
- async getEvals(options = {}) {
3413
- return this.stores.legacyEvals.getEvals(options);
3414
- }
3415
3179
  async getScoreById({ id }) {
3416
3180
  return this.stores.scores.getScoreById({ id });
3417
3181
  }
3418
3182
  async saveScore(score) {
3419
3183
  return this.stores.scores.saveScore(score);
3420
3184
  }
3421
- async getScoresByScorerId({
3185
+ async listScoresByScorerId({
3422
3186
  scorerId,
3423
3187
  entityId,
3424
3188
  entityType,
3425
3189
  source,
3426
3190
  pagination
3427
3191
  }) {
3428
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
3192
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
3429
3193
  }
3430
- async getScoresByRunId({
3194
+ async listScoresByRunId({
3431
3195
  runId,
3432
3196
  pagination
3433
3197
  }) {
3434
- return this.stores.scores.getScoresByRunId({ runId, pagination });
3198
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
3435
3199
  }
3436
- async getScoresByEntityId({
3200
+ async listScoresByEntityId({
3437
3201
  entityId,
3438
3202
  entityType,
3439
3203
  pagination
3440
3204
  }) {
3441
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
3442
- }
3443
- /**
3444
- * TRACES
3445
- */
3446
- /**
3447
- * @deprecated use getTracesPaginated instead.
3448
- */
3449
- async getTraces(args) {
3450
- return this.stores.traces.getTraces(args);
3451
- }
3452
- async getTracesPaginated(args) {
3453
- return this.stores.traces.getTracesPaginated(args);
3454
- }
3455
- async batchTraceInsert(args) {
3456
- return this.stores.traces.batchTraceInsert(args);
3205
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
3457
3206
  }
3458
3207
  /**
3459
3208
  * WORKFLOWS
@@ -3463,9 +3212,9 @@ var LibSQLStore = class extends storage.MastraStorage {
3463
3212
  runId,
3464
3213
  stepId,
3465
3214
  result,
3466
- runtimeContext
3215
+ requestContext
3467
3216
  }) {
3468
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3217
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3469
3218
  }
3470
3219
  async updateWorkflowState({
3471
3220
  workflowName,
@@ -3488,15 +3237,8 @@ var LibSQLStore = class extends storage.MastraStorage {
3488
3237
  }) {
3489
3238
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3490
3239
  }
3491
- async getWorkflowRuns({
3492
- workflowName,
3493
- fromDate,
3494
- toDate,
3495
- limit,
3496
- offset,
3497
- resourceId
3498
- } = {}) {
3499
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3240
+ async listWorkflowRuns(args = {}) {
3241
+ return this.stores.workflows.listWorkflowRuns(args);
3500
3242
  }
3501
3243
  async getWorkflowRunById({
3502
3244
  runId,
@@ -3517,30 +3259,30 @@ var LibSQLStore = class extends storage.MastraStorage {
3517
3259
  }) {
3518
3260
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3519
3261
  }
3520
- async createAISpan(span) {
3521
- return this.stores.observability.createAISpan(span);
3262
+ async createSpan(span) {
3263
+ return this.stores.observability.createSpan(span);
3522
3264
  }
3523
- async updateAISpan(params) {
3524
- return this.stores.observability.updateAISpan(params);
3265
+ async updateSpan(params) {
3266
+ return this.stores.observability.updateSpan(params);
3525
3267
  }
3526
- async getAITrace(traceId) {
3527
- return this.stores.observability.getAITrace(traceId);
3268
+ async getTrace(traceId) {
3269
+ return this.stores.observability.getTrace(traceId);
3528
3270
  }
3529
- async getAITracesPaginated(args) {
3530
- return this.stores.observability.getAITracesPaginated(args);
3271
+ async getTracesPaginated(args) {
3272
+ return this.stores.observability.getTracesPaginated(args);
3531
3273
  }
3532
- async getScoresBySpan({
3274
+ async listScoresBySpan({
3533
3275
  traceId,
3534
3276
  spanId,
3535
3277
  pagination
3536
3278
  }) {
3537
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
3279
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3538
3280
  }
3539
- async batchCreateAISpans(args) {
3540
- return this.stores.observability.batchCreateAISpans(args);
3281
+ async batchCreateSpans(args) {
3282
+ return this.stores.observability.batchCreateSpans(args);
3541
3283
  }
3542
- async batchUpdateAISpans(args) {
3543
- return this.stores.observability.batchUpdateAISpans(args);
3284
+ async batchUpdateSpans(args) {
3285
+ return this.stores.observability.batchUpdateSpans(args);
3544
3286
  }
3545
3287
  };
3546
3288