@mastra/pg 1.27.0-alpha.1 → 1.27.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 (38) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  3. package/dist/index.cjs +234 -195
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.js +234 -195
  6. package/dist/index.js.map +1 -1
  7. package/dist/storage/db/index.d.ts.map +1 -1
  8. package/dist/storage/db/sanitize-json.d.ts +2 -10
  9. package/dist/storage/db/sanitize-json.d.ts.map +1 -1
  10. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  11. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -1
  12. package/dist/storage/domains/channels/index.d.ts.map +1 -1
  13. package/dist/storage/domains/datasets/index.d.ts.map +1 -1
  14. package/dist/storage/domains/experiments/index.d.ts.map +1 -1
  15. package/dist/storage/domains/knowledge/index.d.ts.map +1 -1
  16. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -1
  17. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -1
  18. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  19. package/dist/storage/domains/notifications/index.d.ts.map +1 -1
  20. package/dist/storage/domains/observability/index.d.ts.map +1 -1
  21. package/dist/storage/domains/observability/v-next/discovery.d.ts.map +1 -1
  22. package/dist/storage/domains/observability/v-next/index.d.ts +1 -1
  23. package/dist/storage/domains/observability/v-next/index.d.ts.map +1 -1
  24. package/dist/storage/domains/observability/v-next/metrics.d.ts.map +1 -1
  25. package/dist/storage/domains/observability/v-next/scores.d.ts.map +1 -1
  26. package/dist/storage/domains/observability/v-next/trace-query.d.ts.map +1 -1
  27. package/dist/storage/domains/observability/v-next/traces.d.ts.map +1 -1
  28. package/dist/storage/domains/prompt-blocks/index.d.ts.map +1 -1
  29. package/dist/storage/domains/schedules/index.d.ts.map +1 -1
  30. package/dist/storage/domains/scorer-definitions/index.d.ts.map +1 -1
  31. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  32. package/dist/storage/domains/skills/index.d.ts.map +1 -1
  33. package/dist/storage/domains/thread-state/index.d.ts.map +1 -1
  34. package/dist/storage/domains/workflows/index.d.ts +0 -2
  35. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  36. package/dist/storage/domains/workspaces/index.d.ts.map +1 -1
  37. package/dist/storage/factory-storage.d.ts.map +1 -1
  38. package/package.json +5 -5
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ let _mastra_core_agent = require("@mastra/core/agent");
39
39
  let _mastra_core_features = require("@mastra/core/features");
40
40
  let _mastra_core_evals = require("@mastra/core/evals");
41
41
  let _mastra_core_storage_domains_skills = require("@mastra/core/storage/domains/skills");
42
+ let util = require("util");
42
43
  //#region src/shared/config.ts
43
44
  /**
44
45
  * Type guard for pre-configured pg.Pool config
@@ -2432,6 +2433,29 @@ function isDuplicateSchemaError(error) {
2432
2433
  return /schema .* already exists/i.test(message);
2433
2434
  }
2434
2435
  //#endregion
2436
+ //#region src/storage/db/sanitize-json.ts
2437
+ const repair = (value) => value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�").replaceAll("\0", "");
2438
+ function repairJson(value) {
2439
+ if (typeof value === "string") return repair(value);
2440
+ if (Array.isArray(value)) return value.map(repairJson);
2441
+ if (value && typeof value === "object") {
2442
+ const repaired = Object.create(null);
2443
+ for (const [key, entry] of Object.entries(value)) {
2444
+ const repairedKey = repair(key);
2445
+ if (Object.hasOwn(repaired, repairedKey)) throw new Error(`JSON keys collide after PostgreSQL normalization: ${repairedKey}`);
2446
+ repaired[repairedKey] = repairJson(entry);
2447
+ }
2448
+ return repaired;
2449
+ }
2450
+ return value;
2451
+ }
2452
+ /** Serialize JSON values without emitting Unicode sequences PostgreSQL rejects. */
2453
+ function toPgJson(value) {
2454
+ const json = JSON.stringify(value);
2455
+ if (json === void 0 || !/\\u(?:0000|[dD][89a-fA-F][0-9a-fA-F]{2})/.test(json)) return json;
2456
+ return JSON.stringify(repairJson(JSON.parse(json)));
2457
+ }
2458
+ //#endregion
2435
2459
  //#region src/storage/db/schema-snapshot.ts
2436
2460
  /**
2437
2461
  * Returns the snapshot currently installed on `client`, but only when it was
@@ -2956,7 +2980,7 @@ var PgDB = class extends _mastra_core_base.MastraBase {
2956
2980
  */
2957
2981
  prepareValuesForInsert(record, tableName) {
2958
2982
  return Object.entries(record).map(([key, value]) => {
2959
- if ((_mastra_core_storage.TABLE_SCHEMAS[tableName]?.[key])?.type === "jsonb" && value !== null && value !== void 0) return JSON.stringify(value);
2983
+ if ((_mastra_core_storage.TABLE_SCHEMAS[tableName]?.[key])?.type === "jsonb" && value !== null && value !== void 0) return toPgJson(value);
2960
2984
  return value;
2961
2985
  });
2962
2986
  }
@@ -2974,8 +2998,8 @@ var PgDB = class extends _mastra_core_base.MastraBase {
2974
2998
  prepareValue(value, columnName, tableName) {
2975
2999
  if (value === null || value === void 0) return value;
2976
3000
  if (value instanceof Date) return value.toISOString();
2977
- if ((_mastra_core_storage.TABLE_SCHEMAS[tableName]?.[columnName])?.type === "jsonb") return JSON.stringify(value);
2978
- if (typeof value === "object") return JSON.stringify(value);
3001
+ if ((_mastra_core_storage.TABLE_SCHEMAS[tableName]?.[columnName])?.type === "jsonb") return toPgJson(value);
3002
+ if (typeof value === "object") return toPgJson(value);
2979
3003
  return value;
2980
3004
  }
2981
3005
  async setupSchema() {
@@ -4229,7 +4253,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4229
4253
  "published",
4230
4254
  versionId,
4231
4255
  row.ownerId ?? row.authorId ?? null,
4232
- row.metadata ? JSON.stringify(row.metadata) : null,
4256
+ row.metadata ? toPgJson(row.metadata) : null,
4233
4257
  row.createdAt ?? now,
4234
4258
  row.updatedAt ?? now
4235
4259
  ]);
@@ -4245,17 +4269,17 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4245
4269
  row.name ?? agentId,
4246
4270
  row.description ?? null,
4247
4271
  this.serializeInstructions(row.instructions ?? ""),
4248
- row.model ? JSON.stringify(row.model) : "{}",
4249
- row.tools ? JSON.stringify(row.tools) : null,
4250
- row.defaultOptions ? JSON.stringify(row.defaultOptions) : null,
4251
- row.workflows ? JSON.stringify(row.workflows) : null,
4252
- row.agents ? JSON.stringify(row.agents) : null,
4253
- row.integrationTools ? JSON.stringify(row.integrationTools) : null,
4254
- row.toolProviders ? JSON.stringify(row.toolProviders) : null,
4255
- row.inputProcessors ? JSON.stringify(row.inputProcessors) : null,
4256
- row.outputProcessors ? JSON.stringify(row.outputProcessors) : null,
4257
- row.memory ? JSON.stringify(row.memory) : null,
4258
- row.scorers ? JSON.stringify(row.scorers) : null,
4272
+ row.model ? toPgJson(row.model) : "{}",
4273
+ row.tools ? toPgJson(row.tools) : null,
4274
+ row.defaultOptions ? toPgJson(row.defaultOptions) : null,
4275
+ row.workflows ? toPgJson(row.workflows) : null,
4276
+ row.agents ? toPgJson(row.agents) : null,
4277
+ row.integrationTools ? toPgJson(row.integrationTools) : null,
4278
+ row.toolProviders ? toPgJson(row.toolProviders) : null,
4279
+ row.inputProcessors ? toPgJson(row.inputProcessors) : null,
4280
+ row.outputProcessors ? toPgJson(row.outputProcessors) : null,
4281
+ row.memory ? toPgJson(row.memory) : null,
4282
+ row.scorers ? toPgJson(row.scorers) : null,
4259
4283
  null,
4260
4284
  "Migrated from legacy schema",
4261
4285
  row.createdAt ?? now
@@ -4305,7 +4329,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4305
4329
  for (const toolKey of toolsArray) toolsObject[toolKey] = {};
4306
4330
  await this.#db.client.none(`UPDATE ${fullVersionsTableName}
4307
4331
  SET tools = $1::jsonb
4308
- WHERE id = $2`, [JSON.stringify(toolsObject), record.id]);
4332
+ WHERE id = $2`, [toPgJson(toolsObject), record.id]);
4309
4333
  }
