@mastra/pg 0.11.1-alpha.0 → 0.11.1-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,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var error = require('@mastra/core/error');
3
4
  var utils = require('@mastra/core/utils');
4
5
  var vector = require('@mastra/core/vector');
5
6
  var asyncMutex = require('async-mutex');
@@ -44,10 +45,10 @@ var PGFilterTranslator = class extends filter.BaseFilterTranslator {
44
45
  }
45
46
  const entries = Object.entries(node);
46
47
  const result = {};
47
- if ("$options" in node && !("$regex" in node)) {
48
+ if (node && "$options" in node && !("$regex" in node)) {
48
49
  throw new Error("$options is not valid without $regex");
49
50
  }
50
- if ("$regex" in node) {
51
+ if (node && "$regex" in node) {
51
52
  const options = node.$options || "";
52
53
  return withPath(this.translateRegexPattern(node.$regex, options));
53
54
  }
@@ -376,43 +377,57 @@ var PgVector = class extends vector.MastraVector {
376
377
  schemaName,
377
378
  pgPoolOptions
378
379
  }) {
379
- if (!connectionString || connectionString.trim() === "") {
380
- throw new Error(
381
- "PgVector: connectionString must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults."
382
- );
383
- }
384
- super();
385
- this.schema = schemaName;
386
- const basePool = new pg__default.default.Pool({
387
- connectionString,
388
- max: 20,
389
- // Maximum number of clients in the pool
390
- idleTimeoutMillis: 3e4,
391
- // Close idle connections after 30 seconds
392
- connectionTimeoutMillis: 2e3,
393
- // Fail fast if can't connect
394
- ...pgPoolOptions
395
- });
396
- const telemetry = this.__getTelemetry();
397
- this.pool = telemetry?.traceClass(basePool, {
398
- spanNamePrefix: "pg-vector",
399
- attributes: {
400
- "vector.type": "postgres"
380
+ try {
381
+ if (!connectionString || connectionString.trim() === "") {
382
+ throw new Error(
383
+ "PgVector: connectionString must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults."
384
+ );
401
385
  }
402
- }) ?? basePool;
403
- void (async () => {
404
- const existingIndexes = await this.listIndexes();
405
- void existingIndexes.map(async (indexName) => {
406
- const info = await this.getIndexInfo({ indexName });
407
- const key = await this.getIndexCacheKey({
408
- indexName,
409
- metric: info.metric,
410
- dimension: info.dimension,
411
- type: info.type
412
- });
413
- this.createdIndexes.set(indexName, key);
386
+ super();
387
+ this.schema = schemaName;
388
+ const basePool = new pg__default.default.Pool({
389
+ connectionString,
390
+ max: 20,
391
+ // Maximum number of clients in the pool
392
+ idleTimeoutMillis: 3e4,
393
+ // Close idle connections after 30 seconds
394
+ connectionTimeoutMillis: 2e3,
395
+ // Fail fast if can't connect
396
+ ...pgPoolOptions
414
397
  });
415
- })();
398
+ const telemetry = this.__getTelemetry();
399
+ this.pool = telemetry?.traceClass(basePool, {
400
+ spanNamePrefix: "pg-vector",
401
+ attributes: {
402
+ "vector.type": "postgres"
403
+ }
404
+ }) ?? basePool;
405
+ void (async () => {
406
+ const existingIndexes = await this.listIndexes();
407
+ void existingIndexes.map(async (indexName) => {
408
+ const info = await this.getIndexInfo({ indexName });
409
+ const key = await this.getIndexCacheKey({
410
+ indexName,
411
+ metric: info.metric,
412
+ dimension: info.dimension,
413
+ type: info.type
414
+ });
415
+ this.createdIndexes.set(indexName, key);
416
+ });
417
+ })();
418
+ } catch (error$1) {
419
+ throw new error.MastraError(
420
+ {
421
+ id: "MASTRA_STORAGE_PG_VECTOR_INITIALIZATION_FAILED",
422
+ domain: error.ErrorDomain.MASTRA_VECTOR,
423
+ category: error.ErrorCategory.THIRD_PARTY,
424
+ details: {
425
+ schemaName: schemaName ?? ""
426
+ }
427
+ },
428
+ error$1
429
+ );
430
+ }
416
431
  }
417
432
  getMutexByName(indexName) {
418
433
  if (!this.mutexesByName.has(indexName)) this.mutexesByName.set(indexName, new asyncMutex.Mutex());
@@ -451,11 +466,27 @@ var PgVector = class extends vector.MastraVector {
451
466
  ef,
452
467
  probes
453
468
  }) {
454
- if (!Number.isInteger(topK) || topK <= 0) {
455
- throw new Error("topK must be a positive integer");
456
- }
457
- if (!Array.isArray(queryVector) || !queryVector.every((x) => typeof x === "number" && Number.isFinite(x))) {
458
- throw new Error("queryVector must be an array of finite numbers");
469
+ try {
470
+ if (!Number.isInteger(topK) || topK <= 0) {
471
+ throw new Error("topK must be a positive integer");
472
+ }
473
+ if (!Array.isArray(queryVector) || !queryVector.every((x) => typeof x === "number" && Number.isFinite(x))) {
474
+ throw new Error("queryVector must be an array of finite numbers");
475
+ }
476
+ } catch (error$1) {
477
+ const mastraError = new error.MastraError(
478
+ {
479
+ id: "MASTRA_STORAGE_PG_VECTOR_QUERY_INVALID_INPUT",
480
+ domain: error.ErrorDomain.MASTRA_VECTOR,
481
+ category: error.ErrorCategory.USER,
482
+ details: {
483
+ indexName
484
+ }
485
+ },
486
+ error$1
487
+ );
488
+ this.logger?.trackException(mastraError);
489
+ throw mastraError;
459
490
  }
460
491
  const client = await this.pool.connect();
461
492
  try {
@@ -494,6 +525,20 @@ var PgVector = class extends vector.MastraVector {
494
525
  metadata,
495
526
  ...includeVector && embedding && { vector: JSON.parse(embedding) }
496
527
  }));
528
+ } catch (error$1) {
529
+ const mastraError = new error.MastraError(
530
+ {
531
+ id: "MASTRA_STORAGE_PG_VECTOR_QUERY_FAILED",
532
+ domain: error.ErrorDomain.MASTRA_VECTOR,
533
+ category: error.ErrorCategory.THIRD_PARTY,
534
+ details: {
535
+ indexName
536
+ }
537
+ },
538
+ error$1
539
+ );
540
+ this.logger?.trackException(mastraError);
541
+ throw mastraError;
497
542
  } finally {
498
543
  client.release();
499
544
  }
@@ -518,18 +563,43 @@ var PgVector = class extends vector.MastraVector {
518
563
  }
519
564
  await client.query("COMMIT");
520
565
  return vectorIds;
521
- } catch (error) {
566
+ } catch (error$1) {
522
567
  await client.query("ROLLBACK");
523
- if (error instanceof Error && error.message?.includes("expected") && error.message?.includes("dimensions")) {
524
- const match = error.message.match(/expected (\d+) dimensions, not (\d+)/);
568
+ if (error$1 instanceof Error && error$1.message?.includes("expected") && error$1.message?.includes("dimensions")) {
569
+ const match = error$1.message.match(/expected (\d+) dimensions, not (\d+)/);
525
570
  if (match) {
526
571
  const [, expected, actual] = match;
527
- throw new Error(
528
- `Vector dimension mismatch: Index "${indexName}" expects ${expected} dimensions but got ${actual} dimensions. Either use a matching embedding model or delete and recreate the index with the new dimension.`
572
+ const mastraError2 = new error.MastraError(
573
+ {
574
+ id: "MASTRA_STORAGE_PG_VECTOR_UPSERT_INVALID_INPUT",
575
+ domain: error.ErrorDomain.MASTRA_VECTOR,
576
+ category: error.ErrorCategory.USER,
577
+ text: `Vector dimension mismatch: Index "${indexName}" expects ${expected} dimensions but got ${actual} dimensions. Either use a matching embedding model or delete and recreate the index with the new dimension.`,
578
+ details: {
579
+ indexName,
580
+ expected: expected ?? "",
581
+ actual: actual ?? ""
582
+ }
583
+ },
584
+ error$1
529
585
  );
586
+ this.logger?.trackException(mastraError2);
587
+ throw mastraError2;
530
588
  }
531
589
  }
532
- throw error;
590
+ const mastraError = new error.MastraError(
591
+ {
592
+ id: "MASTRA_STORAGE_PG_VECTOR_UPSERT_FAILED",
593
+ domain: error.ErrorDomain.MASTRA_VECTOR,
594
+ category: error.ErrorCategory.THIRD_PARTY,
595
+ details: {
596
+ indexName
597
+ }
598
+ },
599
+ error$1
600
+ );
601
+ this.logger?.trackException(mastraError);
602
+ throw mastraError;
533
603
  } finally {
534
604
  client.release();
535
605
  }
@@ -597,11 +667,27 @@ var PgVector = class extends vector.MastraVector {
597
667
  buildIndex = true
598
668
  }) {
599
669
  const { tableName } = this.getTableName(indexName);
600
- if (!indexName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
601
- throw new Error("Invalid index name format");
602
- }
603
- if (!Number.isInteger(dimension) || dimension <= 0) {
604
- throw new Error("Dimension must be a positive integer");
670
+ try {
671
+ if (!indexName.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
672
+ throw new Error("Invalid index name format");
673
+ }
674
+ if (!Number.isInteger(dimension) || dimension <= 0) {
675
+ throw new Error("Dimension must be a positive integer");
676
+ }
677
+ } catch (error$1) {
678
+ const mastraError = new error.MastraError(
679
+ {
680
+ id: "MASTRA_STORAGE_PG_VECTOR_CREATE_INDEX_INVALID_INPUT",
681
+ domain: error.ErrorDomain.MASTRA_VECTOR,
682
+ category: error.ErrorCategory.USER,
683
+ details: {
684
+ indexName
685
+ }
686
+ },
687
+ error$1
688
+ );
689
+ this.logger?.trackException(mastraError);
690
+ throw mastraError;
605
691
  }
606
692
  const indexCacheKey = await this.getIndexCacheKey({ indexName, dimension, type: indexConfig.type, metric });
607
693
  if (this.cachedIndexExists(indexName, indexCacheKey)) {
@@ -634,12 +720,40 @@ var PgVector = class extends vector.MastraVector {
634
720
  } finally {
635
721
  client.release();
636
722
  }
723
+ }).catch((error$1) => {
724
+ const mastraError = new error.MastraError(
725
+ {
726
+ id: "MASTRA_STORAGE_PG_VECTOR_CREATE_INDEX_FAILED",
727
+ domain: error.ErrorDomain.MASTRA_VECTOR,
728
+ category: error.ErrorCategory.THIRD_PARTY,
729
+ details: {
730
+ indexName
731
+ }
732
+ },
733
+ error$1
734
+ );
735
+ this.logger?.trackException(mastraError);
736
+ throw mastraError;
637
737
  });
638
738
  }
639
739
  async buildIndex({ indexName, metric = "cosine", indexConfig }) {
640
740
  const client = await this.pool.connect();
641
741
  try {
642
742
  await this.setupIndex({ indexName, metric, indexConfig }, client);
743
+ } catch (error$1) {
744
+ const mastraError = new error.MastraError(
745
+ {
746
+ id: "MASTRA_STORAGE_PG_VECTOR_BUILD_INDEX_FAILED",
747
+ domain: error.ErrorDomain.MASTRA_VECTOR,
748
+ category: error.ErrorCategory.THIRD_PARTY,
749
+ details: {
750
+ indexName
751
+ }
752
+ },
753
+ error$1
754
+ );
755
+ this.logger?.trackException(mastraError);
756
+ throw mastraError;
643
757
  } finally {
644
758
  client.release();
645
759
  }
@@ -736,6 +850,17 @@ var PgVector = class extends vector.MastraVector {
736
850
  `;
737
851
  const vectorTables = await client.query(vectorTablesQuery, [this.schema || "public"]);
738
852
  return vectorTables.rows.map((row) => row.table_name);
853
+ } catch (e) {
854
+ const mastraError = new error.MastraError(
855
+ {
856
+ id: "MASTRA_STORAGE_PG_VECTOR_LIST_INDEXES_FAILED",
857
+ domain: error.ErrorDomain.MASTRA_VECTOR,
858
+ category: error.ErrorCategory.THIRD_PARTY
859
+ },
860
+ e
861
+ );
862
+ this.logger?.trackException(mastraError);
863
+ throw mastraError;
739
864
  } finally {
740
865
  client.release();
741
866
  }
@@ -815,7 +940,19 @@ var PgVector = class extends vector.MastraVector {
815
940
  };
816
941
  } catch (e) {
817
942
  await client.query("ROLLBACK");
818
- throw new Error(`Failed to describe vector table: ${e.message}`);
943
+ const mastraError = new error.MastraError(
944
+ {
945
+ id: "MASTRA_STORAGE_PG_VECTOR_DESCRIBE_INDEX_FAILED",
946
+ domain: error.ErrorDomain.MASTRA_VECTOR,
947
+ category: error.ErrorCategory.THIRD_PARTY,
948
+ details: {
949
+ indexName
950
+ }
951
+ },
952
+ e
953
+ );
954
+ this.logger?.trackException(mastraError);
955
+ throw mastraError;
819
956
  } finally {
820
957
  client.release();
821
958
  }
@@ -826,9 +963,21 @@ var PgVector = class extends vector.MastraVector {
826
963
  const { tableName } = this.getTableName(indexName);
827
964
  await client.query(`DROP TABLE IF EXISTS ${tableName} CASCADE`);
828
965
  this.createdIndexes.delete(indexName);
829
- } catch (error) {
966
+ } catch (error$1) {
830
967
  await client.query("ROLLBACK");
831
- throw new Error(`Failed to delete vector table: ${error.message}`);
968
+ const mastraError = new error.MastraError(
969
+ {
970
+ id: "MASTRA_STORAGE_PG_VECTOR_DELETE_INDEX_FAILED",
971
+ domain: error.ErrorDomain.MASTRA_VECTOR,
972
+ category: error.ErrorCategory.THIRD_PARTY,
973
+ details: {
974
+ indexName
975
+ }
976
+ },
977
+ error$1
978
+ );
979
+ this.logger?.trackException(mastraError);
980
+ throw mastraError;
832
981
  } finally {
833
982
  client.release();
834
983
  }
@@ -840,7 +989,19 @@ var PgVector = class extends vector.MastraVector {
840
989
  await client.query(`TRUNCATE ${tableName}`);
841
990
  } catch (e) {
842
991
  await client.query("ROLLBACK");
843
- throw new Error(`Failed to truncate vector table: ${e.message}`);
992
+ const mastraError = new error.MastraError(
993
+ {
994
+ id: "MASTRA_STORAGE_PG_VECTOR_TRUNCATE_INDEX_FAILED",
995
+ domain: error.ErrorDomain.MASTRA_VECTOR,
996
+ category: error.ErrorCategory.THIRD_PARTY,
997
+ details: {
998
+ indexName
999
+ }
1000
+ },
1001
+ e
1002
+ );
1003
+ this.logger?.trackException(mastraError);
1004
+ throw mastraError;
844
1005
  } finally {
845
1006
  client.release();
846
1007
  }
@@ -859,11 +1020,12 @@ var PgVector = class extends vector.MastraVector {
859
1020
  * @throws Will throw an error if no updates are provided or if the update operation fails.
860
1021
  */
861
1022
  async updateVector({ indexName, id, update }) {
862
- if (!update.vector && !update.metadata) {
863
- throw new Error("No updates provided");
864
- }
865
- const client = await this.pool.connect();
1023
+ let client;
866
1024
  try {
1025
+ if (!update.vector && !update.metadata) {
1026
+ throw new Error("No updates provided");
1027
+ }
1028
+ client = await this.pool.connect();
867
1029
  let updateParts = [];
868
1030
  let values = [id];
869
1031
  let valueIndex = 2;
@@ -886,10 +1048,23 @@ var PgVector = class extends vector.MastraVector {
886
1048
  WHERE vector_id = $1
887
1049
  `;
888
1050
  await client.query(query, values);
889
- } catch (error) {
890
- throw new Error(`Failed to update vector by id: ${id} for index: ${indexName}: ${error.message}`);
1051
+ } catch (error$1) {
1052
+ const mastraError = new error.MastraError(
1053
+ {
1054
+ id: "MASTRA_STORAGE_PG_VECTOR_UPDATE_VECTOR_FAILED",
1055
+ domain: error.ErrorDomain.MASTRA_VECTOR,
1056
+ category: error.ErrorCategory.THIRD_PARTY,
1057
+ details: {
1058
+ indexName,
1059
+ id
1060
+ }
1061
+ },
1062
+ error$1
1063
+ );
1064
+ this.logger?.trackException(mastraError);
1065
+ throw mastraError;
891
1066
  } finally {
892
- client.release();
1067
+ client?.release();
893
1068
  }
894
1069
  }
895
1070
  /**
@@ -900,18 +1075,32 @@ var PgVector = class extends vector.MastraVector {
900
1075
  * @throws Will throw an error if the deletion operation fails.
901
1076
  */
902
1077
  async deleteVector({ indexName, id }) {
903
- const client = await this.pool.connect();
1078
+ let client;
904
1079
  try {
1080
+ client = await this.pool.connect();
905
1081
  const { tableName } = this.getTableName(indexName);
906
1082
  const query = `
907
1083
  DELETE FROM ${tableName}
908
1084
  WHERE vector_id = $1
909
1085
  `;
910
1086
  await client.query(query, [id]);
911
- } catch (error) {
912
- throw new Error(`Failed to delete vector by id: ${id} for index: ${indexName}: ${error.message}`);
1087
+ } catch (error$1) {
1088
+ const mastraError = new error.MastraError(
1089
+ {
1090
+ id: "MASTRA_STORAGE_PG_VECTOR_DELETE_VECTOR_FAILED",
1091
+ domain: error.ErrorDomain.MASTRA_VECTOR,
1092
+ category: error.ErrorCategory.THIRD_PARTY,
1093
+ details: {
1094
+ indexName,
1095
+ id
1096
+ }
1097
+ },
1098
+ error$1
1099
+ );
1100
+ this.logger?.trackException(mastraError);
1101
+ throw mastraError;
913
1102
  } finally {
914
- client.release();
1103
+ client?.release();
915
1104
  }
916
1105
  }
917
1106
  };
@@ -922,39 +1111,51 @@ var PostgresStore = class extends storage.MastraStorage {
922
1111
  setupSchemaPromise = null;
923
1112
  schemaSetupComplete = void 0;
924
1113
  constructor(config) {
925
- if ("connectionString" in config) {
926
- if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
927
- throw new Error(
928
- "PostgresStore: connectionString must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults."
929
- );
930
- }
931
- } else {
932
- const required = ["host", "database", "user", "password"];
933
- for (const key of required) {
934
- if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
1114
+ try {
1115
+ if ("connectionString" in config) {
1116
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
935
1117
  throw new Error(
936
- `PostgresStore: ${key} must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults.`
1118
+ "PostgresStore: connectionString must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults."
937
1119
  );
938
1120
  }
1121
+ } else {
1122
+ const required = ["host", "database", "user", "password"];
1123
+ for (const key of required) {
1124
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
1125
+ throw new Error(
1126
+ `PostgresStore: ${key} must be provided and cannot be empty. Passing an empty string may cause fallback to local Postgres defaults.`
1127
+ );
1128
+ }
1129
+ }
939
1130
  }
1131
+ super({ name: "PostgresStore" });
1132
+ this.pgp = pgPromise__default.default();
1133
+ this.schema = config.schemaName;
1134
+ this.db = this.pgp(
1135
+ `connectionString` in config ? { connectionString: config.connectionString } : {
1136
+ host: config.host,
1137
+ port: config.port,
1138
+ database: config.database,
1139
+ user: config.user,
1140
+ password: config.password,
1141
+ ssl: config.ssl
1142
+ }
1143
+ );
1144
+ } catch (e) {
1145
+ throw new error.MastraError(
1146
+ {
1147
+ id: "MASTRA_STORAGE_PG_STORE_INITIALIZATION_FAILED",
1148
+ domain: error.ErrorDomain.STORAGE,
1149
+ category: error.ErrorCategory.USER
1150
+ },
1151
+ e
1152
+ );
940
1153
  }
941
- super({ name: "PostgresStore" });
942
- this.pgp = pgPromise__default.default();
943
- this.schema = config.schemaName;
944
- this.db = this.pgp(
945
- `connectionString` in config ? { connectionString: config.connectionString } : {
946
- host: config.host,
947
- port: config.port,
948
- database: config.database,
949
- user: config.user,
950
- password: config.password,
951
- ssl: config.ssl
952
- }
953
- );
954
1154
  }
955
1155
  get supports() {
956
1156
  return {
957
- selectByIncludeResourceScope: true
1157
+ selectByIncludeResourceScope: true,
1158
+ resourceWorkingMemory: true
958
1159
  };
959
1160
  }
960
1161
  getTableName(indexName) {
@@ -1011,10 +1212,20 @@ var PostgresStore = class extends storage.MastraStorage {
1011
1212
  await this.insert({ tableName, record });
1012
1213
  }
1013
1214
  await this.db.query("COMMIT");
1014
- } catch (error) {
1015
- console.error(`Error inserting into ${tableName}:`, error);
1215
+ } catch (error$1) {
1016
1216
  await this.db.query("ROLLBACK");
1017
- throw error;
1217
+ throw new error.MastraError(
1218
+ {
1219
+ id: "MASTRA_STORAGE_PG_STORE_BATCH_INSERT_FAILED",
1220
+ domain: error.ErrorDomain.STORAGE,
1221
+ category: error.ErrorCategory.THIRD_PARTY,
1222
+ details: {
1223
+ tableName,
1224
+ numberOfRecords: records.length
1225
+ }
1226
+ },
1227
+ error$1
1228
+ );
1018
1229
  }
1019
1230
  }
1020
1231
  /**
@@ -1071,8 +1282,24 @@ var PostgresStore = class extends storage.MastraStorage {
1071
1282
  }
1072
1283
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1073
1284
  const countQuery = `SELECT COUNT(*) FROM ${this.getTableName(storage.TABLE_TRACES)} ${whereClause}`;
1074
- const countResult = await this.db.one(countQuery, queryParams);
1075
- const total = parseInt(countResult.count, 10);
1285
+ let total = 0;
1286
+ try {
1287
+ const countResult = await this.db.one(countQuery, queryParams);
1288
+ total = parseInt(countResult.count, 10);
1289
+ } catch (error$1) {
1290
+ throw new error.MastraError(
1291
+ {
1292
+ id: "MASTRA_STORAGE_PG_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
1293
+ domain: error.ErrorDomain.STORAGE,
1294
+ category: error.ErrorCategory.THIRD_PARTY,
1295
+ details: {
1296
+ name: args.name ?? "",
1297
+ scope: args.scope ?? ""
1298
+ }
1299
+ },
1300
+ error$1
1301
+ );
1302
+ }
1076
1303
  if (total === 0) {
1077
1304
  return {
1078
1305
  traces: [],
@@ -1086,30 +1313,45 @@ var PostgresStore = class extends storage.MastraStorage {
1086
1313
  storage.TABLE_TRACES
1087
1314
  )} ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
1088
1315
  const finalQueryParams = [...queryParams, perPage, currentOffset];
1089
- const rows = await this.db.manyOrNone(dataQuery, finalQueryParams);
1090
- const traces = rows.map((row) => ({
1091
- id: row.id,
1092
- parentSpanId: row.parentSpanId,
1093
- traceId: row.traceId,
1094
- name: row.name,
1095
- scope: row.scope,
1096
- kind: row.kind,
1097
- status: row.status,
1098
- events: row.events,
1099
- links: row.links,
1100
- attributes: row.attributes,
1101
- startTime: row.startTime,
1102
- endTime: row.endTime,
1103
- other: row.other,
1104
- createdAt: row.createdAt
1105
- }));
1106
- return {
1107
- traces,
1108
- total,
1109
- page,
1110
- perPage,
1111
- hasMore: currentOffset + traces.length < total
1112
- };
1316
+ try {
1317
+ const rows = await this.db.manyOrNone(dataQuery, finalQueryParams);
1318
+ const traces = rows.map((row) => ({
1319
+ id: row.id,
1320
+ parentSpanId: row.parentSpanId,
1321
+ traceId: row.traceId,
1322
+ name: row.name,
1323
+ scope: row.scope,
1324
+ kind: row.kind,
1325
+ status: row.status,
1326
+ events: row.events,
1327
+ links: row.links,
1328
+ attributes: row.attributes,
1329
+ startTime: row.startTime,
1330
+ endTime: row.endTime,
1331
+ other: row.other,
1332
+ createdAt: row.createdAt
1333
+ }));
1334
+ return {
1335
+ traces,
1336
+ total,
1337
+ page,
1338
+ perPage,
1339
+ hasMore: currentOffset + traces.length < total
1340
+ };
1341
+ } catch (error$1) {
1342
+ throw new error.MastraError(
1343
+ {
1344
+ id: "MASTRA_STORAGE_PG_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
1345
+ domain: error.ErrorDomain.STORAGE,
1346
+ category: error.ErrorCategory.THIRD_PARTY,
1347
+ details: {
1348
+ name: args.name ?? "",
1349
+ scope: args.scope ?? ""
1350
+ }
1351
+ },
1352
+ error$1
1353
+ );
1354
+ }
1113
1355
  }
1114
1356
  async setupSchema() {
1115
1357
  if (!this.schema || this.schemaSetupComplete) {
@@ -1183,9 +1425,18 @@ var PostgresStore = class extends storage.MastraStorage {
1183
1425
  ` : ""}
1184
1426
  `;
1185
1427
  await this.db.none(sql);
1186
- } catch (error) {
1187
- console.error(`Error creating table ${tableName}:`, error);
1188
- throw error;
1428
+ } catch (error$1) {
1429
+ throw new error.MastraError(
1430
+ {
1431
+ id: "MASTRA_STORAGE_PG_STORE_CREATE_TABLE_FAILED",
1432
+ domain: error.ErrorDomain.STORAGE,
1433
+ category: error.ErrorCategory.THIRD_PARTY,
1434
+ details: {
1435
+ tableName
1436
+ }
1437
+ },
1438
+ error$1
1439
+ );
1189
1440
  }
1190
1441
  }
1191
1442
  getDefaultValue(type) {
@@ -1223,19 +1474,35 @@ var PostgresStore = class extends storage.MastraStorage {
1223
1474
  this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
1224
1475
  }
1225
1476
  }
1226
- } catch (error) {
1227
- this.logger?.error?.(
1228
- `Error altering table ${tableName}: ${error instanceof Error ? error.message : String(error)}`
1477
+ } catch (error$1) {
1478
+ throw new error.MastraError(
1479
+ {
1480
+ id: "MASTRA_STORAGE_PG_STORE_ALTER_TABLE_FAILED",
1481
+ domain: error.ErrorDomain.STORAGE,
1482
+ category: error.ErrorCategory.THIRD_PARTY,
1483
+ details: {
1484
+ tableName
1485
+ }
1486
+ },
1487
+ error$1
1229
1488
  );
1230
- throw new Error(`Failed to alter table ${tableName}: ${error}`);
1231
1489
  }
1232
1490
  }
1233
1491
  async clearTable({ tableName }) {
1234
1492
  try {
1235
1493
  await this.db.none(`TRUNCATE TABLE ${this.getTableName(tableName)} CASCADE`);
1236
- } catch (error) {
1237
- console.error(`Error clearing table ${tableName}:`, error);
1238
- throw error;
1494
+ } catch (error$1) {
1495
+ throw new error.MastraError(
1496
+ {
1497
+ id: "MASTRA_STORAGE_PG_STORE_CLEAR_TABLE_FAILED",
1498
+ domain: error.ErrorDomain.STORAGE,
1499
+ category: error.ErrorCategory.THIRD_PARTY,
1500
+ details: {
1501
+ tableName
1502
+ }
1503
+ },
1504
+ error$1
1505
+ );
1239
1506
  }
1240
1507
  }
1241
1508
  async insert({ tableName, record }) {
@@ -1247,9 +1514,18 @@ var PostgresStore = class extends storage.MastraStorage {
1247
1514
  `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${placeholders})`,
1248
1515
  values
1249
1516
  );
1250
- } catch (error) {
1251
- console.error(`Error inserting into ${tableName}:`, error);
1252
- throw error;
1517
+ } catch (error$1) {
1518
+ throw new error.MastraError(
1519
+ {
1520
+ id: "MASTRA_STORAGE_PG_STORE_INSERT_FAILED",
1521
+ domain: error.ErrorDomain.STORAGE,
1522
+ category: error.ErrorCategory.THIRD_PARTY,
1523
+ details: {
1524
+ tableName
1525
+ }
1526
+ },
1527
+ error$1
1528
+ );
1253
1529
  }
1254
1530
  }
1255
1531
  async load({ tableName, keys }) {
@@ -1272,9 +1548,18 @@ var PostgresStore = class extends storage.MastraStorage {
1272
1548
  return snapshot;
1273
1549
  }
1274
1550
  return result;
1275
- } catch (error) {
1276
- console.error(`Error loading from ${tableName}:`, error);
1277
- throw error;
1551
+ } catch (error$1) {
1552
+ throw new error.MastraError(
1553
+ {
1554
+ id: "MASTRA_STORAGE_PG_STORE_LOAD_FAILED",
1555
+ domain: error.ErrorDomain.STORAGE,
1556
+ category: error.ErrorCategory.THIRD_PARTY,
1557
+ details: {
1558
+ tableName
1559
+ }
1560
+ },
1561
+ error$1
1562
+ );
1278
1563
  }
1279
1564
  }
1280
1565
  async getThreadById({ threadId }) {
@@ -1300,9 +1585,18 @@ var PostgresStore = class extends storage.MastraStorage {
1300
1585
  createdAt: thread.createdAt,
1301
1586
  updatedAt: thread.updatedAt
1302
1587
  };
1303
- } catch (error) {
1304
- console.error(`Error getting thread ${threadId}:`, error);
1305
- throw error;
1588
+ } catch (error$1) {
1589
+ throw new error.MastraError(
1590
+ {
1591
+ id: "MASTRA_STORAGE_PG_STORE_GET_THREAD_BY_ID_FAILED",
1592
+ domain: error.ErrorDomain.STORAGE,
1593
+ category: error.ErrorCategory.THIRD_PARTY,
1594
+ details: {
1595
+ threadId
1596
+ }
1597
+ },
1598
+ error$1
1599
+ );
1306
1600
  }
1307
1601
  }
1308
1602
  /**
@@ -1361,8 +1655,21 @@ var PostgresStore = class extends storage.MastraStorage {
1361
1655
  perPage,
1362
1656
  hasMore: currentOffset + threads.length < total
1363
1657
  };
1364
- } catch (error) {
1365
- this.logger.error(`Error getting threads for resource ${resourceId}:`, error);
1658
+ } catch (error$1) {
1659
+ const mastraError = new error.MastraError(
1660
+ {
1661
+ id: "MASTRA_STORAGE_PG_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1662
+ domain: error.ErrorDomain.STORAGE,
1663
+ category: error.ErrorCategory.THIRD_PARTY,
1664
+ details: {
1665
+ resourceId,
1666
+ page
1667
+ }
1668
+ },
1669
+ error$1
1670
+ );
1671
+ this.logger?.error?.(mastraError.toString());
1672
+ this.logger?.trackException(mastraError);
1366
1673
  return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
1367
1674
  }
1368
1675
  }
@@ -1393,9 +1700,18 @@ var PostgresStore = class extends storage.MastraStorage {
1393
1700
  ]
1394
1701
  );
1395
1702
  return thread;
1396
- } catch (error) {
1397
- console.error("Error saving thread:", error);
1398
- throw error;
1703
+ } catch (error$1) {
1704
+ throw new error.MastraError(
1705
+ {
1706
+ id: "MASTRA_STORAGE_PG_STORE_SAVE_THREAD_FAILED",
1707
+ domain: error.ErrorDomain.STORAGE,
1708
+ category: error.ErrorCategory.THIRD_PARTY,
1709
+ details: {
1710
+ threadId: thread.id
1711
+ }
1712
+ },
1713
+ error$1
1714
+ );
1399
1715
  }
1400
1716
  }
1401
1717
  async updateThread({
@@ -1403,20 +1719,29 @@ var PostgresStore = class extends storage.MastraStorage {
1403
1719
  title,
1404
1720
  metadata
1405
1721
  }) {
1722
+ const existingThread = await this.getThreadById({ threadId: id });
1723
+ if (!existingThread) {
1724
+ throw new error.MastraError({
1725
+ id: "MASTRA_STORAGE_PG_STORE_UPDATE_THREAD_FAILED",
1726
+ domain: error.ErrorDomain.STORAGE,
1727
+ category: error.ErrorCategory.USER,
1728
+ text: `Thread ${id} not found`,
1729
+ details: {
1730
+ threadId: id,
1731
+ title
1732
+ }
1733
+ });
1734
+ }
1735
+ const mergedMetadata = {
1736
+ ...existingThread.metadata,
1737
+ ...metadata
1738
+ };
1406
1739
  try {
1407
- const existingThread = await this.getThreadById({ threadId: id });
1408
- if (!existingThread) {
1409
- throw new Error(`Thread ${id} not found`);
1410
- }
1411
- const mergedMetadata = {
1412
- ...existingThread.metadata,
1413
- ...metadata
1414
- };
1415
1740
  const thread = await this.db.one(
1416
1741
  `UPDATE ${this.getTableName(storage.TABLE_THREADS)}
1417
1742
  SET title = $1,
1418
- metadata = $2,
1419
- "updatedAt" = $3
1743
+ metadata = $2,
1744
+ "updatedAt" = $3
1420
1745
  WHERE id = $4
1421
1746
  RETURNING *`,
1422
1747
  [title, mergedMetadata, (/* @__PURE__ */ new Date()).toISOString(), id]
