@mastra/pg 0.0.0-studio-deploy-20260404182525 → 0.0.0-studio-cli-20260504022012

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.
Files changed (30) hide show
  1. package/CHANGELOG.md +166 -3
  2. package/dist/docs/SKILL.md +1 -1
  3. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  4. package/dist/docs/references/docs-memory-storage.md +1 -2
  5. package/dist/docs/references/docs-memory-working-memory.md +2 -2
  6. package/dist/docs/references/reference-storage-composite.md +5 -3
  7. package/dist/index.cjs +1111 -172
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.js +1110 -174
  10. package/dist/index.js.map +1 -1
  11. package/dist/storage/db/index.d.ts +2 -0
  12. package/dist/storage/db/index.d.ts.map +1 -1
  13. package/dist/storage/domains/background-tasks/index.d.ts +25 -0
  14. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -0
  15. package/dist/storage/domains/channels/index.d.ts +25 -0
  16. package/dist/storage/domains/channels/index.d.ts.map +1 -0
  17. package/dist/storage/domains/experiments/index.d.ts.map +1 -1
  18. package/dist/storage/domains/memory/index.d.ts +13 -2
  19. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  20. package/dist/storage/domains/observability/index.d.ts +2 -1
  21. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  22. package/dist/storage/domains/schedules/index.d.ts +22 -0
  23. package/dist/storage/domains/schedules/index.d.ts.map +1 -0
  24. package/dist/storage/domains/workflows/index.d.ts +10 -0
  25. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  26. package/dist/storage/index.d.ts +4 -1
  27. package/dist/storage/index.d.ts.map +1 -1
  28. package/dist/vector/index.d.ts +8 -0
  29. package/dist/vector/index.d.ts.map +1 -1
  30. package/package.json +11 -11
package/dist/index.cjs CHANGED
@@ -734,6 +734,25 @@ var PgVector = class extends vector.MastraVector {
734
734
  return null;
735
735
  }
736
736
  }