4310
4334
  this.logger?.info?.(`Migrated ${recordsWithArrayTools.length} agent version(s) tools from array to object format`);
4311
4335
  } catch (error) {
@@ -4402,6 +4426,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4402
4426
  const now = /* @__PURE__ */ new Date();
4403
4427
  const nowIso = now.toISOString();
4404
4428
  const visibility = agent.visibility ?? (agent.authorId ? "private" : null);
4429
+ const metadataJson = agent.metadata ? toPgJson(agent.metadata) : null;
4405
4430
  await this.#db.client.none(`INSERT INTO ${agentsTable} (
4406
4431
  id, status, "authorId", visibility, metadata, "favoriteCount",
4407
4432
  "activeVersionId",
@@ -4411,7 +4436,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4411
4436
  "draft",
4412
4437
  agent.authorId ?? null,
4413
4438
  visibility,
4414
- agent.metadata ? JSON.stringify(agent.metadata) : null,
4439
+ metadataJson,
4415
4440
  0,
4416
4441
  null,
4417
4442
  nowIso,
@@ -4435,7 +4460,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4435
4460
  activeVersionId: void 0,
4436
4461
  authorId: agent.authorId,
4437
4462
  visibility: visibility ?? void 0,
4438
- metadata: agent.metadata,
4463
+ metadata: metadataJson ? JSON.parse(metadataJson) : agent.metadata,
4439
4464
  favoriteCount: 0,
4440
4465
  createdAt: now,
4441
4466
  updatedAt: now
@@ -4493,7 +4518,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4493
4518
  }
4494
4519
  if (metadata !== void 0) {
4495
4520
  setClauses.push(`metadata = $${paramIndex++}`);
4496
- values.push(JSON.stringify(metadata));
4521
+ values.push(toPgJson(metadata));
4497
4522
  }
4498
4523
  const now = (/* @__PURE__ */ new Date()).toISOString();
4499
4524
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -4587,7 +4612,7 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4587
4612
  }
4588
4613
  if (metadata && Object.keys(metadata).length > 0) {
4589
4614
  conditions.push(`a.metadata @> $${paramIdx++}::jsonb`);
4590
- queryParams.push(JSON.stringify(metadata));
4615
+ queryParams.push(toPgJson(metadata));
4591
4616
  }
4592
4617
  if (entityIds && entityIds.length > 0) {
4593
4618
  const placeholders = entityIds.map(() => `$${paramIdx++}`).join(", ");
@@ -4653,9 +4678,8 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4653
4678
  indexName: _mastra_core_storage.TABLE_AGENT_VERSIONS,
4654
4679
  schemaName: getSchemaName$5(this.#schema)
4655
4680
  });
4656
- const now = /* @__PURE__ */ new Date();
4657
- const nowIso = now.toISOString();
4658
- await this.#db.client.none(`INSERT INTO ${tableName} (
4681
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
4682
+ const row = await this.#db.client.one(`INSERT INTO ${tableName} (
4659
4683
  id, "agentId", "versionNumber",
4660
4684
  name, description, instructions, model, tools,
4661
4685
  "defaultOptions", workflows, agents, "integrationTools", "toolProviders",
@@ -4664,40 +4688,37 @@ var AgentsPG = class AgentsPG extends _mastra_core_storage.AgentsStorage {
4664
4688
  durable, browser,
4665
4689
  "changedFields", "changeMessage",
4666
4690
  "createdAt", "createdAtZ"
4667
- ) 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)`, [
4691
+ ) 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) RETURNING *`, [
4668
4692
  input.id,
4669
4693
  input.agentId,
4670
4694
  input.versionNumber,
4671
4695
  input.name,
4672
4696
  input.description ?? null,
4673
4697
  this.serializeInstructions(input.instructions),
4674
- JSON.stringify(input.model),
4675
- input.tools ? JSON.stringify(input.tools) : null,
4676
- input.defaultOptions ? JSON.stringify(input.defaultOptions) : null,
4677
- input.workflows ? JSON.stringify(input.workflows) : null,
4678
- input.agents ? JSON.stringify(input.agents) : null,
4679
- input.integrationTools ? JSON.stringify(input.integrationTools) : null,
4680
- input.toolProviders ? JSON.stringify(input.toolProviders) : null,
4681
- input.inputProcessors ? JSON.stringify(input.inputProcessors) : null,
4682
- input.outputProcessors ? JSON.stringify(input.outputProcessors) : null,
4683
- input.memory ? JSON.stringify(input.memory) : null,
4684
- input.scorers ? JSON.stringify(input.scorers) : null,
4685
- input.mcpClients ? JSON.stringify(input.mcpClients) : null,
4686
- input.requestContextSchema ? JSON.stringify(input.requestContextSchema) : null,
4687
- input.workspace ? JSON.stringify(input.workspace) : null,
4688
- input.skills ? JSON.stringify(input.skills) : null,
4698
+ toPgJson(input.model),
4699
+ input.tools ? toPgJson(input.tools) : null,
4700
+ input.defaultOptions ? toPgJson(input.defaultOptions) : null,
4701
+ input.workflows ? toPgJson(input.workflows) : null,
4702
+ input.agents ? toPgJson(input.agents) : null,
4703
+ input.integrationTools ? toPgJson(input.integrationTools) : null,
4704
+ input.toolProviders ? toPgJson(input.toolProviders) : null,
4705
+ input.inputProcessors ? toPgJson(input.inputProcessors) : null,
4706
+ input.outputProcessors ? toPgJson(input.outputProcessors) : null,
4707
+ input.memory ? toPgJson(input.memory) : null,
4708
+ input.scorers ? toPgJson(input.scorers) : null,
4709
+ input.mcpClients ? toPgJson(input.mcpClients) : null,
4710
+ input.requestContextSchema ? toPgJson(input.requestContextSchema) : null,
4711
+ input.workspace ? toPgJson(input.workspace) : null,
4712
+ input.skills ? toPgJson(input.skills) : null,
4689
4713
  input.skillsFormat ?? null,
4690
- input.durable !== void 0 ? JSON.stringify(input.durable) : null,
4691
- input.browser ? JSON.stringify(input.browser) : null,
4692
- input.changedFields ? JSON.stringify(input.changedFields) : null,
4714
+ input.durable !== void 0 ? toPgJson(input.durable) : null,
4715
+ input.browser ? toPgJson(input.browser) : null,
4716
+ input.changedFields ? toPgJson(input.changedFields) : null,
4693
4717
  input.changeMessage ?? null,
4694
4718
  nowIso,
4695
4719
  nowIso
4696
4720
  ]);