@@ -1427,9 +1752,19 @@ var PostgresStore = class extends storage.MastraStorage {
1427
1752
  createdAt: thread.createdAt,
1428
1753
  updatedAt: thread.updatedAt
1429
1754
  };
1430
- } catch (error) {
1431
- console.error("Error updating thread:", error);
1432
- throw error;
1755
+ } catch (error$1) {
1756
+ throw new error.MastraError(
1757
+ {
1758
+ id: "MASTRA_STORAGE_PG_STORE_UPDATE_THREAD_FAILED",
1759
+ domain: error.ErrorDomain.STORAGE,
1760
+ category: error.ErrorCategory.THIRD_PARTY,
1761
+ details: {
1762
+ threadId: id,
1763
+ title
1764
+ }
1765
+ },
1766
+ error$1
1767
+ );
1433
1768
  }
1434
1769
  }
1435
1770
  async deleteThread({ threadId }) {
@@ -1438,27 +1773,35 @@ var PostgresStore = class extends storage.MastraStorage {
1438
1773
  await t.none(`DELETE FROM ${this.getTableName(storage.TABLE_MESSAGES)} WHERE thread_id = $1`, [threadId]);
1439
1774
  await t.none(`DELETE FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE id = $1`, [threadId]);
1440
1775
  });