737
+ /**
738
+ * Sets search_path on the client connection so that vector operators (e.g. <=>, vector_cosine_ops)
739
+ * are resolvable when the pgvector extension is installed in a non-default schema.
740
+ *
741
+ * PostgreSQL's default search_path is ("$user", public). If the extension lives in a custom schema
742
+ * (e.g. "myapp"), operator classes and distance operators won't resolve without this.
743
+ */
744
+ async ensureSearchPath(client) {
745
+ if (!this.vectorExtensionSchema) {
746
+ await this.detectVectorExtensionSchema(client);
747
+ }
748
+ if (this.vectorExtensionSchema && this.vectorExtensionSchema !== "public" && this.vectorExtensionSchema !== "pg_catalog") {
749
+ const schemas = /* @__PURE__ */ new Set();
750
+ schemas.add(this.vectorExtensionSchema);
751
+ if (this.schema) schemas.add(this.schema);
752
+ schemas.add("public");
753
+ await client.query(`SET search_path TO ${[...schemas].map((s) => `"${s}"`).join(", ")}`);
754
+ }
755
+ }
737
756
  /**
738
757
  * Checks if the installed pgvector version supports halfvec type.
739
758
  * halfvec was introduced in pgvector 0.7.0.
@@ -947,6 +966,7 @@ var PgVector = class extends vector.MastraVector {
947
966
  }
948
967
  const client = await this.pool.connect();
949
968
  try {
969
+ await this.ensureSearchPath(client);
950
970
  await client.query("BEGIN");
951
971
  const translatedFilter = this.transformFilter(filter);
952
972
  const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter, minScore, topK);
@@ -966,7 +986,23 @@ var PgVector = class extends vector.MastraVector {
966
986
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
967
987
  const distanceExpr = `embedding ${ops.distanceOperator} '${vectorStr}'::${qualifiedVectorType}`;
968
988
  const scoreExpr = ops.scoreExpr(distanceExpr);
969
- const query = `
989
+ const hasFilter = filterQuery.trim().length > 0;
990
+ const useIndexedOrder = indexInfo.type === "hnsw" && !hasFilter && minScore <= 0;
991
+ const query = useIndexedOrder ? `
992
+ WITH vector_scores AS (
993
+ SELECT
994
+ vector_id as id,
995
+ ${scoreExpr} as score,
996
+ metadata
997
+ ${includeVector ? ", embedding" : ""}
998
+ FROM ${tableName}
999
+ ORDER BY ${distanceExpr}
1000
+ LIMIT $2
1001
+ )
1002
+ SELECT *
1003
+ FROM vector_scores
1004
+ WHERE score > $1
1005
+ ORDER BY score DESC` : `
970
1006
  WITH vector_scores AS (
971
1007
  SELECT
972
1008
  vector_id as id,
@@ -1019,6 +1055,7 @@ var PgVector = class extends vector.MastraVector {
1019
1055
  const { tableName } = this.getTableName(indexName);
1020
1056
  const client = await this.pool.connect();
1021
1057
  try {
1058
+ await this.ensureSearchPath(client);
1022
1059
  await client.query("BEGIN");
1023
1060
  if (deleteFilter) {
1024
1061
  this.logger?.debug(`Deleting vectors matching filter before upsert`, { indexName, deleteFilter });
@@ -1269,9 +1306,6 @@ var PgVector = class extends vector.MastraVector {
1269
1306
  }
1270
1307
  });
1271
1308
  }
1272
- if (this.schema && this.vectorExtensionSchema && this.schema !== this.vectorExtensionSchema && this.vectorExtensionSchema !== "pg_catalog") {
1273
- await client.query(`SET search_path TO ${this.getSchemaName()}, "${this.vectorExtensionSchema}"`);
1274
- }
1275
1309
  const qualifiedVectorType = this.getVectorTypeName(vectorType);
1276
1310
  await client.query(`
1277
1311
  CREATE TABLE IF NOT EXISTS ${tableName} (
@@ -1414,6 +1448,7 @@ var PgVector = class extends vector.MastraVector {
1414
1448
  this.describeIndexCache.delete(indexName);
1415
1449
  return;
1416
1450
  }
1451
+ await this.ensureSearchPath(client);
1417
1452
  const effectiveVectorType = existingIndexInfo?.vectorType ?? vectorType;
1418
1453
  const metricOp = this.getVectorOps(effectiveVectorType, metric).operatorClass;
1419
1454
  let indexSQL;
@@ -1764,6 +1799,7 @@ var PgVector = class extends vector.MastraVector {
1764
1799
  });
1765
1800
  }
1766
1801
  client = await this.pool.connect();
1802
+ await this.ensureSearchPath(client);
1767
1803
  const { tableName } = this.getTableName(indexName);
1768
1804
  const indexInfo = await this.getIndexInfo({ indexName });
1769
1805
  const qualifiedVectorType = this.getVectorTypeName(indexInfo.vectorType, indexInfo.dimension);
@@ -2002,6 +2038,7 @@ var PoolAdapter = class {
2002
2038
  constructor($pool) {
2003
2039
  this.$pool = $pool;
2004
2040
  }
2041
+ $pool;
2005
2042
  connect() {
2006
2043
  return this.$pool.connect();
2007
2044
  }
@@ -2070,6 +2107,7 @@ var TransactionClient = class {
2070
2107
  constructor(client) {
2071
2108
  this.client = client;
2072
2109
  }
2110
+ client;
2073
2111
  async none(query, values) {
2074
2112
  await this.client.query(query, values);
2075
2113
  return null;
@@ -2499,36 +2537,39 @@ var PgDB = class extends base.MastraBase {
2499
2537
  return storage.getDefaultValue(type);
2500
2538
  }
2501
2539
  }
2502
- async insert({ tableName, record }) {
2503
- try {
2504
- this.addTimestampZColumns(record);
2505
- const filteredRecord = await this.filterRecordToKnownColumns(tableName, record);
2506
- const schemaName = getSchemaName(this.schemaName);
2507
- const columns = Object.keys(filteredRecord).map((col) => utils.parseSqlIdentifier(col, "column name"));
2508
- if (columns.length === 0) return;
2509
- const values = this.prepareValuesForInsert(filteredRecord, tableName);
2510
- const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
2511
- const fullTableName = getTableName({ indexName: tableName, schemaName });
2512
- const columnList = columns.map((c) => `"${c}"`).join(", ");
2513
- if (tableName === storage.TABLE_SPANS) {
2514
- const updateColumns = columns.filter((c) => c !== "traceId" && c !== "spanId");
2515
- if (updateColumns.length > 0) {
2516
- const updateClause = updateColumns.map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ");
2517
- await this.client.none(
2518
- `INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})
2540
+ async executeInsert(client, { tableName, record }) {
2541
+ this.addTimestampZColumns(record);
2542
+ const filteredRecord = await this.filterRecordToKnownColumns(tableName, record);
2543
+ const schemaName = getSchemaName(this.schemaName);
2544
+ const columns = Object.keys(filteredRecord).map((col) => utils.parseSqlIdentifier(col, "column name"));
2545
+ if (columns.length === 0) return;
2546
+ const values = this.prepareValuesForInsert(filteredRecord, tableName);
2547
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
2548
+ const fullTableName = getTableName({ indexName: tableName, schemaName });
2549
+ const columnList = columns.map((c) => `"${c}"`).join(", ");
2550
+ if (tableName === storage.TABLE_SPANS) {
2551
+ const updateColumns = columns.filter((c) => c !== "traceId" && c !== "spanId");
2552
+ if (updateColumns.length > 0) {
2553
+ const updateClause = updateColumns.map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ");
2554
+ await client.none(
2555
+ `INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})
2519
2556
  ON CONFLICT ("traceId", "spanId") DO UPDATE SET ${updateClause}`,
2520
- values
2521
- );
2522
- } else {
2523
- await this.client.none(
2524
- `INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})
2525
- ON CONFLICT ("traceId", "spanId") DO NOTHING`,
2526
- values
2527
- );
2528
- }
2557
+ values
2558
+ );
2529
2559
  } else {
2530
- await this.client.none(`INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})`, values);
2560
+ await client.none(
2561
+ `INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})
2562
+ ON CONFLICT ("traceId", "spanId") DO NOTHING`,
2563
+ values
2564
+ );
2531
2565
  }
2566
+ } else {
2567
+ await client.none(`INSERT INTO ${fullTableName} (${columnList}) VALUES (${placeholders})`, values);
2568
+ }
2569
+ }
2570
+ async insert({ tableName, record }) {
2571
+ try {
2572
+ await this.executeInsert(this.client, { tableName, record });
2532
2573
  } catch (error$1) {
2533
2574
  throw new error.MastraError(
2534
2575
  {
@@ -3003,13 +3044,12 @@ Note: This migration may take some time for large tables.
3003
3044
  }
3004
3045
  async batchInsert({ tableName, records }) {
3005
3046
  try {
3006
- await this.client.query("BEGIN");
3007
- for (const record of records) {
3008
- await this.insert({ tableName, record });
3009
- }
3010
- await this.client.query("COMMIT");
3047
+ await this.client.tx(async (tx) => {
3048
+ for (const record of records) {
3049
+ await this.executeInsert(tx, { tableName, record });
3050
+ }
3051
+ });
3011
3052
  } catch (error$1) {
3012
- await this.client.query("ROLLBACK");
3013
3053
  throw new error.MastraError(
3014
3054
  {
3015
3055
  id: storage.createStorageErrorId("PG", "BATCH_INSERT", "FAILED"),
@@ -3287,30 +3327,7 @@ Note: This migration may take some time for large tables.
3287
3327
  data
3288
3328
  }) {
3289
3329
  try {
3290
- const filteredData = await this.filterRecordToKnownColumns(tableName, data);
3291
- if (Object.keys(filteredData).length === 0) return;
3292
- const setColumns = [];
3293
- const setValues = [];
3294
- let paramIndex = 1;
3295
- Object.entries(filteredData).forEach(([key, value]) => {
3296
- const parsedKey = utils.parseSqlIdentifier(key, "column name");
3297
- setColumns.push(`"${parsedKey}" = $${paramIndex++}`);
3298
- setValues.push(this.prepareValue(value, key, tableName));
3299
- });
3300
- const whereConditions = [];
3301
- const whereValues = [];
3302
- Object.entries(keys).forEach(([key, value]) => {
3303
- const parsedKey = utils.parseSqlIdentifier(key, "column name");
3304
- whereConditions.push(`"${parsedKey}" = $${paramIndex++}`);
3305
- whereValues.push(this.prepareValue(value, key, tableName));
3306
- });
3307
- const tableName_ = getTableName({
3308
- indexName: tableName,
3309
- schemaName: getSchemaName(this.schemaName)
3310
- });
3311
- const sql = `UPDATE ${tableName_} SET ${setColumns.join(", ")} WHERE ${whereConditions.join(" AND ")}`;
3312
- const values = [...setValues, ...whereValues];
3313
- await this.client.none(sql, values);
3330
+ await this.executeUpdate(this.client, { tableName, keys, data });
3314
3331
  } catch (error$1) {
3315
3332
  throw new error.MastraError(
3316
3333
  {
@@ -3330,13 +3347,12 @@ Note: This migration may take some time for large tables.
3330
3347
  updates
3331
3348
  }) {
3332
3349
  try {
3333
- await this.client.query("BEGIN");
3334
- for (const { keys, data } of updates) {
3335
- await this.update({ tableName, keys, data });
3336
- }
3337
- await this.client.query("COMMIT");
3350
+ await this.client.tx(async (tx) => {
3351
+ for (const { keys, data } of updates) {
3352
+ await this.executeUpdate(tx, { tableName, keys, data });
3353
+ }
3354
+ });
3338
3355
  } catch (error$1) {
3339
- await this.client.query("ROLLBACK");
3340
3356
  throw new error.MastraError(
3341
3357
  {
3342
3358
  id: storage.createStorageErrorId("PG", "BATCH_UPDATE", "FAILED"),
@@ -3395,6 +3411,36 @@ Note: This migration may take some time for large tables.
3395
3411
  async deleteData({ tableName }) {
3396
3412
  return this.clearTable({ tableName });
3397
3413
  }
3414
+ async executeUpdate(client, {
3415
+ tableName,
3416
+ keys,
3417
+ data
3418
+ }) {
3419
+ const filteredData = await this.filterRecordToKnownColumns(tableName, data);
3420
+ if (Object.keys(filteredData).length === 0) return;
3421
+ const setColumns = [];
3422
+ const setValues = [];
3423
+ let paramIndex = 1;
3424
+ Object.entries(filteredData).forEach(([key, value]) => {
3425
+ const parsedKey = utils.parseSqlIdentifier(key, "column name");
3426
+ setColumns.push(`"${parsedKey}" = $${paramIndex++}`);
3427
+ setValues.push(this.prepareValue(value, key, tableName));
3428
+ });
3429
+ const whereConditions = [];
3430
+ const whereValues = [];
3431
+ Object.entries(keys).forEach(([key, value]) => {
3432
+ const parsedKey = utils.parseSqlIdentifier(key, "column name");
3433
+ whereConditions.push(`"${parsedKey}" = $${paramIndex++}`);
3434
+ whereValues.push(this.prepareValue(value, key, tableName));
3435
+ });
3436
+ const tableName_ = getTableName({
3437
+ indexName: tableName,
3438
+ schemaName: getSchemaName(this.schemaName)
3439
+ });
3440
+ const sql = `UPDATE ${tableName_} SET ${setColumns.join(", ")} WHERE ${whereConditions.join(" AND ")}`;
3441
+ const values = [...setValues, ...whereValues];
3442
+ await client.none(sql, values);
3443
+ }
3398
3444
  };
3399
3445
  function getSchemaName2(schema) {
3400
3446
  return schema ? `"${utils.parseSqlIdentifier(schema, "schema name")}"` : void 0;
@@ -4234,6 +4280,307 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
4234
4280
  };
4235
4281
  }
4236
4282
  };
4283
+ function getSchemaName3(schema) {
4284
+ return schema ? `"${schema}"` : '"public"';
4285
+ }
4286
+ function getTableName3(schemaName) {
4287
+ const quoted = `"${storage.TABLE_BACKGROUND_TASKS}"`;
4288
+ return schemaName ? `${schemaName}.${quoted}` : quoted;
4289
+ }
4290
+ function serializeJson(v) {
4291
+ if (typeof v === "object" && v != null) return JSON.stringify(v);
4292
+ return v ?? null;
4293
+ }
4294
+ function parseJson(v) {
4295
+ if (typeof v === "string") {
4296
+ try {
4297
+ return JSON.parse(v);
4298
+ } catch {
4299
+ return v;
4300
+ }
4301
+ }
4302
+ return v ?? void 0;
4303
+ }
4304
+ function rowToTask(row) {
4305
+ return {
4306
+ id: row.id,
4307
+ status: row.status,
4308
+ toolName: row.tool_name,
4309
+ toolCallId: row.tool_call_id,
4310
+ args: parseJson(row.args),
4311
+ agentId: row.agent_id,
4312
+ threadId: row.thread_id ?? void 0,
4313
+ resourceId: row.resource_id ?? void 0,
4314
+ runId: row.run_id,
4315
+ result: parseJson(row.result),
4316
+ error: parseJson(row.error),
4317
+ retryCount: Number(row.retry_count),
4318
+ maxRetries: Number(row.max_retries),
4319
+ timeoutMs: Number(row.timeout_ms),
4320
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt),
4321
+ startedAt: row.startedAt ? row.startedAt instanceof Date ? row.startedAt : new Date(row.startedAt) : void 0,
4322
+ completedAt: row.completedAt ? row.completedAt instanceof Date ? row.completedAt : new Date(row.completedAt) : void 0
4323
+ };
4324
+ }
4325
+ var BackgroundTasksPG = class _BackgroundTasksPG extends storage.BackgroundTasksStorage {
4326
+ #db;
4327
+ #schema;
4328
+ #skipDefaultIndexes;
4329
+ #indexes;
4330
+ static MANAGED_TABLES = [storage.TABLE_BACKGROUND_TASKS];
4331
+ constructor(config) {
4332
+ super();
4333
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4334
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
4335
+ this.#schema = schemaName || "public";
4336
+ this.#skipDefaultIndexes = skipDefaultIndexes;
4337
+ this.#indexes = indexes?.filter((idx) => _BackgroundTasksPG.MANAGED_TABLES.includes(idx.table));
4338
+ }
4339
+ async init() {
4340
+ await this.#db.createTable({
4341
+ tableName: storage.TABLE_BACKGROUND_TASKS,
4342
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_BACKGROUND_TASKS]
4343
+ });
4344
+ await this.createDefaultIndexes();
4345
+ await this.createCustomIndexes();
4346
+ }
4347
+ static getDefaultIndexDefs(schemaPrefix) {
4348
+ return [
4349
+ {
4350
+ name: `${schemaPrefix}mastra_bg_tasks_status_created_at_idx`,
4351
+ table: storage.TABLE_BACKGROUND_TASKS,
4352
+ columns: ["status", "createdAt"]
4353
+ },
4354
+ {
4355
+ name: `${schemaPrefix}mastra_bg_tasks_agent_status_idx`,
4356
+ table: storage.TABLE_BACKGROUND_TASKS,
4357
+ columns: ["agent_id", "status"]
4358
+ },
4359
+ {
4360
+ name: `${schemaPrefix}mastra_bg_tasks_thread_idx`,
4361
+ table: storage.TABLE_BACKGROUND_TASKS,
4362
+ columns: ["thread_id", "createdAt"]
4363
+ },
4364
+ {
4365
+ name: `${schemaPrefix}mastra_bg_tasks_tool_call_idx`,
4366
+ table: storage.TABLE_BACKGROUND_TASKS,
4367
+ columns: ["tool_call_id"]
4368
+ }
4369
+ ];
4370
+ }
4371
+ static getExportDDL(schemaName) {
4372
+ const statements = [];
4373
+ const parsedSchema = schemaName ? utils.parseSqlIdentifier(schemaName, "schema name") : "";
4374
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
4375
+ statements.push(
4376
+ generateTableSQL({
4377
+ tableName: storage.TABLE_BACKGROUND_TASKS,
4378
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_BACKGROUND_TASKS],
4379
+ schemaName,
4380
+ includeAllConstraints: true
4381
+ })
4382
+ );
4383
+ for (const idx of _BackgroundTasksPG.getDefaultIndexDefs(schemaPrefix)) {
4384
+ statements.push(generateIndexSQL(idx, schemaName));
4385
+ }
4386
+ return statements;
4387
+ }
4388
+ getDefaultIndexDefinitions() {
4389
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
4390
+ return _BackgroundTasksPG.getDefaultIndexDefs(schemaPrefix);
4391
+ }
4392
+ async createDefaultIndexes() {
4393
+ if (this.#skipDefaultIndexes) return;
4394
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
4395
+ try {
4396
+ await this.#db.createIndex(indexDef);
4397
+ } catch (error) {
4398
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
4399
+ }
4400
+ }
4401
+ }
4402
+ async createCustomIndexes() {
4403
+ if (!this.#indexes || this.#indexes.length === 0) return;
4404
+ for (const indexDef of this.#indexes) {
4405
+ try {
4406
+ await this.#db.createIndex(indexDef);
4407
+ } catch (error) {
4408
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
4409
+ }
4410
+ }
4411
+ }
4412
+ async dangerouslyClearAll() {
4413
+ await this.#db.clearTable({ tableName: storage.TABLE_BACKGROUND_TASKS });
4414
+ }
4415
+ async createTask(task) {
4416
+ await this.#db.insert({
4417
+ tableName: storage.TABLE_BACKGROUND_TASKS,
4418
+ record: {
4419
+ id: task.id,
4420
+ tool_call_id: task.toolCallId,
4421
+ tool_name: task.toolName,
4422
+ agent_id: task.agentId,
4423
+ thread_id: task.threadId ?? null,
4424
+ resource_id: task.resourceId ?? null,
4425
+ run_id: task.runId,
4426
+ status: task.status,
4427
+ args: serializeJson(task.args),
4428
+ result: serializeJson(task.result),
4429
+ error: serializeJson(task.error),
4430
+ retry_count: task.retryCount,
4431
+ max_retries: task.maxRetries,
4432
+ timeout_ms: task.timeoutMs,
4433
+ createdAt: task.createdAt.toISOString(),
4434
+ startedAt: task.startedAt?.toISOString() ?? null,
4435
+ completedAt: task.completedAt?.toISOString() ?? null
4436
+ }
4437
+ });
4438
+ }
4439
+ async updateTask(taskId, update) {
4440
+ const setClauses = [];
4441
+ const params = [];
4442
+ let paramIdx = 1;
4443
+ if ("status" in update) {
4444
+ setClauses.push(`"status" = $${paramIdx++}`);
4445
+ params.push(update.status);
4446
+ }
4447
+ if ("result" in update) {
4448
+ setClauses.push(`"result" = $${paramIdx++}`);
4449
+ params.push(serializeJson(update.result));
4450
+ }
4451
+ if ("error" in update) {
4452
+ setClauses.push(`"error" = $${paramIdx++}`);
4453
+ params.push(serializeJson(update.error));
4454
+ }
4455
+ if ("retryCount" in update) {
4456
+ setClauses.push(`"retry_count" = $${paramIdx++}`);
4457
+ params.push(update.retryCount);
4458
+ }
4459
+ if ("startedAt" in update) {
4460
+ setClauses.push(`"startedAt" = $${paramIdx++}`);
4461
+ params.push(update.startedAt?.toISOString() ?? null);
4462
+ }
4463
+ if ("completedAt" in update) {
4464
+ setClauses.push(`"completedAt" = $${paramIdx++}`);
4465
+ params.push(update.completedAt?.toISOString() ?? null);
4466
+ }
4467
+ if (setClauses.length === 0) return;
4468
+ const table = getTableName3(getSchemaName3(this.#schema));
4469
+ params.push(taskId);
4470
+ await this.#db.client.none(`UPDATE ${table} SET ${setClauses.join(", ")} WHERE "id" = $${paramIdx}`, params);
4471
+ }
4472
+ async getTask(taskId) {
4473
+ const table = getTableName3(getSchemaName3(this.#schema));
4474
+ const row = await this.#db.client.oneOrNone(`SELECT * FROM ${table} WHERE "id" = $1`, [taskId]);
4475
+ return row ? rowToTask(row) : null;
4476
+ }
4477
+ async listTasks(filter) {
4478
+ const table = getTableName3(getSchemaName3(this.#schema));
4479
+ const conditions = [];
4480
+ const params = [];
4481
+ let paramIdx = 1;
4482
+ if (filter.status) {
4483
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
4484
+ const placeholders = statuses.map(() => `$${paramIdx++}`);
4485
+ conditions.push(`"status" IN (${placeholders.join(", ")})`);
4486
+ params.push(...statuses);
4487
+ }
4488
+ if (filter.agentId) {
4489
+ conditions.push(`"agent_id" = $${paramIdx++}`);
4490
+ params.push(filter.agentId);
4491
+ }
4492
+ if (filter.threadId) {
4493
+ conditions.push(`"thread_id" = $${paramIdx++}`);
4494
+ params.push(filter.threadId);
4495
+ }
4496
+ if (filter.resourceId) {
4497
+ conditions.push(`"resource_id" = $${paramIdx++}`);
4498
+ params.push(filter.resourceId);
4499
+ }
4500
+ if (filter.runId) {
4501
+ conditions.push(`"run_id" = $${paramIdx++}`);
4502
+ params.push(filter.runId);
4503
+ }
4504
+ if (filter.toolName) {
4505
+ conditions.push(`"tool_name" = $${paramIdx++}`);
4506
+ params.push(filter.toolName);
4507
+ }
4508
+ const dateCol = filter.dateFilterBy === "startedAt" ? '"startedAt"' : filter.dateFilterBy === "completedAt" ? '"completedAt"' : '"createdAt"';
4509
+ if (filter.fromDate) {
4510
+ conditions.push(`${dateCol} >= $${paramIdx++}`);
4511
+ params.push(filter.fromDate.toISOString());
4512
+ }
4513
+ if (filter.toDate) {
4514
+ conditions.push(`${dateCol} < $${paramIdx++}`);
4515
+ params.push(filter.toDate.toISOString());
4516
+ }
4517
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4518
+ const countResult = await this.#db.client.oneOrNone(
4519
+ `SELECT COUNT(*) as count FROM ${table} ${where}`,
4520
+ params.slice(0, paramIdx - 1)
4521
+ );
4522
+ const total = Number(countResult?.count ?? 0);
4523
+ const orderCol = filter.orderBy === "startedAt" ? '"startedAt"' : filter.orderBy === "completedAt" ? '"completedAt"' : '"createdAt"';
4524
+ const direction = filter.orderDirection === "desc" ? "DESC" : "ASC";
4525
+ let sql = `SELECT * FROM ${table} ${where} ORDER BY ${orderCol} ${direction}`;
4526
+ if (filter.perPage != null) {
4527
+ sql += ` LIMIT $${paramIdx++}`;
4528
+ params.push(filter.perPage);
4529
+ if (filter.page != null) {
4530
+ sql += ` OFFSET $${paramIdx++}`;
4531
+ params.push(filter.page * filter.perPage);
4532
+ }
4533
+ }
4534
+ const rows = await this.#db.client.manyOrNone(sql, params);
4535
+ return { tasks: rows.map(rowToTask), total };
4536
+ }
4537
+ async deleteTask(taskId) {
4538
+ const table = getTableName3(getSchemaName3(this.#schema));
4539
+ await this.#db.client.none(`DELETE FROM ${table} WHERE "id" = $1`, [taskId]);
4540
+ }
4541
+ async deleteTasks(filter) {
4542
+ const table = getTableName3(getSchemaName3(this.#schema));
4543
+ const conditions = [];
4544
+ const params = [];
4545
+ let paramIdx = 1;
4546
+ if (filter.status) {
4547
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
4548
+ const placeholders = statuses.map(() => `$${paramIdx++}`);
4549
+ conditions.push(`"status" IN (${placeholders.join(", ")})`);
4550
+ params.push(...statuses);
4551
+ }
4552
+ const dateCol = filter.dateFilterBy === "startedAt" ? '"startedAt"' : filter.dateFilterBy === "completedAt" ? '"completedAt"' : '"createdAt"';
4553
+ if (filter.fromDate) {
4554
+ conditions.push(`${dateCol} >= $${paramIdx++}`);
4555
+ params.push(filter.fromDate.toISOString());
4556
+ }
4557
+ if (filter.toDate) {
4558
+ conditions.push(`${dateCol} < $${paramIdx++}`);
4559
+ params.push(filter.toDate.toISOString());
4560
+ }
4561
+ if (filter.agentId) {
4562
+ conditions.push(`"agent_id" = $${paramIdx++}`);
4563
+ params.push(filter.agentId);
4564
+ }
4565
+ if (conditions.length === 0) return;
4566
+ await this.#db.client.none(`DELETE FROM ${table} WHERE ${conditions.join(" AND ")}`, params);
4567
+ }
4568
+ async getRunningCount() {
4569
+ const table = getTableName3(getSchemaName3(this.#schema));
4570
+ const result = await this.#db.client.oneOrNone(
4571
+ `SELECT COUNT(*) FROM ${table} WHERE "status" = 'running'`
4572
+ );
4573
+ return Number(result?.count ?? 0);
4574
+ }
4575
+ async getRunningCountByAgent(agentId) {
4576
+ const table = getTableName3(getSchemaName3(this.#schema));
4577
+ const result = await this.#db.client.oneOrNone(
4578
+ `SELECT COUNT(*) FROM ${table} WHERE "status" = 'running' AND "agent_id" = $1`,
4579
+ [agentId]
4580
+ );
4581
+ return Number(result?.count ?? 0);
4582
+ }
4583
+ };
4237
4584
  var BlobsPG = class extends storage.BlobStore {
4238
4585
  #db;
4239
4586
  #schema;
@@ -4311,6 +4658,202 @@ var BlobsPG = class extends storage.BlobStore {
4311
4658
  };
4312
4659
  }
4313
4660
  };
4661
+ var ChannelsPG = class _ChannelsPG extends storage.ChannelsStorage {
4662
+ #db;
4663
+ #schema;
4664
+ #skipDefaultIndexes;
4665
+ #indexes;
4666
+ static MANAGED_TABLES = [storage.TABLE_CHANNEL_INSTALLATIONS, storage.TABLE_CHANNEL_CONFIG];
4667
+ constructor(config) {
4668
+ super();
4669
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
4670
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
4671
+ this.#schema = schemaName || "public";
4672
+ this.#skipDefaultIndexes = skipDefaultIndexes;
4673
+ this.#indexes = indexes?.filter((idx) => _ChannelsPG.MANAGED_TABLES.includes(idx.table));
4674
+ }
4675
+ async init() {
4676
+ await this.#db.createTable({
4677
+ tableName: storage.TABLE_CHANNEL_INSTALLATIONS,
4678
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_CHANNEL_INSTALLATIONS]
4679
+ });
4680
+ await this.#db.createTable({
4681
+ tableName: storage.TABLE_CHANNEL_CONFIG,
4682
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_CHANNEL_CONFIG]
4683
+ });
4684
+ await this.createDefaultIndexes();
4685
+ await this.createCustomIndexes();
4686
+ }
4687
+ static getDefaultIndexDefs(schemaPrefix) {
4688
+ return [
4689
+ {
4690
+ name: `${schemaPrefix}idx_channel_installations_webhook`,
4691
+ table: storage.TABLE_CHANNEL_INSTALLATIONS,
4692
+ columns: ["webhookId"],
4693
+ unique: true
4694
+ },
4695
+ {
4696
+ name: `${schemaPrefix}idx_channel_installations_platform_agent`,
4697
+ table: storage.TABLE_CHANNEL_INSTALLATIONS,
4698
+ columns: ["platform", "agentId"]
4699
+ }
4700
+ ];
4701
+ }
4702
+ static getExportDDL(schemaName) {
4703
+ const statements = [];
4704
+ const parsedSchema = schemaName ? utils.parseSqlIdentifier(schemaName, "schema name") : "";
4705
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
4706
+ for (const tableName of _ChannelsPG.MANAGED_TABLES) {
4707
+ statements.push(
4708
+ generateTableSQL({
4709
+ tableName,
4710
+ schema: storage.TABLE_SCHEMAS[tableName],
4711
+ schemaName,
4712
+ includeAllConstraints: true
4713
+ })
4714
+ );
4715
+ }
4716
+ for (const idx of _ChannelsPG.getDefaultIndexDefs(schemaPrefix)) {
4717
+ statements.push(generateIndexSQL(idx, schemaName));
4718
+ }
4719
+ return statements;
4720
+ }
4721
+ getDefaultIndexDefinitions() {
4722
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
4723
+ return _ChannelsPG.getDefaultIndexDefs(schemaPrefix);
4724
+ }
4725
+ async createDefaultIndexes() {
4726
+ if (this.#skipDefaultIndexes) return;
4727
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
4728
+ try {
4729
+ await this.#db.createIndex(indexDef);
4730
+ } catch (error) {
4731
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
4732
+ }
4733
+ }
4734
+ }
4735
+ async createCustomIndexes() {
4736
+ if (!this.#indexes || this.#indexes.length === 0) return;
4737
+ for (const indexDef of this.#indexes) {
4738
+ try {
4739
+ await this.#db.createIndex(indexDef);
4740
+ } catch (error) {
4741
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
4742
+ }
4743
+ }
4744
+ }
4745
+ async dangerouslyClearAll() {
4746
+ await this.#db.clearTable({ tableName: storage.TABLE_CHANNEL_INSTALLATIONS });
4747
+ await this.#db.clearTable({ tableName: storage.TABLE_CHANNEL_CONFIG });
4748
+ }
4749
+ async saveInstallation(installation) {
4750
+ const schemaName = getSchemaName2(this.#schema);
4751
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4752
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4753
+ await this.#db.client.none(
4754
+ `INSERT INTO ${tableName} ("id", "platform", "agentId", "status", "webhookId", "data", "configHash", "error", "createdAt", "updatedAt")
4755
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10)
4756
+ ON CONFLICT ("id") DO UPDATE SET
4757
+ "platform" = EXCLUDED."platform",
4758
+ "agentId" = EXCLUDED."agentId",
4759
+ "status" = EXCLUDED."status",
4760
+ "webhookId" = EXCLUDED."webhookId",
4761
+ "data" = EXCLUDED."data",
4762
+ "configHash" = EXCLUDED."configHash",
4763
+ "error" = EXCLUDED."error",
4764
+ "updatedAt" = EXCLUDED."updatedAt"`,
4765
+ [
4766
+ installation.id,
4767
+ installation.platform,
4768
+ installation.agentId,
4769
+ installation.status,
4770
+ installation.webhookId ?? null,
4771
+ JSON.stringify(installation.data),
4772
+ installation.configHash ?? null,
4773
+ installation.error ?? null,
4774
+ installation.createdAt?.toISOString() ?? now,
4775
+ now
4776
+ ]
4777
+ );
4778
+ }
4779
+ async getInstallation(id) {
4780
+ const schemaName = getSchemaName2(this.#schema);
4781
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4782
+ const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
4783
+ return row ? this.#parseInstallationRow(row) : null;
4784
+ }
4785
+ async getInstallationByAgent(platform, agentId) {
4786
+ const schemaName = getSchemaName2(this.#schema);
4787
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4788
+ const row = await this.#db.client.oneOrNone(
4789
+ `SELECT * FROM ${tableName} WHERE "platform" = $1 AND "agentId" = $2 ORDER BY CASE "status" WHEN 'active' THEN 0 WHEN 'pending' THEN 1 ELSE 2 END, "updatedAt" DESC LIMIT 1`,
4790
+ [platform, agentId]
4791
+ );
4792
+ return row ? this.#parseInstallationRow(row) : null;
4793
+ }
4794
+ async getInstallationByWebhookId(webhookId) {
4795
+ const schemaName = getSchemaName2(this.#schema);
4796
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4797
+ const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "webhookId" = $1`, [webhookId]);
4798
+ return row ? this.#parseInstallationRow(row) : null;
4799
+ }
4800
+ async listInstallations(platform) {
4801
+ const schemaName = getSchemaName2(this.#schema);
4802
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4803
+ const rows = await this.#db.client.manyOrNone(
4804
+ `SELECT * FROM ${tableName} WHERE "platform" = $1 ORDER BY "createdAt" DESC`,
4805
+ [platform]
4806
+ );
4807
+ return rows.map((row) => this.#parseInstallationRow(row));
4808
+ }
4809
+ async deleteInstallation(id) {
4810
+ const schemaName = getSchemaName2(this.#schema);
4811
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_INSTALLATIONS, schemaName });
4812
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "id" = $1`, [id]);
4813
+ }
4814
+ async saveConfig(config) {
4815
+ const schemaName = getSchemaName2(this.#schema);
4816
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_CONFIG, schemaName });
4817
+ await this.#db.client.none(
4818
+ `INSERT INTO ${tableName} ("platform", "data", "updatedAt")
4819
+ VALUES ($1, $2::jsonb, $3)
4820
+ ON CONFLICT ("platform") DO UPDATE SET
4821
+ "data" = EXCLUDED."data",
4822
+ "updatedAt" = EXCLUDED."updatedAt"`,
4823
+ [config.platform, JSON.stringify(config.data), config.updatedAt.toISOString()]
4824
+ );
4825
+ }
4826
+ async getConfig(platform) {
4827
+ const schemaName = getSchemaName2(this.#schema);
4828
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_CONFIG, schemaName });
4829
+ const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "platform" = $1`, [platform]);
4830
+ if (!row) return null;
4831
+ return {
4832
+ platform: row.platform,
4833
+ data: typeof row.data === "string" ? JSON.parse(row.data) : row.data,
4834
+ updatedAt: new Date(row.updatedAt)
4835
+ };
4836
+ }
4837
+ async deleteConfig(platform) {
4838
+ const schemaName = getSchemaName2(this.#schema);
4839
+ const tableName = getTableName2({ indexName: storage.TABLE_CHANNEL_CONFIG, schemaName });
4840
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "platform" = $1`, [platform]);
4841
+ }
4842
+ #parseInstallationRow(row) {
4843
+ return {
4844
+ id: row.id,
4845
+ platform: row.platform,
4846
+ agentId: row.agentId,
4847
+ status: row.status,
4848
+ webhookId: row.webhookId || void 0,
4849
+ data: typeof row.data === "string" ? JSON.parse(row.data) : row.data,
4850
+ configHash: row.configHash || void 0,
4851
+ error: row.error || void 0,
4852
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt),
4853
+ updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt)
4854
+ };
4855
+ }
4856
+ };
4314
4857
  function jsonbArg(value) {
4315
4858
  return value === void 0 || value === null ? null : JSON.stringify(value);
4316
4859
  }
@@ -5308,6 +5851,16 @@ var ExperimentsPG = class _ExperimentsPG extends storage.ExperimentsStorage {
5308
5851
  async init() {
5309
5852
  await this.#db.createTable({ tableName: storage.TABLE_EXPERIMENTS, schema: storage.EXPERIMENTS_SCHEMA });
5310
5853
  await this.#db.createTable({ tableName: storage.TABLE_EXPERIMENT_RESULTS, schema: storage.EXPERIMENT_RESULTS_SCHEMA });
5854
+ await this.#db.alterTable({
5855
+ tableName: storage.TABLE_EXPERIMENTS,
5856
+ schema: storage.EXPERIMENTS_SCHEMA,
5857
+ ifNotExists: ["agentVersion"]
5858
+ });
5859
+ await this.#db.alterTable({
5860
+ tableName: storage.TABLE_EXPERIMENT_RESULTS,
5861
+ schema: storage.EXPERIMENT_RESULTS_SCHEMA,
5862
+ ifNotExists: ["status", "tags"]
5863
+ });
5311
5864
  await this.createDefaultIndexes();
5312
5865
  await this.createCustomIndexes();
5313
5866
  }
@@ -5547,6 +6100,22 @@ var ExperimentsPG = class _ExperimentsPG extends storage.ExperimentsStorage {
5547
6100
  conditions.push(`"datasetId" = $${paramIndex++}`);
5548
6101
  queryParams.push(args.datasetId);
5549
6102
  }
6103
+ if (args.targetType) {
6104
+ conditions.push(`"targetType" = $${paramIndex++}`);
6105
+ queryParams.push(args.targetType);
6106
+ }
6107
+ if (args.targetId) {
6108
+ conditions.push(`"targetId" = $${paramIndex++}`);
6109
+ queryParams.push(args.targetId);
6110
+ }
6111
+ if (args.agentVersion) {
6112
+ conditions.push(`"agentVersion" = $${paramIndex++}`);
6113
+ queryParams.push(args.agentVersion);
6114
+ }
6115
+ if (args.status) {
6116
+ conditions.push(`"status" = $${paramIndex++}`);
6117
+ queryParams.push(args.status);
6118
+ }
5550
6119
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5551
6120
  const countResult = await this.#db.client.one(
5552
6121
  `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
@@ -5735,9 +6304,21 @@ var ExperimentsPG = class _ExperimentsPG extends storage.ExperimentsStorage {
5735
6304
  try {
5736
6305
  const { page, perPage: perPageInput } = args.pagination;
5737
6306
  const tableName = getTableName2({ indexName: storage.TABLE_EXPERIMENT_RESULTS, schemaName: getSchemaName2(this.#schema) });
6307
+ const conditions = ['"experimentId" = $1'];
6308
+ const queryParams = [args.experimentId];
6309
+ let paramIndex = 2;
6310
+ if (args.traceId) {
6311
+ conditions.push(`"traceId" = $${paramIndex++}`);
6312
+ queryParams.push(args.traceId);
6313
+ }
6314
+ if (args.status) {
6315
+ conditions.push(`"status" = $${paramIndex++}`);
6316
+ queryParams.push(args.status);
6317
+ }
6318
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
5738
6319
  const countResult = await this.#db.client.one(
5739
- `SELECT COUNT(*) as count FROM ${tableName} WHERE "experimentId" = $1`,
5740
- [args.experimentId]
6320
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
6321
+ queryParams
5741
6322
  );
5742
6323
  const total = parseInt(countResult.count, 10);
5743
6324
  if (total === 0) {
@@ -5747,8 +6328,8 @@ var ExperimentsPG = class _ExperimentsPG extends storage.ExperimentsStorage {
5747
6328
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
5748
6329
  const limitValue = perPageInput === false ? total : perPage;
5749
6330
  const rows = await this.#db.client.manyOrNone(
5750
- `SELECT * FROM ${tableName} WHERE "experimentId" = $1 ORDER BY "startedAt" ASC LIMIT $2 OFFSET $3`,
5751
- [args.experimentId, limitValue, offset]
6331
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "startedAt" ASC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`,
6332
+ [...queryParams, limitValue, offset]
5752
6333
  );
5753
6334
  return {
5754
6335
  results: (rows || []).map((row) => this.transformExperimentResultRow(row)),
@@ -7078,6 +7659,23 @@ var MCPServersPG = class _MCPServersPG extends storage.MCPServersStorage {
7078
7659
  }
7079
7660
  };
7080
7661
  var OM_TABLE = "mastra_observational_memory";
7662
+ var OM_MIGRATION_COLUMNS = [
7663
+ "observedMessageIds",
7664
+ "observedTimezone",
7665
+ "bufferedObservations",
7666
+ "bufferedObservationTokens",
7667
+ "bufferedMessageIds",
7668
+ "bufferedReflection",
7669
+ "bufferedReflectionTokens",
7670
+ "bufferedReflectionInputTokens",
7671
+ "reflectedObservationLineCount",
7672
+ "bufferedObservationChunks",
7673
+ "isBufferingObservation",
7674
+ "isBufferingReflection",
7675
+ "lastBufferedAtTokens",
7676
+ "lastBufferedAtTime",
7677
+ "metadata"
7678
+ ];
7081
7679
  var _omTableSchema;
7082
7680
  try {
7083
7681
  const __require2 = typeof __require === "function" ? __require : module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
@@ -7085,10 +7683,10 @@ try {
7085
7683
  _omTableSchema = storage.OBSERVATIONAL_MEMORY_TABLE_SCHEMA;
7086
7684
  } catch {
7087
7685
  }
7088
- function getSchemaName3(schema) {
7686
+ function getSchemaName4(schema) {
7089
7687
  return schema ? `"${schema}"` : '"public"';
7090
7688
  }
7091
- function getTableName3({ indexName, schemaName }) {
7689
+ function getTableName4({ indexName, schemaName }) {
7092
7690
  const quotedIndexName = `"${indexName}"`;
7093
7691
  return schemaName ? `${schemaName}.${quotedIndexName}` : quotedIndexName;
7094
7692
  }
@@ -7129,22 +7727,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7129
7727
  await this.#db.alterTable({
7130
7728
  tableName: OM_TABLE,
7131
7729
  schema: omSchema,
7132
- ifNotExists: [
7133
- "observedMessageIds",
7134
- "observedTimezone",
7135
- "bufferedObservations",
7136
- "bufferedObservationTokens",
7137
- "bufferedMessageIds",
7138
- "bufferedReflection",
7139
- "bufferedReflectionTokens",
7140
- "bufferedReflectionInputTokens",
7141
- "bufferedObservationChunks",
7142
- "isBufferingObservation",
7143
- "isBufferingReflection",
7144
- "lastBufferedAtTokens",
7145
- "lastBufferedAtTime",
7146
- "metadata"
7147
- ]
7730
+ ifNotExists: OM_MIGRATION_COLUMNS
7148
7731
  });
7149
7732
  }
7150
7733
  await this.#db.alterTable({
@@ -7153,9 +7736,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7153
7736
  ifNotExists: ["resourceId"]
7154
7737
  });
7155
7738
  if (omSchema) {
7156
- const omTableName = getTableName3({
7739
+ const omTableName = getTableName4({
7157
7740
  indexName: OM_TABLE,
7158
- schemaName: getSchemaName3(this.#schema)
7741
+ schemaName: getSchemaName4(this.#schema)
7159
7742
  });
7160
7743
  await this.#db.client.none(`CREATE INDEX IF NOT EXISTS idx_om_lookup_key ON ${omTableName} ("lookupKey")`);
7161
7744
  }
@@ -7278,7 +7861,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7278
7861
  }
7279
7862
  async getThreadById({ threadId }) {
7280
7863
  try {
7281
- const tableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
7864
+ const tableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
7282
7865
  const thread = await this.#db.client.oneOrNone(
7283
7866
  `SELECT * FROM ${tableName} WHERE id = $1`,
7284
7867
  [threadId]
@@ -7336,7 +7919,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7336
7919
  const { field, direction } = this.parseOrderBy(orderBy);
7337
7920
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
7338
7921
  try {
7339
- const tableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
7922
+ const tableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
7340
7923
  const whereClauses = [];
7341
7924
  const queryParams = [];
7342
7925
  let paramIndex = 1;
@@ -7415,7 +7998,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7415
7998
  }
7416
7999
  async saveThread({ thread }) {
7417
8000
  try {
7418
- const tableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8001
+ const tableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
7419
8002
  await this.#db.client.none(
7420
8003
  `INSERT INTO ${tableName} (
7421
8004
  id,
@@ -7466,7 +8049,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7466
8049
  title,
7467
8050
  metadata
7468
8051
  }) {
7469
- const threadTableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8052
+ const threadTableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
7470
8053
  const existingThread = await this.getThreadById({ threadId: id });
7471
8054
  if (!existingThread) {
7472
8055
  throw new error.MastraError({
@@ -7523,8 +8106,8 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7523
8106
  }
7524
8107
  async deleteThread({ threadId }) {
7525
8108
  try {
7526
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
7527
- const threadTableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8109
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
8110
+ const threadTableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
7528
8111
  await this.#db.client.tx(async (t) => {
7529
8112
  await t.none(`DELETE FROM ${tableName} WHERE thread_id = $1`, [threadId]);
7530
8113
  const schemaName = this.#schema || "public";
@@ -7538,7 +8121,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7538
8121
  [schemaName]
7539
8122
  );
7540
8123
  for (const { tablename } of vectorTables) {
7541
- const vectorTableName = getTableName3({ indexName: tablename, schemaName: getSchemaName3(this.#schema) });
8124
+ const vectorTableName = getTableName4({ indexName: tablename, schemaName: getSchemaName4(this.#schema) });
7542
8125
  await t.none(`DELETE FROM ${vectorTableName} WHERE metadata->>'thread_id' = $1`, [threadId]);
7543
8126
  }
7544
8127
  await t.none(`DELETE FROM ${threadTableName} WHERE id = $1`, [threadId]);
@@ -7589,7 +8172,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7589
8172
  }
7590
8173
  async _getIncludedMessages({ include }) {
7591
8174
  if (!include || include.length === 0) return null;
7592
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8175
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
7593
8176
  const selectColumns = `id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
7594
8177
  const targetIds = include.map((inc) => inc.id).filter(Boolean);
7595
8178
  if (targetIds.length === 0) return null;
@@ -7670,7 +8253,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7670
8253
  if (messageIds.length === 0) return { messages: [] };
7671
8254
  const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
7672
8255
  try {
7673
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8256
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
7674
8257
  const query = `
7675
8258
  ${selectStatement} FROM ${tableName}
7676
8259
  WHERE id IN (${inPlaceholders(messageIds.length)})
@@ -7733,7 +8316,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7733
8316
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
7734
8317
  const orderByStatement = `ORDER BY COALESCE("${field}Z", "${field}") ${direction}`;
7735
8318
  const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
7736
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8319
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
7737
8320
  const conditions = [`thread_id IN (${inPlaceholders(threadIds.length)})`];
7738
8321
  const queryParams = [...threadIds];
7739
8322
  let paramIndex = threadIds.length + 1;
@@ -7872,7 +8455,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7872
8455
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
7873
8456
  const orderByStatement = `ORDER BY COALESCE("${field}Z", "${field}") ${direction}`;
7874
8457
  const selectStatement = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"`;
7875
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8458
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
7876
8459
  const conditions = [];
7877
8460
  const queryParams = [];
7878
8461
  let paramIndex = 1;
@@ -7999,7 +8582,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7999
8582
  });
8000
8583
  }
8001
8584
  try {
8002
- const tableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8585
+ const tableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
8003
8586
  await this.#db.client.tx(async (t) => {
8004
8587
  for (const message of messages) {
8005
8588
  if (!message.threadId) {
@@ -8033,7 +8616,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8033
8616
  ]
8034
8617
  );
8035
8618
  }
8036
- const threadTableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8619
+ const threadTableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
8037
8620
  const now = /* @__PURE__ */ new Date();