4697
- return {
4698
- ...input,
4699
- createdAt: now
4700
- };
4721
+ return this.parseVersionRow(row);
4701
4722
  } catch (error) {
4702
4723
  if (error instanceof _mastra_core_error.MastraError) throw error;
4703
4724
  throw new _mastra_core_error.MastraError({
@@ -4981,7 +5002,7 @@ function getTableName$4(schemaName) {
4981
5002
  return schemaName ? `${schemaName}.${quoted}` : quoted;
4982
5003
  }
4983
5004
  function serializeJson(v) {
4984
- if (typeof v === "object" && v != null) return JSON.stringify(v);
5005
+ if (typeof v === "object" && v != null) return toPgJson(v);
4985
5006
  return v ?? null;
4986
5007
  }
4987
5008
  function parseJson$2(v) {
@@ -5560,7 +5581,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5560
5581
  installation.agentId,
5561
5582
  installation.status,
5562
5583
  installation.webhookId ?? null,
5563
- JSON.stringify(installation.data),
5584
+ toPgJson(installation.data),
5564
5585
  installation.configHash ?? null,
5565
5586
  installation.error ?? null,
5566
5587
  createdAt,
@@ -5620,7 +5641,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5620
5641
  "updatedAt" = EXCLUDED."updatedAt",
5621
5642
  "updatedAtZ" = EXCLUDED."updatedAtZ"`, [
5622
5643
  config.platform,
5623
- JSON.stringify(config.data),
5644
+ toPgJson(config.data),
5624
5645
  now,
5625
5646
  now
5626
5647
  ]);
@@ -5664,7 +5685,7 @@ var ChannelsPG = class ChannelsPG extends _mastra_core_storage.ChannelsStorage {
5664
5685
  //#region src/storage/domains/datasets/index.ts
5665
5686
  /** Serialize a value for a jsonb column. Returns null for null/undefined. */
5666
5687
  function jsonbArg(value) {
5667
- return value === void 0 || value === null ? null : JSON.stringify(value);
5688
+ return value === void 0 || value === null ? null : toPgJson(value);
5668
5689
  }
5669
5690
  /** Preserve JSON null as data, rather than converting it to an absent SQL value. */
5670
5691
  function jsonDataArg(value) {
@@ -6045,23 +6066,23 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6045
6066
  }
6046
6067
  if (args.metadata !== void 0) {
6047
6068
  setClauses.push(`"metadata" = $${paramIndex++}`);
6048
- values.push(JSON.stringify(args.metadata));
6069
+ values.push(toPgJson(args.metadata));
6049
6070
  }
6050
6071
  if (args.inputSchema !== void 0) {
6051
6072
  setClauses.push(`"inputSchema" = $${paramIndex++}`);
6052
- values.push(args.inputSchema === null ? null : JSON.stringify(args.inputSchema));
6073
+ values.push(args.inputSchema === null ? null : toPgJson(args.inputSchema));
6053
6074
  }
6054
6075
  if (args.groundTruthSchema !== void 0) {
6055
6076
  setClauses.push(`"groundTruthSchema" = $${paramIndex++}`);
6056
- values.push(args.groundTruthSchema === null ? null : JSON.stringify(args.groundTruthSchema));
6077
+ values.push(args.groundTruthSchema === null ? null : toPgJson(args.groundTruthSchema));
6057
6078
  }
6058
6079
  if (args.requestContextSchema !== void 0) {
6059
6080
  setClauses.push(`"requestContextSchema" = $${paramIndex++}`);
6060
- values.push(args.requestContextSchema === null ? null : JSON.stringify(args.requestContextSchema));
6081
+ values.push(args.requestContextSchema === null ? null : toPgJson(args.requestContextSchema));
6061
6082
  }
6062
6083
  if (args.tags !== void 0) {
6063
6084
  setClauses.push(`"tags" = $${paramIndex++}`);
6064
- values.push(args.tags === null ? null : JSON.stringify(args.tags));
6085
+ values.push(args.tags === null ? null : toPgJson(args.tags));
6065
6086
  }
6066
6087
  if (args.targetType !== void 0) {
6067
6088
  setClauses.push(`"targetType" = $${paramIndex++}`);
@@ -6069,11 +6090,11 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6069
6090
  }
6070
6091
  if (args.targetIds !== void 0) {
6071
6092
  setClauses.push(`"targetIds" = $${paramIndex++}`);
6072
- values.push(args.targetIds === null ? null : JSON.stringify(args.targetIds));
6093
+ values.push(args.targetIds === null ? null : toPgJson(args.targetIds));
6073
6094
  }
6074
6095
  if (args.scorerIds !== void 0) {
6075
6096
  setClauses.push(`"scorerIds" = $${paramIndex++}`);
6076
- values.push(args.scorerIds === null ? null : JSON.stringify(args.scorerIds));
6097
+ values.push(args.scorerIds === null ? null : toPgJson(args.scorerIds));
6077
6098
  }
6078
6099
  values.push(args.id);
6079
6100
  await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE "id" = $${paramIndex}`, values);
@@ -6521,10 +6542,9 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6521
6542
  indexName: _mastra_core_storage.TABLE_EXPERIMENT_RESULTS,
6522
6543
  schemaName: getSchemaName$5(this.#schema)
6523
6544
  });
6524
- const purgedAt = (/* @__PURE__ */ new Date()).toISOString();
6525
- const purgedMetadata = JSON.stringify({
6545
+ const purgedMetadata = toPgJson({
6526
6546
  __purged: true,
6527
- purgedAt
6547
+ purgedAt: (/* @__PURE__ */ new Date()).toISOString()
6528
6548
  });
6529
6549
  await this.#db.client.tx(async (t) => {
6530
6550
  if (!await t.oneOrNone(`SELECT "id" FROM ${datasetsTable} WHERE "id" = $1 FOR UPDATE`, [datasetId])) return;
@@ -7324,7 +7344,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7324
7344
  }
7325
7345
  if (input.metadata !== void 0) {
7326
7346
  setClauses.push(`"metadata" = $${paramIndex++}`);
7327
- values.push(JSON.stringify(input.metadata));
7347
+ values.push(toPgJson(input.metadata));
7328
7348
  }
7329
7349
  if (input.status !== void 0) {
7330
7350
  setClauses.push(`"status" = $${paramIndex++}`);
@@ -7555,19 +7575,19 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7555
7575
  input.itemDatasetVersion ?? null,
7556
7576
  input.organizationId ?? null,
7557
7577
  input.projectId ?? null,
7558
- JSON.stringify(purgeMetadata ? null : input.input),
7559
- purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7560
- purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7561
- JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7562
- purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7578
+ toPgJson(purgeMetadata ? null : input.input),
7579
+ purgeMetadata || input.output == null ? null : toPgJson(input.output),
7580
+ purgeMetadata || input.groundTruth == null ? null : toPgJson(input.groundTruth),
7581
+ toPgJson(purgeMetadata ?? input.metadata ?? null),
7582
+ purgeMetadata || input.error == null ? null : toPgJson(input.error),
7563
7583
  input.startedAt.toISOString(),
7564
7584
  input.completedAt.toISOString(),
7565
7585
  input.retryCount,
7566
7586
  input.attempt ?? 0,
7567
7587
  input.traceId ?? null,
7568
7588
  input.status ?? null,
7569
- purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7570
- purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport),
7589
+ purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7590
+ purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport),
7571
7591
  nowIso
7572
7592
  ]);
7573
7593
  });
@@ -7613,19 +7633,19 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7613
7633
  input.itemDatasetVersion ?? null,
7614
7634
  input.organizationId ?? null,
7615
7635
  input.projectId ?? null,
7616
- JSON.stringify(purgeMetadata ? null : input.input),
7617
- purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7618
- purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7619
- JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7620
- purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7636
+ toPgJson(purgeMetadata ? null : input.input),
7637
+ purgeMetadata || input.output == null ? null : toPgJson(input.output),
7638
+ purgeMetadata || input.groundTruth == null ? null : toPgJson(input.groundTruth),
7639
+ toPgJson(purgeMetadata ?? input.metadata ?? null),
7640
+ purgeMetadata || input.error == null ? null : toPgJson(input.error),
7621
7641
  input.startedAt.toISOString(),
7622
7642
  input.completedAt.toISOString(),
7623
7643
  input.retryCount,
7624
7644
  attempt,
7625
7645
  input.traceId ?? null,
7626
7646
  input.status ?? null,
7627
- purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7628
- purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport),
7647
+ purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7648
+ purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport),
7629
7649
  (/* @__PURE__ */ new Date()).toISOString()
7630
7650
  ]);
7631
7651
  }
@@ -7639,19 +7659,19 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7639
7659
  input.itemDatasetVersion ?? null,
7640
7660
  input.organizationId ?? null,
7641
7661
  input.projectId ?? null,
7642
- JSON.stringify(purgeMetadata ? null : input.input),
7643
- purgeMetadata || input.output == null ? null : JSON.stringify(input.output),
7644
- purgeMetadata || input.groundTruth == null ? null : JSON.stringify(input.groundTruth),
7645
- JSON.stringify(purgeMetadata ?? input.metadata ?? null),
7646
- purgeMetadata || input.error == null ? null : JSON.stringify(input.error),
7662
+ toPgJson(purgeMetadata ? null : input.input),
7663
+ purgeMetadata || input.output == null ? null : toPgJson(input.output),
7664
+ purgeMetadata || input.groundTruth == null ? null : toPgJson(input.groundTruth),
7665
+ toPgJson(purgeMetadata ?? input.metadata ?? null),
7666
+ purgeMetadata || input.error == null ? null : toPgJson(input.error),
7647
7667
  input.startedAt.toISOString(),
7648
7668
  input.completedAt.toISOString(),
7649
7669
  input.retryCount,
7650
7670
  attempt,
7651
7671
  input.traceId ?? null,
7652
7672
  input.status ?? null,
7653
- purgeMetadata || input.tags == null ? null : JSON.stringify(input.tags),
7654
- purgeMetadata || input.toolMockReport == null ? null : JSON.stringify(input.toolMockReport)
7673
+ purgeMetadata || input.tags == null ? null : toPgJson(input.tags),
7674
+ purgeMetadata || input.toolMockReport == null ? null : toPgJson(input.toolMockReport)
7655
7675
  ]);
7656
7676
  });
7657
7677
  return this.transformExperimentResultRow(row);
@@ -7691,7 +7711,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7691
7711
  input.status ?? null,
7692
7712
  Boolean(purgeMetadata),
7693
7713
  input.tags !== void 0,
