@mastra/pg 1.2.0 → 1.3.0-alpha.0

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 (40) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/docs/SKILL.md +28 -25
  3. package/dist/docs/{SOURCE_MAP.json → assets/SOURCE_MAP.json} +1 -1
  4. package/dist/docs/{memory/03-semantic-recall.md → references/docs-memory-semantic-recall.md} +33 -17
  5. package/dist/docs/{memory/01-storage.md → references/docs-memory-storage.md} +29 -39
  6. package/dist/docs/{memory/02-working-memory.md → references/docs-memory-working-memory.md} +16 -27
  7. package/dist/docs/{rag/01-overview.md → references/docs-rag-overview.md} +2 -4
  8. package/dist/docs/{rag/03-retrieval.md → references/docs-rag-retrieval.md} +26 -53
  9. package/dist/docs/{rag/02-vector-databases.md → references/docs-rag-vector-databases.md} +198 -202
  10. package/dist/docs/{memory/04-reference.md → references/reference-memory-memory-class.md} +28 -14
  11. package/dist/docs/references/reference-processors-message-history-processor.md +85 -0
  12. package/dist/docs/references/reference-processors-semantic-recall-processor.md +123 -0
  13. package/dist/docs/references/reference-processors-working-memory-processor.md +154 -0
  14. package/dist/docs/{rag/04-reference.md → references/reference-rag-metadata-filters.md} +26 -179
  15. package/dist/docs/references/reference-storage-composite.md +235 -0
  16. package/dist/docs/references/reference-storage-dynamodb.md +282 -0
  17. package/dist/docs/references/reference-storage-postgresql.md +529 -0
  18. package/dist/docs/{tools/01-reference.md → references/reference-tools-vector-query-tool.md} +137 -118
  19. package/dist/docs/{vectors/01-reference.md → references/reference-vectors-pg.md} +115 -14
  20. package/dist/index.cjs +1998 -217
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.js +1998 -219
  23. package/dist/index.js.map +1 -1
  24. package/dist/storage/db/constraint-utils.d.ts +16 -0
  25. package/dist/storage/db/constraint-utils.d.ts.map +1 -0
  26. package/dist/storage/db/index.d.ts.map +1 -1
  27. package/dist/storage/domains/agents/index.d.ts +9 -12
  28. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  29. package/dist/storage/domains/memory/index.d.ts +7 -1
  30. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  31. package/dist/storage/domains/prompt-blocks/index.d.ts +33 -0
  32. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -0
  33. package/dist/storage/domains/scorer-definitions/index.d.ts +33 -0
  34. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -0
  35. package/dist/storage/index.d.ts +3 -1
  36. package/dist/storage/index.d.ts.map +1 -1
  37. package/package.json +2 -3
  38. package/dist/docs/README.md +0 -36
  39. package/dist/docs/processors/01-reference.md +0 -296
  40. package/dist/docs/storage/01-reference.md +0 -905
package/dist/index.cjs CHANGED
@@ -9,6 +9,7 @@ var pg = require('pg');
9
9
  var xxhash = require('xxhash-wasm');
10
10
  var filter = require('@mastra/core/vector/filter');
11
11
  var base = require('@mastra/core/base');
12
+ var crypto$1 = require('crypto');
12
13
  var agent = require('@mastra/core/agent');
13
14
  var evals = require('@mastra/core/evals');
14
15
 
@@ -1906,6 +1907,32 @@ var TransactionClient = class {
1906
1907
  return Promise.all(promises);
1907
1908
  }
1908
1909
  };
1910
+
1911
+ // src/storage/db/constraint-utils.ts
1912
+ var POSTGRES_IDENTIFIER_MAX_LENGTH = 63;
1913
+ function truncateIdentifier(value, maxLength = POSTGRES_IDENTIFIER_MAX_LENGTH) {
1914
+ if (maxLength <= 0) return "";
1915
+ if (Buffer.byteLength(value, "utf-8") <= maxLength) return value;
1916
+ let bytes = 0;
1917
+ let end = 0;
1918
+ for (const ch of value) {
1919
+ const chBytes = Buffer.byteLength(ch, "utf-8");
1920
+ if (bytes + chBytes > maxLength) break;
1921
+ bytes += chBytes;
1922
+ end += ch.length;
1923
+ }
1924
+ return value.slice(0, end);
1925
+ }
1926
+ function buildConstraintName({
1927
+ baseName,
1928
+ schemaName,
1929
+ maxLength = POSTGRES_IDENTIFIER_MAX_LENGTH
1930
+ }) {
1931
+ const prefix = schemaName ? `${schemaName}_` : "";
1932
+ return truncateIdentifier(`${prefix}${baseName}`.toLowerCase(), maxLength);
1933
+ }
1934
+
1935
+ // src/storage/db/index.ts
1909
1936
  function resolvePgConfig(config) {
1910
1937
  if ("client" in config) {
1911
1938
  return {
@@ -1984,8 +2011,16 @@ function generateTableSQL({
1984
2011
  });
1985
2012
  const finalColumns = [...columns, ...timeZColumns].join(",\n");
1986
2013
  const parsedSchemaName = schemaName ? utils.parseSqlIdentifier(schemaName, "schema name") : "";
1987
- const constraintPrefix = parsedSchemaName ? `${parsedSchemaName}_` : "";
2014
+ const workflowSnapshotConstraint = buildConstraintName({
2015
+ baseName: "mastra_workflow_snapshot_workflow_name_run_id_key",
2016
+ schemaName: parsedSchemaName || void 0
2017
+ });
2018
+ const spansPrimaryKeyConstraint = buildConstraintName({
2019
+ baseName: "mastra_ai_spans_traceid_spanid_pk",
2020
+ schemaName: parsedSchemaName || void 0
2021
+ });
1988
2022
  const quotedSchemaName = getSchemaName(schemaName);
2023
+ const schemaFilter = parsedSchemaName || "public";
1989
2024
  const sql = `
1990
2025
  CREATE TABLE IF NOT EXISTS ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })} (
1991
2026
  ${finalColumns}
@@ -1993,12 +2028,12 @@ function generateTableSQL({
1993
2028
  ${tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? `
1994
2029
  DO $$ BEGIN
1995
2030
  IF NOT EXISTS (
1996
- SELECT 1 FROM pg_constraint WHERE conname = lower('${constraintPrefix}mastra_workflow_snapshot_workflow_name_run_id_key')
2031
+ SELECT 1 FROM pg_constraint WHERE conname = lower('${workflowSnapshotConstraint}') AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = '${schemaFilter}')
1997
2032
  ) AND NOT EXISTS (
1998
- SELECT 1 FROM pg_indexes WHERE indexname = lower('${constraintPrefix}mastra_workflow_snapshot_workflow_name_run_id_key')
2033
+ SELECT 1 FROM pg_indexes WHERE indexname = lower('${workflowSnapshotConstraint}') AND schemaname = '${schemaFilter}'
1999
2034
  ) THEN
2000
2035
  ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
2001
- ADD CONSTRAINT ${constraintPrefix}mastra_workflow_snapshot_workflow_name_run_id_key
2036
+ ADD CONSTRAINT ${workflowSnapshotConstraint}
2002
2037
  UNIQUE (workflow_name, run_id);
2003
2038
  END IF;
2004
2039
  END $$;
@@ -2007,10 +2042,10 @@ function generateTableSQL({
2007
2042
  tableName === storage.TABLE_SPANS && includeAllConstraints ? `
2008
2043
  DO $$ BEGIN
2009
2044
  IF NOT EXISTS (
2010
- SELECT 1 FROM pg_constraint WHERE conname = lower('${constraintPrefix}mastra_ai_spans_traceid_spanid_pk')
2045
+ SELECT 1 FROM pg_constraint WHERE conname = lower('${spansPrimaryKeyConstraint}') AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = '${schemaFilter}')
2011
2046
  ) THEN
2012
2047
  ALTER TABLE ${getTableName({ indexName: tableName, schemaName: quotedSchemaName })}
2013
- ADD CONSTRAINT ${constraintPrefix}mastra_ai_spans_traceid_spanid_pk
2048
+ ADD CONSTRAINT ${spansPrimaryKeyConstraint}
2014
2049
  PRIMARY KEY ("traceId", "spanId");
2015
2050
  END IF;
2016
2051
  END $$;
@@ -2496,11 +2531,14 @@ Note: This migration may take some time for large tables.
2496
2531
  */
2497
2532
  async spansPrimaryKeyExists() {
2498
2533
  const parsedSchemaName = this.schemaName ? utils.parseSqlIdentifier(this.schemaName, "schema name") : "";
2499
- const constraintPrefix = parsedSchemaName ? `${parsedSchemaName}_` : "";
2500
- const constraintName = `${constraintPrefix}mastra_ai_spans_traceid_spanid_pk`;
2534
+ const constraintName = buildConstraintName({
2535
+ baseName: "mastra_ai_spans_traceid_spanid_pk",
2536
+ schemaName: parsedSchemaName || void 0
2537
+ });
2538
+ const schemaFilter = this.schemaName || "public";
2501
2539
  const result = await this.client.oneOrNone(
2502
- `SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = $1) as exists`,
2503
- [constraintName]
2540
+ `SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = lower($1) AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = $2)) as exists`,
2541
+ [constraintName, schemaFilter]
2504
2542
  );
2505
2543
  return result?.exists ?? false;
2506
2544
  }
@@ -2511,16 +2549,19 @@ Note: This migration may take some time for large tables.
2511
2549
  async addSpansPrimaryKey() {
2512
2550
  const fullTableName = getTableName({ indexName: storage.TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
2513
2551
  const parsedSchemaName = this.schemaName ? utils.parseSqlIdentifier(this.schemaName, "schema name") : "";
2514
- const constraintPrefix = parsedSchemaName ? `${parsedSchemaName}_` : "";
2515
- const constraintName = `${constraintPrefix}mastra_ai_spans_traceid_spanid_pk`;
2552
+ const constraintName = buildConstraintName({
2553
+ baseName: "mastra_ai_spans_traceid_spanid_pk",
2554
+ schemaName: parsedSchemaName || void 0
2555
+ });
2556
+ const schemaFilter = this.schemaName || "public";
2516
2557
  try {
2517
2558
  const constraintExists = await this.client.oneOrNone(
2518
2559
  `
2519
2560
  SELECT EXISTS (
2520
- SELECT 1 FROM pg_constraint WHERE conname = $1
2561
+ SELECT 1 FROM pg_constraint WHERE conname = lower($1) AND connamespace = (SELECT oid FROM pg_namespace WHERE nspname = $2)
2521
2562
  ) as exists
2522
2563
  `,
2523
- [constraintName]
2564
+ [constraintName, schemaFilter]
2524
2565
  );
2525
2566
  if (constraintExists?.exists) {
2526
2567
  this.logger?.debug?.(`PRIMARY KEY constraint ${constraintName} already exists on ${fullTableName}`);
@@ -3152,6 +3193,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3152
3193
  schema: storage.TABLE_SCHEMAS[storage.TABLE_AGENTS],
3153
3194
  ifNotExists: ["status", "authorId"]
3154
3195
  });
3196
+ await this.#migrateToolsToJsonbFormat();
3155
3197
  await this.createDefaultIndexes();
3156
3198
  await this.createCustomIndexes();
3157
3199
  await this.#cleanupStaleDrafts();
@@ -3212,7 +3254,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3212
3254
  1,
3213
3255
  row.name ?? agentId,
3214
3256
  row.description ?? null,
3215
- row.instructions ?? "",
3257
+ this.serializeInstructions(row.instructions ?? ""),
3216
3258
  row.model ? JSON.stringify(row.model) : "{}",
3217
3259
  row.tools ? JSON.stringify(row.tools) : null,
3218
3260
  row.defaultOptions ? JSON.stringify(row.defaultOptions) : null,
@@ -3250,6 +3292,45 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3250
3292
  await this.#db.client.none(`DROP TABLE IF EXISTS ${fullVersionsTableName}`);
3251
3293
  await this.#db.client.none(`DROP TABLE IF EXISTS ${legacyTableName}`);
3252
3294
  }
3295
+ /**
3296
+ * Migrates the tools field from string[] format to JSONB format { "tool-key": { "description": "..." } }.
3297
+ * This handles the transition from the old format where tools were stored as an array of string keys
3298
+ * to the new format where tools can have per-agent description overrides.
3299
+ */
3300
+ async #migrateToolsToJsonbFormat() {
3301
+ const fullVersionsTableName = getTableName2({
3302
+ indexName: storage.TABLE_AGENT_VERSIONS,
3303
+ schemaName: getSchemaName2(this.#schema)
3304
+ });
3305
+ try {
3306
+ const recordsWithArrayTools = await this.#db.client.any(
3307
+ `SELECT id, tools FROM ${fullVersionsTableName}
3308
+ WHERE tools IS NOT NULL
3309
+ AND jsonb_typeof(tools) = 'array'`
3310
+ );
3311
+ if (recordsWithArrayTools.length === 0) {
3312
+ return;
3313
+ }
3314
+ for (const record of recordsWithArrayTools) {
3315
+ const toolsArray = record.tools;
3316
+ const toolsObject = {};
3317
+ for (const toolKey of toolsArray) {
3318
+ toolsObject[toolKey] = {};
3319
+ }
3320
+ await this.#db.client.none(
3321
+ `UPDATE ${fullVersionsTableName}
3322
+ SET tools = $1::jsonb
3323
+ WHERE id = $2`,
3324
+ [JSON.stringify(toolsObject), record.id]
3325
+ );
3326
+ }
3327
+ this.logger?.info?.(
3328
+ `Migrated ${recordsWithArrayTools.length} agent version(s) tools from array to object format`
3329
+ );
3330
+ } catch (error) {
3331
+ this.logger?.warn?.("Failed to migrate tools to JSONB format:", error);
3332
+ }
3333
+ }
3253
3334
  /**
3254
3335
  * Removes stale draft agent records that have no activeVersionId.
3255
3336
  * These are left behind when createAgent partially fails (inserts thin record
@@ -3287,6 +3368,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3287
3368
  try {
3288
3369
  return JSON.parse(value);
3289
3370
  } catch (error$1) {
3371
+ if (error$1 instanceof error.MastraError) throw error$1;
3290
3372
  const details = {
3291
3373
  value: value.length > 100 ? value.substring(0, 100) + "..." : value
3292
3374
  };
@@ -3316,7 +3398,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3316
3398
  updatedAt: row.updatedAtZ || row.updatedAt
3317
3399
  };
3318
3400
  }
3319
- async getAgentById({ id }) {
3401
+ async getById(id) {
3320
3402
  try {
3321
3403
  const tableName = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3322
3404
  const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
@@ -3325,6 +3407,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3325
3407
  }
3326
3408
  return this.parseRow(result);
3327
3409
  } catch (error$1) {
3410
+ if (error$1 instanceof error.MastraError) throw error$1;
3328
3411
  throw new error.MastraError(
3329
3412
  {
3330
3413
  id: storage.createStorageErrorId("PG", "GET_AGENT_BY_ID", "FAILED"),
@@ -3336,7 +3419,8 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3336
3419
  );
3337
3420
  }
3338
3421
  }
3339
- async createAgent({ agent }) {
3422
+ async create(input) {
3423
+ const { agent } = input;
3340
3424
  try {
3341
3425
  const agentsTable = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3342
3426
  const now = /* @__PURE__ */ new Date();
@@ -3380,6 +3464,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3380
3464
  updatedAt: now
3381
3465
  };
3382
3466
  } catch (error$1) {
3467
+ if (error$1 instanceof error.MastraError) throw error$1;
3383
3468
  try {
3384
3469
  const agentsTable = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3385
3470
  await this.#db.client.none(
@@ -3399,10 +3484,11 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3399
3484
  );
3400
3485
  }
3401
3486
  }
3402
- async updateAgent({ id, ...updates }) {
3487
+ async update(input) {
3488
+ const { id, ...updates } = input;
3403
3489
  try {
3404
3490
  const tableName = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3405
- const existingAgent = await this.getAgentById({ id });
3491
+ const existingAgent = await this.getById(id);
3406
3492
  if (!existingAgent) {
3407
3493
  throw new error.MastraError({
3408
3494
  id: storage.createStorageErrorId("PG", "UPDATE_AGENT", "NOT_FOUND"),
@@ -3449,12 +3535,15 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3449
3535
  createdAt: _createdAt,
3450
3536
  ...latestConfig
3451
3537
  } = latestVersion;
3538
+ const sanitizedConfigFields = Object.fromEntries(
3539
+ Object.entries(configFields).map(([key, value]) => [key, value === null ? void 0 : value])
3540
+ );
3452
3541
  const newConfig = {
3453
3542
  ...latestConfig,
3454
- ...configFields
3543
+ ...sanitizedConfigFields
3455
3544
  };
3456
3545
  const changedFields = configFieldNames.filter(
3457
- (field) => field in configFields && configFields[field] !== latestConfig[field]
3546
+ (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
3458
3547
  );
3459
3548
  if (changedFields.length > 0) {
3460
3549
  const newVersionId = crypto.randomUUID();
@@ -3496,7 +3585,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3496
3585
  values
3497
3586
  );
3498
3587
  }
3499
- const updatedAgent = await this.getAgentById({ id });
3588
+ const updatedAgent = await this.getById(id);
3500
3589
  if (!updatedAgent) {
3501
3590
  throw new error.MastraError({
3502
3591
  id: storage.createStorageErrorId("PG", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
@@ -3522,12 +3611,13 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3522
3611
  );
3523
3612
  }
3524
3613
  }
3525
- async deleteAgent({ id }) {
3614
+ async delete(id) {
3526
3615
  try {
3527
3616
  const tableName = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3528
- await this.deleteVersionsByAgentId(id);
3617
+ await this.deleteVersionsByParentId(id);
3529
3618
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
3530
3619
  } catch (error$1) {
3620
+ if (error$1 instanceof error.MastraError) throw error$1;
3531
3621
  throw new error.MastraError(
3532
3622
  {
3533
3623
  id: storage.createStorageErrorId("PG", "DELETE_AGENT", "FAILED"),
@@ -3539,7 +3629,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3539
3629
  );
3540
3630
  }
3541
3631
  }
3542
- async listAgents(args) {
3632
+ async list(args) {
3543
3633
  const { page = 0, perPage: perPageInput, orderBy } = args || {};
3544
3634
  const { field, direction } = this.parseOrderBy(orderBy);
3545
3635
  if (page < 0) {
@@ -3582,6 +3672,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3582
3672
  hasMore: perPageInput === false ? false : offset + perPage < total
3583
3673
  };
3584
3674
  } catch (error$1) {
3675
+ if (error$1 instanceof error.MastraError) throw error$1;
3585
3676
  throw new error.MastraError(
3586
3677
  {
3587
3678
  id: storage.createStorageErrorId("PG", "LIST_AGENTS", "FAILED"),
@@ -3592,124 +3683,6 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3592
3683
  );
3593
3684
  }
3594
3685
  }
3595
- async listAgentsResolved(args) {
3596
- const { page = 0, perPage: perPageInput, orderBy } = args || {};
3597
- const { field, direction } = this.parseOrderBy(orderBy);
3598
- if (page < 0) {
3599
- throw new error.MastraError(
3600
- {
3601
- id: storage.createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
3602
- domain: error.ErrorDomain.STORAGE,
3603
- category: error.ErrorCategory.USER,
3604
- details: { page }
3605
- },
3606
- new Error("page must be >= 0")
3607
- );
3608
- }
3609
- const perPage = storage.normalizePerPage(perPageInput, 100);
3610
- const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
3611
- try {
3612
- const agentsTableName = getTableName2({ indexName: storage.TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3613
- const versionsTableName = getTableName2({
3614
- indexName: storage.TABLE_AGENT_VERSIONS,
3615
- schemaName: getSchemaName2(this.#schema)
3616
- });
3617
- const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${agentsTableName}`);
3618
- const total = parseInt(countResult.count, 10);
3619
- if (total === 0) {
3620
- return {
3621
- agents: [],
3622
- total: 0,
3623
- page,
3624
- perPage: perPageForResponse,
3625
- hasMore: false
3626
- };
3627
- }
3628
- const limitValue = perPageInput === false ? total : perPage;
3629
- const query = `
3630
- WITH latest_versions AS (
3631
- SELECT v.*
3632
- FROM ${versionsTableName} v
3633
- INNER JOIN (
3634
- SELECT "agentId", MAX("versionNumber") as max_version
3635
- FROM ${versionsTableName}
3636
- GROUP BY "agentId"
3637
- ) lv ON v."agentId" = lv."agentId" AND v."versionNumber" = lv.max_version
3638
- )
3639
- SELECT
3640
- a.*,
3641
- COALESCE(av.id, lv.id) as version_id,
3642
- COALESCE(av."versionNumber", lv."versionNumber") as version_number,
3643
- COALESCE(av.name, lv.name) as version_name,
3644
- COALESCE(av.description, lv.description) as version_description,
3645
- COALESCE(av.instructions, lv.instructions) as version_instructions,
3646
- COALESCE(av.model, lv.model) as version_model,
3647
- COALESCE(av.tools, lv.tools) as version_tools,
3648
- COALESCE(av."defaultOptions", lv."defaultOptions") as version_defaultOptions,
3649
- COALESCE(av.workflows, lv.workflows) as version_workflows,
3650
- COALESCE(av.agents, lv.agents) as version_agents,
3651
- COALESCE(av."integrationTools", lv."integrationTools") as version_integrationTools,
3652
- COALESCE(av."inputProcessors", lv."inputProcessors") as version_inputProcessors,
3653
- COALESCE(av."outputProcessors", lv."outputProcessors") as version_outputProcessors,
3654
- COALESCE(av.memory, lv.memory) as version_memory,
3655
- COALESCE(av.scorers, lv.scorers) as version_scorers
3656
- FROM ${agentsTableName} a
3657
- LEFT JOIN ${versionsTableName} av ON a."activeVersionId" = av.id
3658
- LEFT JOIN latest_versions lv ON a.id = lv."agentId"
3659
- ORDER BY a."${field}" ${direction}
3660
- LIMIT $1 OFFSET $2
3661
- `;
3662
- const dataResult = await this.#db.client.manyOrNone(query, [limitValue, offset]);
3663
- const resolvedAgents = (dataResult || []).map((row) => {
3664
- const agent = this.parseRow({
3665
- id: row.id,
3666
- status: row.status,
3667
- activeVersionId: row.activeVersionId,
3668
- authorId: row.authorId,
3669
- metadata: row.metadata,
3670
- createdAt: row.createdAt,
3671
- createdAtZ: row.createdAtZ,
3672
- updatedAt: row.updatedAt,
3673
- updatedAtZ: row.updatedAtZ
3674
- });
3675
- if (row.version_id) {
3676
- return {
3677
- ...agent,
3678
- name: row.version_name,
3679
- description: row.version_description,
3680
- instructions: row.version_instructions,
3681
- model: this.parseJson(row.version_model, "model"),
3682
- tools: this.parseJson(row.version_tools, "tools"),
3683
- defaultOptions: this.parseJson(row.version_defaultOptions, "defaultOptions"),
3684
- workflows: this.parseJson(row.version_workflows, "workflows"),
3685
- agents: this.parseJson(row.version_agents, "agents"),
3686
- integrationTools: this.parseJson(row.version_integrationTools, "integrationTools"),
3687
- inputProcessors: this.parseJson(row.version_inputProcessors, "inputProcessors"),
3688
- outputProcessors: this.parseJson(row.version_outputProcessors, "outputProcessors"),
3689
- memory: this.parseJson(row.version_memory, "memory"),
3690
- scorers: this.parseJson(row.version_scorers, "scorers")
3691
- };
3692
- }
3693
- return agent;
3694
- });
3695
- return {
3696
- agents: resolvedAgents,
3697
- total,
3698
- page,
3699
- perPage: perPageForResponse,
3700
- hasMore: perPageInput === false ? false : offset + perPage < total
3701
- };
3702
- } catch (error$1) {
3703
- throw new error.MastraError(
3704
- {
3705
- id: storage.createStorageErrorId("PG", "LIST_AGENTS_RESOLVED", "FAILED"),
3706
- domain: error.ErrorDomain.STORAGE,
3707
- category: error.ErrorCategory.THIRD_PARTY
3708
- },
3709
- error$1
3710
- );
3711
- }
3712
- }
3713
3686
  // ==========================================================================