8038
8621
  await t.none(
8039
8622
  `UPDATE ${threadTableName}
@@ -8077,7 +8660,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8077
8660
  return [];
8078
8661
  }
8079
8662
  const messageIds = messages.map((m) => m.id);
8080
- const selectQuery = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId" FROM ${getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) })} WHERE id IN (${inPlaceholders(messageIds.length)})`;
8663
+ const selectQuery = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId" FROM ${getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) })} WHERE id IN (${inPlaceholders(messageIds.length)})`;
8081
8664
  const existingMessagesDb = await this.#db.client.manyOrNone(selectQuery, messageIds);
8082
8665
  if (existingMessagesDb.length === 0) {
8083
8666
  return [];
@@ -8134,7 +8717,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8134
8717
  }
8135
8718
  if (setClauses.length > 0) {
8136
8719
  values.push(id);
8137
- const sql = `UPDATE ${getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) })} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`;
8720
+ const sql = `UPDATE ${getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) })} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`;
8138
8721
  queries.push(t.none(sql, values));
8139
8722
  }
8140
8723
  }
@@ -8142,7 +8725,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8142
8725
  const threadIds = Array.from(threadIdsToUpdate);
8143
8726
  queries.push(
8144
8727
  t.none(
8145
- `UPDATE ${getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) })} SET "updatedAt" = NOW(), "updatedAtZ" = NOW() WHERE id IN (${inPlaceholders(threadIds.length)})`,
8728
+ `UPDATE ${getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) })} SET "updatedAt" = NOW(), "updatedAtZ" = NOW() WHERE id IN (${inPlaceholders(threadIds.length)})`,
8146
8729
  threadIds
8147
8730
  )
8148
8731
  );