7694
- input.tags === void 0 ? null : JSON.stringify(input.tags),
7714
+ input.tags === void 0 ? null : toPgJson(input.tags),
7695
7715
  input.comment !== void 0,
7696
7716
  input.comment ?? null,
7697
7717
  ...input.experimentId !== void 0 ? [input.experimentId] : []
@@ -7762,7 +7782,7 @@ var ExperimentsPG = class ExperimentsPG extends _mastra_core_storage.Experiments
7762
7782
  }
7763
7783
  for (const tag of args.tags ?? []) {
7764
7784
  conditions.push(`"tags" @> $${paramIndex++}::jsonb`);
7765
- queryParams.push(JSON.stringify([tag]));
7785
+ queryParams.push(toPgJson([tag]));
7766
7786
  }
7767
7787
  if (args.filters) {
7768
7788
  const { organizationId, projectId } = args.filters;
@@ -8689,6 +8709,7 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8689
8709
  return this.#transaction(async (tx) => {
8690
8710
  const parent = await this.#resolveTerminalNode(tx, nodeReferenceId(input.node));
8691
8711
  if (!parent) throw new _mastra_core_storage.KnowledgeNotFoundError("node", nodeReferenceId(input.node));
8712
+ const metadataJson = input.metadata ? toPgJson(input.metadata) : null;
8692
8713
  const record = {
8693
8714
  id: input.id ?? (0, _mastra_core_storage.createKnowledgeUlid)(),
8694
8715
  node: parent.id,
@@ -8712,13 +8733,16 @@ var KnowledgePG = class extends _mastra_core_storage.KnowledgeStorage {
8712
8733
  record.capturedAt.toISOString(),
8713
8734
  record.when?.toISOString() ?? null,
8714
8735
  record.maxScope ?? null,
8715
- record.metadata ? JSON.stringify(record.metadata) : null
8736
+ metadataJson
8716
8737
  ]
8717
8738
  });
8718
8739
  await this.#replaceMentions(tx, "record", record.id, record.text, resolutionScope, defaultScope);
8719
8740
  await this.#activity(tx, "record-created", "record", record.id, scope, record.sourceThreadId);
8720
8741
  await this.#outbox(tx, "record", record.id, "upsert", record.id, scope);
8721
- return record;
8742
+ return metadataJson ? {
8743
+ ...record,
8744
+ metadata: JSON.parse(metadataJson)
8745
+ } : record;
8722
8746
  });
8723
8747
  }
8724
8748
  async getKnowledge(input) {
@@ -9287,6 +9311,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9287
9311
  });
9288
9312
  const now = /* @__PURE__ */ new Date();
9289
9313
  const nowIso = now.toISOString();
9314
+ const metadataJson = mcpClient.metadata ? toPgJson(mcpClient.metadata) : null;
9290
9315
  await this.#db.client.none(`INSERT INTO ${tableName} (
9291
9316
  id, status, "activeVersionId", "authorId", metadata,
9292
9317
  "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
@@ -9295,7 +9320,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9295
9320
  "draft",
9296
9321
  null,
9297
9322
  mcpClient.authorId ?? null,
9298
- mcpClient.metadata ? JSON.stringify(mcpClient.metadata) : null,
9323
+ metadataJson,
9299
9324
  nowIso,
9300
9325
  nowIso,
9301
9326
  nowIso,
@@ -9316,7 +9341,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9316
9341
  status: "draft",
9317
9342
  activeVersionId: void 0,
9318
9343
  authorId: mcpClient.authorId,
9319
- metadata: mcpClient.metadata,
9344
+ metadata: metadataJson ? JSON.parse(metadataJson) : mcpClient.metadata,
9320
9345
  createdAt: now,
9321
9346
  updatedAt: now
9322
9347
  };
@@ -9374,7 +9399,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9374
9399
  ...metadata
9375
9400
  };
9376
9401
  setClauses.push(`metadata = $${paramIndex++}`);
9377
- values.push(JSON.stringify(mergedMetadata));
9402
+ values.push(toPgJson(mergedMetadata));
9378
9403
  }
9379
9404
  const now = (/* @__PURE__ */ new Date()).toISOString();
9380
9405
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -9447,7 +9472,7 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9447
9472
  }
9448
9473
  if (metadata && Object.keys(metadata).length > 0) {
9449
9474
  conditions.push(`metadata @> $${paramIdx++}::jsonb`);
9450
- queryParams.push(JSON.stringify(metadata));
9475
+ queryParams.push(toPgJson(metadata));
9451
9476
  }
9452
9477
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
9453
9478
  const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
@@ -9498,6 +9523,8 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9498
9523
  });
9499
9524
  const now = /* @__PURE__ */ new Date();
9500
9525
  const nowIso = now.toISOString();
9526
+ const serversJson = toPgJson(input.servers);
9527
+ const changedFieldsJson = input.changedFields ? toPgJson(input.changedFields) : null;
9501
9528
  await this.#db.client.none(`INSERT INTO ${tableName} (
9502
9529
  id, "mcpClientId", "versionNumber",
9503
9530
  name, description, servers,
@@ -9509,14 +9536,16 @@ var MCPClientsPG = class MCPClientsPG extends _mastra_core_storage.MCPClientsSto
9509
9536
  input.versionNumber,
9510
9537
  input.name,
9511
9538
  input.description ?? null,
9512
- JSON.stringify(input.servers),
9513
- input.changedFields ? JSON.stringify(input.changedFields) : null,
9539
+ serversJson,
9540
+ changedFieldsJson,
9514
9541
  input.changeMessage ?? null,
9515
9542
  nowIso,
9516
9543
  nowIso
9517
9544
  ]);
9518
9545
  return {
9519
9546
  ...input,
9547
+ servers: JSON.parse(serversJson),
9548
+ changedFields: changedFieldsJson ? JSON.parse(changedFieldsJson) : input.changedFields,
9520
9549
  createdAt: now
9521
9550
  };
9522
9551
  } catch (error) {
@@ -9858,7 +9887,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9858
9887
  "draft",
9859
9888
  null,
9860
9889
  mcpServer.authorId ?? null,
9861
- mcpServer.metadata ? JSON.stringify(mcpServer.metadata) : null,
9890
+ mcpServer.metadata ? toPgJson(mcpServer.metadata) : null,
9862
9891
  nowIso,
9863
9892
  nowIso,
9864
9893
  nowIso,
@@ -9937,7 +9966,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
9937
9966
  ...metadata
9938
9967
  };
9939
9968
  setClauses.push(`metadata = $${paramIndex++}`);
9940
- values.push(JSON.stringify(mergedMetadata));
9969
+ values.push(toPgJson(mergedMetadata));
9941
9970
  }
9942
9971
  const now = (/* @__PURE__ */ new Date()).toISOString();
9943
9972
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -10010,7 +10039,7 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
10010
10039
  }
10011
10040
  if (metadata && Object.keys(metadata).length > 0) {
10012
10041
  conditions.push(`metadata @> $${paramIdx++}::jsonb`);
10013
- queryParams.push(JSON.stringify(metadata));
10042
+ queryParams.push(toPgJson(metadata));
10014
10043
  }
10015
10044
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
10016
10045
  const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
@@ -10076,14 +10105,14 @@ var MCPServersPG = class MCPServersPG extends _mastra_core_storage.MCPServersSto
10076
10105
  input.version,
10077
10106
  input.description ?? null,
10078
10107
  input.instructions ?? null,
10079
- input.repository ? JSON.stringify(input.repository) : null,
10108
+ input.repository ? toPgJson(input.repository) : null,
10080
10109
  input.releaseDate ?? null,
10081
10110
  input.isLatest ?? null,
10082
10111
  input.packageCanonical ?? null,
10083
- input.tools ? JSON.stringify(input.tools) : null,
10084
- input.agents ? JSON.stringify(input.agents) : null,
10085
- input.workflows ? JSON.stringify(input.workflows) : null,
10086
- input.changedFields ? JSON.stringify(input.changedFields) : null,
10112
+ input.tools ? toPgJson(input.tools) : null,
10113
+ input.agents ? toPgJson(input.agents) : null,
10114
+ input.workflows ? toPgJson(input.workflows) : null,
10115
+ input.changedFields ? toPgJson(input.changedFields) : null,
10087
10116
  input.changeMessage ?? null,
10088
10117
  nowIso,
10089
10118
  nowIso
@@ -10818,7 +10847,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10818
10847
  }
10819
10848
  if (filter?.metadata && Object.keys(filter.metadata).length > 0) for (const [key, value] of Object.entries(filter.metadata)) {
10820
10849
  whereClauses.push(`metadata::jsonb @> $${paramIndex}::jsonb`);
10821
- queryParams.push(JSON.stringify({ [key]: value }));
10850
+ queryParams.push(toPgJson({ [key]: value }));
10822
10851
  paramIndex++;
10823
10852
  }
