@mastra/libsql 0.10.4-alpha.0 → 0.10.4-alpha.2

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
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var client = require('@libsql/client');
4
+ var error = require('@mastra/core/error');
4
5
  var utils = require('@mastra/core/utils');
5
6
  var vector = require('@mastra/core/vector');
6
7
  var filter = require('@mastra/core/vector/filter');
@@ -408,7 +409,7 @@ function buildCondition(key, value, parentPath) {
408
409
  return handleOperator(key, value);
409
410
  }
410
411
  function handleLogicalOperator(key, value, parentPath) {
411
- if (!value || value.length === 0) {
412
+ if (!value || Array.isArray(value) && value.length === 0) {
412
413
  switch (key) {
413
414
  case "$and":
414
415
  case "$nor":
@@ -432,7 +433,7 @@ function handleLogicalOperator(key, value, parentPath) {
432
433
  const values = [];
433
434
  const joinOperator = key === "$or" || key === "$nor" ? "OR" : "AND";
434
435
  const conditions = Array.isArray(value) ? value.map((f) => {
435
- const entries = Object.entries(f);
436
+ const entries = !!f ? Object.entries(f) : [];
436
437
  return entries.map(([k, v]) => buildCondition(k, v));
437
438
  }) : [buildCondition(key, value)];
438
439
  const joined = conditions.flat().map((c) => {
@@ -556,6 +557,17 @@ var LibSQLVector = class extends vector.MastraVector {
556
557
  if (!Array.isArray(queryVector) || !queryVector.every((x) => typeof x === "number" && Number.isFinite(x))) {
557
558
  throw new Error("queryVector must be an array of finite numbers");
558
559
  }
560
+ } catch (error$1) {
561
+ throw new error.MastraError(
562
+ {
563
+ id: "LIBSQL_VECTOR_QUERY_INVALID_ARGS",
564
+ domain: error.ErrorDomain.STORAGE,
565
+ category: error.ErrorCategory.USER
566
+ },
567
+ error$1
568
+ );
569
+ }
570
+ try {
559
571
  const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
560
572
  const vectorStr = `[${queryVector.join(",")}]`;
561
573
  const translatedFilter = this.transformFilter(filter);
@@ -587,11 +599,30 @@ var LibSQLVector = class extends vector.MastraVector {
587
599
  metadata: JSON.parse(metadata ?? "{}"),
588
600
  ...includeVector && embedding && { vector: JSON.parse(embedding) }
589
601
  }));
590
- } finally {
602
+ } catch (error$1) {
603
+ throw new error.MastraError(
604
+ {
605
+ id: "LIBSQL_VECTOR_QUERY_FAILED",
606
+ domain: error.ErrorDomain.STORAGE,
607
+ category: error.ErrorCategory.THIRD_PARTY
608
+ },
609
+ error$1
610
+ );
591
611
  }
592
612
  }
593
613
  upsert(args) {
594
- return this.executeWriteOperationWithRetry(() => this.doUpsert(args), true);
614
+ try {
615
+ return this.executeWriteOperationWithRetry(() => this.doUpsert(args), true);
616
+ } catch (error$1) {
617
+ throw new error.MastraError(
618
+ {
619
+ id: "LIBSQL_VECTOR_UPSERT_FAILED",
620
+ domain: error.ErrorDomain.STORAGE,
621
+ category: error.ErrorCategory.THIRD_PARTY
622
+ },
623
+ error$1
624
+ );
625
+ }
595
626
  }
596
627
  async doUpsert({ indexName, vectors, metadata, ids }) {
597
628
  const tx = await this.turso.transaction("write");
@@ -634,7 +665,19 @@ var LibSQLVector = class extends vector.MastraVector {
634
665
  }
635
666
  }
636
667
  createIndex(args) {
637
- return this.executeWriteOperationWithRetry(() => this.doCreateIndex(args));
668
+ try {
669
+ return this.executeWriteOperationWithRetry(() => this.doCreateIndex(args));
670
+ } catch (error$1) {
671
+ throw new error.MastraError(
672
+ {
673
+ id: "LIBSQL_VECTOR_CREATE_INDEX_FAILED",
674
+ domain: error.ErrorDomain.STORAGE,
675
+ category: error.ErrorCategory.THIRD_PARTY,
676
+ details: { indexName: args.indexName, dimension: args.dimension }
677
+ },
678
+ error$1
679
+ );
680
+ }
638
681
  }
639
682
  async doCreateIndex({ indexName, dimension }) {
640
683
  if (!Number.isInteger(dimension) || dimension <= 0) {
@@ -661,7 +704,19 @@ var LibSQLVector = class extends vector.MastraVector {
661
704
  });
662
705
  }
663
706
  deleteIndex(args) {
664
- return this.executeWriteOperationWithRetry(() => this.doDeleteIndex(args));
707
+ try {
708
+ return this.executeWriteOperationWithRetry(() => this.doDeleteIndex(args));
709
+ } catch (error$1) {
710
+ throw new error.MastraError(
711
+ {
712
+ id: "LIBSQL_VECTOR_DELETE_INDEX_FAILED",
713
+ domain: error.ErrorDomain.STORAGE,
714
+ category: error.ErrorCategory.THIRD_PARTY,
715
+ details: { indexName: args.indexName }
716
+ },
717
+ error$1
718
+ );
719
+ }
665
720
  }
666
721
  async doDeleteIndex({ indexName }) {
667
722
  const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
@@ -682,8 +737,15 @@ var LibSQLVector = class extends vector.MastraVector {
682
737
  args: []
683
738
  });
684
739
  return result.rows.map((row) => row.name);
685
- } catch (error) {
686
- throw new Error(`Failed to list vector tables: ${error.message}`);
740
+ } catch (error$1) {
741
+ throw new error.MastraError(
742
+ {
743
+ id: "LIBSQL_VECTOR_LIST_INDEXES_FAILED",
744
+ domain: error.ErrorDomain.STORAGE,
745
+ category: error.ErrorCategory.THIRD_PARTY
746
+ },
747
+ error$1
748
+ );
687
749
  }
688
750
  }
689
751
  /**
@@ -724,7 +786,15 @@ var LibSQLVector = class extends vector.MastraVector {
724
786
  metric
725
787
  };
726
788
  } catch (e) {
727
- throw new Error(`Failed to describe vector table: ${e.message}`);
789
+ throw new error.MastraError(
790
+ {
791
+ id: "LIBSQL_VECTOR_DESCRIBE_INDEX_FAILED",
792
+ domain: error.ErrorDomain.STORAGE,
793
+ category: error.ErrorCategory.THIRD_PARTY,
794
+ details: { indexName }
795
+ },
796
+ e
797
+ );
728
798
  }
729
799
  }
730
800
  /**
@@ -754,7 +824,13 @@ var LibSQLVector = class extends vector.MastraVector {
754
824
  args.push(JSON.stringify(update.metadata));
755
825
  }
756
826
  if (updates.length === 0) {
757
- throw new Error("No updates provided");
827
+ throw new error.MastraError({
828
+ id: "LIBSQL_VECTOR_UPDATE_VECTOR_INVALID_ARGS",
829
+ domain: error.ErrorDomain.STORAGE,
830
+ category: error.ErrorCategory.USER,
831
+ details: { indexName, id },
832
+ text: "No updates provided"
833
+ });
758
834
  }
759
835
  args.push(id);
760
836
  const query = `
@@ -762,10 +838,22 @@ var LibSQLVector = class extends vector.MastraVector {
762
838
  SET ${updates.join(", ")}
763
839
  WHERE vector_id = ?;
764
840
  `;
765
- await this.turso.execute({
766
- sql: query,
767
- args
768
- });
841
+ try {
842
+ await this.turso.execute({
843
+ sql: query,
844
+ args
845
+ });
846
+ } catch (error$1) {
847
+ throw new error.MastraError(
848
+ {
849
+ id: "LIBSQL_VECTOR_UPDATE_VECTOR_FAILED",
850
+ domain: error.ErrorDomain.STORAGE,
851
+ category: error.ErrorCategory.THIRD_PARTY,
852
+ details: { indexName, id }
853
+ },
854
+ error$1
855
+ );
856
+ }
769
857
  }
770
858
  /**
771
859
  * Deletes a vector by its ID.
@@ -775,7 +863,19 @@ var LibSQLVector = class extends vector.MastraVector {
775
863
  * @throws Will throw an error if the deletion operation fails.
776
864
  */
777
865
  deleteVector(args) {
778
- return this.executeWriteOperationWithRetry(() => this.doDeleteVector(args));
866
+ try {
867
+ return this.executeWriteOperationWithRetry(() => this.doDeleteVector(args));
868
+ } catch (error$1) {
869
+ throw new error.MastraError(
870
+ {
871
+ id: "LIBSQL_VECTOR_DELETE_VECTOR_FAILED",
872
+ domain: error.ErrorDomain.STORAGE,
873
+ category: error.ErrorCategory.THIRD_PARTY,
874
+ details: { indexName: args.indexName, id: args.id }
875
+ },
876
+ error$1
877
+ );
878
+ }
779
879
  }
780
880
  async doDeleteVector({ indexName, id }) {
781
881
  const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
@@ -785,7 +885,19 @@ var LibSQLVector = class extends vector.MastraVector {
785
885
  });
786
886
  }
787
887
  truncateIndex(args) {
788
- return this.executeWriteOperationWithRetry(() => this._doTruncateIndex(args));
888
+ try {
889
+ return this.executeWriteOperationWithRetry(() => this._doTruncateIndex(args));
890
+ } catch (error$1) {
891
+ throw new error.MastraError(
892
+ {
893
+ id: "LIBSQL_VECTOR_TRUNCATE_INDEX_FAILED",
894
+ domain: error.ErrorDomain.STORAGE,
895
+ category: error.ErrorCategory.THIRD_PARTY,
896
+ details: { indexName: args.indexName }
897
+ },
898
+ error$1
899
+ );
900
+ }
789
901
  }
790
902
  async _doTruncateIndex({ indexName }) {
791
903
  await this.turso.execute({
@@ -820,7 +932,8 @@ var LibSQLStore = class extends storage.MastraStorage {
820
932
  }
821
933
  get supports() {
822
934
  return {
823
- selectByIncludeResourceScope: true
935
+ selectByIncludeResourceScope: true,
936
+ resourceWorkingMemory: true
824
937
  };
825
938
  }
826
939
  getCreateTableSQL(tableName, schema) {
@@ -851,9 +964,18 @@ var LibSQLStore = class extends storage.MastraStorage {
851
964
  this.logger.debug(`Creating database table`, { tableName, operation: "schema init" });
852
965
  const sql = this.getCreateTableSQL(tableName, schema);
853
966
  await this.client.execute(sql);
854
- } catch (error) {
855
- this.logger.error(`Error creating table ${tableName}: ${error}`);
856
- throw error;
967
+ } catch (error$1) {
968
+ throw new error.MastraError(
969
+ {
970
+ id: "LIBSQL_STORE_CREATE_TABLE_FAILED",
971
+ domain: error.ErrorDomain.STORAGE,
972
+ category: error.ErrorCategory.THIRD_PARTY,
973
+ details: {
974
+ tableName
975
+ }
976
+ },
977
+ error$1
978
+ );
857
979
  }
858
980
  }
859
981
  getSqlType(type) {
@@ -895,11 +1017,18 @@ var LibSQLStore = class extends storage.MastraStorage {
895
1017
  this.logger?.debug?.(`Added column ${columnName} to table ${parsedTableName}`);
896
1018
  }
897
1019
  }
898
- } catch (error) {
899
- this.logger?.error?.(
900
- `Error altering table ${tableName}: ${error instanceof Error ? error.message : String(error)}`
1020
+ } catch (error$1) {
1021
+ throw new error.MastraError(
1022
+ {
1023
+ id: "LIBSQL_STORE_ALTER_TABLE_FAILED",
1024
+ domain: error.ErrorDomain.STORAGE,
1025
+ category: error.ErrorCategory.THIRD_PARTY,
1026
+ details: {
1027
+ tableName
1028
+ }
1029
+ },
1030
+ error$1
901
1031
  );
902
- throw new Error(`Failed to alter table ${tableName}: ${error}`);
903
1032
  }
904
1033
  }
905
1034
  async clearTable({ tableName }) {
@@ -907,9 +1036,19 @@ var LibSQLStore = class extends storage.MastraStorage {
907
1036
  try {
908
1037
  await this.client.execute(`DELETE FROM ${parsedTableName}`);
909
1038
  } catch (e) {
910
- if (e instanceof Error) {
911
- this.logger.error(e.message);
912
- }
1039
+ const mastraError = new error.MastraError(
1040
+ {
1041
+ id: "LIBSQL_STORE_CLEAR_TABLE_FAILED",
1042
+ domain: error.ErrorDomain.STORAGE,
1043
+ category: error.ErrorCategory.THIRD_PARTY,
1044
+ details: {
1045
+ tableName
1046
+ }
1047
+ },
1048
+ e
1049
+ );
1050
+ this.logger?.trackException?.(mastraError);
1051
+ this.logger?.error?.(mastraError.toString());
913
1052
  }
914
1053
  }
915
1054
  prepareStatement({ tableName, record }) {
@@ -968,7 +1107,19 @@ var LibSQLStore = class extends storage.MastraStorage {
968
1107
  return this.executeWriteOperationWithRetry(
969
1108
  () => this.doBatchInsert(args),
970
1109
  `batch insert into table ${args.tableName}`
971
- );
1110
+ ).catch((error$1) => {
1111
+ throw new error.MastraError(
1112
+ {
1113
+ id: "LIBSQL_STORE_BATCH_INSERT_FAILED",
1114
+ domain: error.ErrorDomain.STORAGE,
1115
+ category: error.ErrorCategory.THIRD_PARTY,
1116
+ details: {
1117
+ tableName: args.tableName
1118
+ }
1119
+ },
1120
+ error$1
1121
+ );
1122
+ });
972
1123
  }
973
1124
  async doBatchInsert({
974
1125
  tableName,
@@ -1003,17 +1154,29 @@ var LibSQLStore = class extends storage.MastraStorage {
1003
1154
  return parsed;
1004
1155
  }
1005
1156
  async getThreadById({ threadId }) {
1006
- const result = await this.load({
1007
- tableName: storage.TABLE_THREADS,
1008
- keys: { id: threadId }
1009
- });
1010
- if (!result) {
1011
- return null;
1157
+ try {
1158
+ const result = await this.load({
1159
+ tableName: storage.TABLE_THREADS,
1160
+ keys: { id: threadId }
1161
+ });
1162
+ if (!result) {
1163
+ return null;
1164
+ }
1165
+ return {
1166
+ ...result,
1167
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1168
+ };
1169
+ } catch (error$1) {
1170
+ throw new error.MastraError(
1171
+ {
1172
+ id: "LIBSQL_STORE_GET_THREAD_BY_ID_FAILED",
1173
+ domain: error.ErrorDomain.STORAGE,
1174
+ category: error.ErrorCategory.THIRD_PARTY,
1175
+ details: { threadId }
1176
+ },
1177
+ error$1
1178
+ );
1012
1179
  }
1013
- return {
1014
- ...result,
1015
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1016
- };
1017
1180
  }
1018
1181
  /**
1019
1182
  * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
@@ -1041,8 +1204,18 @@ var LibSQLStore = class extends storage.MastraStorage {
1041
1204
  return [];
1042
1205
  }
1043
1206
  return result.rows.map(mapRowToStorageThreadType);
1044
- } catch (error) {
1045
- this.logger.error(`Error getting threads for resource ${resourceId}:`, error);
1207
+ } catch (error$1) {
1208
+ const mastraError = new error.MastraError(
1209
+ {
1210
+ id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1211
+ domain: error.ErrorDomain.STORAGE,
1212
+ category: error.ErrorCategory.THIRD_PARTY,
1213
+ details: { resourceId }
1214
+ },
1215
+ error$1
1216
+ );
1217
+ this.logger?.trackException?.(mastraError);
1218
+ this.logger?.error?.(mastraError.toString());
1046
1219
  return [];
1047
1220
  }
1048
1221
  }
@@ -1088,20 +1261,45 @@ var LibSQLStore = class extends storage.MastraStorage {
1088
1261
  perPage,
1089
1262
  hasMore: currentOffset + threads.length < total
1090
1263
  };
1091
- } catch (error) {
1092
- this.logger.error(`Error getting threads for resource ${resourceId}:`, error);
1264
+ } catch (error$1) {
1265
+ const mastraError = new error.MastraError(
1266
+ {
1267
+ id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1268
+ domain: error.ErrorDomain.STORAGE,
1269
+ category: error.ErrorCategory.THIRD_PARTY,
1270
+ details: { resourceId }
1271
+ },
1272
+ error$1
1273
+ );
1274
+ this.logger?.trackException?.(mastraError);
1275
+ this.logger?.error?.(mastraError.toString());
1093
1276
  return { threads: [], total: 0, page, perPage, hasMore: false };
1094
1277
  }
1095
1278
  }
1096
1279
  async saveThread({ thread }) {
1097
- await this.insert({
1098
- tableName: storage.TABLE_THREADS,
1099
- record: {
1100
- ...thread,
1101
- metadata: JSON.stringify(thread.metadata)
1102
- }
1103
- });
1104
- return thread;
1280
+ try {
1281
+ await this.insert({
1282
+ tableName: storage.TABLE_THREADS,
1283
+ record: {
1284
+ ...thread,
1285
+ metadata: JSON.stringify(thread.metadata)
1286
+ }
1287
+ });
1288
+ return thread;
1289
+ } catch (error$1) {
1290
+ const mastraError = new error.MastraError(
1291
+ {
1292
+ id: "LIBSQL_STORE_SAVE_THREAD_FAILED",
1293
+ domain: error.ErrorDomain.STORAGE,
1294
+ category: error.ErrorCategory.THIRD_PARTY,
1295
+ details: { threadId: thread.id }
1296
+ },
1297
+ error$1
1298
+ );
1299
+ this.logger?.trackException?.(mastraError);
1300
+ this.logger?.error?.(mastraError.toString());
1301
+ throw mastraError;
1302
+ }
1105
1303
  }
1106
1304
  async updateThread({
1107
1305
  id,
@@ -1110,7 +1308,13 @@ var LibSQLStore = class extends storage.MastraStorage {
1110
1308
  }) {
1111
1309
  const thread = await this.getThreadById({ threadId: id });
1112
1310
  if (!thread) {
1113
- throw new Error(`Thread ${id} not found`);
1311
+ throw new error.MastraError({
1312
+ id: "LIBSQL_STORE_UPDATE_THREAD_FAILED_THREAD_NOT_FOUND",
1313
+ domain: error.ErrorDomain.STORAGE,
1314
+ category: error.ErrorCategory.USER,
1315
+ text: `Thread ${id} not found`,
1316
+ details: { threadId: id }
1317
+ });
1114
1318
  }
1115
1319
  const updatedThread = {
1116
1320
  ...thread,
@@ -1120,21 +1324,46 @@ var LibSQLStore = class extends storage.MastraStorage {
1120
1324
  ...metadata
1121
1325
  }
1122
1326
  };
1123
- await this.client.execute({
1124
- sql: `UPDATE ${storage.TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
1125
- args: [title, JSON.stringify(updatedThread.metadata), id]
1126
- });
1127
- return updatedThread;
1327
+ try {
1328
+ await this.client.execute({
1329
+ sql: `UPDATE ${storage.TABLE_THREADS} SET title = ?, metadata = ? WHERE id = ?`,
1330
+ args: [title, JSON.stringify(updatedThread.metadata), id]
1331
+ });
1332
+ return updatedThread;
1333
+ } catch (error$1) {
1334
+ throw new error.MastraError(
1335
+ {
1336
+ id: "LIBSQL_STORE_UPDATE_THREAD_FAILED",
1337
+ domain: error.ErrorDomain.STORAGE,
1338
+ category: error.ErrorCategory.THIRD_PARTY,
1339
+ text: `Failed to update thread ${id}`,
1340
+ details: { threadId: id }
1341
+ },
1342
+ error$1
1343
+ );
1344
+ }
1128
1345
  }
1129
1346
  async deleteThread({ threadId }) {
1130
- await this.client.execute({
1131
- sql: `DELETE FROM ${storage.TABLE_MESSAGES} WHERE thread_id = ?`,
1132
- args: [threadId]
1133
- });
1134
- await this.client.execute({
1135
- sql: `DELETE FROM ${storage.TABLE_THREADS} WHERE id = ?`,
1136
- args: [threadId]
1137
- });
1347
+ try {
1348
+ await this.client.execute({
1349
+ sql: `DELETE FROM ${storage.TABLE_MESSAGES} WHERE thread_id = ?`,
1350
+ args: [threadId]
1351
+ });
1352
+ await this.client.execute({
1353
+ sql: `DELETE FROM ${storage.TABLE_THREADS} WHERE id = ?`,
1354
+ args: [threadId]
1355
+ });
1356
+ } catch (error$1) {
1357
+ throw new error.MastraError(
1358
+ {
1359
+ id: "LIBSQL_STORE_DELETE_THREAD_FAILED",
1360
+ domain: error.ErrorDomain.STORAGE,
1361
+ category: error.ErrorCategory.THIRD_PARTY,
1362
+ details: { threadId }
1363
+ },
1364
+ error$1
1365
+ );
1366
+ }
1138
1367
  }
1139
1368
  parseRow(row) {
1140
1369
  let content = row.content;
@@ -1207,7 +1436,7 @@ var LibSQLStore = class extends storage.MastraStorage {
1207
1436
  }) {
1208
1437
  try {
1209
1438
  const messages = [];
1210
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
1439
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1211
1440
  if (selectBy?.include?.length) {
1212
1441
  const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1213
1442
  if (includeMessages) {
@@ -1239,21 +1468,41 @@ var LibSQLStore = class extends storage.MastraStorage {
1239
1468
  const list = new agent.MessageList().add(messages, "memory");
1240
1469
  if (format === `v2`) return list.get.all.v2();
1241
1470
  return list.get.all.v1();
1242
- } catch (error) {
1243
- this.logger.error("Error getting messages:", error);
1244
- throw error;
1471
+ } catch (error$1) {
1472
+ throw new error.MastraError(
1473
+ {
1474
+ id: "LIBSQL_STORE_GET_MESSAGES_FAILED",
1475
+ domain: error.ErrorDomain.STORAGE,
1476
+ category: error.ErrorCategory.THIRD_PARTY,
1477
+ details: { threadId }
1478
+ },
1479
+ error$1
1480
+ );
1245
1481
  }
1246
1482
  }
1247
1483
  async getMessagesPaginated(args) {
1248
1484
  const { threadId, format, selectBy } = args;
1249
- const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1485
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
1486
+ const perPage = perPageInput !== void 0 ? perPageInput : this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1250
1487
  const fromDate = dateRange?.start;
1251
1488
  const toDate = dateRange?.end;
1252
1489
  const messages = [];
1253
1490
  if (selectBy?.include?.length) {
1254
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1255
- if (includeMessages) {
1256
- messages.push(...includeMessages);
1491
+ try {
1492
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1493
+ if (includeMessages) {
1494
+ messages.push(...includeMessages);
1495
+ }
1496
+ } catch (error$1) {
1497
+ throw new error.MastraError(
1498
+ {
1499
+ id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_GET_INCLUDE_MESSAGES_FAILED",
1500
+ domain: error.ErrorDomain.STORAGE,
1501
+ category: error.ErrorCategory.THIRD_PARTY,
1502
+ details: { threadId }
1503
+ },
1504
+ error$1
1505
+ );
1257
1506
  }
1258
1507
  }
1259
1508
  try {
@@ -1274,7 +1523,7 @@ var LibSQLStore = class extends storage.MastraStorage {
1274
1523
  args: queryParams
1275
1524
  });
1276
1525
  const total = Number(countResult.rows?.[0]?.count ?? 0);
1277
- if (total === 0) {
1526
+ if (total === 0 && messages.length === 0) {
1278
1527
  return {
1279
1528
  messages: [],
1280
1529
  total: 0,
@@ -1283,9 +1532,11 @@ var LibSQLStore = class extends storage.MastraStorage {
1283
1532
  hasMore: false
1284
1533
  };
1285
1534
  }
1535
+ const excludeIds = messages.map((m) => m.id);
1536
+ const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + queryParams.length + 1}`).join(", ");
1286
1537
  const dataResult = await this.client.execute({
1287
- sql: `SELECT id, content, role, type, "createdAt", thread_id FROM ${storage.TABLE_MESSAGES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ? OFFSET ?`,
1288
- args: [...queryParams, perPage, currentOffset]
1538
+ 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 ?`,
1539
+ args: [...queryParams, ...excludeIds, perPage, currentOffset]
1289
1540
  });
1290
1541
  messages.push(...(dataResult.rows || []).map((row) => this.parseRow(row)));
1291
1542
  const messagesToReturn = format === "v1" ? new agent.MessageList().add(messages, "memory").get.all.v1() : new agent.MessageList().add(messages, "memory").get.all.v2();
@@ -1296,8 +1547,18 @@ var LibSQLStore = class extends storage.MastraStorage {
1296
1547
  perPage,
1297
1548
  hasMore: currentOffset + messages.length < total
1298
1549
  };
1299
- } catch (error) {
1300
- this.logger.error("Error getting paginated messages:", error);
1550
+ } catch (error$1) {
1551
+ const mastraError = new error.MastraError(
1552
+ {
1553
+ id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
1554
+ domain: error.ErrorDomain.STORAGE,
1555
+ category: error.ErrorCategory.THIRD_PARTY,
1556
+ details: { threadId }
1557
+ },
1558
+ error$1
1559
+ );
1560
+ this.logger?.trackException?.(mastraError);
1561
+ this.logger?.error?.(mastraError.toString());
1301
1562
  return { messages: [], total: 0, page, perPage, hasMore: false };
1302
1563
  }
1303
1564
  }
@@ -1325,7 +1586,14 @@ var LibSQLStore = class extends storage.MastraStorage {
1325
1586
  }
1326
1587
  return {
1327
1588
  sql: `INSERT INTO ${storage.TABLE_MESSAGES} (id, thread_id, content, role, type, createdAt, resourceId)
1328
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
1589
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1590
+ ON CONFLICT(id) DO UPDATE SET
1591
+ thread_id=excluded.thread_id,
1592
+ content=excluded.content,
1593
+ role=excluded.role,
1594
+ type=excluded.type,
1595
+ resourceId=excluded.resourceId
1596
+ `,
1329
1597
  args: [
1330
1598
  message.id,
1331
1599
  message.threadId,
@@ -1346,9 +1614,15 @@ var LibSQLStore = class extends storage.MastraStorage {
1346
1614
  const list = new agent.MessageList().add(messages, "memory");
1347
1615
  if (format === `v2`) return list.get.all.v2();
1348
1616
  return list.get.all.v1();
1349
- } catch (error) {
1350
- this.logger.error("Failed to save messages in database: " + error?.message);
1351
- throw error;
1617
+ } catch (error$1) {
1618
+ throw new error.MastraError(
1619
+ {
1620
+ id: "LIBSQL_STORE_SAVE_MESSAGES_FAILED",
1621
+ domain: error.ErrorDomain.STORAGE,
1622
+ category: error.ErrorCategory.THIRD_PARTY
1623
+ },
1624
+ error$1
1625
+ );
1352
1626
  }
1353
1627
  }
1354
1628
  async updateMessages({
@@ -1459,12 +1733,19 @@ var LibSQLStore = class extends storage.MastraStorage {
1459
1733
  args: [agentName]
1460
1734
  });
1461
1735
  return result.rows?.map((row) => this.transformEvalRow(row)) ?? [];
1462
- } catch (error) {
1463
- if (error instanceof Error && error.message.includes("no such table")) {
1736
+ } catch (error$1) {
1737
+ if (error$1 instanceof Error && error$1.message.includes("no such table")) {
1464
1738
  return [];
1465
1739
  }
1466
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
1467
- throw error;
1740
+ throw new error.MastraError(
1741
+ {
1742
+ id: "LIBSQL_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
1743
+ domain: error.ErrorDomain.STORAGE,
1744
+ category: error.ErrorCategory.THIRD_PARTY,
1745
+ details: { agentName }
1746
+ },
1747
+ error$1
1748
+ );
1468
1749
  }
1469
1750
  }
1470
1751
  async getEvals(options = {}) {
@@ -1491,33 +1772,44 @@ var LibSQLStore = class extends storage.MastraStorage {
1491
1772
  queryParams.push(toDate.toISOString());
1492
1773
  }
1493
1774
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1494
- const countResult = await this.client.execute({
1495
- sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
1496
- args: queryParams
1497
- });
1498
- const total = Number(countResult.rows?.[0]?.count ?? 0);
1499
- const currentOffset = page * perPage;
1500
- const hasMore = currentOffset + perPage < total;
1501
- if (total === 0) {
1775
+ try {
1776
+ const countResult = await this.client.execute({
1777
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_EVALS} ${whereClause}`,
1778
+ args: queryParams
1779
+ });
1780
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
1781
+ const currentOffset = page * perPage;
1782
+ const hasMore = currentOffset + perPage < total;
1783
+ if (total === 0) {
1784
+ return {
1785
+ evals: [],
1786
+ total: 0,
1787
+ page,
1788
+ perPage,
1789
+ hasMore: false
1790
+ };
1791
+ }
1792
+ const dataResult = await this.client.execute({
1793
+ sql: `SELECT * FROM ${storage.TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
1794
+ args: [...queryParams, perPage, currentOffset]
1795
+ });
1502
1796
  return {
1503
- evals: [],
1504
- total: 0,
1797
+ evals: dataResult.rows?.map((row) => this.transformEvalRow(row)) ?? [],
1798
+ total,
1505
1799
  page,
1506
1800
  perPage,
1507
- hasMore: false
1801
+ hasMore
1508
1802
  };
1803
+ } catch (error$1) {
1804
+ throw new error.MastraError(
1805
+ {
1806
+ id: "LIBSQL_STORE_GET_EVALS_FAILED",
1807
+ domain: error.ErrorDomain.STORAGE,
1808
+ category: error.ErrorCategory.THIRD_PARTY
1809
+ },
1810
+ error$1
1811
+ );
1509
1812
  }
1510
- const dataResult = await this.client.execute({
1511
- sql: `SELECT * FROM ${storage.TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
1512
- args: [...queryParams, perPage, currentOffset]
1513
- });
1514
- return {
1515
- evals: dataResult.rows?.map((row) => this.transformEvalRow(row)) ?? [],
1516
- total,
1517
- page,
1518
- perPage,
1519
- hasMore
1520
- };
1521
1813
  }
1522
1814
  /**
1523
1815
  * @deprecated use getTracesPaginated instead.
@@ -1529,8 +1821,19 @@ var LibSQLStore = class extends storage.MastraStorage {
1529
1821
  end: args.toDate
1530
1822
  };
1531
1823
  }
1532
- const result = await this.getTracesPaginated(args);
1533
- return result.traces;
1824
+ try {
1825
+ const result = await this.getTracesPaginated(args);
1826
+ return result.traces;
1827
+ } catch (error$1) {
1828
+ throw new error.MastraError(
1829
+ {
1830
+ id: "LIBSQL_STORE_GET_TRACES_FAILED",
1831
+ domain: error.ErrorDomain.STORAGE,
1832
+ category: error.ErrorCategory.THIRD_PARTY
1833
+ },
1834
+ error$1
1835
+ );
1836
+ }
1534
1837
  }
1535
1838
  async getTracesPaginated(args) {
1536
1839
  const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
@@ -1568,49 +1871,60 @@ var LibSQLStore = class extends storage.MastraStorage {
1568
1871
  queryArgs.push(toDate.toISOString());
1569
1872
  }
1570
1873
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1571
- const countResult = await this.client.execute({
1572
- sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
1573
- args: queryArgs
1574
- });
1575
- const total = Number(countResult.rows?.[0]?.count ?? 0);
1576
- if (total === 0) {
1874
+ try {
1875
+ const countResult = await this.client.execute({
1876
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_TRACES} ${whereClause}`,
1877
+ args: queryArgs
1878
+ });
1879
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
1880
+ if (total === 0) {
1881
+ return {
1882
+ traces: [],
1883
+ total: 0,
1884
+ page,
1885
+ perPage,
1886
+ hasMore: false
1887
+ };
1888
+ }
1889
+ const dataResult = await this.client.execute({
1890
+ sql: `SELECT * FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
1891
+ args: [...queryArgs, perPage, currentOffset]
1892
+ });
1893
+ const traces = dataResult.rows?.map(
1894
+ (row) => ({
1895
+ id: row.id,
1896
+ parentSpanId: row.parentSpanId,
1897
+ traceId: row.traceId,
1898
+ name: row.name,
1899
+ scope: row.scope,
1900
+ kind: row.kind,
1901
+ status: safelyParseJSON(row.status),
1902
+ events: safelyParseJSON(row.events),
1903
+ links: safelyParseJSON(row.links),
1904
+ attributes: safelyParseJSON(row.attributes),
1905
+ startTime: row.startTime,
1906
+ endTime: row.endTime,
1907
+ other: safelyParseJSON(row.other),
1908
+ createdAt: row.createdAt
1909
+ })
1910
+ ) ?? [];
1577
1911
  return {
1578
- traces: [],
1579
- total: 0,
1912
+ traces,
1913
+ total,
1580
1914
  page,
1581
1915
  perPage,
1582
- hasMore: false
1916
+ hasMore: currentOffset + traces.length < total
1583
1917
  };
1918
+ } catch (error$1) {
1919
+ throw new error.MastraError(
1920
+ {
1921
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1922
+ domain: error.ErrorDomain.STORAGE,
1923
+ category: error.ErrorCategory.THIRD_PARTY
1924
+ },
1925
+ error$1
1926
+ );
1584
1927
  }
1585
- const dataResult = await this.client.execute({
1586
- sql: `SELECT * FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
1587
- args: [...queryArgs, perPage, currentOffset]
1588
- });
1589
- const traces = dataResult.rows?.map(
1590
- (row) => ({
1591
- id: row.id,
1592
- parentSpanId: row.parentSpanId,
1593
- traceId: row.traceId,
1594
- name: row.name,
1595
- scope: row.scope,
1596
- kind: row.kind,
1597
- status: safelyParseJSON(row.status),
1598
- events: safelyParseJSON(row.events),
1599
- links: safelyParseJSON(row.links),
1600
- attributes: safelyParseJSON(row.attributes),
1601
- startTime: row.startTime,
1602
- endTime: row.endTime,
1603
- other: safelyParseJSON(row.other),
1604
- createdAt: row.createdAt
1605
- })
1606
- ) ?? [];
1607
- return {
1608
- traces,
1609
- total,
1610
- page,
1611
- perPage,
1612
- hasMore: currentOffset + traces.length < total
1613
- };
1614
1928
  }
1615
1929
  async getWorkflowRuns({
1616
1930
  workflowName,
@@ -1659,9 +1973,15 @@ var LibSQLStore = class extends storage.MastraStorage {
1659
1973
  });
1660
1974
  const runs = (result.rows || []).map((row) => this.parseWorkflowRun(row));
1661
1975
  return { runs, total: total || runs.length };
1662
- } catch (error) {
1663
- console.error("Error getting workflow runs:", error);
1664
- throw error;
1976
+ } catch (error$1) {
1977
+ throw new error.MastraError(
1978
+ {
1979
+ id: "LIBSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
1980
+ domain: error.ErrorDomain.STORAGE,
1981
+ category: error.ErrorCategory.THIRD_PARTY
1982
+ },
1983
+ error$1
1984
+ );
1665
1985
  }
1666
1986
  }
1667
1987
  async getWorkflowRunById({
@@ -1679,14 +1999,94 @@ var LibSQLStore = class extends storage.MastraStorage {
1679
1999
  args.push(workflowName);
1680
2000
  }
1681
2001
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1682
- const result = await this.client.execute({
1683
- sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
1684
- args
2002
+ try {
2003
+ const result = await this.client.execute({
2004
+ sql: `SELECT * FROM ${storage.TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
2005
+ args
2006
+ });
2007
+ if (!result.rows?.[0]) {
2008
+ return null;
2009
+ }
2010
+ return this.parseWorkflowRun(result.rows[0]);
2011
+ } catch (error$1) {
2012
+ throw new error.MastraError(
2013
+ {
2014
+ id: "LIBSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2015
+ domain: error.ErrorDomain.STORAGE,
2016
+ category: error.ErrorCategory.THIRD_PARTY
2017
+ },
2018
+ error$1
2019
+ );
2020
+ }
2021
+ }
2022
+ async getResourceById({ resourceId }) {
2023
+ const result = await this.load({
2024
+ tableName: storage.TABLE_RESOURCES,
2025
+ keys: { id: resourceId }
1685
2026
  });
1686
- if (!result.rows?.[0]) {
2027
+ if (!result) {
1687
2028
  return null;
1688
2029
  }
1689
- return this.parseWorkflowRun(result.rows[0]);
2030
+ return {
2031
+ ...result,
2032
+ // Ensure workingMemory is always returned as a string, even if auto-parsed as JSON
2033
+ workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
2034
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
2035
+ };
2036
+ }
2037
+ async saveResource({ resource }) {
2038
+ await this.insert({
2039
+ tableName: storage.TABLE_RESOURCES,
2040
+ record: {
2041
+ ...resource,
2042
+ metadata: JSON.stringify(resource.metadata)
2043
+ }
2044
+ });
2045
+ return resource;
2046
+ }
2047
+ async updateResource({
2048
+ resourceId,
2049
+ workingMemory,
2050
+ metadata
2051
+ }) {
2052
+ const existingResource = await this.getResourceById({ resourceId });
2053
+ if (!existingResource) {
2054
+ const newResource = {
2055
+ id: resourceId,
2056
+ workingMemory,
2057
+ metadata: metadata || {},
2058
+ createdAt: /* @__PURE__ */ new Date(),
2059
+ updatedAt: /* @__PURE__ */ new Date()
2060
+ };
2061
+ return this.saveResource({ resource: newResource });
2062
+ }
2063
+ const updatedResource = {
2064
+ ...existingResource,
2065
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
2066
+ metadata: {
2067
+ ...existingResource.metadata,
2068
+ ...metadata
2069
+ },
2070
+ updatedAt: /* @__PURE__ */ new Date()
2071
+ };
2072
+ const updates = [];
2073
+ const values = [];
2074
+ if (workingMemory !== void 0) {
2075
+ updates.push("workingMemory = ?");
2076
+ values.push(workingMemory);
2077
+ }
2078
+ if (metadata) {
2079
+ updates.push("metadata = ?");
2080
+ values.push(JSON.stringify(updatedResource.metadata));
2081
+ }
2082
+ updates.push("updatedAt = ?");
2083
+ values.push(updatedResource.updatedAt.toISOString());
2084
+ values.push(resourceId);
2085
+ await this.client.execute({
2086
+ sql: `UPDATE ${storage.TABLE_RESOURCES} SET ${updates.join(", ")} WHERE id = ?`,
2087
+ args: values
2088
+ });
2089
+ return updatedResource;
1690
2090
  }
1691
2091
  async hasColumn(table, column) {
1692
2092
  const result = await this.client.execute({