@@ -8168,8 +8751,8 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8168
8751
  return;
8169
8752
  }
8170
8753
  try {
8171
- const messageTableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8172
- const threadTableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8754
+ const messageTableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
8755
+ const threadTableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
8173
8756
  await this.#db.client.tx(async (t) => {
8174
8757
  const placeholders = messageIds.map((_, idx) => `$${idx + 1}`).join(",");
8175
8758
  const messages = await t.manyOrNone(
@@ -8198,7 +8781,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8198
8781
  }
8199
8782
  }
8200
8783
  async getResourceById({ resourceId }) {
8201
- const tableName = getTableName3({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName3(this.#schema) });
8784
+ const tableName = getTableName4({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName4(this.#schema) });
8202
8785
  const result = await this.#db.client.oneOrNone(
8203
8786
  `SELECT * FROM ${tableName} WHERE id = $1`,
8204
8787
  [resourceId]
@@ -8249,7 +8832,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8249
8832
  },
8250
8833
  updatedAt: /* @__PURE__ */ new Date()
8251
8834
  };
8252
- const tableName = getTableName3({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName3(this.#schema) });
8835
+ const tableName = getTableName4({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName4(this.#schema) });
8253
8836
  const updates = [];
8254
8837
  const values = [];
8255
8838
  let paramIndex = 1;
@@ -8295,8 +8878,8 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8295
8878
  details: { newThreadId }
8296
8879
  });
8297
8880
  }
8298
- const threadTableName = getTableName3({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName3(this.#schema) });
8299
- const messageTableName = getTableName3({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName3(this.#schema) });
8881
+ const threadTableName = getTableName4({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName4(this.#schema) });
8882
+ const messageTableName = getTableName4({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName4(this.#schema) });
8300
8883
  try {
8301
8884
  return await this.#db.client.tx(async (t) => {
8302
8885
  let messageQuery = `SELECT id, content, role, type, "createdAt", "createdAtZ", thread_id AS "threadId", "resourceId"
@@ -8466,9 +9049,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8466
9049
  async getObservationalMemory(threadId, resourceId) {
8467
9050
  try {
8468
9051
  const lookupKey = this.getOMKey(threadId, resourceId);
8469
- const tableName = getTableName3({
9052
+ const tableName = getTableName4({
8470
9053
  indexName: OM_TABLE,
8471
- schemaName: getSchemaName3(this.#schema)
9054
+ schemaName: getSchemaName4(this.#schema)
8472
9055
  });
8473
9056
  const result = await this.#db.client.oneOrNone(
8474
9057
  `SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT 1`,
@@ -8488,17 +9071,34 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8488
9071
  );
8489
9072
  }
8490
9073
  }
8491
- async getObservationalMemoryHistory(threadId, resourceId, limit = 10) {
9074
+ async getObservationalMemoryHistory(threadId, resourceId, limit = 10, options) {
8492
9075
  try {
8493
9076
  const lookupKey = this.getOMKey(threadId, resourceId);
8494
- const tableName = getTableName3({
9077
+ const tableName = getTableName4({
8495
9078
  indexName: OM_TABLE,
8496
- schemaName: getSchemaName3(this.#schema)
9079
+ schemaName: getSchemaName4(this.#schema)
8497
9080
  });
8498
- const result = await this.#db.client.manyOrNone(
8499
- `SELECT * FROM ${tableName} WHERE "lookupKey" = $1 ORDER BY "generationCount" DESC LIMIT $2`,
8500
- [lookupKey, limit]
8501
- );
9081
+ const conditions = [`"lookupKey" = $1`];
9082
+ const params = [lookupKey];
9083
+ let paramIndex = 2;
9084
+ if (options?.from) {
9085
+ conditions.push(`"createdAtZ" >= $${paramIndex}`);
9086
+ params.push(options.from.toISOString());
9087
+ paramIndex++;
9088
+ }
9089
+ if (options?.to) {
9090
+ conditions.push(`"createdAtZ" <= $${paramIndex}`);
9091
+ params.push(options.to.toISOString());
9092
+ paramIndex++;
9093
+ }
9094
+ params.push(limit);
9095
+ let sql = `SELECT * FROM ${tableName} WHERE ${conditions.join(" AND ")} ORDER BY "generationCount" DESC LIMIT $${paramIndex}`;
9096
+ paramIndex++;
9097
+ if (options?.offset != null) {
9098
+ params.push(options.offset);
9099
+ sql += ` OFFSET $${paramIndex}`;
9100
+ }
9101
+ const result = await this.#db.client.manyOrNone(sql, params);
8502
9102
  if (!result) return [];
8503
9103
  return result.map((row) => this.parseOMRow(row));
8504
9104
  } catch (error$1) {
@@ -8541,9 +9141,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8541
9141
  config: input.config,
8542
9142
  observedTimezone: input.observedTimezone
8543
9143
  };
8544
- const tableName = getTableName3({
9144
+ const tableName = getTableName4({
8545
9145
  indexName: OM_TABLE,
8546
- schemaName: getSchemaName3(this.#schema)
9146
+ schemaName: getSchemaName4(this.#schema)
8547
9147
  });
8548
9148
  const nowStr = now.toISOString();
8549
9149
  await this.#db.client.none(
@@ -8614,9 +9214,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8614
9214
  async insertObservationalMemoryRecord(record) {
8615
9215
  try {
8616
9216
  const lookupKey = this.getOMKey(record.threadId, record.resourceId);
8617
- const tableName = getTableName3({
9217
+ const tableName = getTableName4({
8618
9218
  indexName: OM_TABLE,
8619
- schemaName: getSchemaName3(this.#schema)
9219
+ schemaName: getSchemaName4(this.#schema)
8620
9220
  });
8621
9221
  const lastObservedAtStr = record.lastObservedAt ? record.lastObservedAt.toISOString() : null;
8622
9222
  const lastBufferedAtTimeStr = record.lastBufferedAtTime ? record.lastBufferedAtTime.toISOString() : null;
@@ -8688,9 +9288,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8688
9288
  async updateActiveObservations(input) {
8689
9289
  try {
8690
9290
  const now = /* @__PURE__ */ new Date();
8691
- const tableName = getTableName3({
9291
+ const tableName = getTableName4({
8692
9292
  indexName: OM_TABLE,
8693
- schemaName: getSchemaName3(this.#schema)
9293
+ schemaName: getSchemaName4(this.#schema)
8694
9294
  });
8695
9295
  const lastObservedAtStr = input.lastObservedAt.toISOString();
8696
9296
  const nowStr = now.toISOString();
@@ -8772,9 +9372,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8772
9372
  metadata: input.currentRecord.metadata,
8773
9373
  observedTimezone: input.currentRecord.observedTimezone
8774
9374
  };
8775
- const tableName = getTableName3({
9375
+ const tableName = getTableName4({
8776
9376
  indexName: OM_TABLE,
8777
- schemaName: getSchemaName3(this.#schema)
9377
+ schemaName: getSchemaName4(this.#schema)
8778
9378
  });
8779
9379
  const nowStr = now.toISOString();
8780
9380
  const lastObservedAtStr = record.lastObservedAt?.toISOString() || null;
@@ -8848,9 +9448,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8848
9448
  }
8849
9449
  async setReflectingFlag(id, isReflecting) {
8850
9450
  try {
8851
- const tableName = getTableName3({
9451
+ const tableName = getTableName4({
8852
9452
  indexName: OM_TABLE,
8853
- schemaName: getSchemaName3(this.#schema)
9453
+ schemaName: getSchemaName4(this.#schema)
8854
9454
  });
8855
9455
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8856
9456
  const result = await this.#db.client.query(
@@ -8883,9 +9483,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8883
9483
  }
8884
9484
  async setObservingFlag(id, isObserving) {
8885
9485
  try {
8886
- const tableName = getTableName3({
9486
+ const tableName = getTableName4({
8887
9487
  indexName: OM_TABLE,
8888
- schemaName: getSchemaName3(this.#schema)
9488
+ schemaName: getSchemaName4(this.#schema)
8889
9489
  });
8890
9490
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8891
9491
  const result = await this.#db.client.query(
@@ -8918,9 +9518,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8918
9518
  }
8919
9519
  async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
8920
9520
  try {
8921
- const tableName = getTableName3({
9521
+ const tableName = getTableName4({
8922
9522
  indexName: OM_TABLE,
8923
- schemaName: getSchemaName3(this.#schema)
9523
+ schemaName: getSchemaName4(this.#schema)
8924
9524
  });
8925
9525
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8926
9526
  let query;
@@ -8959,9 +9559,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8959
9559
  }
8960
9560
  async setBufferingReflectionFlag(id, isBuffering) {
8961
9561
  try {
8962
- const tableName = getTableName3({
9562
+ const tableName = getTableName4({
8963
9563
  indexName: OM_TABLE,
8964
- schemaName: getSchemaName3(this.#schema)
9564
+ schemaName: getSchemaName4(this.#schema)
8965
9565
  });
8966
9566
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
8967
9567
  const result = await this.#db.client.query(
@@ -8995,9 +9595,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8995
9595
  async clearObservationalMemory(threadId, resourceId) {
8996
9596
  try {
8997
9597
  const lookupKey = this.getOMKey(threadId, resourceId);
8998
- const tableName = getTableName3({
9598
+ const tableName = getTableName4({
8999
9599
  indexName: OM_TABLE,
9000
- schemaName: getSchemaName3(this.#schema)
9600
+ schemaName: getSchemaName4(this.#schema)
9001
9601
  });
9002
9602
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE "lookupKey" = $1`, [lookupKey]);
9003
9603
  } catch (error$1) {
@@ -9014,9 +9614,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
9014
9614
  }
9015
9615
  async setPendingMessageTokens(id, tokenCount) {
9016
9616
  try {
9017
- const tableName = getTableName3({
9617
+ const tableName = getTableName4({
9018
9618
  indexName: OM_TABLE,
9019
- schemaName: getSchemaName3(this.#schema)
9619
+ schemaName: getSchemaName4(this.#schema)
9020
9620
  });
9021
9621
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9022
9622
  const result = await this.#db.client.query(
@@ -9051,14 +9651,53 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
9051
9651
  );
9052
9652
  }
9053
9653
  }
9654
+ async updateObservationalMemoryConfig(input) {
9655
+ try {
9656
+ const tableName = getTableName4({
9657
+ indexName: OM_TABLE,
9658
+ schemaName: getSchemaName4(this.#schema)
9659
+ });
9660
+ const selectResult = await this.#db.client.query(`SELECT config FROM ${tableName} WHERE id = $1`, [input.id]);
9661
+ if (selectResult.rowCount === 0) {
9662
+ throw new error.MastraError({
9663
+ id: storage.createStorageErrorId("PG", "UPDATE_OM_CONFIG", "NOT_FOUND"),
9664
+ text: `Observational memory record not found: ${input.id}`,
9665
+ domain: error.ErrorDomain.STORAGE,
9666
+ category: error.ErrorCategory.THIRD_PARTY,
9667
+ details: { id: input.id }
9668
+ });
9669
+ }
9670
+ const row = selectResult.rows[0];
9671
+ const existing = row.config ? typeof row.config === "string" ? JSON.parse(row.config) : row.config : {};
9672
+ const merged = this.deepMergeConfig(existing, input.config);
9673
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9674
+ await this.#db.client.query(
9675
+ `UPDATE ${tableName} SET config = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`,
9676
+ [JSON.stringify(merged), nowStr, nowStr, input.id]
9677
+ );
9678
+ } catch (error$1) {
9679
+ if (error$1 instanceof error.MastraError) {
9680
+ throw error$1;
9681
+ }
9682
+ throw new error.MastraError(
9683
+ {
9684
+ id: storage.createStorageErrorId("PG", "UPDATE_OM_CONFIG", "FAILED"),
9685
+ domain: error.ErrorDomain.STORAGE,
9686
+ category: error.ErrorCategory.THIRD_PARTY,
9687
+ details: { id: input.id }
9688
+ },
9689
+ error$1
9690
+ );
9691
+ }
9692
+ }
9054
9693
  // ============================================
9055
9694
  // Async Buffering Methods
9056
9695
  // ============================================
9057
9696
  async updateBufferedObservations(input) {
9058
9697
  try {
9059
- const tableName = getTableName3({
9698
+ const tableName = getTableName4({
9060
9699
  indexName: OM_TABLE,
9061
- schemaName: getSchemaName3(this.#schema)
9700
+ schemaName: getSchemaName4(this.#schema)
9062
9701
  });
9063
9702
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9064
9703
  const newChunk = {
@@ -9110,9 +9749,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
9110
9749
  }
9111
9750
  async swapBufferedToActive(input) {
9112
9751
  try {
9113
- const tableName = getTableName3({
9752
+ const tableName = getTableName4({
9114
9753
  indexName: OM_TABLE,
9115
- schemaName: getSchemaName3(this.#schema)
9754
+ schemaName: getSchemaName4(this.#schema)
9116
9755
  });
9117
9756
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9118
9757
  const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.id]);
@@ -9275,9 +9914,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
9275
9914
  }
9276
9915
  async updateBufferedReflection(input) {
9277
9916
  try {
9278
- const tableName = getTableName3({
9917
+ const tableName = getTableName4({
9279
9918
  indexName: OM_TABLE,
9280
- schemaName: getSchemaName3(this.#schema)
9919
+ schemaName: getSchemaName4(this.#schema)
9281
9920
  });
9282
9921
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
9283
9922
  const result = await this.#db.client.query(
@@ -9329,9 +9968,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
9329
9968
  }
9330
9969
  async swapBufferedReflectionToActive(input) {
9331
9970
  try {
9332
- const tableName = getTableName3({
9971
+ const tableName = getTableName4({
9333
9972
  indexName: OM_TABLE,
9334
- schemaName: getSchemaName3(this.#schema)
9973
+ schemaName: getSchemaName4(this.#schema)
9335
9974
  });
9336
9975
  const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [
9337
9976
  input.currentRecord.id
@@ -9737,6 +10376,51 @@ var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorag
9737
10376
  );
9738
10377
  }
9739
10378
  }
10379
+ async getTraceLight(args) {
10380
+ const { traceId } = args;
10381
+ try {
10382
+ const tableName = getTableName2({
10383
+ indexName: storage.TABLE_SPANS,
10384
+ schemaName: getSchemaName2(this.#schema)
10385
+ });
10386
+ const spans = await this.#db.client.manyOrNone(
10387
+ `SELECT
10388
+ "traceId", "spanId", "parentSpanId", "name",
10389
+ "entityType", "entityId", "entityName",
10390
+ "spanType", "error", "isEvent",
10391
+ "startedAtZ" as "startedAt", "endedAtZ" as "endedAt",
10392
+ "createdAtZ" as "createdAt", "updatedAtZ" as "updatedAt"
10393
+ FROM ${tableName}
10394
+ WHERE "traceId" = $1
10395
+ ORDER BY "startedAtZ" ASC`,
10396
+ [traceId]
10397
+ );
10398
+ if (!spans || spans.length === 0) {
10399
+ return null;
10400
+ }
10401
+ return {
10402
+ traceId,
10403
+ spans: spans.map(
10404
+ (span) => transformFromSqlRow({
10405
+ tableName: storage.TABLE_SPANS,
10406
+ sqlRow: span
10407
+ })
10408
+ )
10409
+ };
10410
+ } catch (error$1) {
10411
+ throw new error.MastraError(
10412
+ {
10413
+ id: storage.createStorageErrorId("PG", "GET_TRACE_LIGHT", "FAILED"),
10414
+ domain: error.ErrorDomain.STORAGE,
10415
+ category: error.ErrorCategory.USER,
10416
+ details: {
10417
+ traceId
10418
+ }
10419
+ },
10420
+ error$1
10421
+ );
10422
+ }
10423
+ }
9740
10424
  async updateSpan(args) {
9741
10425
  const { traceId, spanId, updates } = args;
9742
10426
  try {
@@ -10693,6 +11377,252 @@ var PromptBlocksPG = class _PromptBlocksPG extends storage.PromptBlocksStorage {
10693
11377
  };
10694
11378
  }
10695
11379
  };
11380
+ function getSchemaName5(schema) {
11381
+ return schema ? `"${schema}"` : '"public"';
11382
+ }
11383
+ function getTableName5(table, schema) {
11384
+ const quoted = `"${table}"`;
11385
+ return schema ? `${schema}.${quoted}` : quoted;
11386
+ }
11387
+ function parseJson2(val) {
11388
+ if (val == null) return void 0;
11389
+ if (typeof val === "string") {
11390
+ try {
11391
+ return JSON.parse(val);
11392
+ } catch {
11393
+ return val;
11394
+ }
11395
+ }
11396
+ return val;
11397
+ }
11398
+ function toNumber(val) {
11399
+ if (typeof val === "bigint") return Number(val);
11400
+ return Number(val);
11401
+ }
11402
+ function rowToSchedule(row) {
11403
+ const target = parseJson2(row.target);
11404
+ if (!target) {
11405
+ throw new Error(`Schedule row ${row.id} has invalid target`);
11406
+ }
11407
+ const schedule = {
11408
+ id: String(row.id),
11409
+ target,
11410
+ cron: String(row.cron),
11411
+ status: String(row.status),
11412
+ nextFireAt: toNumber(row.next_fire_at),
11413
+ createdAt: toNumber(row.created_at),
11414
+ updatedAt: toNumber(row.updated_at)
11415
+ };
11416
+ if (row.timezone != null) schedule.timezone = String(row.timezone);
11417
+ if (row.last_fire_at != null) schedule.lastFireAt = toNumber(row.last_fire_at);
11418
+ if (row.last_run_id != null) schedule.lastRunId = String(row.last_run_id);
11419
+ const metadata = parseJson2(row.metadata);
11420
+ if (metadata !== void 0) schedule.metadata = metadata;
11421
+ return schedule;
11422
+ }
11423
+ function rowToTrigger(row) {
11424
+ const trigger = {
11425
+ scheduleId: String(row.schedule_id),
11426
+ runId: String(row.run_id),
11427
+ scheduledFireAt: toNumber(row.scheduled_fire_at),
11428
+ actualFireAt: toNumber(row.actual_fire_at),
11429
+ status: String(row.status)
11430
+ };
11431
+ if (row.error != null) trigger.error = String(row.error);
11432
+ return trigger;
11433
+ }
11434
+ var SchedulesPG = class extends storage.SchedulesStorage {
11435
+ #db;
11436
+ #client;
11437
+ #schema;
11438
+ /** Tables managed by this domain */
11439
+ static MANAGED_TABLES = [storage.TABLE_SCHEDULES, storage.TABLE_SCHEDULE_TRIGGERS];
11440
+ constructor(config) {
11441
+ super();
11442
+ const { client, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
11443
+ this.#client = client;
11444
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
11445
+ this.#schema = schemaName || "public";
11446
+ }
11447
+ async init() {
11448
+ await this.#db.createTable({
11449
+ tableName: storage.TABLE_SCHEDULES,
11450
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCHEDULES]
11451
+ });
11452
+ await this.#db.createTable({
11453
+ tableName: storage.TABLE_SCHEDULE_TRIGGERS,
11454
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCHEDULE_TRIGGERS]
11455
+ });
11456
+ }
11457
+ static getExportDDL(schemaName) {
11458
+ return [
11459
+ generateTableSQL({
11460
+ tableName: storage.TABLE_SCHEDULES,
11461
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCHEDULES],
11462
+ schemaName,
11463
+ includeAllConstraints: true
11464
+ }),
11465
+ generateTableSQL({
11466
+ tableName: storage.TABLE_SCHEDULE_TRIGGERS,
11467
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCHEDULE_TRIGGERS],
11468
+ schemaName,
11469
+ includeAllConstraints: true
11470
+ })
11471
+ ];
11472
+ }
11473
+ async dangerouslyClearAll() {
11474
+ await this.#db.clearTable({ tableName: storage.TABLE_SCHEDULE_TRIGGERS });
11475
+ await this.#db.clearTable({ tableName: storage.TABLE_SCHEDULES });
11476
+ }
11477
+ #table(tableName) {
11478
+ const schema = utils.parseSqlIdentifier(this.#schema, "schema name");
11479
+ return getTableName5(tableName, getSchemaName5(schema));
11480
+ }
11481
+ async createSchedule(schedule) {
11482
+ const existing = await this.getSchedule(schedule.id);
11483
+ if (existing) {
11484
+ throw new Error(`Schedule with id "${schedule.id}" already exists`);
11485
+ }
11486
+ await this.#db.insert({
11487
+ tableName: storage.TABLE_SCHEDULES,
11488
+ record: {
11489
+ id: schedule.id,
11490
+ target: schedule.target,
11491
+ cron: schedule.cron,
11492
+ timezone: schedule.timezone ?? null,
11493
+ status: schedule.status,
11494
+ next_fire_at: schedule.nextFireAt,
11495
+ last_fire_at: schedule.lastFireAt ?? null,
11496
+ last_run_id: schedule.lastRunId ?? null,
11497
+ created_at: schedule.createdAt,
11498
+ updated_at: schedule.updatedAt,
11499
+ metadata: schedule.metadata ?? null
11500
+ }
11501
+ });
11502
+ return schedule;
11503
+ }
11504
+ async getSchedule(id) {
11505
+ const row = await this.#client.oneOrNone(
11506
+ `SELECT * FROM ${this.#table(storage.TABLE_SCHEDULES)} WHERE id = $1`,
11507
+ [id]
11508
+ );
11509
+ return row ? rowToSchedule(row) : null;
11510
+ }
11511
+ async listSchedules(filter) {
11512
+ const conditions = [];
11513
+ const params = [];
11514
+ if (filter?.status) {
11515
+ params.push(filter.status);
11516
+ conditions.push(`status = $${params.length}`);
11517
+ }
11518
+ if (filter?.workflowId) {
11519
+ params.push(filter.workflowId);
11520
+ conditions.push(`target->>'workflowId' = $${params.length}`);
11521
+ }
11522
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
11523
+ const rows = await this.#client.manyOrNone(
11524
+ `SELECT * FROM ${this.#table(storage.TABLE_SCHEDULES)} ${where} ORDER BY created_at ASC`,
11525
+ params
11526
+ );
11527
+ return rows.map(rowToSchedule);
11528
+ }
11529
+ async listDueSchedules(now, limit) {
11530
+ const cap = limit ?? 100;
11531
+ const rows = await this.#client.manyOrNone(
11532
+ `SELECT * FROM ${this.#table(storage.TABLE_SCHEDULES)}
11533
+ WHERE status = $1 AND next_fire_at <= $2
11534
+ ORDER BY next_fire_at ASC
11535
+ LIMIT $3`,
11536
+ ["active", now, cap]
11537
+ );
11538
+ return rows.map(rowToSchedule);
11539
+ }
11540
+ async updateSchedule(id, patch) {
11541
+ const setClauses = [];
11542
+ const params = [];
11543
+ const push = (frag, value) => {
11544
+ params.push(value);
11545
+ setClauses.push(frag.replace("?", `$${params.length}`));
11546
+ };
11547
+ if ("cron" in patch && patch.cron !== void 0) push("cron = ?", patch.cron);
11548
+ if ("timezone" in patch) push("timezone = ?", patch.timezone ?? null);
11549
+ if ("status" in patch && patch.status !== void 0) push("status = ?", patch.status);
11550
+ if ("nextFireAt" in patch && patch.nextFireAt !== void 0) push("next_fire_at = ?", patch.nextFireAt);
11551
+ if ("target" in patch && patch.target !== void 0) {
11552
+ push("target = ?::jsonb", JSON.stringify(patch.target));
11553
+ }
11554
+ if ("metadata" in patch) {
11555
+ push("metadata = ?::jsonb", patch.metadata != null ? JSON.stringify(patch.metadata) : null);
11556
+ }
11557
+ push("updated_at = ?", Date.now());
11558
+ if (setClauses.length === 1) {
11559
+ const existing = await this.getSchedule(id);
11560
+ if (!existing) throw new Error(`Schedule ${id} not found`);
11561
+ return existing;
11562
+ }
11563
+ params.push(id);
11564
+ await this.#client.none(
11565
+ `UPDATE ${this.#table(storage.TABLE_SCHEDULES)} SET ${setClauses.join(", ")} WHERE id = $${params.length}`,
11566
+ params
11567
+ );
11568
+ const updated = await this.getSchedule(id);
11569
+ if (!updated) throw new Error(`Schedule ${id} not found`);
11570
+ return updated;
11571
+ }
11572
+ async updateScheduleNextFire(id, expectedNextFireAt, newNextFireAt, lastFireAt, lastRunId) {
11573
+ const result = await this.#client.query(
11574
+ `UPDATE ${this.#table(storage.TABLE_SCHEDULES)}
11575
+ SET next_fire_at = $1, last_fire_at = $2, last_run_id = $3, updated_at = $4
11576
+ WHERE id = $5 AND next_fire_at = $6 AND status = $7`,
11577
+ [newNextFireAt, lastFireAt, lastRunId, Date.now(), id, expectedNextFireAt, "active"]
11578
+ );
11579
+ return (result.rowCount ?? 0) > 0;
11580
+ }
11581
+ async deleteSchedule(id) {
11582
+ await this.#client.none(`DELETE FROM ${this.#table(storage.TABLE_SCHEDULE_TRIGGERS)} WHERE schedule_id = $1`, [id]);
11583
+ await this.#client.none(`DELETE FROM ${this.#table(storage.TABLE_SCHEDULES)} WHERE id = $1`, [id]);
11584
+ }
11585
+ async recordTrigger(trigger) {
11586
+ await this.#db.insert({
11587
+ tableName: storage.TABLE_SCHEDULE_TRIGGERS,
11588
+ record: {
11589
+ schedule_id: trigger.scheduleId,
11590
+ run_id: trigger.runId,
11591
+ scheduled_fire_at: trigger.scheduledFireAt,
11592
+ actual_fire_at: trigger.actualFireAt,
11593
+ status: trigger.status,
11594
+ error: trigger.error ?? null
11595
+ }
11596
+ });
11597
+ }
11598
+ async listTriggers(scheduleId, opts) {
11599
+ const conditions = [];
11600
+ const params = [];
11601
+ params.push(scheduleId);
11602
+ conditions.push(`schedule_id = $${params.length}`);
11603
+ if (opts?.fromActualFireAt != null) {
11604
+ params.push(opts.fromActualFireAt);
11605
+ conditions.push(`actual_fire_at >= $${params.length}`);
11606
+ }
11607
+ if (opts?.toActualFireAt != null) {
11608
+ params.push(opts.toActualFireAt);
11609
+ conditions.push(`actual_fire_at < $${params.length}`);
11610
+ }
11611
+ let limitClause = "";
11612
+ if (opts?.limit != null) {
11613
+ params.push(Math.floor(opts.limit));
11614
+ limitClause = `LIMIT $${params.length}`;
11615
+ }
11616
+ const rows = await this.#client.manyOrNone(
11617
+ `SELECT * FROM ${this.#table(storage.TABLE_SCHEDULE_TRIGGERS)}
11618
+ WHERE ${conditions.join(" AND ")}
11619
+ ORDER BY actual_fire_at DESC
11620
+ ${limitClause}`,
11621
+ params
11622
+ );
11623
+ return rows.map(rowToTrigger);
11624
+ }
11625
+ };
10696
11626
  var SNAPSHOT_FIELDS4 = [
10697
11627
  "name",
10698
11628
  "description",
@@ -11360,10 +12290,10 @@ var ScorerDefinitionsPG = class _ScorerDefinitionsPG extends storage.ScorerDefin
11360
12290
  };
11361
12291
  }
11362
12292
  };
11363
- function getSchemaName4(schema) {
12293
+ function getSchemaName6(schema) {
11364
12294
  return schema ? `"${schema}"` : '"public"';
11365
12295
  }
11366
- function getTableName4({ indexName, schemaName }) {
12296
+ function getTableName6({ indexName, schemaName }) {
11367
12297
  const quotedIndexName = `"${indexName}"`;
11368
12298
  return schemaName ? `${schemaName}.${quotedIndexName}` : quotedIndexName;
11369
12299
  }
@@ -11477,7 +12407,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11477
12407
  async getScoreById({ id }) {
11478
12408
  try {
11479
12409
  const result = await this.#db.client.oneOrNone(
11480
- `SELECT * FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE id = $1`,
12410
+ `SELECT * FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE id = $1`,
11481
12411
  [id]
11482
12412
  );
11483
12413
  return result ? transformScoreRow(result) : null;
@@ -11517,7 +12447,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11517
12447
  }
11518
12448
  const whereClause = conditions.join(" AND ");
11519
12449
  const total = await this.#db.client.oneOrNone(
11520
- `SELECT COUNT(*) FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE ${whereClause}`,
12450
+ `SELECT COUNT(*) FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE ${whereClause}`,
11521
12451
  queryParams
11522
12452
  );
11523
12453
  const { page, perPage: perPageInput } = pagination;
@@ -11537,7 +12467,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11537
12467
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
11538
12468
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
11539
12469
  const result = await this.#db.client.manyOrNone(
11540
- `SELECT * FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`,
12470
+ `SELECT * FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE ${whereClause} ORDER BY "createdAt" DESC LIMIT $${paramIndex++} OFFSET $${paramIndex++}`,
11541
12471
  [...queryParams, limitValue, start]
11542
12472
  );
11543
12473
  return {
@@ -11632,7 +12562,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11632
12562
  }) {
11633
12563
  try {
11634
12564
  const total = await this.#db.client.oneOrNone(
11635
- `SELECT COUNT(*) FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE "runId" = $1`,
12565
+ `SELECT COUNT(*) FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE "runId" = $1`,
11636
12566
  [runId]
11637
12567
  );
11638
12568
  const { page, perPage: perPageInput } = pagination;
@@ -11652,7 +12582,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11652
12582
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
11653
12583
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
11654
12584
  const result = await this.#db.client.manyOrNone(
11655
- `SELECT * FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE "runId" = $1 LIMIT $2 OFFSET $3`,
12585
+ `SELECT * FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE "runId" = $1 LIMIT $2 OFFSET $3`,
11656
12586
  [runId, limitValue, start]
11657
12587
  );
11658
12588
  return {
@@ -11682,7 +12612,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11682
12612
  }) {
11683
12613
  try {
11684
12614
  const total = await this.#db.client.oneOrNone(
11685
- `SELECT COUNT(*) FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE "entityId" = $1 AND "entityType" = $2`,
12615
+ `SELECT COUNT(*) FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE "entityId" = $1 AND "entityType" = $2`,
11686
12616
  [entityId, entityType]
11687
12617
  );
11688
12618
  const { page, perPage: perPageInput } = pagination;
@@ -11702,7 +12632,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11702
12632
  const limitValue = perPageInput === false ? Number(total?.count) : perPage;
11703
12633
  const end = perPageInput === false ? Number(total?.count) : start + perPage;
11704
12634
  const result = await this.#db.client.manyOrNone(
11705
- `SELECT * FROM ${getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) })} WHERE "entityId" = $1 AND "entityType" = $2 LIMIT $3 OFFSET $4`,
12635
+ `SELECT * FROM ${getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) })} WHERE "entityId" = $1 AND "entityType" = $2 LIMIT $3 OFFSET $4`,
11706
12636
  [entityId, entityType, limitValue, start]
11707
12637
  );
11708
12638
  return {
@@ -11731,7 +12661,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
11731
12661
  pagination
11732
12662
  }) {
11733
12663
  try {
11734
- const tableName = getTableName4({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName4(this.#schema) });
12664
+ const tableName = getTableName6({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName6(this.#schema) });
11735
12665
  const countSQLResult = await this.#db.client.oneOrNone(
11736
12666
  `SELECT COUNT(*) as count FROM ${tableName} WHERE "traceId" = $1 AND "spanId" = $2`,
11737
12667
  [traceId, spanId]
@@ -12434,15 +13364,15 @@ var SkillsPG = class _SkillsPG extends storage.SkillsStorage {
12434
13364
  };
12435
13365
  }
12436
13366
  };
12437
- function getSchemaName5(schema) {
13367
+ function getSchemaName7(schema) {
12438
13368
  return schema ? `"${schema}"` : '"public"';
12439
13369
  }
12440
- function getTableName5({ indexName, schemaName }) {
13370
+ function getTableName7({ indexName, schemaName }) {
12441
13371
  const quotedIndexName = `"${indexName}"`;
12442
13372
  return schemaName ? `${schemaName}.${quotedIndexName}` : quotedIndexName;
12443
13373
  }
12444
13374
  function sanitizeJsonForPg(jsonString) {
12445
- return jsonString.replace(/(^|[^\\])(\\(?!["\\/bfnrtu]))/g, "$1\\\\").replace(/\\u(0000|[Dd][89A-Fa-f][0-9A-Fa-f]{2})/g, "");
13375
+ return jsonString.replace(/\\\\?u(0000|[Dd][89A-Fa-f][0-9A-Fa-f]{2})/g, "").replace(/(^|[^\\])(\\(?!["\\/bfnrtu]))/g, "$1\\\\");
12446
13376
  }
12447
13377
  var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12448
13378
  #db;
@@ -12549,7 +13479,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12549
13479
  }) {
12550
13480
  try {
12551
13481
  return await this.#db.client.tx(async (t) => {
12552
- const tableName = getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) });
13482
+ const tableName = getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) });
12553
13483
  const existingSnapshotResult = await t.oneOrNone(
12554
13484
  `SELECT snapshot FROM ${tableName} WHERE workflow_name = $1 AND run_id = $2 FOR UPDATE`,
12555
13485
  [workflowName, runId]
@@ -12610,7 +13540,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12610
13540
  }) {
12611
13541
  try {
12612
13542
  return await this.#db.client.tx(async (t) => {
12613
- const tableName = getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) });
13543
+ const tableName = getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) });
12614
13544
  const existingSnapshotResult = await t.oneOrNone(
12615
13545
  `SELECT snapshot FROM ${tableName} WHERE workflow_name = $1 AND run_id = $2 FOR UPDATE`,
12616
13546
  [workflowName, runId]
@@ -12660,7 +13590,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12660
13590
  const updatedAtValue = updatedAt ? updatedAt : now;
12661
13591
  const sanitizedSnapshot = sanitizeJsonForPg(JSON.stringify(snapshot));
12662
13592
  await this.#db.client.none(
12663
- `INSERT INTO ${getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) })} (workflow_name, run_id, "resourceId", snapshot, "createdAt", "updatedAt")
13593
+ `INSERT INTO ${getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) })} (workflow_name, run_id, "resourceId", snapshot, "createdAt", "updatedAt")
12664
13594
  VALUES ($1, $2, $3, $4, $5, $6)
12665
13595
  ON CONFLICT (workflow_name, run_id) DO UPDATE
12666
13596
  SET "resourceId" = $3, snapshot = $4, "updatedAt" = $6`,
@@ -12718,7 +13648,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12718
13648
  }
12719
13649
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
12720
13650
  const query = `
12721
- SELECT * FROM ${getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) })}
13651
+ SELECT * FROM ${getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) })}
12722
13652
  ${whereClause}
12723
13653
  ORDER BY "createdAt" DESC LIMIT 1
12724
13654
  `;
@@ -12746,7 +13676,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12746
13676
  async deleteWorkflowRunById({ runId, workflowName }) {
12747
13677
  try {
12748
13678
  await this.#db.client.none(
12749
- `DELETE FROM ${getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) })} WHERE run_id = $1 AND workflow_name = $2`,
13679
+ `DELETE FROM ${getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) })} WHERE run_id = $1 AND workflow_name = $2`,
12750
13680
  [runId, workflowName]
12751
13681
  );
12752
13682
  } catch (error$1) {
@@ -12814,7 +13744,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12814
13744
  const usePagination = typeof perPage === "number" && typeof page === "number";
12815
13745
  if (usePagination) {
12816
13746
  const countResult = await this.#db.client.one(
12817
- `SELECT COUNT(*) as count FROM ${getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) })} ${whereClause}`,
13747
+ `SELECT COUNT(*) as count FROM ${getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) })} ${whereClause}`,
12818
13748
  values
12819
13749
  );
12820
13750
  total = Number(countResult.count);
@@ -12822,7 +13752,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
12822
13752
  const normalizedPerPage = usePagination ? storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER) : 0;
12823
13753
  const offset = usePagination ? page * normalizedPerPage : void 0;
12824
13754
  const query = `
12825
- SELECT * FROM ${getTableName5({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName5(this.#schema) })}
13755
+ SELECT * FROM ${getTableName7({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName7(this.#schema) })}
12826
13756
  ${whereClause}
12827
13757
  ORDER BY "createdAt" DESC
12828
13758
  ${usePagination ? ` LIMIT $${paramIndex} OFFSET $${paramIndex + 1}` : ""}
@@ -13545,7 +14475,10 @@ var ALL_DOMAINS = [
13545
14475
  AgentsPG,
13546
14476
  WorkflowsPG,
13547
14477
  DatasetsPG,
13548
- ExperimentsPG
14478
+ ExperimentsPG,
14479
+ BackgroundTasksPG,
14480
+ ChannelsPG,
14481
+ SchedulesPG
13549
14482
  ];
13550
14483
  function exportSchemas(schemaName) {
13551
14484
  const statements = [];
@@ -13599,7 +14532,10 @@ var PostgresStore = class extends storage.MastraCompositeStore {
13599
14532
  skills: new SkillsPG(domainConfig),
13600
14533
  blobs: new BlobsPG(domainConfig),
13601
14534
  datasets: new DatasetsPG(domainConfig),
13602
- experiments: new ExperimentsPG(domainConfig)
14535
+ experiments: new ExperimentsPG(domainConfig),
14536
+ backgroundTasks: new BackgroundTasksPG(domainConfig),
14537
+ channels: new ChannelsPG(domainConfig),
14538
+ schedules: new SchedulesPG(domainConfig)
13603
14539
  };
13604
14540
  } catch (e) {
13605
14541
  throw new error.MastraError(
@@ -13789,7 +14725,9 @@ Example Complex Query:
13789
14725
  }`;
13790
14726
 
13791
14727
  exports.AgentsPG = AgentsPG;
14728
+ exports.BackgroundTasksPG = BackgroundTasksPG;
13792
14729
  exports.BlobsPG = BlobsPG;
14730
+ exports.ChannelsPG = ChannelsPG;
13793
14731
  exports.DatasetsPG = DatasetsPG;
13794
14732
  exports.ExperimentsPG = ExperimentsPG;
13795
14733
  exports.MCPClientsPG = MCPClientsPG;
@@ -13801,6 +14739,7 @@ exports.PgVector = PgVector;
13801
14739
  exports.PoolAdapter = PoolAdapter;
13802
14740
  exports.PostgresStore = PostgresStore;
13803
14741
  exports.PromptBlocksPG = PromptBlocksPG;
14742
+ exports.SchedulesPG = SchedulesPG;
13804
14743
  exports.ScorerDefinitionsPG = ScorerDefinitionsPG;
13805
14744
  exports.ScoresPG = ScoresPG;
13806
14745
  exports.SkillsPG = SkillsPG;