10824
10853
  const baseQuery = `FROM ${tableName} ${whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : ""}`;
@@ -10877,6 +10906,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10877
10906
  });
10878
10907
  const createdAt = toUtcISOString(thread.createdAt);
10879
10908
  const updatedAt = toUtcISOString(thread.updatedAt);
10909
+ const metadataJson = thread.metadata ? toPgJson(thread.metadata) : null;
10880
10910
  await this.#db.client.none(`INSERT INTO ${tableName} (
10881
10911
  id,
10882
10912
  "resourceId",
@@ -10898,13 +10928,16 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
10898
10928
  thread.id,
10899
10929
  thread.resourceId,
10900
10930
  thread.title,
10901
- thread.metadata ? JSON.stringify(thread.metadata) : null,
10931
+ metadataJson,
10902
10932
  createdAt,
10903
10933
  createdAt,
10904
10934
  updatedAt,
10905
10935
  updatedAt
10906
10936
  ]);
10907
- return thread;
10937
+ return {
10938
+ ...thread,
10939
+ metadata: metadataJson ? JSON.parse(metadataJson) : thread.metadata
10940
+ };
10908
10941
  } catch (error) {
10909
10942
  throw new _mastra_core_error.MastraError({
10910
10943
  id: (0, _mastra_core_storage.createStorageErrorId)("PG", "SAVE_THREAD", "FAILED"),
@@ -11720,16 +11753,20 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11720
11753
  async saveResource({ resource }) {
11721
11754
  const createdAt = toUtcISOString(resource.createdAt);
11722
11755
  const updatedAt = toUtcISOString(resource.updatedAt);
11756
+ const metadataJson = toPgJson(resource.metadata);
11723
11757
  await this.#db.insert({
11724
11758
  tableName: _mastra_core_storage.TABLE_RESOURCES,
11725
11759
  record: {
11726
11760
  ...resource,
11727
- metadata: JSON.stringify(resource.metadata),
11761
+ metadata: metadataJson,
11728
11762
  createdAt,
11729
11763
  updatedAt
11730
11764
  }
11731
11765
  });
11732
- return resource;
11766
+ return {
11767
+ ...resource,
11768
+ metadata: metadataJson ? JSON.parse(metadataJson) : resource.metadata
11769
+ };
11733
11770
  }
11734
11771
  async updateResource({ resourceId, workingMemory, metadata }) {
11735
11772
  const existingResource = await this.#getResourceById(this.#db.client, resourceId);
@@ -11764,9 +11801,11 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11764
11801
  values.push(workingMemory);
11765
11802
  paramIndex++;
11766
11803
  }
11804
+ let metadataJson;
11767
11805
  if (metadata) {
11806
+ metadataJson = toPgJson(updatedResource.metadata);
11768
11807
  updates.push(`metadata = $${paramIndex}`);
11769
- values.push(JSON.stringify(updatedResource.metadata));
11808
+ values.push(metadataJson);
11770
11809
  paramIndex++;
11771
11810
  }
11772
11811
  const updatedAtStr = updatedResource.updatedAt.toISOString();
@@ -11776,7 +11815,10 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11776
11815
  values.push(updatedAtStr);
11777
11816
  values.push(resourceId);
11778
11817
  await this.#db.client.none(`UPDATE ${tableName} SET ${updates.join(", ")} WHERE id = $${paramIndex}`, values);
11779
- return updatedResource;
11818
+ return metadataJson ? {
11819
+ ...updatedResource,
11820
+ metadata: JSON.parse(metadataJson)
11821
+ } : updatedResource;
11780
11822
  }
11781
11823
  async copyThread(args) {
11782
11824
  const { sourceThreadId, newThreadId: providedThreadId, resourceId, title, metadata, options } = args;
@@ -11861,7 +11903,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
11861
11903
  newThread.id,
11862
11904
  newThread.resourceId,
11863
11905
  newThread.title,
11864
- newThread.metadata ? JSON.stringify(newThread.metadata) : null,
11906
+ newThread.metadata ? toPgJson(newThread.metadata) : null,
11865
11907
  nowStr,
11866
11908
  nowStr,
11867
11909
  nowStr,
@@ -12052,7 +12094,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12052
12094
  "",
12053
12095
  null,
12054
12096
  "initial",
12055
- JSON.stringify(input.config),
12097
+ toPgJson(input.config),
12056
12098
  0,
12057
12099
  null,
12058
12100
  null,
@@ -12115,7 +12157,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12115
12157
  record.activeObservations || "",
12116
12158
  null,
12117
12159
  record.originType || "initial",
12118
- record.config ? JSON.stringify(record.config) : null,
12160
+ record.config ? toPgJson(record.config) : null,
12119
12161
  record.generationCount || 0,
12120
12162
  lastObservedAtStr,
12121
12163
  lastObservedAtStr,
@@ -12124,8 +12166,8 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12124
12166
  record.pendingMessageTokens || 0,
12125
12167
  record.totalTokensObserved || 0,
12126
12168
  record.observationTokenCount || 0,
12127
- record.observedMessageIds ? JSON.stringify(record.observedMessageIds) : null,
12128
- record.bufferedObservationChunks ? JSON.stringify(record.bufferedObservationChunks) : null,
12169
+ record.observedMessageIds ? toPgJson(record.observedMessageIds) : null,
12170
+ record.bufferedObservationChunks ? toPgJson(record.bufferedObservationChunks) : null,
12129
12171
  record.bufferedReflection || null,
12130
12172
  record.bufferedReflectionTokens ?? null,
12131
12173
  record.bufferedReflectionInputTokens ?? null,
@@ -12137,7 +12179,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12137
12179
  record.lastBufferedAtTokens || 0,
12138
12180
  lastBufferedAtTimeStr,
12139
12181
  record.observedTimezone || null,
12140
- record.metadata ? JSON.stringify(record.metadata) : null,
12182
+ record.metadata ? toPgJson(record.metadata) : null,
12141
12183
  record.createdAt.toISOString(),
12142
12184
  record.createdAt.toISOString(),
12143
12185
  record.updatedAt.toISOString(),
@@ -12165,7 +12207,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12165
12207
  });
12166
12208
  const lastObservedAtStr = input.lastObservedAt.toISOString();
12167
12209
  const nowStr = now.toISOString();