1441
- } catch (error) {
1442
- console.error("Error deleting thread:", error);
1443
- throw error;
1776
+ } catch (error$1) {
1777
+ throw new error.MastraError(
1778
+ {
1779
+ id: "MASTRA_STORAGE_PG_STORE_DELETE_THREAD_FAILED",
1780
+ domain: error.ErrorDomain.STORAGE,
1781
+ category: error.ErrorCategory.THIRD_PARTY,
1782
+ details: {
1783
+ threadId
1784
+ }
1785
+ },
1786
+ error$1
1787
+ );
1444
1788
  }
1445
1789
  }
1446
- async getMessages(args) {
1447
- const { threadId, format, selectBy } = args;
1448
- const selectStatement = `SELECT id, content, role, type, "createdAt", thread_id AS "threadId"`;
1449
- const orderByStatement = `ORDER BY "createdAt" DESC`;
1450
- try {
1451
- let rows = [];
1452
- const include = selectBy?.include || [];
1453
- if (include.length) {
1454
- const unionQueries = [];
1455
- const params = [];
1456
- let paramIdx = 1;
1457
- for (const inc of include) {
1458
- const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
1459
- const searchId = inc.threadId || threadId;
1460
- unionQueries.push(
1461
- `
1790
+ async _getIncludedMessages({
1791
+ threadId,
1792
+ selectBy,
1793
+ orderByStatement
1794
+ }) {
1795
+ const include = selectBy?.include;
1796
+ if (!include) return null;
1797
+ const unionQueries = [];
1798
+ const params = [];
1799
+ let paramIdx = 1;
1800
+ for (const inc of include) {
1801
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
1802
+ const searchId = inc.threadId || threadId;
1803
+ unionQueries.push(
1804
+ `
1462
1805
  SELECT * FROM (
1463
1806
  WITH ordered_messages AS (
1464
1807
  SELECT
@@ -1490,34 +1833,45 @@ var PostgresStore = class extends storage.MastraStorage {
1490
1833
  )
1491
1834
  ) AS query_${paramIdx}
1492
1835
  `
1493
- // Keep ASC for final sorting after fetching context
1494
- );
1495
- params.push(searchId, id, withPreviousMessages, withNextMessages);
1496
- paramIdx += 4;
1497
- }
1498
- const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" ASC';
1499
- const includedRows = await this.db.manyOrNone(finalQuery, params);
1500
- const seen = /* @__PURE__ */ new Set();
1501
- const dedupedRows = includedRows.filter((row) => {
1502
- if (seen.has(row.id)) return false;
1503
- seen.add(row.id);
1504
- return true;
1505
- });
1506
- rows = dedupedRows;
1507
- } else {
1508
- const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
1509
- if (limit === 0 && selectBy?.last !== false) ; else {
1510
- let query = `${selectStatement} FROM ${this.getTableName(
1511
- storage.TABLE_MESSAGES
1512
- )} WHERE thread_id = $1 ${orderByStatement}`;
1513
- const queryParams = [threadId];
1514
- if (limit !== void 0 && selectBy?.last !== false) {
1515
- query += ` LIMIT $2`;
1516
- queryParams.push(limit);
1517
- }
1518
- rows = await this.db.manyOrNone(query, queryParams);
1836
+ // Keep ASC for final sorting after fetching context
1837
+ );
1838
+ params.push(searchId, id, withPreviousMessages, withNextMessages);
1839
+ paramIdx += 4;
1840
+ }
1841
+ const finalQuery = unionQueries.join(" UNION ALL ") + ' ORDER BY "createdAt" ASC';
1842
+ const includedRows = await this.db.manyOrNone(finalQuery, params);
1843
+ const seen = /* @__PURE__ */ new Set();
1844
+ const dedupedRows = includedRows.filter((row) => {
1845
+ if (seen.has(row.id)) return false;
1846
+ seen.add(row.id);
1847
+ return true;
1848
+ });
1849
+ return dedupedRows;
1850
+ }
1851
+ async getMessages(args) {
1852
+ const { threadId, format, selectBy } = args;
1853
+ const selectStatement = `SELECT id, content, role, type, "createdAt", thread_id AS "threadId"`;
1854
+ const orderByStatement = `ORDER BY "createdAt" DESC`;
1855
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1856
+ try {
1857
+ let rows = [];
1858
+ const include = selectBy?.include || [];
1859
+ if (include?.length) {
1860
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
1861
+ if (includeMessages) {
1862
+ rows.push(...includeMessages);
1519
1863
  }
1520
1864
  }
1865
+ const excludeIds = rows.map((m) => m.id);
1866
+ const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + 2}`).join(", ");
1867
+ let query = `${selectStatement} FROM ${this.getTableName(storage.TABLE_MESSAGES)} WHERE thread_id = $1
1868
+ ${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""}
1869
+ ${orderByStatement}
1870
+ LIMIT $${excludeIds.length + 2}
1871
+ `;
1872
+ const queryParams = [threadId, ...excludeIds, limit];
1873
+ const remainingRows = await this.db.manyOrNone(query, queryParams);
1874
+ rows.push(...remainingRows);
1521
1875
  const fetchedMessages = (rows || []).map((message) => {
1522
1876
  if (typeof message.content === "string") {
1523
1877
  try {
@@ -1534,8 +1888,20 @@ var PostgresStore = class extends storage.MastraStorage {
1534
1888
  return format === "v2" ? sortedMessages.map(
1535
1889
  (m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
1536
1890
  ) : sortedMessages;
1537
- } catch (error) {
1538
- this.logger.error("Error getting messages:", error);
1891
+ } catch (error$1) {
1892
+ const mastraError = new error.MastraError(
1893
+ {
1894
+ id: "MASTRA_STORAGE_PG_STORE_GET_MESSAGES_FAILED",
1895
+ domain: error.ErrorDomain.STORAGE,
1896
+ category: error.ErrorCategory.THIRD_PARTY,
1897
+ details: {
1898
+ threadId
1899
+ }
1900
+ },
1901
+ error$1
1902
+ );
1903
+ this.logger?.error?.(mastraError.toString());
1904
+ this.logger?.trackException(mastraError);
1539
1905
  return [];
1540
1906
  }
1541
1907
  }
@@ -1546,8 +1912,15 @@ var PostgresStore = class extends storage.MastraStorage {
1546
1912
  const toDate = dateRange?.end;
1547
1913
  const selectStatement = `SELECT id, content, role, type, "createdAt", thread_id AS "threadId"`;
1548
1914
  const orderByStatement = `ORDER BY "createdAt" DESC`;
1915
+ const messages = [];
1916
+ if (selectBy?.include?.length) {
1917
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
1918
+ if (includeMessages) {
1919
+ messages.push(...includeMessages);
1920
+ }
1921
+ }
1549
1922
  try {
1550
- const perPage = perPageInput !== void 0 ? perPageInput : 40;
1923
+ const perPage = perPageInput !== void 0 ? perPageInput : this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1551
1924
  const currentOffset = page * perPage;
1552
1925
  const conditions = [`thread_id = $1`];
1553
1926
  const queryParams = [threadId];
@@ -1564,7 +1937,7 @@ var PostgresStore = class extends storage.MastraStorage {
1564
1937
  const countQuery = `SELECT COUNT(*) FROM ${this.getTableName(storage.TABLE_MESSAGES)} ${whereClause}`;
1565
1938
  const countResult = await this.db.one(countQuery, queryParams);
1566
1939
  const total = parseInt(countResult.count, 10);
1567
- if (total === 0) {
1940
+ if (total === 0 && messages.length === 0) {
1568
1941
  return {
1569
1942
  messages: [],
1570
1943
  total: 0,
@@ -1573,11 +1946,15 @@ var PostgresStore = class extends storage.MastraStorage {
1573
1946
  hasMore: false
1574
1947
  };
1575
1948
  }
1949
+ const excludeIds = messages.map((m) => m.id);
1950
+ const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + paramIndex}`).join(", ");
1951
+ paramIndex += excludeIds.length;
1576
1952
  const dataQuery = `${selectStatement} FROM ${this.getTableName(
1577
1953
  storage.TABLE_MESSAGES
1578
- )} ${whereClause} ${orderByStatement} LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
1579
- const rows = await this.db.manyOrNone(dataQuery, [...queryParams, perPage, currentOffset]);
1580
- const list = new agent.MessageList().add(rows || [], "memory");
1954
+ )} ${whereClause} ${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""}${orderByStatement} LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
1955
+ const rows = await this.db.manyOrNone(dataQuery, [...queryParams, ...excludeIds, perPage, currentOffset]);
1956
+ messages.push(...rows || []);
1957
+ const list = new agent.MessageList().add(messages, "memory");
1581
1958
  const messagesToReturn = format === `v2` ? list.get.all.v2() : list.get.all.v1();
1582
1959
  return {
1583
1960
  messages: messagesToReturn,
@@ -1586,8 +1963,21 @@ var PostgresStore = class extends storage.MastraStorage {
1586
1963
  perPage,
1587
1964
  hasMore: currentOffset + rows.length < total
1588
1965
  };
1589
- } catch (error) {
1590
- this.logger.error("Error getting messages:", error);
1966
+ } catch (error$1) {
1967
+ const mastraError = new error.MastraError(
1968
+ {
1969
+ id: "MASTRA_STORAGE_PG_STORE_GET_MESSAGES_PAGINATED_FAILED",
1970
+ domain: error.ErrorDomain.STORAGE,
1971
+ category: error.ErrorCategory.THIRD_PARTY,
1972
+ details: {
1973
+ threadId,
1974
+ page
1975
+ }
1976
+ },
1977
+ error$1
1978
+ );
1979
+ this.logger?.error?.(mastraError.toString());
1980
+ this.logger?.trackException(mastraError);
1591
1981
  return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1592
1982
  }
1593
1983
  }
@@ -1596,15 +1986,28 @@ var PostgresStore = class extends storage.MastraStorage {
1596
1986
  format
1597
1987
  }) {
1598
1988
  if (messages.length === 0) return messages;
1989
+ const threadId = messages[0]?.threadId;
1990
+ if (!threadId) {
1991
+ throw new error.MastraError({
1992
+ id: "MASTRA_STORAGE_PG_STORE_SAVE_MESSAGES_FAILED",
1993
+ domain: error.ErrorDomain.STORAGE,
1994
+ category: error.ErrorCategory.THIRD_PARTY,
1995
+ text: `Thread ID is required`
1996
+ });
1997
+ }
1998
+ const thread = await this.getThreadById({ threadId });
1999
+ if (!thread) {
2000
+ throw new error.MastraError({
2001
+ id: "MASTRA_STORAGE_PG_STORE_SAVE_MESSAGES_FAILED",
2002
+ domain: error.ErrorDomain.STORAGE,
2003
+ category: error.ErrorCategory.THIRD_PARTY,
2004
+ text: `Thread ${threadId} not found`,
2005
+ details: {
2006
+ threadId
2007
+ }
2008
+ });
2009
+ }
1599
2010
  try {
1600
- const threadId = messages[0]?.threadId;
1601
- if (!threadId) {
1602
- throw new Error("Thread ID is required");
1603
- }
1604
- const thread = await this.getThreadById({ threadId });
1605
- if (!thread) {
1606
- throw new Error(`Thread ${threadId} not found`);
1607
- }
1608
2011
  await this.db.tx(async (t) => {
1609
2012
  const messageInserts = messages.map((message) => {
1610
2013
  if (!message.threadId) {
@@ -1619,7 +2022,13 @@ var PostgresStore = class extends storage.MastraStorage {
1619
2022
  }
1620
2023
  return t.none(
1621
2024
  `INSERT INTO ${this.getTableName(storage.TABLE_MESSAGES)} (id, thread_id, content, "createdAt", role, type, "resourceId")
1622
- VALUES ($1, $2, $3, $4, $5, $6, $7)`,
2025
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
2026
+ ON CONFLICT (id) DO UPDATE SET
2027
+ thread_id = EXCLUDED.thread_id,
2028
+ content = EXCLUDED.content,
2029
+ role = EXCLUDED.role,
2030
+ type = EXCLUDED.type,
2031
+ "resourceId" = EXCLUDED."resourceId"`,
1623
2032
  [
1624
2033
  message.id,
1625
2034
  message.threadId,
@@ -1642,9 +2051,18 @@ var PostgresStore = class extends storage.MastraStorage {
1642
2051
  const list = new agent.MessageList().add(messages, "memory");
1643
2052
  if (format === `v2`) return list.get.all.v2();
1644
2053
  return list.get.all.v1();
1645
- } catch (error) {
1646
- console.error("Error saving messages:", error);
1647
- throw error;
2054
+ } catch (error$1) {
2055
+ throw new error.MastraError(
2056
+ {
2057
+ id: "MASTRA_STORAGE_PG_STORE_SAVE_MESSAGES_FAILED",
2058
+ domain: error.ErrorDomain.STORAGE,
2059
+ category: error.ErrorCategory.THIRD_PARTY,
2060
+ details: {
2061
+ threadId
2062
+ }
2063
+ },
2064
+ error$1
2065
+ );
1648
2066
  }
1649
2067
  }
1650
2068
  async persistWorkflowSnapshot({
@@ -1667,9 +2085,19 @@ var PostgresStore = class extends storage.MastraStorage {
1667
2085
  "updatedAt" = EXCLUDED."updatedAt"`,
1668
2086
  [workflowName, runId, JSON.stringify(snapshot), now, now]
1669
2087
  );
1670
- } catch (error) {
1671
- console.error("Error persisting workflow snapshot:", error);
1672
- throw error;
2088
+ } catch (error$1) {
2089
+ throw new error.MastraError(
2090
+ {
2091
+ id: "MASTRA_STORAGE_PG_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2092
+ domain: error.ErrorDomain.STORAGE,
2093
+ category: error.ErrorCategory.THIRD_PARTY,
2094
+ details: {
2095
+ workflowName,
2096
+ runId
2097
+ }
2098
+ },
2099
+ error$1
2100
+ );
1673
2101
  }
1674
2102
  }
1675
2103
  async loadWorkflowSnapshot({
@@ -1688,9 +2116,19 @@ var PostgresStore = class extends storage.MastraStorage {
1688
2116
  return null;
1689
2117
  }
1690
2118
  return result.snapshot;
1691
- } catch (error) {
1692
- console.error("Error loading workflow snapshot:", error);
1693
- throw error;
2119
+ } catch (error$1) {
2120
+ throw new error.MastraError(
2121
+ {
2122
+ id: "MASTRA_STORAGE_PG_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2123
+ domain: error.ErrorDomain.STORAGE,
2124
+ category: error.ErrorCategory.THIRD_PARTY,
2125
+ details: {
2126
+ workflowName,
2127
+ runId
2128
+ }
2129
+ },
2130
+ error$1
2131
+ );
1694
2132
  }
1695
2133
  }
1696
2134
  async hasColumn(table, column) {
@@ -1777,9 +2215,18 @@ var PostgresStore = class extends storage.MastraStorage {
1777
2215
  return this.parseWorkflowRun(row);
1778
2216
  });
1779
2217
  return { runs, total: total || runs.length };
1780
- } catch (error) {
1781
- console.error("Error getting workflow runs:", error);
1782
- throw error;
2218
+ } catch (error$1) {
2219
+ throw new error.MastraError(
2220
+ {
2221
+ id: "MASTRA_STORAGE_PG_STORE_GET_WORKFLOW_RUNS_FAILED",
2222
+ domain: error.ErrorDomain.STORAGE,
2223
+ category: error.ErrorCategory.THIRD_PARTY,
2224
+ details: {
2225
+ workflowName: workflowName || "all"
2226
+ }
2227
+ },
2228
+ error$1
2229
+ );
1783
2230
  }
1784
2231
  }
1785
2232
  async getWorkflowRunById({
@@ -1811,9 +2258,19 @@ var PostgresStore = class extends storage.MastraStorage {
1811
2258
  return null;
1812
2259
  }
1813
2260
  return this.parseWorkflowRun(result);
1814
- } catch (error) {
1815
- console.error("Error getting workflow run by ID:", error);
1816
- throw error;
2261
+ } catch (error$1) {
2262
+ throw new error.MastraError(
2263
+ {
2264
+ id: "MASTRA_STORAGE_PG_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2265
+ domain: error.ErrorDomain.STORAGE,
2266
+ category: error.ErrorCategory.THIRD_PARTY,
2267
+ details: {
2268
+ runId,
2269
+ workflowName: workflowName || ""
2270
+ }
2271
+ },
2272
+ error$1
2273
+ );
1817
2274
  }
1818
2275
  }
1819
2276
  async close() {
@@ -1845,29 +2302,49 @@ var PostgresStore = class extends storage.MastraStorage {
1845
2302
  }
1846
2303
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1847
2304
  const countQuery = `SELECT COUNT(*) FROM ${this.getTableName(storage.TABLE_EVALS)} ${whereClause}`;
1848
- const countResult = await this.db.one(countQuery, queryParams);
1849
- const total = parseInt(countResult.count, 10);
1850
- const currentOffset = page * perPage;
1851
- if (total === 0) {
2305
+ try {
2306
+ const countResult = await this.db.one(countQuery, queryParams);
2307
+ const total = parseInt(countResult.count, 10);
2308
+ const currentOffset = page * perPage;
2309
+ if (total === 0) {
2310
+ return {
2311
+ evals: [],
2312
+ total: 0,
2313
+ page,
2314
+ perPage,
2315
+ hasMore: false
2316
+ };
2317
+ }
2318
+ const dataQuery = `SELECT * FROM ${this.getTableName(
2319
+ storage.TABLE_EVALS
2320
+ )} ${whereClause} ORDER BY created_at DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
2321
+ const rows = await this.db.manyOrNone(dataQuery, [...queryParams, perPage, currentOffset]);
1852
2322
  return {
1853
- evals: [],
1854
- total: 0,
2323
+ evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
2324
+ total,
1855
2325
  page,
1856
2326
  perPage,
1857
- hasMore: false
2327
+ hasMore: currentOffset + (rows?.length ?? 0) < total
1858
2328
  };
2329
+ } catch (error$1) {
2330
+ const mastraError = new error.MastraError(
2331
+ {
2332
+ id: "MASTRA_STORAGE_PG_STORE_GET_EVALS_FAILED",
2333
+ domain: error.ErrorDomain.STORAGE,
2334
+ category: error.ErrorCategory.THIRD_PARTY,
2335
+ details: {
2336
+ agentName: agentName || "all",
2337
+ type: type || "all",
2338
+ page,
2339
+ perPage
2340
+ }
2341
+ },
2342
+ error$1
2343
+ );
2344
+ this.logger?.error?.(mastraError.toString());
2345
+ this.logger?.trackException(mastraError);
2346
+ throw mastraError;
1859
2347
  }
1860
- const dataQuery = `SELECT * FROM ${this.getTableName(
1861
- storage.TABLE_EVALS
1862
- )} ${whereClause} ORDER BY created_at DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`;
1863
- const rows = await this.db.manyOrNone(dataQuery, [...queryParams, perPage, currentOffset]);
1864
- return {
1865
- evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
1866
- total,
1867
- page,
1868
- perPage,
1869
- hasMore: currentOffset + (rows?.length ?? 0) < total
1870
- };
1871
2348
  }
1872
2349
  async updateMessages({
1873
2350
  messages
@@ -1964,6 +2441,82 @@ var PostgresStore = class extends storage.MastraStorage {
1964
2441
  return message;
1965
2442
  });
1966
2443
  }
2444
+ async getResourceById({ resourceId }) {
2445
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
2446
+ const result = await this.db.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [
2447
+ resourceId
2448
+ ]);
2449
+ if (!result) {
2450
+ return null;
2451
+ }
2452
+ return {
2453
+ ...result,
2454
+ // Ensure workingMemory is always returned as a string, regardless of automatic parsing
2455
+ workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
2456
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
2457
+ };
2458
+ }
2459
+ async saveResource({ resource }) {
2460
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
2461
+ await this.db.none(
2462
+ `INSERT INTO ${tableName} (id, "workingMemory", metadata, "createdAt", "updatedAt")
2463
+ VALUES ($1, $2, $3, $4, $5)`,
2464
+ [
2465
+ resource.id,
2466
+ resource.workingMemory,
2467
+ JSON.stringify(resource.metadata),
2468
+ resource.createdAt.toISOString(),
2469
+ resource.updatedAt.toISOString()
2470
+ ]
2471
+ );
2472
+ return resource;
2473
+ }
2474
+ async updateResource({
2475
+ resourceId,
2476
+ workingMemory,
2477
+ metadata
2478
+ }) {
2479
+ const existingResource = await this.getResourceById({ resourceId });
2480
+ if (!existingResource) {
2481
+ const newResource = {
2482
+ id: resourceId,
2483
+ workingMemory,
2484
+ metadata: metadata || {},
2485
+ createdAt: /* @__PURE__ */ new Date(),
2486
+ updatedAt: /* @__PURE__ */ new Date()
2487
+ };
2488
+ return this.saveResource({ resource: newResource });
2489
+ }
2490
+ const updatedResource = {
2491
+ ...existingResource,
2492
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
2493
+ metadata: {
2494
+ ...existingResource.metadata,
2495
+ ...metadata
2496
+ },
2497
+ updatedAt: /* @__PURE__ */ new Date()
2498
+ };
2499
+ const tableName = this.getTableName(storage.TABLE_RESOURCES);
2500
+ const updates = [];
2501
+ const values = [];
2502
+ let paramIndex = 1;
2503
+ if (workingMemory !== void 0) {
2504
+ updates.push(`"workingMemory" = $${paramIndex}`);
2505
+ values.push(workingMemory);
2506
+ paramIndex++;
2507
+ }
2508
+ if (metadata) {
2509
+ updates.push(`metadata = $${paramIndex}`);
2510
+ values.push(JSON.stringify(updatedResource.metadata));
2511
+ paramIndex++;
2512
+ }
2513
+ updates.push(`"updatedAt" = $${paramIndex}`);
2514
+ values.push(updatedResource.updatedAt.toISOString());
2515
+ paramIndex++;
2516
+ values.push(resourceId);
2517
+ await this.db.none(`UPDATE ${tableName} SET ${updates.join(", ")} WHERE id = $${paramIndex}`, values);
2518
+ return updatedResource;
2519
+ }
1967
2520
  };
1968
2521
 
1969
2522
  // src/vector/prompt.ts