3714
3687
  // Agent Version Methods
3715
3688
  // ==========================================================================
@@ -3733,7 +3706,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3733
3706
  input.versionNumber,
3734
3707
  input.name,
3735
3708
  input.description ?? null,
3736
- input.instructions,
3709
+ this.serializeInstructions(input.instructions),
3737
3710
  JSON.stringify(input.model),
3738
3711
  input.tools ? JSON.stringify(input.tools) : null,
3739
3712
  input.defaultOptions ? JSON.stringify(input.defaultOptions) : null,
@@ -3755,6 +3728,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3755
3728
  createdAt: now
3756
3729
  };
3757
3730
  } catch (error$1) {
3731
+ if (error$1 instanceof error.MastraError) throw error$1;
3758
3732
  throw new error.MastraError(
3759
3733
  {
3760
3734
  id: storage.createStorageErrorId("PG", "CREATE_VERSION", "FAILED"),
@@ -3775,6 +3749,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3775
3749
  }
3776
3750
  return this.parseVersionRow(result);
3777
3751
  } catch (error$1) {
3752
+ if (error$1 instanceof error.MastraError) throw error$1;
3778
3753
  throw new error.MastraError(
3779
3754
  {
3780
3755
  id: storage.createStorageErrorId("PG", "GET_VERSION", "FAILED"),
@@ -3798,6 +3773,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3798
3773
  }
3799
3774
  return this.parseVersionRow(result);
3800
3775
  } catch (error$1) {
3776
+ if (error$1 instanceof error.MastraError) throw error$1;
3801
3777
  throw new error.MastraError(
3802
3778
  {
3803
3779
  id: storage.createStorageErrorId("PG", "GET_VERSION_BY_NUMBER", "FAILED"),
@@ -3821,6 +3797,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3821
3797
  }
3822
3798
  return this.parseVersionRow(result);
3823
3799
  } catch (error$1) {
3800
+ if (error$1 instanceof error.MastraError) throw error$1;
3824
3801
  throw new error.MastraError(
3825
3802
  {
3826
3803
  id: storage.createStorageErrorId("PG", "GET_LATEST_VERSION", "FAILED"),
@@ -3877,6 +3854,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3877
3854
  hasMore: perPageInput === false ? false : offset + perPage < total
3878
3855
  };
3879
3856
  } catch (error$1) {
3857
+ if (error$1 instanceof error.MastraError) throw error$1;
3880
3858
  throw new error.MastraError(
3881
3859
  {
3882
3860
  id: storage.createStorageErrorId("PG", "LIST_VERSIONS", "FAILED"),
@@ -3893,6 +3871,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3893
3871
  const tableName = getTableName2({ indexName: storage.TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3894
3872
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
3895
3873
  } catch (error$1) {
3874
+ if (error$1 instanceof error.MastraError) throw error$1;
3896
3875
  throw new error.MastraError(
3897
3876
  {
3898
3877
  id: storage.createStorageErrorId("PG", "DELETE_VERSION", "FAILED"),
@@ -3904,17 +3883,18 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3904
3883
  );
3905
3884
  }
3906
3885
  }
3907
- async deleteVersionsByAgentId(agentId) {
3886
+ async deleteVersionsByParentId(entityId) {
3908
3887
  try {
3909
3888
  const tableName = getTableName2({ indexName: storage.TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3910
- await this.#db.client.none(`DELETE FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
3889
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "agentId" = $1`, [entityId]);
3911
3890
  } catch (error$1) {
3891
+ if (error$1 instanceof error.MastraError) throw error$1;
3912
3892
  throw new error.MastraError(
3913
3893
  {
3914
3894
  id: storage.createStorageErrorId("PG", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
3915
3895
  domain: error.ErrorDomain.STORAGE,
3916
3896
  category: error.ErrorCategory.THIRD_PARTY,
3917
- details: { agentId }
3897
+ details: { agentId: entityId }
3918
3898
  },
3919
3899
  error$1
3920
3900
  );
@@ -3928,6 +3908,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3928
3908
  ]);
3929
3909
  return parseInt(result.count, 10);
3930
3910
  } catch (error$1) {
3911
+ if (error$1 instanceof error.MastraError) throw error$1;
3931
3912
  throw new error.MastraError(
3932
3913
  {
3933
3914
  id: storage.createStorageErrorId("PG", "COUNT_VERSIONS", "FAILED"),
@@ -3942,6 +3923,19 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3942
3923
  // ==========================================================================
3943
3924
  // Private Helper Methods
3944
3925
  // ==========================================================================
3926
+ serializeInstructions(instructions) {
3927
+ if (instructions == null) return void 0;
3928
+ return Array.isArray(instructions) ? JSON.stringify(instructions) : instructions;
3929
+ }
3930
+ deserializeInstructions(raw) {
3931
+ if (!raw) return "";
3932
+ try {
3933
+ const parsed = JSON.parse(raw);
3934
+ if (Array.isArray(parsed)) return parsed;
3935
+ } catch {
3936
+ }
3937
+ return raw;
3938
+ }
3945
3939
  parseVersionRow(row) {
3946
3940
  return {
3947
3941
  id: row.id,
@@ -3949,7 +3943,7 @@ var AgentsPG = class _AgentsPG extends storage.AgentsStorage {
3949
3943
  versionNumber: row.versionNumber,
3950
3944
  name: row.name,
3951
3945
  description: row.description,
3952
- instructions: row.instructions,
3946
+ instructions: this.deserializeInstructions(row.instructions),
3953
3947
  model: this.parseJson(row.model, "model"),
3954
3948
  tools: this.parseJson(row.tools, "tools"),
3955
3949
  defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
@@ -4008,6 +4002,25 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
4008
4002
  tableName: OM_TABLE,
4009
4003
  schema: omSchema
4010
4004
  });
4005
+ await this.#db.alterTable({
4006
+ tableName: OM_TABLE,
4007
+ schema: omSchema,
4008
+ ifNotExists: [
4009
+ "observedMessageIds",
4010
+ "observedTimezone",
4011
+ "bufferedObservations",
4012
+ "bufferedObservationTokens",
4013
+ "bufferedMessageIds",
4014
+ "bufferedReflection",
4015
+ "bufferedReflectionTokens",
4016
+ "bufferedReflectionInputTokens",
4017
+ "bufferedObservationChunks",
4018
+ "isBufferingObservation",
4019
+ "isBufferingReflection",
4020
+ "lastBufferedAtTokens",
4021
+ "lastBufferedAtTime"
4022
+ ]
4023
+ });
4011
4024
  }
4012
4025
  await this.#db.alterTable({
4013
4026
  tableName: storage.TABLE_MESSAGES,
@@ -5203,12 +5216,26 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5203
5216
  originType: row.originType || "initial",
5204
5217
  generationCount: Number(row.generationCount || 0),
5205
5218
  activeObservations: row.activeObservations || "",
5219
+ // Handle new chunk-based structure
5220
+ bufferedObservationChunks: row.bufferedObservationChunks ? typeof row.bufferedObservationChunks === "string" ? JSON.parse(row.bufferedObservationChunks) : row.bufferedObservationChunks : void 0,
5221
+ // Deprecated fields (for backward compatibility)
5206
5222
  bufferedObservations: row.activeObservationsPendingUpdate || void 0,
5223
+ bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
5224
+ bufferedMessageIds: void 0,
5225
+ // Use bufferedObservationChunks instead
5226
+ bufferedReflection: row.bufferedReflection || void 0,
5227
+ bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
5228
+ bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
5229
+ reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
5207
5230
  totalTokensObserved: Number(row.totalTokensObserved || 0),
5208
5231
  observationTokenCount: Number(row.observationTokenCount || 0),
5209
5232
  pendingMessageTokens: Number(row.pendingMessageTokens || 0),
5210
5233
  isReflecting: Boolean(row.isReflecting),
5211
5234
  isObserving: Boolean(row.isObserving),
5235
+ isBufferingObservation: row.isBufferingObservation === true || row.isBufferingObservation === "true",
5236
+ isBufferingReflection: row.isBufferingReflection === true || row.isBufferingReflection === "true",
5237
+ lastBufferedAtTokens: typeof row.lastBufferedAtTokens === "number" ? row.lastBufferedAtTokens : parseInt(String(row.lastBufferedAtTokens ?? "0"), 10) || 0,
5238
+ lastBufferedAtTime: row.lastBufferedAtTime ? new Date(String(row.lastBufferedAtTime)) : null,
5212
5239
  config: row.config ? typeof row.config === "string" ? JSON.parse(row.config) : row.config : {},
5213
5240
  metadata: row.metadata ? typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata : void 0,
5214
5241
  observedMessageIds: row.observedMessageIds ? typeof row.observedMessageIds === "string" ? JSON.parse(row.observedMessageIds) : row.observedMessageIds : void 0,
@@ -5286,6 +5313,10 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5286
5313
  pendingMessageTokens: 0,
5287
5314
  isReflecting: false,
5288
5315
  isObserving: false,
5316
+ isBufferingObservation: false,
5317
+ isBufferingReflection: false,
5318
+ lastBufferedAtTokens: 0,
5319
+ lastBufferedAtTime: null,
5289
5320
  config: input.config,
5290
5321
  observedTimezone: input.observedTimezone
5291
5322
  };
@@ -5300,8 +5331,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5300
5331
  "activeObservations", "activeObservationsPendingUpdate",
5301
5332
  "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
5302
5333
  "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
5303
- "isObserving", "isReflecting", "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
5304
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)`,
5334
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
5335
+ "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
5336
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)`,
5305
5337
  [
5306
5338
  id,
5307
5339
  lookupKey,
@@ -5326,6 +5358,14 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5326
5358
  0,
5327
5359
  false,
5328
5360
  false,
5361
+ false,
5362
+ // isBufferingObservation
5363
+ false,
5364
+ // isBufferingReflection
5365
+ 0,
5366
+ // lastBufferedAtTokens
5367
+ null,
5368
+ // lastBufferedAtTime
5329
5369
  input.observedTimezone || null,
5330
5370
  nowStr,
5331
5371
  // createdAt
@@ -5429,6 +5469,10 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5429
5469
  pendingMessageTokens: 0,
5430
5470
  isReflecting: false,
5431
5471
  isObserving: false,
5472
+ isBufferingObservation: false,
5473
+ isBufferingReflection: false,
5474
+ lastBufferedAtTokens: 0,
5475
+ lastBufferedAtTime: null,
5432
5476
  config: input.currentRecord.config,
5433
5477
  metadata: input.currentRecord.metadata,
5434
5478
  observedTimezone: input.currentRecord.observedTimezone
@@ -5445,8 +5489,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5445
5489
  "activeObservations", "activeObservationsPendingUpdate",
5446
5490
  "originType", config, "generationCount", "lastObservedAt", "lastObservedAtZ", "lastReflectionAt", "lastReflectionAtZ",
5447
5491
  "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
5448
- "isObserving", "isReflecting", "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
5449
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)`,
5492
+ "isObserving", "isReflecting", "isBufferingObservation", "isBufferingReflection", "lastBufferedAtTokens", "lastBufferedAtTime",
5493
+ "observedTimezone", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
5494
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)`,
5450
5495
  [
5451
5496
  id,
5452
5497
  lookupKey,
@@ -5470,7 +5515,17 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5470
5515
  record.totalTokensObserved,
5471
5516
  record.observationTokenCount,
5472
5517
  false,
5518
+ // isObserving
5473
5519
  false,
5520
+ // isReflecting
5521
+ false,
5522
+ // isBufferingObservation
5523
+ false,
5524
+ // isBufferingReflection
5525
+ 0,
5526
+ // lastBufferedAtTokens
5527
+ null,
5528
+ // lastBufferedAtTime
5474
5529
  record.observedTimezone || null,
5475
5530
  nowStr,
5476
5531
  // createdAt
@@ -5565,6 +5620,82 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5565
5620
  );
5566
5621
  }
5567
5622
  }
5623
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
5624
+ try {
5625
+ const tableName = getTableName3({
5626
+ indexName: OM_TABLE,
5627
+ schemaName: getSchemaName3(this.#schema)
5628
+ });
5629
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
5630
+ let query;
5631
+ let values;
5632
+ if (lastBufferedAtTokens !== void 0) {
5633
+ query = `UPDATE ${tableName} SET "isBufferingObservation" = $1, "lastBufferedAtTokens" = $2, "updatedAt" = $3, "updatedAtZ" = $4 WHERE id = $5`;
5634
+ values = [isBuffering, lastBufferedAtTokens, nowStr, nowStr, id];
5635
+ } else {
5636
+ query = `UPDATE ${tableName} SET "isBufferingObservation" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`;
5637
+ values = [isBuffering, nowStr, nowStr, id];
5638
+ }
5639
+ const result = await this.#db.client.query(query, values);
5640
+ if (result.rowCount === 0) {
5641
+ throw new error.MastraError({
5642
+ id: storage.createStorageErrorId("PG", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
5643
+ text: `Observational memory record not found: ${id}`,
5644
+ domain: error.ErrorDomain.STORAGE,
5645
+ category: error.ErrorCategory.THIRD_PARTY,
5646
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
5647
+ });
5648
+ }
5649
+ } catch (error$1) {
5650
+ if (error$1 instanceof error.MastraError) {
5651
+ throw error$1;
5652
+ }
5653
+ throw new error.MastraError(
5654
+ {
5655
+ id: storage.createStorageErrorId("PG", "SET_BUFFERING_OBSERVATION_FLAG", "FAILED"),
5656
+ domain: error.ErrorDomain.STORAGE,
5657
+ category: error.ErrorCategory.THIRD_PARTY,
5658
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
5659
+ },
5660
+ error$1
5661
+ );
5662
+ }
5663
+ }
5664
+ async setBufferingReflectionFlag(id, isBuffering) {
5665
+ try {
5666
+ const tableName = getTableName3({
5667
+ indexName: OM_TABLE,
5668
+ schemaName: getSchemaName3(this.#schema)
5669
+ });
5670
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
5671
+ const result = await this.#db.client.query(
5672
+ `UPDATE ${tableName} SET "isBufferingReflection" = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`,
5673
+ [isBuffering, nowStr, nowStr, id]
5674
+ );
5675
+ if (result.rowCount === 0) {
5676
+ throw new error.MastraError({
5677
+ id: storage.createStorageErrorId("PG", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
5678
+ text: `Observational memory record not found: ${id}`,
5679
+ domain: error.ErrorDomain.STORAGE,
5680
+ category: error.ErrorCategory.THIRD_PARTY,
5681
+ details: { id, isBuffering }
5682
+ });
5683
+ }
5684
+ } catch (error$1) {
5685
+ if (error$1 instanceof error.MastraError) {
5686
+ throw error$1;
5687
+ }
5688
+ throw new error.MastraError(
5689
+ {
5690
+ id: storage.createStorageErrorId("PG", "SET_BUFFERING_REFLECTION_FLAG", "FAILED"),
5691
+ domain: error.ErrorDomain.STORAGE,
5692
+ category: error.ErrorCategory.THIRD_PARTY,
5693
+ details: { id, isBuffering }
5694
+ },
5695
+ error$1
5696
+ );
5697
+ }
5698
+ }
5568
5699
  async clearObservationalMemory(threadId, resourceId) {
5569
5700
  try {
5570
5701
  const lookupKey = this.getOMKey(threadId, resourceId);
@@ -5624,71 +5755,385 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
5624
5755
  );
5625
5756
  }
5626
5757
  }
5627
- };
5628
- var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorage {
5629
- #db;
5630
- #schema;
5631
- #skipDefaultIndexes;
5632
- #indexes;
5633
- /** Tables managed by this domain */
5634
- static MANAGED_TABLES = [storage.TABLE_SPANS];
5635
- constructor(config) {
5636
- super();
5637
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5638
- this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
5639
- this.#schema = schemaName || "public";
5640
- this.#skipDefaultIndexes = skipDefaultIndexes;
5641
- this.#indexes = indexes?.filter((idx) => _ObservabilityPG.MANAGED_TABLES.includes(idx.table));
5642
- }
5643
- async init() {
5644
- await this.#db.createTable({ tableName: storage.TABLE_SPANS, schema: storage.TABLE_SCHEMAS[storage.TABLE_SPANS] });
5645
- await this.createDefaultIndexes();
5646
- await this.createCustomIndexes();
5758
+ // ============================================
5759
+ // Async Buffering Methods
5760
+ // ============================================
5761
+ async updateBufferedObservations(input) {
5762
+ try {
5763
+ const tableName = getTableName3({
5764
+ indexName: OM_TABLE,
5765
+ schemaName: getSchemaName3(this.#schema)
5766
+ });
5767
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
5768
+ const newChunk = {
5769
+ id: `ombuf-${crypto$1.randomUUID()}`,
5770
+ cycleId: input.chunk.cycleId,
5771
+ observations: input.chunk.observations,
5772
+ tokenCount: input.chunk.tokenCount,
5773
+ messageIds: input.chunk.messageIds,
5774
+ messageTokens: input.chunk.messageTokens,
5775
+ lastObservedAt: input.chunk.lastObservedAt,
5776
+ createdAt: /* @__PURE__ */ new Date(),
5777
+ suggestedContinuation: input.chunk.suggestedContinuation,
5778
+ currentTask: input.chunk.currentTask
5779
+ };
5780
+ const lastBufferedAtTime = input.lastBufferedAtTime ? input.lastBufferedAtTime.toISOString() : null;
5781
+ const result = await this.#db.client.query(
5782
+ `UPDATE ${tableName} SET
5783
+ "bufferedObservationChunks" = COALESCE("bufferedObservationChunks", '[]'::jsonb) || $1::jsonb,
5784
+ "lastBufferedAtTime" = COALESCE($2, "lastBufferedAtTime"),
5785
+ "updatedAt" = $3,
5786
+ "updatedAtZ" = $4
5787
+ WHERE id = $5`,
5788
+ [JSON.stringify([newChunk]), lastBufferedAtTime, nowStr, nowStr, input.id]
5789
+ );
5790
+ if (result.rowCount === 0) {
5791
+ throw new error.MastraError({
5792
+ id: storage.createStorageErrorId("PG", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
5793
+ text: `Observational memory record not found: ${input.id}`,
5794
+ domain: error.ErrorDomain.STORAGE,
5795
+ category: error.ErrorCategory.THIRD_PARTY,
5796
+ details: { id: input.id }
5797
+ });
5798
+ }
5799
+ } catch (error$1) {
5800
+ if (error$1 instanceof error.MastraError) {
5801
+ throw error$1;
5802
+ }
5803
+ throw new error.MastraError(
5804
+ {
5805
+ id: storage.createStorageErrorId("PG", "UPDATE_BUFFERED_OBSERVATIONS", "FAILED"),
5806
+ domain: error.ErrorDomain.STORAGE,
5807
+ category: error.ErrorCategory.THIRD_PARTY,
5808
+ details: { id: input.id }
5809
+ },
5810
+ error$1
5811
+ );
5812
+ }
5647
5813
  }
5648
- /**
5649
- * Returns default index definitions for the observability domain tables.
5650
- */
5651
- getDefaultIndexDefinitions() {
5652
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
5653
- return [
5654
- {
5655
- name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
5656
- table: storage.TABLE_SPANS,
5657
- columns: ["traceId", "startedAt DESC"]
5658
- },
5659
- {
5660
- name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
5661
- table: storage.TABLE_SPANS,
5662
- columns: ["parentSpanId", "startedAt DESC"]
5663
- },
5664
- {
5665
- name: `${schemaPrefix}mastra_ai_spans_name_idx`,
5666
- table: storage.TABLE_SPANS,
5667
- columns: ["name"]
5668
- },
5669
- {
5670
- name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
5671
- table: storage.TABLE_SPANS,
5672
- columns: ["spanType", "startedAt DESC"]
5673
- },
5674
- // Root spans partial index - every listTraces query filters parentSpanId IS NULL
5675
- {
5676
- name: `${schemaPrefix}mastra_ai_spans_root_spans_idx`,
5677
- table: storage.TABLE_SPANS,
5678
- columns: ["startedAt DESC"],
5679
- where: '"parentSpanId" IS NULL'
5680
- },
5681
- // Entity identification indexes - common filtering patterns
5682
- {
5683
- name: `${schemaPrefix}mastra_ai_spans_entitytype_entityid_idx`,
5684
- table: storage.TABLE_SPANS,
5685
- columns: ["entityType", "entityId"]
5686
- },
5687
- {
5688
- name: `${schemaPrefix}mastra_ai_spans_entitytype_entityname_idx`,
5689
- table: storage.TABLE_SPANS,
5690
- columns: ["entityType", "entityName"]
5691
- },
5814
+ async swapBufferedToActive(input) {
5815
+ try {
5816
+ const tableName = getTableName3({
5817
+ indexName: OM_TABLE,
5818
+ schemaName: getSchemaName3(this.#schema)
5819
+ });
5820
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
5821
+ const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [input.id]);
5822
+ if (!record) {
5823
+ throw new error.MastraError({
5824
+ id: storage.createStorageErrorId("PG", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
5825
+ text: `Observational memory record not found: ${input.id}`,
5826
+ domain: error.ErrorDomain.STORAGE,
5827
+ category: error.ErrorCategory.THIRD_PARTY,
5828
+ details: { id: input.id }
5829
+ });
5830
+ }
5831
+ let chunks = [];
5832
+ if (record.bufferedObservationChunks) {
5833
+ try {
5834
+ const parsed = typeof record.bufferedObservationChunks === "string" ? JSON.parse(record.bufferedObservationChunks) : record.bufferedObservationChunks;
5835
+ chunks = Array.isArray(parsed) ? parsed : [];
5836
+ } catch {
5837
+ chunks = [];
5838
+ }
5839
+ }
5840
+ if (chunks.length === 0) {
5841
+ return {
5842
+ chunksActivated: 0,
5843
+ messageTokensActivated: 0,
5844
+ observationTokensActivated: 0,
5845
+ messagesActivated: 0,
5846
+ activatedCycleIds: [],
5847
+ activatedMessageIds: []
5848
+ };
5849
+ }
5850
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
5851
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
5852
+ let cumulativeMessageTokens = 0;
5853
+ let chunksToActivate = 0;
5854
+ let bestBoundary = 0;
5855
+ let bestBoundaryMessageTokens = 0;
5856
+ for (let i = 0; i < chunks.length; i++) {
5857
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
5858
+ const boundary = i + 1;
5859
+ const isUnder = cumulativeMessageTokens <= targetMessageTokens;
5860
+ const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
5861
+ if (bestBoundary === 0) {
5862
+ bestBoundary = boundary;
5863
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
5864
+ } else if (isUnder && !bestIsUnder) {
5865
+ bestBoundary = boundary;
5866
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
5867
+ } else if (isUnder && bestIsUnder) {
5868
+ if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
5869
+ bestBoundary = boundary;
5870
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
5871
+ }
5872
+ } else if (!isUnder && !bestIsUnder) {
5873
+ if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
5874
+ bestBoundary = boundary;
5875
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
5876
+ }
5877
+ }
5878
+ }
5879
+ chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
5880
+ const activatedChunks = chunks.slice(0, chunksToActivate);
5881
+ const remainingChunks = chunks.slice(chunksToActivate);
5882
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
5883
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
5884
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
5885
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
5886
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
5887
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
5888
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
5889
+ const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
5890
+ const lastObservedAtStr = lastObservedAt.toISOString();
5891
+ await this.#db.client.query(
5892
+ `UPDATE ${tableName} SET
5893
+ "activeObservations" = CASE
5894
+ WHEN "activeObservations" IS NOT NULL AND "activeObservations" != ''
5895
+ THEN "activeObservations" || E'\\n\\n' || $1
5896
+ ELSE $1
5897
+ END,
5898
+ "observationTokenCount" = COALESCE("observationTokenCount", 0) + $2,
5899
+ "pendingMessageTokens" = GREATEST(0, COALESCE("pendingMessageTokens", 0) - $3),
5900
+ "bufferedObservationChunks" = $4,
5901
+ "lastObservedAt" = $5,
5902
+ "lastObservedAtZ" = $6,
5903
+ "updatedAt" = $7,
5904
+ "updatedAtZ" = $8
5905
+ WHERE id = $9`,
5906
+ [
5907
+ activatedContent,
5908
+ activatedTokens,
5909
+ activatedMessageTokens,
5910
+ remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
5911
+ lastObservedAtStr,
5912
+ lastObservedAtStr,
5913
+ nowStr,
5914
+ nowStr,
5915
+ input.id
5916
+ ]
5917
+ );
5918
+ return {
5919
+ chunksActivated: activatedChunks.length,
5920
+ messageTokensActivated: activatedMessageTokens,
5921
+ observationTokensActivated: activatedTokens,
5922
+ messagesActivated: activatedMessageCount,
5923
+ activatedCycleIds,
5924
+ activatedMessageIds,
5925
+ observations: activatedContent,
5926
+ perChunk: activatedChunks.map((c) => ({
5927
+ cycleId: c.cycleId ?? "",
5928
+ messageTokens: c.messageTokens ?? 0,
5929
+ observationTokens: c.tokenCount,
5930
+ messageCount: c.messageIds.length,
5931
+ observations: c.observations
5932
+ }))
5933
+ };
5934
+ } catch (error$1) {
5935
+ if (error$1 instanceof error.MastraError) {
5936
+ throw error$1;
5937
+ }
5938
+ throw new error.MastraError(
5939
+ {
5940
+ id: storage.createStorageErrorId("PG", "SWAP_BUFFERED_TO_ACTIVE", "FAILED"),
5941
+ domain: error.ErrorDomain.STORAGE,
5942
+ category: error.ErrorCategory.THIRD_PARTY,
5943
+ details: { id: input.id }
5944
+ },
5945
+ error$1
5946
+ );
5947
+ }
5948
+ }
5949
+ async updateBufferedReflection(input) {
5950
+ try {
5951
+ const tableName = getTableName3({
5952
+ indexName: OM_TABLE,
5953
+ schemaName: getSchemaName3(this.#schema)
5954
+ });
5955
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
5956
+ const result = await this.#db.client.query(
5957
+ `UPDATE ${tableName} SET
5958
+ "bufferedReflection" = CASE
5959
+ WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
5960
+ THEN "bufferedReflection" || E'\\n\\n' || $1
5961
+ ELSE $1
5962
+ END,
5963
+ "bufferedReflectionTokens" = COALESCE("bufferedReflectionTokens", 0) + $2,
5964
+ "bufferedReflectionInputTokens" = COALESCE("bufferedReflectionInputTokens", 0) + $3,
5965
+ "reflectedObservationLineCount" = $4,
5966
+ "updatedAt" = $5,
5967
+ "updatedAtZ" = $6
5968
+ WHERE id = $7`,
5969
+ [
5970
+ input.reflection,
5971
+ input.tokenCount,
5972
+ input.inputTokenCount,
5973
+ input.reflectedObservationLineCount,
5974
+ nowStr,
5975
+ nowStr,
5976
+ input.id
5977
+ ]
5978
+ );
5979
+ if (result.rowCount === 0) {
5980
+ throw new error.MastraError({
5981
+ id: storage.createStorageErrorId("PG", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
5982
+ text: `Observational memory record not found: ${input.id}`,
5983
+ domain: error.ErrorDomain.STORAGE,
5984
+ category: error.ErrorCategory.THIRD_PARTY,
5985
+ details: { id: input.id }
5986
+ });
5987
+ }
5988
+ } catch (error$1) {
5989
+ if (error$1 instanceof error.MastraError) {
5990
+ throw error$1;
5991
+ }
5992
+ throw new error.MastraError(
5993
+ {
5994
+ id: storage.createStorageErrorId("PG", "UPDATE_BUFFERED_REFLECTION", "FAILED"),
5995
+ domain: error.ErrorDomain.STORAGE,
5996
+ category: error.ErrorCategory.THIRD_PARTY,
5997
+ details: { id: input.id }
5998
+ },
5999
+ error$1
6000
+ );
6001
+ }
6002
+ }
6003
+ async swapBufferedReflectionToActive(input) {
6004
+ try {
6005
+ const tableName = getTableName3({
6006
+ indexName: OM_TABLE,
6007
+ schemaName: getSchemaName3(this.#schema)
6008
+ });
6009
+ const record = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [
6010
+ input.currentRecord.id
6011
+ ]);
6012
+ if (!record) {
6013
+ throw new error.MastraError({
6014
+ id: storage.createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
6015
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
6016
+ domain: error.ErrorDomain.STORAGE,
6017
+ category: error.ErrorCategory.THIRD_PARTY,
6018
+ details: { id: input.currentRecord.id }
6019
+ });
6020
+ }
6021
+ const bufferedReflection = record.bufferedReflection || "";
6022
+ const reflectedLineCount = Number(record.reflectedObservationLineCount || 0);
6023
+ if (!bufferedReflection) {
6024
+ throw new error.MastraError({
6025
+ id: storage.createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
6026
+ text: "No buffered reflection to swap",
6027
+ domain: error.ErrorDomain.STORAGE,
6028
+ category: error.ErrorCategory.USER,
6029
+ details: { id: input.currentRecord.id }
6030
+ });
6031
+ }
6032
+ const currentObservations = record.activeObservations || "";
6033
+ const allLines = currentObservations.split("\n");
6034
+ const unreflectedLines = allLines.slice(reflectedLineCount);
6035
+ const unreflectedContent = unreflectedLines.join("\n").trim();
6036
+ const newObservations = unreflectedContent ? `${bufferedReflection}
6037
+
6038
+ ${unreflectedContent}` : bufferedReflection;
6039
+ const newRecord = await this.createReflectionGeneration({
6040
+ currentRecord: input.currentRecord,
6041
+ reflection: newObservations,
6042
+ tokenCount: input.tokenCount
6043
+ });
6044
+ const nowStr = (/* @__PURE__ */ new Date()).toISOString();
6045
+ await this.#db.client.query(
6046
+ `UPDATE ${tableName} SET
6047
+ "bufferedReflection" = NULL,
6048
+ "bufferedReflectionTokens" = NULL,
6049
+ "bufferedReflectionInputTokens" = NULL,
6050
+ "reflectedObservationLineCount" = NULL,
6051
+ "updatedAt" = $1,
6052
+ "updatedAtZ" = $2
6053
+ WHERE id = $3`,
6054
+ [nowStr, nowStr, input.currentRecord.id]
6055
+ );
6056
+ return newRecord;
6057
+ } catch (error$1) {
6058
+ if (error$1 instanceof error.MastraError) {
6059
+ throw error$1;
6060
+ }
6061
+ throw new error.MastraError(
6062
+ {
6063
+ id: storage.createStorageErrorId("PG", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "FAILED"),
6064
+ domain: error.ErrorDomain.STORAGE,
6065
+ category: error.ErrorCategory.THIRD_PARTY,
6066
+ details: { id: input.currentRecord.id }
6067
+ },
6068
+ error$1
6069
+ );
6070
+ }
6071
+ }
6072
+ };
6073
+ var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorage {
6074
+ #db;
6075
+ #schema;
6076
+ #skipDefaultIndexes;
6077
+ #indexes;
6078
+ /** Tables managed by this domain */
6079
+ static MANAGED_TABLES = [storage.TABLE_SPANS];
6080
+ constructor(config) {
6081
+ super();
6082
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6083
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
6084
+ this.#schema = schemaName || "public";
6085
+ this.#skipDefaultIndexes = skipDefaultIndexes;
6086
+ this.#indexes = indexes?.filter((idx) => _ObservabilityPG.MANAGED_TABLES.includes(idx.table));
6087
+ }
6088
+ async init() {
6089
+ await this.#db.createTable({ tableName: storage.TABLE_SPANS, schema: storage.TABLE_SCHEMAS[storage.TABLE_SPANS] });
6090
+ await this.createDefaultIndexes();
6091
+ await this.createCustomIndexes();
6092
+ }
6093
+ /**
6094
+ * Returns default index definitions for the observability domain tables.
6095
+ */
6096
+ getDefaultIndexDefinitions() {
6097
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
6098
+ return [
6099
+ {
6100
+ name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
6101
+ table: storage.TABLE_SPANS,
6102
+ columns: ["traceId", "startedAt DESC"]
6103
+ },
6104
+ {
6105
+ name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
6106
+ table: storage.TABLE_SPANS,
6107
+ columns: ["parentSpanId", "startedAt DESC"]
6108
+ },
6109
+ {
6110
+ name: `${schemaPrefix}mastra_ai_spans_name_idx`,
6111
+ table: storage.TABLE_SPANS,
6112
+ columns: ["name"]
6113
+ },
6114
+ {
6115
+ name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
6116
+ table: storage.TABLE_SPANS,
6117
+ columns: ["spanType", "startedAt DESC"]
6118
+ },
6119
+ // Root spans partial index - every listTraces query filters parentSpanId IS NULL
6120
+ {
6121
+ name: `${schemaPrefix}mastra_ai_spans_root_spans_idx`,
6122
+ table: storage.TABLE_SPANS,
6123
+ columns: ["startedAt DESC"],
6124
+ where: '"parentSpanId" IS NULL'
6125
+ },
6126
+ // Entity identification indexes - common filtering patterns
6127
+ {
6128
+ name: `${schemaPrefix}mastra_ai_spans_entitytype_entityid_idx`,
6129
+ table: storage.TABLE_SPANS,
6130
+ columns: ["entityType", "entityId"]
6131
+ },
6132
+ {
6133
+ name: `${schemaPrefix}mastra_ai_spans_entitytype_entityname_idx`,
6134
+ table: storage.TABLE_SPANS,
6135
+ columns: ["entityType", "entityName"]
6136
+ },
5692
6137
  // Multi-tenant filtering - organizationId + userId
5693
6138
  {
5694
6139
  name: `${schemaPrefix}mastra_ai_spans_orgid_userid_idx`,
@@ -6239,6 +6684,1338 @@ var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorag
6239
6684
  }
6240
6685
  }
6241
6686
  };
6687
+ var SNAPSHOT_FIELDS = ["name", "description", "content", "rules"];
6688
+ var PromptBlocksPG = class _PromptBlocksPG extends storage.PromptBlocksStorage {
6689
+ #db;
6690
+ #schema;
6691
+ #skipDefaultIndexes;
6692
+ #indexes;
6693
+ static MANAGED_TABLES = [storage.TABLE_PROMPT_BLOCKS, storage.TABLE_PROMPT_BLOCK_VERSIONS];
6694
+ constructor(config) {
6695
+ super();
6696
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6697
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
6698
+ this.#schema = schemaName || "public";
6699
+ this.#skipDefaultIndexes = skipDefaultIndexes;
6700
+ this.#indexes = indexes?.filter((idx) => _PromptBlocksPG.MANAGED_TABLES.includes(idx.table));
6701
+ }
6702
+ getDefaultIndexDefinitions() {
6703
+ return [
6704
+ {
6705
+ name: "idx_prompt_block_versions_block_version",
6706
+ table: storage.TABLE_PROMPT_BLOCK_VERSIONS,
6707
+ columns: ["blockId", "versionNumber"],
6708
+ unique: true
6709
+ }
6710
+ ];
6711
+ }
6712
+ async createDefaultIndexes() {
6713
+ if (this.#skipDefaultIndexes) {
6714
+ return;
6715
+ }
6716
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
6717
+ try {
6718
+ await this.#db.createIndex(indexDef);
6719
+ } catch {
6720
+ }
6721
+ }
6722
+ }
6723
+ async init() {
6724
+ await this.#db.createTable({ tableName: storage.TABLE_PROMPT_BLOCKS, schema: storage.TABLE_SCHEMAS[storage.TABLE_PROMPT_BLOCKS] });
6725
+ await this.#db.createTable({
6726
+ tableName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
6727
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_PROMPT_BLOCK_VERSIONS]
6728
+ });
6729
+ await this.createDefaultIndexes();
6730
+ await this.createCustomIndexes();
6731
+ }
6732
+ async createCustomIndexes() {
6733
+ if (!this.#indexes || this.#indexes.length === 0) {
6734
+ return;
6735
+ }
6736
+ for (const indexDef of this.#indexes) {
6737
+ try {
6738
+ await this.#db.createIndex(indexDef);
6739
+ } catch (error) {
6740
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
6741
+ }
6742
+ }
6743
+ }
6744
+ async dangerouslyClearAll() {
6745
+ await this.#db.clearTable({ tableName: storage.TABLE_PROMPT_BLOCK_VERSIONS });
6746
+ await this.#db.clearTable({ tableName: storage.TABLE_PROMPT_BLOCKS });
6747
+ }
6748
+ // ==========================================================================
6749
+ // Prompt Block CRUD Methods
6750
+ // ==========================================================================
6751
+ async getById(id) {
6752
+ try {
6753
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6754
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
6755
+ if (!result) {
6756
+ return null;
6757
+ }
6758
+ return this.parseBlockRow(result);
6759
+ } catch (error$1) {
6760
+ if (error$1 instanceof error.MastraError) throw error$1;
6761
+ throw new error.MastraError(
6762
+ {
6763
+ id: storage.createStorageErrorId("PG", "GET_PROMPT_BLOCK_BY_ID", "FAILED"),
6764
+ domain: error.ErrorDomain.STORAGE,
6765
+ category: error.ErrorCategory.THIRD_PARTY,
6766
+ details: { blockId: id }
6767
+ },
6768
+ error$1
6769
+ );
6770
+ }
6771
+ }
6772
+ async create(input) {
6773
+ const { promptBlock } = input;
6774
+ try {
6775
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6776
+ const now = /* @__PURE__ */ new Date();
6777
+ const nowIso = now.toISOString();
6778
+ await this.#db.client.none(
6779
+ `INSERT INTO ${tableName} (
6780
+ id, status, "activeVersionId", "authorId", metadata,
6781
+ "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
6782
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
6783
+ [
6784
+ promptBlock.id,
6785
+ "draft",
6786
+ null,
6787
+ promptBlock.authorId ?? null,
6788
+ promptBlock.metadata ? JSON.stringify(promptBlock.metadata) : null,
6789
+ nowIso,
6790
+ nowIso,
6791
+ nowIso,
6792
+ nowIso
6793
+ ]
6794
+ );
6795
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = promptBlock;
6796
+ const versionId = crypto.randomUUID();
6797
+ await this.createVersion({
6798
+ id: versionId,
6799
+ blockId: promptBlock.id,
6800
+ versionNumber: 1,
6801
+ ...snapshotConfig,
6802
+ changedFields: [...SNAPSHOT_FIELDS],
6803
+ changeMessage: "Initial version"
6804
+ });
6805
+ return {
6806
+ id: promptBlock.id,
6807
+ status: "draft",
6808
+ activeVersionId: void 0,
6809
+ authorId: promptBlock.authorId,
6810
+ metadata: promptBlock.metadata,
6811
+ createdAt: now,
6812
+ updatedAt: now
6813
+ };
6814
+ } catch (error$1) {
6815
+ if (error$1 instanceof error.MastraError) throw error$1;
6816
+ try {
6817
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6818
+ await this.#db.client.none(
6819
+ `DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
6820
+ [promptBlock.id]
6821
+ );
6822
+ } catch {
6823
+ }
6824
+ throw new error.MastraError(
6825
+ {
6826
+ id: storage.createStorageErrorId("PG", "CREATE_PROMPT_BLOCK", "FAILED"),
6827
+ domain: error.ErrorDomain.STORAGE,
6828
+ category: error.ErrorCategory.THIRD_PARTY,
6829
+ details: { blockId: promptBlock.id }
6830
+ },
6831
+ error$1
6832
+ );
6833
+ }
6834
+ }
6835
+ async update(input) {
6836
+ const { id, ...updates } = input;
6837
+ try {
6838
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6839
+ const existingBlock = await this.getById(id);
6840
+ if (!existingBlock) {
6841
+ throw new error.MastraError({
6842
+ id: storage.createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
6843
+ domain: error.ErrorDomain.STORAGE,
6844
+ category: error.ErrorCategory.USER,
6845
+ text: `Prompt block ${id} not found`,
6846
+ details: { blockId: id }
6847
+ });
6848
+ }
6849
+ const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
6850
+ let versionCreated = false;
6851
+ const hasConfigUpdate = SNAPSHOT_FIELDS.some((field) => field in configFields);
6852
+ if (hasConfigUpdate) {
6853
+ const latestVersion = await this.getLatestVersion(id);
6854
+ if (!latestVersion) {
6855
+ throw new error.MastraError({
6856
+ id: storage.createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NO_VERSIONS"),
6857
+ domain: error.ErrorDomain.STORAGE,
6858
+ category: error.ErrorCategory.SYSTEM,
6859
+ text: `No versions found for prompt block ${id}`,
6860
+ details: { blockId: id }
6861
+ });
6862
+ }
6863
+ const {
6864
+ id: _versionId,
6865
+ blockId: _blockId,
6866
+ versionNumber: _versionNumber,
6867
+ changedFields: _changedFields,
6868
+ changeMessage: _changeMessage,
6869
+ createdAt: _createdAt,
6870
+ ...latestConfig
6871
+ } = latestVersion;
6872
+ const newConfig = { ...latestConfig, ...configFields };
6873
+ const changedFields = SNAPSHOT_FIELDS.filter(
6874
+ (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
6875
+ );
6876
+ if (changedFields.length > 0) {
6877
+ versionCreated = true;
6878
+ const newVersionId = crypto.randomUUID();
6879
+ await this.createVersion({
6880
+ id: newVersionId,
6881
+ blockId: id,
6882
+ versionNumber: latestVersion.versionNumber + 1,
6883
+ ...newConfig,
6884
+ changedFields: [...changedFields],
6885
+ changeMessage: `Updated ${changedFields.join(", ")}`
6886
+ });
6887
+ }
6888
+ }
6889
+ const setClauses = [];
6890
+ const values = [];
6891
+ let paramIndex = 1;
6892
+ if (authorId !== void 0) {
6893
+ setClauses.push(`"authorId" = $${paramIndex++}`);
6894
+ values.push(authorId);
6895
+ }
6896
+ if (activeVersionId !== void 0) {
6897
+ setClauses.push(`"activeVersionId" = $${paramIndex++}`);
6898
+ values.push(activeVersionId);
6899
+ if (status === void 0) {
6900
+ setClauses.push(`status = $${paramIndex++}`);
6901
+ values.push("published");
6902
+ }
6903
+ }
6904
+ if (status !== void 0) {
6905
+ setClauses.push(`status = $${paramIndex++}`);
6906
+ values.push(status);
6907
+ }
6908
+ if (metadata !== void 0) {
6909
+ const mergedMetadata = { ...existingBlock.metadata || {}, ...metadata };
6910
+ setClauses.push(`metadata = $${paramIndex++}`);
6911
+ values.push(JSON.stringify(mergedMetadata));
6912
+ }
6913
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6914
+ setClauses.push(`"updatedAt" = $${paramIndex++}`);
6915
+ values.push(now);
6916
+ setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
6917
+ values.push(now);
6918
+ values.push(id);
6919
+ if (setClauses.length > 2 || versionCreated) {
6920
+ await this.#db.client.none(
6921
+ `UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`,
6922
+ values
6923
+ );
6924
+ }
6925
+ const updatedBlock = await this.getById(id);
6926
+ if (!updatedBlock) {
6927
+ throw new error.MastraError({
6928
+ id: storage.createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
6929
+ domain: error.ErrorDomain.STORAGE,
6930
+ category: error.ErrorCategory.SYSTEM,
6931
+ text: `Prompt block ${id} not found after update`,
6932
+ details: { blockId: id }
6933
+ });
6934
+ }
6935
+ return updatedBlock;
6936
+ } catch (error$1) {
6937
+ if (error$1 instanceof error.MastraError) throw error$1;
6938
+ throw new error.MastraError(
6939
+ {
6940
+ id: storage.createStorageErrorId("PG", "UPDATE_PROMPT_BLOCK", "FAILED"),
6941
+ domain: error.ErrorDomain.STORAGE,
6942
+ category: error.ErrorCategory.THIRD_PARTY,
6943
+ details: { blockId: id }
6944
+ },
6945
+ error$1
6946
+ );
6947
+ }
6948
+ }
6949
+ async delete(id) {
6950
+ try {
6951
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6952
+ await this.deleteVersionsByParentId(id);
6953
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
6954
+ } catch (error$1) {
6955
+ if (error$1 instanceof error.MastraError) throw error$1;
6956
+ throw new error.MastraError(
6957
+ {
6958
+ id: storage.createStorageErrorId("PG", "DELETE_PROMPT_BLOCK", "FAILED"),
6959
+ domain: error.ErrorDomain.STORAGE,
6960
+ category: error.ErrorCategory.THIRD_PARTY,
6961
+ details: { blockId: id }
6962
+ },
6963
+ error$1
6964
+ );
6965
+ }
6966
+ }
6967
+ async list(args) {
6968
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
6969
+ const { field, direction } = this.parseOrderBy(orderBy);
6970
+ if (page < 0) {
6971
+ throw new error.MastraError(
6972
+ {
6973
+ id: storage.createStorageErrorId("PG", "LIST_PROMPT_BLOCKS", "INVALID_PAGE"),
6974
+ domain: error.ErrorDomain.STORAGE,
6975
+ category: error.ErrorCategory.USER,
6976
+ details: { page }
6977
+ },
6978
+ new Error("page must be >= 0")
6979
+ );
6980
+ }
6981
+ const perPage = storage.normalizePerPage(perPageInput, 100);
6982
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
6983
+ try {
6984
+ const tableName = getTableName2({ indexName: storage.TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
6985
+ const conditions = [];
6986
+ const queryParams = [];
6987
+ let paramIdx = 1;
6988
+ if (authorId !== void 0) {
6989
+ conditions.push(`"authorId" = $${paramIdx++}`);
6990
+ queryParams.push(authorId);
6991
+ }
6992
+ if (metadata && Object.keys(metadata).length > 0) {
6993
+ conditions.push(`metadata @> $${paramIdx++}::jsonb`);
6994
+ queryParams.push(JSON.stringify(metadata));
6995
+ }
6996
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
6997
+ const countResult = await this.#db.client.one(
6998
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
6999
+ queryParams
7000
+ );
7001
+ const total = parseInt(countResult.count, 10);
7002
+ if (total === 0) {
7003
+ return {
7004
+ promptBlocks: [],
7005
+ total: 0,
7006
+ page,
7007
+ perPage: perPageForResponse,
7008
+ hasMore: false
7009
+ };
7010
+ }
7011
+ const limitValue = perPageInput === false ? total : perPage;
7012
+ const dataResult = await this.#db.client.manyOrNone(
7013
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
7014
+ [...queryParams, limitValue, offset]
7015
+ );
7016
+ const promptBlocks = (dataResult || []).map((row) => this.parseBlockRow(row));
7017
+ return {
7018
+ promptBlocks,
7019
+ total,
7020
+ page,
7021
+ perPage: perPageForResponse,
7022
+ hasMore: perPageInput === false ? false : offset + perPage < total
7023
+ };
7024
+ } catch (error$1) {
7025
+ if (error$1 instanceof error.MastraError) throw error$1;
7026
+ throw new error.MastraError(
7027
+ {
7028
+ id: storage.createStorageErrorId("PG", "LIST_PROMPT_BLOCKS", "FAILED"),
7029
+ domain: error.ErrorDomain.STORAGE,
7030
+ category: error.ErrorCategory.THIRD_PARTY
7031
+ },
7032
+ error$1
7033
+ );
7034
+ }
7035
+ }
7036
+ // ==========================================================================
7037
+ // Prompt Block Version Methods
7038
+ // ==========================================================================
7039
+ async createVersion(input) {
7040
+ try {
7041
+ const tableName = getTableName2({
7042
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7043
+ schemaName: getSchemaName2(this.#schema)
7044
+ });
7045
+ const now = /* @__PURE__ */ new Date();
7046
+ const nowIso = now.toISOString();
7047
+ await this.#db.client.none(
7048
+ `INSERT INTO ${tableName} (
7049
+ id, "blockId", "versionNumber",
7050
+ name, description, content, rules,
7051
+ "changedFields", "changeMessage",
7052
+ "createdAt", "createdAtZ"
7053
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
7054
+ [
7055
+ input.id,
7056
+ input.blockId,
7057
+ input.versionNumber,
7058
+ input.name,
7059
+ input.description ?? null,
7060
+ input.content,
7061
+ input.rules ? JSON.stringify(input.rules) : null,
7062
+ input.changedFields ? JSON.stringify(input.changedFields) : null,
7063
+ input.changeMessage ?? null,
7064
+ nowIso,
7065
+ nowIso
7066
+ ]
7067
+ );
7068
+ return {
7069
+ ...input,
7070
+ createdAt: now
7071
+ };
7072
+ } catch (error$1) {
7073
+ if (error$1 instanceof error.MastraError) throw error$1;
7074
+ throw new error.MastraError(
7075
+ {
7076
+ id: storage.createStorageErrorId("PG", "CREATE_PROMPT_BLOCK_VERSION", "FAILED"),
7077
+ domain: error.ErrorDomain.STORAGE,
7078
+ category: error.ErrorCategory.THIRD_PARTY,
7079
+ details: { versionId: input.id, blockId: input.blockId }
7080
+ },
7081
+ error$1
7082
+ );
7083
+ }
7084
+ }
7085
+ async getVersion(id) {
7086
+ try {
7087
+ const tableName = getTableName2({
7088
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7089
+ schemaName: getSchemaName2(this.#schema)
7090
+ });
7091
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
7092
+ if (!result) {
7093
+ return null;
7094
+ }
7095
+ return this.parseVersionRow(result);
7096
+ } catch (error$1) {
7097
+ if (error$1 instanceof error.MastraError) throw error$1;
7098
+ throw new error.MastraError(
7099
+ {
7100
+ id: storage.createStorageErrorId("PG", "GET_PROMPT_BLOCK_VERSION", "FAILED"),
7101
+ domain: error.ErrorDomain.STORAGE,
7102
+ category: error.ErrorCategory.THIRD_PARTY,
7103
+ details: { versionId: id }
7104
+ },
7105
+ error$1
7106
+ );
7107
+ }
7108
+ }
7109
+ async getVersionByNumber(blockId, versionNumber) {
7110
+ try {
7111
+ const tableName = getTableName2({
7112
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7113
+ schemaName: getSchemaName2(this.#schema)
7114
+ });
7115
+ const result = await this.#db.client.oneOrNone(
7116
+ `SELECT * FROM ${tableName} WHERE "blockId" = $1 AND "versionNumber" = $2`,
7117
+ [blockId, versionNumber]
7118
+ );
7119
+ if (!result) {
7120
+ return null;
7121
+ }
7122
+ return this.parseVersionRow(result);
7123
+ } catch (error$1) {
7124
+ if (error$1 instanceof error.MastraError) throw error$1;
7125
+ throw new error.MastraError(
7126
+ {
7127
+ id: storage.createStorageErrorId("PG", "GET_PROMPT_BLOCK_VERSION_BY_NUMBER", "FAILED"),
7128
+ domain: error.ErrorDomain.STORAGE,
7129
+ category: error.ErrorCategory.THIRD_PARTY,
7130
+ details: { blockId, versionNumber }
7131
+ },
7132
+ error$1
7133
+ );
7134
+ }
7135
+ }
7136
+ async getLatestVersion(blockId) {
7137
+ try {
7138
+ const tableName = getTableName2({
7139
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7140
+ schemaName: getSchemaName2(this.#schema)
7141
+ });
7142
+ const result = await this.#db.client.oneOrNone(
7143
+ `SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
7144
+ [blockId]
7145
+ );
7146
+ if (!result) {
7147
+ return null;
7148
+ }
7149
+ return this.parseVersionRow(result);
7150
+ } catch (error$1) {
7151
+ if (error$1 instanceof error.MastraError) throw error$1;
7152
+ throw new error.MastraError(
7153
+ {
7154
+ id: storage.createStorageErrorId("PG", "GET_LATEST_PROMPT_BLOCK_VERSION", "FAILED"),
7155
+ domain: error.ErrorDomain.STORAGE,
7156
+ category: error.ErrorCategory.THIRD_PARTY,
7157
+ details: { blockId }
7158
+ },
7159
+ error$1
7160
+ );
7161
+ }
7162
+ }
7163
+ async listVersions(input) {
7164
+ const { blockId, page = 0, perPage: perPageInput, orderBy } = input;
7165
+ if (page < 0) {
7166
+ throw new error.MastraError(
7167
+ {
7168
+ id: storage.createStorageErrorId("PG", "LIST_PROMPT_BLOCK_VERSIONS", "INVALID_PAGE"),
7169
+ domain: error.ErrorDomain.STORAGE,
7170
+ category: error.ErrorCategory.USER,
7171
+ details: { page }
7172
+ },
7173
+ new Error("page must be >= 0")
7174
+ );
7175
+ }
7176
+ const perPage = storage.normalizePerPage(perPageInput, 20);
7177
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
7178
+ try {
7179
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
7180
+ const tableName = getTableName2({
7181
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7182
+ schemaName: getSchemaName2(this.#schema)
7183
+ });
7184
+ const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [
7185
+ blockId
7186
+ ]);
7187
+ const total = parseInt(countResult.count, 10);
7188
+ if (total === 0) {
7189
+ return {
7190
+ versions: [],
7191
+ total: 0,
7192
+ page,
7193
+ perPage: perPageForResponse,
7194
+ hasMore: false
7195
+ };
7196
+ }
7197
+ const limitValue = perPageInput === false ? total : perPage;
7198
+ const dataResult = await this.#db.client.manyOrNone(
7199
+ `SELECT * FROM ${tableName} WHERE "blockId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
7200
+ [blockId, limitValue, offset]
7201
+ );
7202
+ const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
7203
+ return {
7204
+ versions,
7205
+ total,
7206
+ page,
7207
+ perPage: perPageForResponse,
7208
+ hasMore: perPageInput === false ? false : offset + perPage < total
7209
+ };
7210
+ } catch (error$1) {
7211
+ if (error$1 instanceof error.MastraError) throw error$1;
7212
+ throw new error.MastraError(
7213
+ {
7214
+ id: storage.createStorageErrorId("PG", "LIST_PROMPT_BLOCK_VERSIONS", "FAILED"),
7215
+ domain: error.ErrorDomain.STORAGE,
7216
+ category: error.ErrorCategory.THIRD_PARTY,
7217
+ details: { blockId }
7218
+ },
7219
+ error$1
7220
+ );
7221
+ }
7222
+ }
7223
+ async deleteVersion(id) {
7224
+ try {
7225
+ const tableName = getTableName2({
7226
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7227
+ schemaName: getSchemaName2(this.#schema)
7228
+ });
7229
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
7230
+ } catch (error$1) {
7231
+ if (error$1 instanceof error.MastraError) throw error$1;
7232
+ throw new error.MastraError(
7233
+ {
7234
+ id: storage.createStorageErrorId("PG", "DELETE_PROMPT_BLOCK_VERSION", "FAILED"),
7235
+ domain: error.ErrorDomain.STORAGE,
7236
+ category: error.ErrorCategory.THIRD_PARTY,
7237
+ details: { versionId: id }
7238
+ },
7239
+ error$1
7240
+ );
7241
+ }
7242
+ }
7243
+ async deleteVersionsByParentId(entityId) {
7244
+ try {
7245
+ const tableName = getTableName2({
7246
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7247
+ schemaName: getSchemaName2(this.#schema)
7248
+ });
7249
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "blockId" = $1`, [entityId]);
7250
+ } catch (error$1) {
7251
+ if (error$1 instanceof error.MastraError) throw error$1;
7252
+ throw new error.MastraError(
7253
+ {
7254
+ id: storage.createStorageErrorId("PG", "DELETE_PROMPT_BLOCK_VERSIONS_BY_BLOCK_ID", "FAILED"),
7255
+ domain: error.ErrorDomain.STORAGE,
7256
+ category: error.ErrorCategory.THIRD_PARTY,
7257
+ details: { blockId: entityId }
7258
+ },
7259
+ error$1
7260
+ );
7261
+ }
7262
+ }
7263
+ async countVersions(blockId) {
7264
+ try {
7265
+ const tableName = getTableName2({
7266
+ indexName: storage.TABLE_PROMPT_BLOCK_VERSIONS,
7267
+ schemaName: getSchemaName2(this.#schema)
7268
+ });
7269
+ const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "blockId" = $1`, [
7270
+ blockId
7271
+ ]);
7272
+ return parseInt(result.count, 10);
7273
+ } catch (error$1) {
7274
+ if (error$1 instanceof error.MastraError) throw error$1;
7275
+ throw new error.MastraError(
7276
+ {
7277
+ id: storage.createStorageErrorId("PG", "COUNT_PROMPT_BLOCK_VERSIONS", "FAILED"),
7278
+ domain: error.ErrorDomain.STORAGE,
7279
+ category: error.ErrorCategory.THIRD_PARTY,
7280
+ details: { blockId }
7281
+ },
7282
+ error$1
7283
+ );
7284
+ }
7285
+ }
7286
+ // ==========================================================================
7287
+ // Private Helper Methods
7288
+ // ==========================================================================
7289
+ parseJson(value, fieldName) {
7290
+ if (!value) return void 0;
7291
+ if (typeof value !== "string") return value;
7292
+ try {
7293
+ return JSON.parse(value);
7294
+ } catch (error$1) {
7295
+ const details = {
7296
+ value: value.length > 100 ? value.substring(0, 100) + "..." : value
7297
+ };
7298
+ if (fieldName) {
7299
+ details.field = fieldName;
7300
+ }
7301
+ throw new error.MastraError(
7302
+ {
7303
+ id: storage.createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
7304
+ domain: error.ErrorDomain.STORAGE,
7305
+ category: error.ErrorCategory.SYSTEM,
7306
+ text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error$1 instanceof Error ? error$1.message : "Unknown error"}`,
7307
+ details
7308
+ },
7309
+ error$1
7310
+ );
7311
+ }
7312
+ }
7313
+ parseBlockRow(row) {
7314
+ return {
7315
+ id: row.id,
7316
+ status: row.status,
7317
+ activeVersionId: row.activeVersionId,
7318
+ authorId: row.authorId,
7319
+ metadata: this.parseJson(row.metadata, "metadata"),
7320
+ createdAt: new Date(row.createdAtZ || row.createdAt),
7321
+ updatedAt: new Date(row.updatedAtZ || row.updatedAt)
7322
+ };
7323
+ }
7324
+ parseVersionRow(row) {
7325
+ return {
7326
+ id: row.id,
7327
+ blockId: row.blockId,
7328
+ versionNumber: row.versionNumber,
7329
+ name: row.name,
7330
+ description: row.description,
7331
+ content: row.content,
7332
+ rules: this.parseJson(row.rules, "rules"),
7333
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
7334
+ changeMessage: row.changeMessage,
7335
+ createdAt: new Date(row.createdAtZ || row.createdAt)
7336
+ };
7337
+ }
7338
+ };
7339
+ var SNAPSHOT_FIELDS2 = [
7340
+ "name",
7341
+ "description",
7342
+ "type",
7343
+ "model",
7344
+ "instructions",
7345
+ "scoreRange",
7346
+ "presetConfig",
7347
+ "defaultSampling"
7348
+ ];
7349
+ var ScorerDefinitionsPG = class _ScorerDefinitionsPG extends storage.ScorerDefinitionsStorage {
7350
+ #db;
7351
+ #schema;
7352
+ #skipDefaultIndexes;
7353
+ #indexes;
7354
+ static MANAGED_TABLES = [storage.TABLE_SCORER_DEFINITIONS, storage.TABLE_SCORER_DEFINITION_VERSIONS];
7355
+ constructor(config) {
7356
+ super();
7357
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
7358
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
7359
+ this.#schema = schemaName || "public";
7360
+ this.#skipDefaultIndexes = skipDefaultIndexes;
7361
+ this.#indexes = indexes?.filter(
7362
+ (idx) => _ScorerDefinitionsPG.MANAGED_TABLES.includes(idx.table)
7363
+ );
7364
+ }
7365
+ getDefaultIndexDefinitions() {
7366
+ return [
7367
+ {
7368
+ name: "idx_scorer_definition_versions_def_version",
7369
+ table: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7370
+ columns: ["scorerDefinitionId", "versionNumber"],
7371
+ unique: true
7372
+ }
7373
+ ];
7374
+ }
7375
+ async createDefaultIndexes() {
7376
+ if (this.#skipDefaultIndexes) {
7377
+ return;
7378
+ }
7379
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
7380
+ try {
7381
+ await this.#db.createIndex(indexDef);
7382
+ } catch {
7383
+ }
7384
+ }
7385
+ }
7386
+ async init() {
7387
+ await this.#db.createTable({
7388
+ tableName: storage.TABLE_SCORER_DEFINITIONS,
7389
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCORER_DEFINITIONS]
7390
+ });
7391
+ await this.#db.createTable({
7392
+ tableName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7393
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_SCORER_DEFINITION_VERSIONS]
7394
+ });
7395
+ await this.createDefaultIndexes();
7396
+ await this.createCustomIndexes();
7397
+ }
7398
+ async createCustomIndexes() {
7399
+ if (!this.#indexes || this.#indexes.length === 0) {
7400
+ return;
7401
+ }
7402
+ for (const indexDef of this.#indexes) {
7403
+ try {
7404
+ await this.#db.createIndex(indexDef);
7405
+ } catch (error) {
7406
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
7407
+ }
7408
+ }
7409
+ }
7410
+ async dangerouslyClearAll() {
7411
+ await this.#db.clearTable({ tableName: storage.TABLE_SCORER_DEFINITION_VERSIONS });
7412
+ await this.#db.clearTable({ tableName: storage.TABLE_SCORER_DEFINITIONS });
7413
+ }
7414
+ // ==========================================================================
7415
+ // Scorer Definition CRUD Methods
7416
+ // ==========================================================================
7417
+ async getById(id) {
7418
+ try {
7419
+ const tableName = getTableName2({ indexName: storage.TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
7420
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
7421
+ if (!result) {
7422
+ return null;
7423
+ }
7424
+ return this.parseScorerRow(result);
7425
+ } catch (error$1) {
7426
+ if (error$1 instanceof error.MastraError) throw error$1;
7427
+ throw new error.MastraError(
7428
+ {
7429
+ id: storage.createStorageErrorId("PG", "GET_SCORER_DEFINITION_BY_ID", "FAILED"),
7430
+ domain: error.ErrorDomain.STORAGE,
7431
+ category: error.ErrorCategory.THIRD_PARTY,
7432
+ details: { scorerDefinitionId: id }
7433
+ },
7434
+ error$1
7435
+ );
7436
+ }
7437
+ }
7438
+ async create(input) {
7439
+ const { scorerDefinition } = input;
7440
+ try {
7441
+ const tableName = getTableName2({ indexName: storage.TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
7442
+ const now = /* @__PURE__ */ new Date();
7443
+ const nowIso = now.toISOString();
7444
+ await this.#db.client.none(
7445
+ `INSERT INTO ${tableName} (
7446
+ id, status, "activeVersionId", "authorId", metadata,
7447
+ "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
7448
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
7449
+ [
7450
+ scorerDefinition.id,
7451
+ "draft",
7452
+ null,
7453
+ scorerDefinition.authorId ?? null,
7454
+ scorerDefinition.metadata ? JSON.stringify(scorerDefinition.metadata) : null,
7455
+ nowIso,
7456
+ nowIso,
7457
+ nowIso,
7458
+ nowIso
7459
+ ]
7460
+ );
7461
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
7462
+ const versionId = crypto.randomUUID();
7463
+ await this.createVersion({
7464
+ id: versionId,
7465
+ scorerDefinitionId: scorerDefinition.id,
7466
+ versionNumber: 1,
7467
+ ...snapshotConfig,
7468
+ changedFields: [...SNAPSHOT_FIELDS2],
7469
+ changeMessage: "Initial version"
7470
+ });
7471
+ return {
7472
+ id: scorerDefinition.id,
7473
+ status: "draft",
7474
+ activeVersionId: void 0,
7475
+ authorId: scorerDefinition.authorId,
7476
+ metadata: scorerDefinition.metadata,
7477
+ createdAt: now,
7478
+ updatedAt: now
7479
+ };
7480
+ } catch (error$1) {
7481
+ try {
7482
+ const tableName = getTableName2({
7483
+ indexName: storage.TABLE_SCORER_DEFINITIONS,
7484
+ schemaName: getSchemaName2(this.#schema)
7485
+ });
7486
+ await this.#db.client.none(
7487
+ `DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
7488
+ [scorerDefinition.id]
7489
+ );
7490
+ } catch {
7491
+ }
7492
+ if (error$1 instanceof error.MastraError) throw error$1;
7493
+ throw new error.MastraError(
7494
+ {
7495
+ id: storage.createStorageErrorId("PG", "CREATE_SCORER_DEFINITION", "FAILED"),
7496
+ domain: error.ErrorDomain.STORAGE,
7497
+ category: error.ErrorCategory.THIRD_PARTY,
7498
+ details: { scorerDefinitionId: scorerDefinition.id }
7499
+ },
7500
+ error$1
7501
+ );
7502
+ }
7503
+ }
7504
+ async update(input) {
7505
+ const { id, ...updates } = input;
7506
+ try {
7507
+ const tableName = getTableName2({ indexName: storage.TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
7508
+ const existingScorer = await this.getById(id);
7509
+ if (!existingScorer) {
7510
+ throw new error.MastraError({
7511
+ id: storage.createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
7512
+ domain: error.ErrorDomain.STORAGE,
7513
+ category: error.ErrorCategory.USER,
7514
+ text: `Scorer definition ${id} not found`,
7515
+ details: { scorerDefinitionId: id }
7516
+ });
7517
+ }
7518
+ const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
7519
+ let versionCreated = false;
7520
+ const hasConfigUpdate = SNAPSHOT_FIELDS2.some((field) => field in configFields);
7521
+ if (hasConfigUpdate) {
7522
+ const latestVersion = await this.getLatestVersion(id);
7523
+ if (!latestVersion) {
7524
+ throw new error.MastraError({
7525
+ id: storage.createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NO_VERSIONS"),
7526
+ domain: error.ErrorDomain.STORAGE,
7527
+ category: error.ErrorCategory.SYSTEM,
7528
+ text: `No versions found for scorer definition ${id}`,
7529
+ details: { scorerDefinitionId: id }
7530
+ });
7531
+ }
7532
+ const {
7533
+ id: _versionId,
7534
+ scorerDefinitionId: _scorerDefinitionId,
7535
+ versionNumber: _versionNumber,
7536
+ changedFields: _changedFields,
7537
+ changeMessage: _changeMessage,
7538
+ createdAt: _createdAt,
7539
+ ...latestConfig
7540
+ } = latestVersion;
7541
+ const newConfig = { ...latestConfig, ...configFields };
7542
+ const changedFields = SNAPSHOT_FIELDS2.filter(
7543
+ (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
7544
+ );
7545
+ if (changedFields.length > 0) {
7546
+ versionCreated = true;
7547
+ const newVersionId = crypto.randomUUID();
7548
+ await this.createVersion({
7549
+ id: newVersionId,
7550
+ scorerDefinitionId: id,
7551
+ versionNumber: latestVersion.versionNumber + 1,
7552
+ ...newConfig,
7553
+ changedFields: [...changedFields],
7554
+ changeMessage: `Updated ${changedFields.join(", ")}`
7555
+ });
7556
+ }
7557
+ }
7558
+ const setClauses = [];
7559
+ const values = [];
7560
+ let paramIndex = 1;
7561
+ if (authorId !== void 0) {
7562
+ setClauses.push(`"authorId" = $${paramIndex++}`);
7563
+ values.push(authorId);
7564
+ }
7565
+ if (activeVersionId !== void 0) {
7566
+ setClauses.push(`"activeVersionId" = $${paramIndex++}`);
7567
+ values.push(activeVersionId);
7568
+ if (status === void 0) {
7569
+ setClauses.push(`status = $${paramIndex++}`);
7570
+ values.push("published");
7571
+ }
7572
+ }
7573
+ if (status !== void 0) {
7574
+ setClauses.push(`status = $${paramIndex++}`);
7575
+ values.push(status);
7576
+ }
7577
+ if (metadata !== void 0) {
7578
+ const mergedMetadata = { ...existingScorer.metadata || {}, ...metadata };
7579
+ setClauses.push(`metadata = $${paramIndex++}`);
7580
+ values.push(JSON.stringify(mergedMetadata));
7581
+ }
7582
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7583
+ setClauses.push(`"updatedAt" = $${paramIndex++}`);
7584
+ values.push(now);
7585
+ setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
7586
+ values.push(now);
7587
+ values.push(id);
7588
+ if (setClauses.length > 2 || versionCreated) {
7589
+ await this.#db.client.none(
7590
+ `UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`,
7591
+ values
7592
+ );
7593
+ }
7594
+ const updatedScorer = await this.getById(id);
7595
+ if (!updatedScorer) {
7596
+ throw new error.MastraError({
7597
+ id: storage.createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
7598
+ domain: error.ErrorDomain.STORAGE,
7599
+ category: error.ErrorCategory.SYSTEM,
7600
+ text: `Scorer definition ${id} not found after update`,
7601
+ details: { scorerDefinitionId: id }
7602
+ });
7603
+ }
7604
+ return updatedScorer;
7605
+ } catch (error$1) {
7606
+ if (error$1 instanceof error.MastraError) throw error$1;
7607
+ throw new error.MastraError(
7608
+ {
7609
+ id: storage.createStorageErrorId("PG", "UPDATE_SCORER_DEFINITION", "FAILED"),
7610
+ domain: error.ErrorDomain.STORAGE,
7611
+ category: error.ErrorCategory.THIRD_PARTY,
7612
+ details: { scorerDefinitionId: id }
7613
+ },
7614
+ error$1
7615
+ );
7616
+ }
7617
+ }
7618
+ async delete(id) {
7619
+ try {
7620
+ const tableName = getTableName2({ indexName: storage.TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
7621
+ await this.deleteVersionsByParentId(id);
7622
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
7623
+ } catch (error$1) {
7624
+ if (error$1 instanceof error.MastraError) throw error$1;
7625
+ throw new error.MastraError(
7626
+ {
7627
+ id: storage.createStorageErrorId("PG", "DELETE_SCORER_DEFINITION", "FAILED"),
7628
+ domain: error.ErrorDomain.STORAGE,
7629
+ category: error.ErrorCategory.THIRD_PARTY,
7630
+ details: { scorerDefinitionId: id }
7631
+ },
7632
+ error$1
7633
+ );
7634
+ }
7635
+ }
7636
+ async list(args) {
7637
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
7638
+ const { field, direction } = this.parseOrderBy(orderBy);
7639
+ if (page < 0) {
7640
+ throw new error.MastraError(
7641
+ {
7642
+ id: storage.createStorageErrorId("PG", "LIST_SCORER_DEFINITIONS", "INVALID_PAGE"),
7643
+ domain: error.ErrorDomain.STORAGE,
7644
+ category: error.ErrorCategory.USER,
7645
+ details: { page }
7646
+ },
7647
+ new Error("page must be >= 0")
7648
+ );
7649
+ }
7650
+ const perPage = storage.normalizePerPage(perPageInput, 100);
7651
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
7652
+ try {
7653
+ const tableName = getTableName2({ indexName: storage.TABLE_SCORER_DEFINITIONS, schemaName: getSchemaName2(this.#schema) });
7654
+ const conditions = [];
7655
+ const queryParams = [];
7656
+ let paramIdx = 1;
7657
+ if (authorId !== void 0) {
7658
+ conditions.push(`"authorId" = $${paramIdx++}`);
7659
+ queryParams.push(authorId);
7660
+ }
7661
+ if (metadata && Object.keys(metadata).length > 0) {
7662
+ conditions.push(`metadata @> $${paramIdx++}::jsonb`);
7663
+ queryParams.push(JSON.stringify(metadata));
7664
+ }
7665
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
7666
+ const countResult = await this.#db.client.one(
7667
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
7668
+ queryParams
7669
+ );
7670
+ const total = parseInt(countResult.count, 10);
7671
+ if (total === 0) {
7672
+ return {
7673
+ scorerDefinitions: [],
7674
+ total: 0,
7675
+ page,
7676
+ perPage: perPageForResponse,
7677
+ hasMore: false
7678
+ };
7679
+ }
7680
+ const limitValue = perPageInput === false ? total : perPage;
7681
+ const dataResult = await this.#db.client.manyOrNone(
7682
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
7683
+ [...queryParams, limitValue, offset]
7684
+ );
7685
+ const scorerDefinitions = (dataResult || []).map((row) => this.parseScorerRow(row));
7686
+ return {
7687
+ scorerDefinitions,
7688
+ total,
7689
+ page,
7690
+ perPage: perPageForResponse,
7691
+ hasMore: perPageInput === false ? false : offset + perPage < total
7692
+ };
7693
+ } catch (error$1) {
7694
+ if (error$1 instanceof error.MastraError) throw error$1;
7695
+ throw new error.MastraError(
7696
+ {
7697
+ id: storage.createStorageErrorId("PG", "LIST_SCORER_DEFINITIONS", "FAILED"),
7698
+ domain: error.ErrorDomain.STORAGE,
7699
+ category: error.ErrorCategory.THIRD_PARTY
7700
+ },
7701
+ error$1
7702
+ );
7703
+ }
7704
+ }
7705
+ // ==========================================================================
7706
+ // Scorer Definition Version Methods
7707
+ // ==========================================================================
7708
+ async createVersion(input) {
7709
+ try {
7710
+ const tableName = getTableName2({
7711
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7712
+ schemaName: getSchemaName2(this.#schema)
7713
+ });
7714
+ const now = /* @__PURE__ */ new Date();
7715
+ const nowIso = now.toISOString();
7716
+ await this.#db.client.none(
7717
+ `INSERT INTO ${tableName} (
7718
+ id, "scorerDefinitionId", "versionNumber",
7719
+ name, description, type, model, instructions, "scoreRange", "presetConfig", "defaultSampling",
7720
+ "changedFields", "changeMessage",
7721
+ "createdAt", "createdAtZ"
7722
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,
7723
+ [
7724
+ input.id,
7725
+ input.scorerDefinitionId,
7726
+ input.versionNumber,
7727
+ input.name,
7728
+ input.description ?? null,
7729
+ input.type,
7730
+ input.model ? JSON.stringify(input.model) : null,
7731
+ input.instructions ?? null,
7732
+ input.scoreRange ? JSON.stringify(input.scoreRange) : null,
7733
+ input.presetConfig ? JSON.stringify(input.presetConfig) : null,
7734
+ input.defaultSampling ? JSON.stringify(input.defaultSampling) : null,
7735
+ input.changedFields ? JSON.stringify(input.changedFields) : null,
7736
+ input.changeMessage ?? null,
7737
+ nowIso,
7738
+ nowIso
7739
+ ]
7740
+ );
7741
+ return {
7742
+ ...input,
7743
+ createdAt: now
7744
+ };
7745
+ } catch (error$1) {
7746
+ if (error$1 instanceof error.MastraError) throw error$1;
7747
+ throw new error.MastraError(
7748
+ {
7749
+ id: storage.createStorageErrorId("PG", "CREATE_SCORER_DEFINITION_VERSION", "FAILED"),
7750
+ domain: error.ErrorDomain.STORAGE,
7751
+ category: error.ErrorCategory.THIRD_PARTY,
7752
+ details: { versionId: input.id, scorerDefinitionId: input.scorerDefinitionId }
7753
+ },
7754
+ error$1
7755
+ );
7756
+ }
7757
+ }
7758
+ async getVersion(id) {
7759
+ try {
7760
+ const tableName = getTableName2({
7761
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7762
+ schemaName: getSchemaName2(this.#schema)
7763
+ });
7764
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
7765
+ if (!result) {
7766
+ return null;
7767
+ }
7768
+ return this.parseVersionRow(result);
7769
+ } catch (error$1) {
7770
+ if (error$1 instanceof error.MastraError) throw error$1;
7771
+ throw new error.MastraError(
7772
+ {
7773
+ id: storage.createStorageErrorId("PG", "GET_SCORER_DEFINITION_VERSION", "FAILED"),
7774
+ domain: error.ErrorDomain.STORAGE,
7775
+ category: error.ErrorCategory.THIRD_PARTY,
7776
+ details: { versionId: id }
7777
+ },
7778
+ error$1
7779
+ );
7780
+ }
7781
+ }
7782
+ async getVersionByNumber(scorerDefinitionId, versionNumber) {
7783
+ try {
7784
+ const tableName = getTableName2({
7785
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7786
+ schemaName: getSchemaName2(this.#schema)
7787
+ });
7788
+ const result = await this.#db.client.oneOrNone(
7789
+ `SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 AND "versionNumber" = $2`,
7790
+ [scorerDefinitionId, versionNumber]
7791
+ );
7792
+ if (!result) {
7793
+ return null;
7794
+ }
7795
+ return this.parseVersionRow(result);
7796
+ } catch (error$1) {
7797
+ if (error$1 instanceof error.MastraError) throw error$1;
7798
+ throw new error.MastraError(
7799
+ {
7800
+ id: storage.createStorageErrorId("PG", "GET_SCORER_DEFINITION_VERSION_BY_NUMBER", "FAILED"),
7801
+ domain: error.ErrorDomain.STORAGE,
7802
+ category: error.ErrorCategory.THIRD_PARTY,
7803
+ details: { scorerDefinitionId, versionNumber }
7804
+ },
7805
+ error$1
7806
+ );
7807
+ }
7808
+ }
7809
+ async getLatestVersion(scorerDefinitionId) {
7810
+ try {
7811
+ const tableName = getTableName2({
7812
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7813
+ schemaName: getSchemaName2(this.#schema)
7814
+ });
7815
+ const result = await this.#db.client.oneOrNone(
7816
+ `SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
7817
+ [scorerDefinitionId]
7818
+ );
7819
+ if (!result) {
7820
+ return null;
7821
+ }
7822
+ return this.parseVersionRow(result);
7823
+ } catch (error$1) {
7824
+ if (error$1 instanceof error.MastraError) throw error$1;
7825
+ throw new error.MastraError(
7826
+ {
7827
+ id: storage.createStorageErrorId("PG", "GET_LATEST_SCORER_DEFINITION_VERSION", "FAILED"),
7828
+ domain: error.ErrorDomain.STORAGE,
7829
+ category: error.ErrorCategory.THIRD_PARTY,
7830
+ details: { scorerDefinitionId }
7831
+ },
7832
+ error$1
7833
+ );
7834
+ }
7835
+ }
7836
+ async listVersions(input) {
7837
+ const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
7838
+ if (page < 0) {
7839
+ throw new error.MastraError(
7840
+ {
7841
+ id: storage.createStorageErrorId("PG", "LIST_SCORER_DEFINITION_VERSIONS", "INVALID_PAGE"),
7842
+ domain: error.ErrorDomain.STORAGE,
7843
+ category: error.ErrorCategory.USER,
7844
+ details: { page }
7845
+ },
7846
+ new Error("page must be >= 0")
7847
+ );
7848
+ }
7849
+ const perPage = storage.normalizePerPage(perPageInput, 20);
7850
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
7851
+ try {
7852
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
7853
+ const tableName = getTableName2({
7854
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7855
+ schemaName: getSchemaName2(this.#schema)
7856
+ });
7857
+ const countResult = await this.#db.client.one(
7858
+ `SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`,
7859
+ [scorerDefinitionId]
7860
+ );
7861
+ const total = parseInt(countResult.count, 10);
7862
+ if (total === 0) {
7863
+ return {
7864
+ versions: [],
7865
+ total: 0,
7866
+ page,
7867
+ perPage: perPageForResponse,
7868
+ hasMore: false
7869
+ };
7870
+ }
7871
+ const limitValue = perPageInput === false ? total : perPage;
7872
+ const dataResult = await this.#db.client.manyOrNone(
7873
+ `SELECT * FROM ${tableName} WHERE "scorerDefinitionId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
7874
+ [scorerDefinitionId, limitValue, offset]
7875
+ );
7876
+ const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
7877
+ return {
7878
+ versions,
7879
+ total,
7880
+ page,
7881
+ perPage: perPageForResponse,
7882
+ hasMore: perPageInput === false ? false : offset + perPage < total
7883
+ };
7884
+ } catch (error$1) {
7885
+ if (error$1 instanceof error.MastraError) throw error$1;
7886
+ throw new error.MastraError(
7887
+ {
7888
+ id: storage.createStorageErrorId("PG", "LIST_SCORER_DEFINITION_VERSIONS", "FAILED"),
7889
+ domain: error.ErrorDomain.STORAGE,
7890
+ category: error.ErrorCategory.THIRD_PARTY,
7891
+ details: { scorerDefinitionId }
7892
+ },
7893
+ error$1
7894
+ );
7895
+ }
7896
+ }
7897
+ async deleteVersion(id) {
7898
+ try {
7899
+ const tableName = getTableName2({
7900
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7901
+ schemaName: getSchemaName2(this.#schema)
7902
+ });
7903
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
7904
+ } catch (error$1) {
7905
+ if (error$1 instanceof error.MastraError) throw error$1;
7906
+ throw new error.MastraError(
7907
+ {
7908
+ id: storage.createStorageErrorId("PG", "DELETE_SCORER_DEFINITION_VERSION", "FAILED"),
7909
+ domain: error.ErrorDomain.STORAGE,
7910
+ category: error.ErrorCategory.THIRD_PARTY,
7911
+ details: { versionId: id }
7912
+ },
7913
+ error$1
7914
+ );
7915
+ }
7916
+ }
7917
+ async deleteVersionsByParentId(entityId) {
7918
+ try {
7919
+ const tableName = getTableName2({
7920
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7921
+ schemaName: getSchemaName2(this.#schema)
7922
+ });
7923
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "scorerDefinitionId" = $1`, [entityId]);
7924
+ } catch (error$1) {
7925
+ if (error$1 instanceof error.MastraError) throw error$1;
7926
+ throw new error.MastraError(
7927
+ {
7928
+ id: storage.createStorageErrorId("PG", "DELETE_SCORER_DEFINITION_VERSIONS_BY_SCORER_DEFINITION_ID", "FAILED"),
7929
+ domain: error.ErrorDomain.STORAGE,
7930
+ category: error.ErrorCategory.THIRD_PARTY,
7931
+ details: { scorerDefinitionId: entityId }
7932
+ },
7933
+ error$1
7934
+ );
7935
+ }
7936
+ }
7937
+ async countVersions(scorerDefinitionId) {
7938
+ try {
7939
+ const tableName = getTableName2({
7940
+ indexName: storage.TABLE_SCORER_DEFINITION_VERSIONS,
7941
+ schemaName: getSchemaName2(this.#schema)
7942
+ });
7943
+ const result = await this.#db.client.one(
7944
+ `SELECT COUNT(*) as count FROM ${tableName} WHERE "scorerDefinitionId" = $1`,
7945
+ [scorerDefinitionId]
7946
+ );
7947
+ return parseInt(result.count, 10);
7948
+ } catch (error$1) {
7949
+ if (error$1 instanceof error.MastraError) throw error$1;
7950
+ throw new error.MastraError(
7951
+ {
7952
+ id: storage.createStorageErrorId("PG", "COUNT_SCORER_DEFINITION_VERSIONS", "FAILED"),
7953
+ domain: error.ErrorDomain.STORAGE,
7954
+ category: error.ErrorCategory.THIRD_PARTY,
7955
+ details: { scorerDefinitionId }
7956
+ },
7957
+ error$1
7958
+ );
7959
+ }
7960
+ }
7961
+ // ==========================================================================
7962
+ // Private Helper Methods
7963
+ // ==========================================================================
7964
+ parseJson(value, fieldName) {
7965
+ if (!value) return void 0;
7966
+ if (typeof value !== "string") return value;
7967
+ try {
7968
+ return JSON.parse(value);
7969
+ } catch (error$1) {
7970
+ if (error$1 instanceof error.MastraError) throw error$1;
7971
+ const details = {
7972
+ value: value.length > 100 ? value.substring(0, 100) + "..." : value
7973
+ };
7974
+ if (fieldName) {
7975
+ details.field = fieldName;
7976
+ }
7977
+ throw new error.MastraError(
7978
+ {
7979
+ id: storage.createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
7980
+ domain: error.ErrorDomain.STORAGE,
7981
+ category: error.ErrorCategory.SYSTEM,
7982
+ text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error$1 instanceof Error ? error$1.message : "Unknown error"}`,
7983
+ details
7984
+ },
7985
+ error$1
7986
+ );
7987
+ }
7988
+ }
7989
+ parseScorerRow(row) {
7990
+ return {
7991
+ id: row.id,
7992
+ status: row.status,
7993
+ activeVersionId: row.activeVersionId,
7994
+ authorId: row.authorId,
7995
+ metadata: this.parseJson(row.metadata, "metadata"),
7996
+ createdAt: new Date(row.createdAtZ || row.createdAt),
7997
+ updatedAt: new Date(row.updatedAtZ || row.updatedAt)
7998
+ };
7999
+ }
8000
+ parseVersionRow(row) {
8001
+ return {
8002
+ id: row.id,
8003
+ scorerDefinitionId: row.scorerDefinitionId,
8004
+ versionNumber: row.versionNumber,
8005
+ name: row.name,
8006
+ description: row.description,
8007
+ type: row.type,
8008
+ model: this.parseJson(row.model, "model"),
8009
+ instructions: row.instructions,
8010
+ scoreRange: this.parseJson(row.scoreRange, "scoreRange"),
8011
+ presetConfig: this.parseJson(row.presetConfig, "presetConfig"),
8012
+ defaultSampling: this.parseJson(row.defaultSampling, "defaultSampling"),
8013
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
8014
+ changeMessage: row.changeMessage,
8015
+ createdAt: new Date(row.createdAtZ || row.createdAt)
8016
+ };
8017
+ }
8018
+ };
6242
8019
  function getSchemaName4(schema) {
6243
8020
  return schema ? `"${schema}"` : '"public"';
6244
8021
  }
@@ -6960,7 +8737,9 @@ var PostgresStore = class extends storage.MastraCompositeStore {
6960
8737
  workflows: new WorkflowsPG(domainConfig),
6961
8738
  memory: new MemoryPG(domainConfig),
6962
8739
  observability: new ObservabilityPG(domainConfig),
6963
- agents: new AgentsPG(domainConfig)
8740
+ agents: new AgentsPG(domainConfig),
8741
+ promptBlocks: new PromptBlocksPG(domainConfig),
8742
+ scorerDefinitions: new ScorerDefinitionsPG(domainConfig)
6964
8743
  };
6965
8744
  } catch (e) {
6966
8745
  throw new error.MastraError(
@@ -7156,6 +8935,8 @@ exports.PGVECTOR_PROMPT = PGVECTOR_PROMPT;
7156
8935
  exports.PgVector = PgVector;
7157
8936
  exports.PoolAdapter = PoolAdapter;
7158
8937
  exports.PostgresStore = PostgresStore;
8938
+ exports.PromptBlocksPG = PromptBlocksPG;
8939
+ exports.ScorerDefinitionsPG = ScorerDefinitionsPG;
7159
8940
  exports.ScoresPG = ScoresPG;
7160
8941
  exports.WorkflowsPG = WorkflowsPG;
7161
8942
  exports.exportSchemas = exportSchemas;