12168
- const observedMessageIdsJson = input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null;
12210
+ const observedMessageIdsJson = input.observedMessageIds ? toPgJson(input.observedMessageIds) : null;
12169
12211
  if ((await this.#db.client.query(`UPDATE ${tableName} SET
12170
12212
  "activeObservations" = $1,
12171
12213
  "lastObservedAt" = $2,
@@ -12254,7 +12296,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12254
12296
  input.reflection,
12255
12297
  null,
12256
12298
  "reflection",
12257
- JSON.stringify(record.config),
12299
+ toPgJson(record.config),
12258
12300
  input.currentRecord.generationCount + 1,
12259
12301
  lastObservedAtStr,
12260
12302
  lastObservedAtStr,
@@ -12270,7 +12312,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12270
12312
  0,
12271
12313
  null,
12272
12314
  record.observedTimezone || null,
12273
- record.metadata ? JSON.stringify(record.metadata) : null,
12315
+ record.metadata ? toPgJson(record.metadata) : null,
12274
12316
  nowStr,
12275
12317
  nowStr,
12276
12318
  nowStr,
@@ -12521,7 +12563,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12521
12563
  const merged = this.deepMergeConfig(existing, input.config);
12522
12564
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12523
12565
  await this.#db.client.query(`UPDATE ${tableName} SET config = $1, "updatedAt" = $2, "updatedAtZ" = $3 WHERE id = $4`, [
12524
- JSON.stringify(merged),
12566
+ toPgJson(merged),
12525
12567
  nowStr,
12526
12568
  nowStr,
12527
12569
  input.id
@@ -12572,7 +12614,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12572
12614
  "updatedAt" = $4,
12573
12615
  "updatedAtZ" = $5
12574
12616
  WHERE id = $6`, [
12575
- JSON.stringify([newChunk]),
12617
+ toPgJson([newChunk]),
12576
12618
  input.chunk.cycleId,
12577
12619
  lastBufferedAtTime,
12578
12620
  nowStr,
@@ -12687,7 +12729,7 @@ var MemoryPG = class MemoryPG extends _mastra_core_storage.MemoryStorage {
12687
12729
  activatedContent,
12688
12730
  activatedTokens,
12689
12731
  activatedMessageTokens,
12690
- remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,
12732
+ remainingChunks.length > 0 ? toPgJson(remainingChunks) : null,
12691
12733
  lastObservedAtStr,
12692
12734
  lastObservedAtStr,
12693
12735
  nowStr,
@@ -13067,7 +13109,7 @@ var NotificationsPG = class NotificationsPG extends _mastra_core_storage.Notific
13067
13109
  });
13068
13110
  const setColumns = entries.map(([key], index) => `"${(0, _mastra_core_utils.parseSqlIdentifier)(key, "column name")}" = $${index + 1}`);
13069
13111
  const values = entries.map(([key, value]) => {
13070
- if (_mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_NOTIFICATIONS][key]?.type === "jsonb" && value !== null) return JSON.stringify(value);
13112
+ if (_mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_NOTIFICATIONS][key]?.type === "jsonb" && value !== null) return toPgJson(value);
13071
13113
  return value;
13072
13114
  });
13073
13115
  await this.#db.client.none(`UPDATE ${tableName} SET ${setColumns.join(", ")} WHERE "threadId" = $${values.length + 1} AND "id" = $${values.length + 2}`, [
@@ -13788,15 +13830,15 @@ var ObservabilityPG = class ObservabilityPG extends _mastra_core_storage.Observa
13788
13830
  }
13789
13831
  if (filters.scope != null) {
13790
13832
  conditions.push(`r."scope" @> $${paramIndex++}`);
13791
- params.push(JSON.stringify(filters.scope));
13833
+ params.push(toPgJson(filters.scope));
13792
13834
  }
13793
13835
  if (filters.metadata != null) {
13794
13836
  conditions.push(`r."metadata" @> $${paramIndex++}`);
13795
- params.push(JSON.stringify(filters.metadata));
13837
+ params.push(toPgJson(filters.metadata));
13796
13838
  }
13797
13839
  if (filters.tags != null && filters.tags.length > 0) {
13798
13840
  conditions.push(`r."tags" @> $${paramIndex++}`);
13799
- params.push(JSON.stringify(filters.tags));
13841
+ params.push(toPgJson(filters.tags));
13800
13842
  }
13801
13843
  if (filters.status !== void 0) switch (filters.status) {
13802
13844
  case _mastra_core_storage.TraceStatus.ERROR:
@@ -15105,7 +15147,7 @@ async function upsertCache(client, schema, cacheKey, values) {
15105
15147
  VALUES ($1, NOW(), $2::jsonb)
15106
15148
  ON CONFLICT ("cacheKey") DO UPDATE SET
15107
15149
  "refreshedAt" = EXCLUDED."refreshedAt",
15108
- "values" = EXCLUDED."values"`, [cacheKey, JSON.stringify(values)]);
15150
+ "values" = EXCLUDED."values"`, [cacheKey, toPgJson(values)]);
15109
15151
  }
15110
15152
  /**
15111
15153
  * Time predicate that bounds a discovery refresh to recent events.
@@ -16059,20 +16101,6 @@ const COMPLEX_GROUP_BY_EXCLUDED = /* @__PURE__ */ new Set([
16059
16101
  "requestContext"
16060
16102
  ]);
16061
16103
  //#endregion
16062
- //#region src/storage/db/sanitize-json.ts
16063
- /**
16064
- * Sanitizes JSON string for PostgreSQL jsonb:
16065
- * - Removes problematic Unicode sequences:
16066
- * - \u0000 (null character) - causes error 22P05 "unsupported Unicode escape sequence"
16067
- * - \uD800-\uDFFF (unpaired surrogates) - causes "Unicode low surrogate must follow a high surrogate"
16068
- * - \\uD800 (escaped-backslash + surrogate, e.g. from JS regex literals like [^\ud800-\udfff]):
16069
- * removing just \uXXXX would leave a dangling backslash that creates a new invalid escape (e.g. \-)
16070
- * - Escapes any remaining invalid JSON escape sequences (e.g. \v, \k, \-)
16071
- */
16072
- function sanitizeJsonForPg(jsonString) {
16073
- return jsonString.replace(/\\\\?u(0000|[Dd][89A-Fa-f][0-9A-Fa-f]{2})/g, "").replace(/(^|[^\\])(\\(?!["\\/bfnrtu]))/g, "$1\\\\");
16074
- }
16075
- //#endregion
16076
16104
  //#region src/storage/domains/observability/v-next/sql.ts
16077
16105
  /**
16078
16106
  * SQL helpers for the v-next Postgres observability domain.
@@ -16094,7 +16122,7 @@ function sanitizeJsonForPg(jsonString) {
16094
16122
  */
16095
16123
  function encodeJsonb(value) {
16096
16124
  if (value === null || value === void 0) return null;
16097
- return sanitizeJsonForPg(JSON.stringify(value));
16125
+ return toPgJson(value);
16098
16126
  }
16099
16127
  /**
16100
16128
  * Build a multi-row INSERT with explicit column types and ON CONFLICT DO NOTHING.
@@ -16495,7 +16523,7 @@ function applyMetricFilters(acc, filters) {
16495
16523
  applySingleOrArrayFilter(acc, "costUnit", filters?.costUnit);
16496
16524
  if (filters?.labels) {
16497
16525
  acc.conditions.push(`"labels" @> $${acc.next++}::jsonb`);
16498
- acc.params.push(JSON.stringify(filters.labels));
16526
+ acc.params.push(toPgJson(filters.labels));
16499
16527
  }
16500
16528
  }
16501
16529
  /** Additional WHERE for metric-name restriction (OLAP queries take a `name` array). */
@@ -17008,7 +17036,7 @@ function applyScoreFilters(acc, filters) {
17008
17036
  }
17009
17037
  if (filters?.metadata && Object.keys(filters.metadata).length > 0) for (const [key, value] of Object.entries(filters.metadata)) {
17010
17038
  acc.conditions.push(`"metadata"->($${acc.next++}::text) = $${acc.next++}::jsonb`);
17011
- acc.params.push(key, JSON.stringify(value ?? null));
17039
+ acc.params.push(key, toPgJson(value ?? null));
17012
17040
  }
17013
17041
  }
17014
17042
  /** OLAP queries take an explicit scorerId / scoreSource pair as identity. */
@@ -17274,12 +17302,16 @@ async function getScorePercentiles(client, schema, args) {
17274
17302
  //#endregion
17275
17303
  //#region src/storage/domains/observability/v-next/trace-query.ts
17276
17304
  const TRACE_STATUS_SQL = `CASE WHEN r."error" IS NOT NULL THEN 'error' ELSE 'success' END`;
17305
+ function durationMsSql(startedAt, endedAt) {
17306
+ return `EXTRACT(EPOCH FROM (${endedAt} - ${startedAt}))::numeric * 1000`;
17307
+ }
17277
17308
  const TRACE_FIELDS = {
17278
17309
  traceId: "r.\"traceId\"",
17279
17310
  threadId: "r.\"threadId\"",
17280
17311
  resourceId: "r.\"resourceId\"",
17281
17312
  startedAt: "r.\"startedAt\"",
17282
17313
  endedAt: "r.\"endedAt\"",
17314
+ durationMs: durationMsSql("r.\"startedAt\"", "r.\"endedAt\""),
17283
17315
  entityName: "r.\"entityName\"",
17284
17316
  entityType: "r.\"entityType\"",
17285
17317
  environment: "r.\"environment\"",
@@ -17608,7 +17640,7 @@ function compilePostgresTraceScope(schema, selection, relationCollections, scope
17608
17640
  CASE WHEN s."isPending" THEN NULL ELSE s."endedAt" END AS "endedAt",
17609
17641
  CASE
17610
17642
  WHEN s."isPending" THEN NULL
17611
- ELSE EXTRACT(EPOCH FROM (s."endedAt" - s."startedAt")) * 1000
17643
+ ELSE ${durationMsSql("s.\"startedAt\"", "s.\"endedAt\"")}
17612
17644
  END AS "durationMs",
17613
17645
  CASE WHEN s."error" IS NOT NULL THEN 'error' ELSE 'success' END AS "status",
17614
17646
  s."error",
@@ -18207,7 +18239,7 @@ function buildListTracesFilters(filters, spanTable, nextParamIdx) {
18207
18239
  }
18208
18240
  if (filters.metadata != null) {
18209
18241
  conditions.push(`r."metadataSearch" @> $${i++}::jsonb`);
18210
- params.push(JSON.stringify(filters.metadata));
18242
+ params.push(toPgJson(filters.metadata));
18211
18243
  }
18212
18244
  if (filters.tags != null && filters.tags.length > 0) {
18213
18245
  conditions.push(`r."tags" @> $${i++}::text[]`);
@@ -18485,7 +18517,7 @@ function buildListBranchesFilters(filters, spanType, spanTable, nextParamIdx) {
18485
18517
  }
18486
18518
  if (filters.metadata != null) {
18487
18519
  conditions.push(`r."metadataSearch" @> $${i++}::jsonb`);
18488
- params.push(JSON.stringify(filters.metadata));
18520
+ params.push(toPgJson(filters.metadata));
18489
18521
  }
18490
18522
  if (filters.tags != null && filters.tags.length > 0) {
18491
18523
  conditions.push(`r."tags" @> $${i++}::text[]`);
@@ -18950,6 +18982,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
18950
18982
  "metrics",
18951
18983
  "logs",
18952
18984
  "trace-query",
18985
+ "trace-query-root-duration",
18953
18986
  "trace-query-discovery",
18954
18987
  "thread-query",
18955
18988
  "trace-query-tenant-scope"
@@ -18959,6 +18992,7 @@ var ObservabilityStoragePostgresVNext = class ObservabilityStoragePostgresVNext
18959
18992
  "logs",
18960
18993
  "delta-polling",
18961
18994
  "trace-query",
18995
+ "trace-query-root-duration",
18962
18996
  "trace-query-discovery",
18963
18997
  "thread-query",
18964
18998
  "trace-query-tenant-scope"
@@ -19276,7 +19310,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19276
19310
  "draft",
19277
19311
  null,
19278
19312
  promptBlock.authorId ?? null,
19279
- promptBlock.metadata ? JSON.stringify(promptBlock.metadata) : null,
19313
+ promptBlock.metadata ? toPgJson(promptBlock.metadata) : null,
19280
19314
  nowIso,
19281
19315
  nowIso,
19282
19316
  nowIso,
@@ -19355,7 +19389,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19355
19389
  ...metadata
19356
19390
  };
19357
19391
  setClauses.push(`metadata = $${paramIndex++}`);
19358
- values.push(JSON.stringify(mergedMetadata));
19392
+ values.push(toPgJson(mergedMetadata));
19359
19393
  }
19360
19394
  const now = (/* @__PURE__ */ new Date()).toISOString();
19361
19395
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -19430,7 +19464,7 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19430
19464
  }
19431
19465
  if (metadata && Object.keys(metadata).length > 0) {
19432
19466
  conditions.push(`metadata @> $${paramIdx++}::jsonb`);
19433
- queryParams.push(JSON.stringify(metadata));
19467
+ queryParams.push(toPgJson(metadata));
19434
19468
  }
19435
19469
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
19436
19470
  const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
@@ -19493,9 +19527,9 @@ var PromptBlocksPG = class PromptBlocksPG extends _mastra_core_storage.PromptBlo
19493
19527
  input.name,
19494
19528
  input.description ?? null,
19495
19529
  input.content,
19496
- input.rules ? JSON.stringify(input.rules) : null,
19497
- input.requestContextSchema ? JSON.stringify(input.requestContextSchema) : null,
19498
- input.changedFields ? JSON.stringify(input.changedFields) : null,
19530
+ input.rules ? toPgJson(input.rules) : null,
19531
+ input.requestContextSchema ? toPgJson(input.requestContextSchema) : null,
19532
+ input.changedFields ? toPgJson(input.changedFields) : null,
19499
19533
  input.changeMessage ?? null,
19500
19534
  nowIso,
19501
19535
  nowIso
@@ -20002,8 +20036,8 @@ var SchedulesPG = class SchedulesPG extends _mastra_core_storage.SchedulesStorag
20002
20036
  if ("timezone" in patch) push("timezone = ?", patch.timezone ?? null);
20003
20037
  if ("status" in patch && patch.status !== void 0) push("status = ?", patch.status);
20004
20038
  if ("nextFireAt" in patch && patch.nextFireAt !== void 0) push("next_fire_at = ?", patch.nextFireAt);
20005
- if ("target" in patch && patch.target !== void 0) push("target = ?::jsonb", JSON.stringify(patch.target));
20006
- if ("metadata" in patch) push("metadata = ?::jsonb", patch.metadata != null ? JSON.stringify(patch.metadata) : null);
20039
+ if ("target" in patch && patch.target !== void 0) push("target = ?::jsonb", toPgJson(patch.target));
20040
+ if ("metadata" in patch) push("metadata = ?::jsonb", patch.metadata != null ? toPgJson(patch.metadata) : null);
20007
20041
  if ("ownerType" in patch) push("owner_type = ?", patch.ownerType ?? null);
20008
20042
  if ("ownerId" in patch) push("owner_id = ?", patch.ownerId ?? null);
20009
20043
  push("updated_at = ?", Date.now());
@@ -20221,7 +20255,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20221
20255
  scorerDefinition.authorId ?? null,
20222
20256
  scorerDefinition.organizationId ?? null,
20223
20257
  scorerDefinition.projectId ?? null,
20224
- scorerDefinition.metadata ? JSON.stringify(scorerDefinition.metadata) : null,
20258
+ scorerDefinition.metadata ? toPgJson(scorerDefinition.metadata) : null,
20225
20259
  nowIso,
20226
20260
  nowIso,
20227
20261
  nowIso,
@@ -20302,7 +20336,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20302
20336
  ...metadata
20303
20337
  };
20304
20338
  setClauses.push(`metadata = $${paramIndex++}`);
20305
- values.push(JSON.stringify(mergedMetadata));
20339
+ values.push(toPgJson(mergedMetadata));
20306
20340
  }
20307
20341
  const now = (/* @__PURE__ */ new Date()).toISOString();
20308
20342
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -20385,7 +20419,7 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20385
20419
  }
20386
20420
  if (metadata && Object.keys(metadata).length > 0) {
20387
20421
  conditions.push(`metadata @> $${paramIdx++}::jsonb`);
20388
- queryParams.push(JSON.stringify(metadata));
20422
+ queryParams.push(toPgJson(metadata));
20389
20423
  }
20390
20424
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
20391
20425
  const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
@@ -20448,12 +20482,12 @@ var ScorerDefinitionsPG = class ScorerDefinitionsPG extends _mastra_core_storage
20448
20482
  input.name,
20449
20483
  input.description ?? null,
20450
20484
  input.type,
20451
- input.model ? JSON.stringify(input.model) : null,
20485
+ input.model ? toPgJson(input.model) : null,
20452
20486
  input.instructions ?? null,
20453
- input.scoreRange ? JSON.stringify(input.scoreRange) : null,
20454
- input.presetConfig ? JSON.stringify(input.presetConfig) : null,
20455
- input.defaultSampling ? JSON.stringify(input.defaultSampling) : null,
20456
- input.changedFields ? JSON.stringify(input.changedFields) : null,
20487
+ input.scoreRange ? toPgJson(input.scoreRange) : null,
20488
+ input.presetConfig ? toPgJson(input.presetConfig) : null,
20489
+ input.defaultSampling ? toPgJson(input.defaultSampling) : null,
20490
+ input.changedFields ? toPgJson(input.changedFields) : null,
20457
20491
  input.changeMessage ?? null,
20458
20492
  nowIso,
20459
20493
  nowIso
@@ -20973,15 +21007,15 @@ var ScoresPG = class ScoresPG extends _mastra_core_storage.ScoresStorage {
20973
21007
  record: {
20974
21008
  id,
20975
21009
  ...rest,
20976
- input: JSON.stringify(input) || "",
20977
- output: JSON.stringify(output) || "",
20978
- scorer: scorer ? JSON.stringify(scorer) : null,
20979
- preprocessStepResult: preprocessStepResult ? JSON.stringify(preprocessStepResult) : null,
20980
- analyzeStepResult: analyzeStepResult ? JSON.stringify(analyzeStepResult) : null,
20981
- metadata: metadata ? JSON.stringify(metadata) : null,
20982
- additionalContext: additionalContext ? JSON.stringify(additionalContext) : null,
20983
- requestContext: requestContext ? JSON.stringify(requestContext) : null,
20984
- entity: entity ? JSON.stringify(entity) : null,
21010
+ input: toPgJson(input) || "",
21011
+ output: toPgJson(output) || "",
21012
+ scorer: scorer ? toPgJson(scorer) : null,
21013
+ preprocessStepResult: preprocessStepResult ? toPgJson(preprocessStepResult) : null,
21014
+ analyzeStepResult: analyzeStepResult ? toPgJson(analyzeStepResult) : null,
21015
+ metadata: metadata ? toPgJson(metadata) : null,
21016
+ additionalContext: additionalContext ? toPgJson(additionalContext) : null,
21017
+ requestContext: requestContext ? toPgJson(requestContext) : null,
21018
+ entity: entity ? toPgJson(entity) : null,
20985
21019
  createdAt: now.toISOString(),
20986
21020
  updatedAt: now.toISOString()
20987
21021
  }
@@ -21566,15 +21600,15 @@ var SkillsPG = class SkillsPG extends _mastra_core_storage.SkillsStorage {
21566
21600
  input.description ?? null,
21567
21601
  input.instructions ?? null,
21568
21602
  input.license ?? null,
21569
- input.compatibility ? JSON.stringify(input.compatibility) : null,
21570
- input.source ? JSON.stringify(input.source) : null,
21571
- input.references ? JSON.stringify(input.references) : null,
21572
- input.scripts ? JSON.stringify(input.scripts) : null,
21573
- input.assets ? JSON.stringify(input.assets) : null,
21574
- input.files ? JSON.stringify(input.files) : null,
21575
- input.metadata ? JSON.stringify(input.metadata) : null,
21576
- input.tree ? JSON.stringify(input.tree) : null,
21577
- input.changedFields ? JSON.stringify(input.changedFields) : null,
21603
+ input.compatibility ? toPgJson(input.compatibility) : null,
21604
+ input.source ? toPgJson(input.source) : null,
21605
+ input.references ? toPgJson(input.references) : null,
21606
+ input.scripts ? toPgJson(input.scripts) : null,
21607
+ input.assets ? toPgJson(input.assets) : null,
21608
+ input.files ? toPgJson(input.files) : null,
21609
+ input.metadata ? toPgJson(input.metadata) : null,
21610
+ input.tree ? toPgJson(input.tree) : null,
21611
+ input.changedFields ? toPgJson(input.changedFields) : null,
21578
21612
  input.changeMessage ?? null,
21579
21613
  nowIso,
21580
21614
  nowIso
@@ -21950,7 +21984,7 @@ var ThreadStatePG = class ThreadStatePG extends _mastra_core_storage.ThreadState
21950
21984
  }
21951
21985
  async setState({ threadId, type, value }) {
21952
21986
  const now = (/* @__PURE__ */ new Date()).toISOString();
21953
- const serialized = JSON.stringify(value ?? null);
21987
+ const serialized = toPgJson(value ?? null);
21954
21988
  try {
21955
21989
  await this.#db.client.none(`INSERT INTO ${this.#table} ("threadId", "type", "value", "createdAt", "createdAtZ", "updatedAt", "updatedAtZ")
21956
21990
  VALUES ($1, $2, $3::jsonb, $4::timestamp, $5::timestamptz, $4::timestamp, $5::timestamptz)
@@ -22727,7 +22761,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22727
22761
  requestContext
22728
22762
  });
22729
22763
  const now = /* @__PURE__ */ new Date();
22730
- const sanitizedSnapshot = sanitizeJsonForPg(JSON.stringify(snapshot));
22764
+ const sanitizedSnapshot = toPgJson(snapshot);
22731
22765
  await t.none(`INSERT INTO ${tableName}
22732
22766
  (workflow_name, run_id, snapshot, "createdAt", "updatedAt", "createdAtZ", "updatedAtZ")
22733
22767
  VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -22774,7 +22808,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22774
22808
  ...snapshot,
22775
22809
  ...state
22776
22810
  };
22777
- const sanitizedSnapshot = sanitizeJsonForPg(JSON.stringify(updatedSnapshot));
22811
+ const sanitizedSnapshot = toPgJson(updatedSnapshot);
22778
22812
  const now = /* @__PURE__ */ new Date();
22779
22813
  await t.none(`UPDATE ${tableName}
22780
22814
  SET snapshot = $1, "updatedAt" = $2, "updatedAtZ" = $3
@@ -22804,7 +22838,7 @@ var WorkflowsPG = class WorkflowsPG extends _mastra_core_storage.WorkflowsStorag
22804
22838
  const now = /* @__PURE__ */ new Date();
22805
22839
  const createdAtValue = createdAt ? createdAt : now;
22806
22840
  const updatedAtValue = updatedAt ? updatedAt : now;
22807
- const sanitizedSnapshot = sanitizeJsonForPg(JSON.stringify(snapshot));
22841
+ const sanitizedSnapshot = toPgJson(snapshot);
22808
22842
  await this.#db.client.none(`INSERT INTO ${getTableName({
22809
22843
  indexName: _mastra_core_storage.TABLE_WORKFLOW_SNAPSHOT,
22810
22844
  schemaName: getSchemaName(this.#schema)
@@ -23116,7 +23150,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23116
23150
  "draft",
23117
23151
  null,
23118
23152
  workspace.authorId ?? null,
23119
- workspace.metadata ? JSON.stringify(workspace.metadata) : null,
23153
+ workspace.metadata ? toPgJson(workspace.metadata) : null,
23120
23154
  nowIso,
23121
23155
  nowIso,
23122
23156
  nowIso,
@@ -23191,7 +23225,11 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23191
23225
  ...latestConfig,
23192
23226
  ...configFields
23193
23227
  };
23194
- const changedFields = SNAPSHOT_FIELDS.filter((field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field]));
23228
+ const normalized = (value) => {
23229
+ const json = toPgJson(value);
23230
+ return json === void 0 ? void 0 : JSON.parse(json);
23231
+ };
23232
+ const changedFields = SNAPSHOT_FIELDS.filter((field) => field in configFields && !(0, util.isDeepStrictEqual)(normalized(configFields[field]), normalized(latestConfig[field])));
23195
23233
  if (changedFields.length > 0) {
23196
23234
  versionCreated = true;
23197
23235
  const newVersionId = crypto.randomUUID();
@@ -23225,12 +23263,13 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23225
23263
  values.push(status);
23226
23264
  }
23227
23265
  if (metadata !== void 0) {
23266
+ const normalizedMetadata = JSON.parse(toPgJson(metadata));
23228
23267
  const mergedMetadata = {
23229
23268
  ...existingWorkspace.metadata || {},
23230
- ...metadata
23269
+ ...normalizedMetadata
23231
23270
  };
23232
23271
  setClauses.push(`metadata = $${paramIndex++}`);
23233
- values.push(JSON.stringify(mergedMetadata));
23272
+ values.push(toPgJson(mergedMetadata));
23234
23273
  }
23235
23274
  const now = (/* @__PURE__ */ new Date()).toISOString();
23236
23275
  setClauses.push(`"updatedAt" = $${paramIndex++}`);
@@ -23301,7 +23340,7 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23301
23340
  }
23302
23341
  if (metadata && Object.keys(metadata).length > 0) {
23303
23342
  conditions.push(`metadata @> $${paramIdx++}::jsonb`);
23304
- queryParams.push(JSON.stringify(metadata));
23343
+ queryParams.push(toPgJson(metadata));
23305
23344
  }
23306
23345
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
23307
23346
  const countResult = await this.#db.readClient.one(`SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`, queryParams);
@@ -23364,15 +23403,15 @@ var WorkspacesPG = class WorkspacesPG extends _mastra_core_storage.WorkspacesSto
23364
23403
  input.versionNumber,
23365
23404
  input.name,
23366
23405
  input.description ?? null,
23367
- input.filesystem ? JSON.stringify(input.filesystem) : null,
23368
- input.sandbox ? JSON.stringify(input.sandbox) : null,
23369
- input.mounts ? JSON.stringify(input.mounts) : null,
23370
- input.search ? JSON.stringify(input.search) : null,
23371
- input.skills ? JSON.stringify(input.skills) : null,
23372
- input.tools ? JSON.stringify(input.tools) : null,
23406
+ input.filesystem ? toPgJson(input.filesystem) : null,
23407
+ input.sandbox ? toPgJson(input.sandbox) : null,
23408
+ input.mounts ? toPgJson(input.mounts) : null,
23409
+ input.search ? toPgJson(input.search) : null,
23410
+ input.skills ? toPgJson(input.skills) : null,
23411
+ input.tools ? toPgJson(input.tools) : null,
23373
23412
  input.autoSync ?? false,
23374
23413
  input.operationTimeout ?? null,
23375
- input.changedFields ? JSON.stringify(input.changedFields) : null,
23414
+ input.changedFields ? toPgJson(input.changedFields) : null,
23376
23415
  input.changeMessage ?? null,
23377
23416
  nowIso,
23378
23417
  nowIso
@@ -23664,7 +23703,7 @@ var PgFactoryStorageOps = class {
23664
23703
  switch (spec.type) {
23665
23704
  case "timestamp": return value instanceof Date ? value : new Date(String(value));
23666
23705
  case "boolean": return Boolean(value);
23667
- case "json": return JSON.stringify(value);
23706
+ case "json": return toPgJson(value);
23668
23707
  case "bigint":
23669
23708
  case "integer": return Number(value);
23670
23709
  default: return String(value);