@mastra/pg 1.0.0 → 1.1.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { createVectorErrorId, TABLE_SCHEMAS, AgentsStorage, TABLE_AGENTS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
2
+ import { createVectorErrorId, TABLE_SCHEMAS, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
3
3
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
4
4
  import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
5
5
  import { Mutex } from 'async-mutex';
@@ -3093,7 +3093,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3093
3093
  #skipDefaultIndexes;
3094
3094
  #indexes;
3095
3095
  /** Tables managed by this domain */
3096
- static MANAGED_TABLES = [TABLE_AGENTS];
3096
+ static MANAGED_TABLES = [TABLE_AGENTS, TABLE_AGENT_VERSIONS];
3097
3097
  constructor(config) {
3098
3098
  super();
3099
3099
  const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
@@ -3120,6 +3120,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3120
3120
  }
3121
3121
  async init() {
3122
3122
  await this.#db.createTable({ tableName: TABLE_AGENTS, schema: TABLE_SCHEMAS[TABLE_AGENTS] });
3123
+ await this.#db.createTable({ tableName: TABLE_AGENT_VERSIONS, schema: TABLE_SCHEMAS[TABLE_AGENT_VERSIONS] });
3123
3124
  await this.createDefaultIndexes();
3124
3125
  await this.createCustomIndexes();
3125
3126
  }
@@ -3139,6 +3140,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3139
3140
  }
3140
3141
  }
3141
3142
  async dangerouslyClearAll() {
3143
+ await this.#db.clearTable({ tableName: TABLE_AGENT_VERSIONS });
3142
3144
  await this.#db.clearTable({ tableName: TABLE_AGENTS });
3143
3145
  }
3144
3146
  parseJson(value, fieldName) {
@@ -3176,11 +3178,14 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3176
3178
  defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
3177
3179
  workflows: this.parseJson(row.workflows, "workflows"),
3178
3180
  agents: this.parseJson(row.agents, "agents"),
3181
+ integrationTools: this.parseJson(row.integrationTools, "integrationTools"),
3179
3182
  inputProcessors: this.parseJson(row.inputProcessors, "inputProcessors"),
3180
3183
  outputProcessors: this.parseJson(row.outputProcessors, "outputProcessors"),
3181
3184
  memory: this.parseJson(row.memory, "memory"),
3182
3185
  scorers: this.parseJson(row.scorers, "scorers"),
3183
3186
  metadata: this.parseJson(row.metadata, "metadata"),
3187
+ ownerId: row.ownerId,
3188
+ activeVersionId: row.activeVersionId,
3184
3189
  createdAt: row.createdAtZ || row.createdAt,
3185
3190
  updatedAt: row.updatedAtZ || row.updatedAt
3186
3191
  };
@@ -3212,10 +3217,12 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3212
3217
  const nowIso = now.toISOString();
3213
3218
  await this.#db.client.none(
3214
3219
  `INSERT INTO ${tableName} (
3215
- id, name, description, instructions, model, tools,
3216
- "defaultOptions", workflows, agents, "inputProcessors", "outputProcessors", memory, scorers, metadata,
3220
+ id, name, description, instructions, model, tools,
3221
+ "defaultOptions", workflows, agents, "integrationTools",
3222
+ "inputProcessors", "outputProcessors", memory, scorers, metadata,
3223
+ "ownerId", "activeVersionId",
3217
3224
  "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
3218
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)`,
3225
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)`,
3219
3226
  [
3220
3227
  agent.id,
3221
3228
  agent.name,
@@ -3226,11 +3233,14 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3226
3233
  agent.defaultOptions ? JSON.stringify(agent.defaultOptions) : null,
3227
3234
  agent.workflows ? JSON.stringify(agent.workflows) : null,
3228
3235
  agent.agents ? JSON.stringify(agent.agents) : null,
3236
+ agent.integrationTools ? JSON.stringify(agent.integrationTools) : null,
3229
3237
  agent.inputProcessors ? JSON.stringify(agent.inputProcessors) : null,
3230
3238
  agent.outputProcessors ? JSON.stringify(agent.outputProcessors) : null,
3231
3239
  agent.memory ? JSON.stringify(agent.memory) : null,
3232
3240
  agent.scorers ? JSON.stringify(agent.scorers) : null,
3233
3241
  agent.metadata ? JSON.stringify(agent.metadata) : null,
3242
+ agent.ownerId ?? null,
3243
+ agent.activeVersionId ?? null,
3234
3244
  nowIso,
3235
3245
  nowIso,
3236
3246
  nowIso,
@@ -3318,6 +3328,18 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3318
3328
  setClauses.push(`scorers = $${paramIndex++}`);
3319
3329
  values.push(JSON.stringify(updates.scorers));
3320
3330
  }
3331
+ if (updates.integrationTools !== void 0) {
3332
+ setClauses.push(`"integrationTools" = $${paramIndex++}`);
3333
+ values.push(JSON.stringify(updates.integrationTools));
3334
+ }
3335
+ if (updates.ownerId !== void 0) {
3336
+ setClauses.push(`"ownerId" = $${paramIndex++}`);
3337
+ values.push(updates.ownerId);
3338
+ }
3339
+ if (updates.activeVersionId !== void 0) {
3340
+ setClauses.push(`"activeVersionId" = $${paramIndex++}`);
3341
+ values.push(updates.activeVersionId);
3342
+ }
3321
3343
  if (updates.metadata !== void 0) {
3322
3344
  const mergedMetadata = { ...existingAgent.metadata, ...updates.metadata };
3323
3345
  setClauses.push(`metadata = $${paramIndex++}`);
@@ -3364,6 +3386,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3364
3386
  async deleteAgent({ id }) {
3365
3387
  try {
3366
3388
  const tableName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.#schema) });
3389
+ await this.deleteVersionsByAgentId(id);
3367
3390
  await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
3368
3391
  } catch (error) {
3369
3392
  throw new MastraError(
@@ -3430,6 +3453,234 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3430
3453
  );
3431
3454
  }
3432
3455
  }
3456
+ // ==========================================================================
3457
+ // Agent Version Methods
3458
+ // ==========================================================================
3459
+ async createVersion(input) {
3460
+ try {
3461
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3462
+ const now = /* @__PURE__ */ new Date();
3463
+ const nowIso = now.toISOString();
3464
+ await this.#db.client.none(
3465
+ `INSERT INTO ${tableName} (
3466
+ id, "agentId", "versionNumber", name, snapshot, "changedFields", "changeMessage", "createdAt", "createdAtZ"
3467
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
3468
+ [
3469
+ input.id,
3470
+ input.agentId,
3471
+ input.versionNumber,
3472
+ input.name ?? null,
3473
+ JSON.stringify(input.snapshot),
3474
+ input.changedFields ? JSON.stringify(input.changedFields) : null,
3475
+ input.changeMessage ?? null,
3476
+ nowIso,
3477
+ nowIso
3478
+ ]
3479
+ );
3480
+ return {
3481
+ ...input,
3482
+ createdAt: now
3483
+ };
3484
+ } catch (error) {
3485
+ throw new MastraError(
3486
+ {
3487
+ id: createStorageErrorId("PG", "CREATE_VERSION", "FAILED"),
3488
+ domain: ErrorDomain.STORAGE,
3489
+ category: ErrorCategory.THIRD_PARTY,
3490
+ details: { versionId: input.id, agentId: input.agentId }
3491
+ },
3492
+ error
3493
+ );
3494
+ }
3495
+ }
3496
+ async getVersion(id) {
3497
+ try {
3498
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3499
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
3500
+ if (!result) {
3501
+ return null;
3502
+ }
3503
+ return this.parseVersionRow(result);
3504
+ } catch (error) {
3505
+ throw new MastraError(
3506
+ {
3507
+ id: createStorageErrorId("PG", "GET_VERSION", "FAILED"),
3508
+ domain: ErrorDomain.STORAGE,
3509
+ category: ErrorCategory.THIRD_PARTY,
3510
+ details: { versionId: id }
3511
+ },
3512
+ error
3513
+ );
3514
+ }
3515
+ }
3516
+ async getVersionByNumber(agentId, versionNumber) {
3517
+ try {
3518
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3519
+ const result = await this.#db.client.oneOrNone(
3520
+ `SELECT * FROM ${tableName} WHERE "agentId" = $1 AND "versionNumber" = $2`,
3521
+ [agentId, versionNumber]
3522
+ );
3523
+ if (!result) {
3524
+ return null;
3525
+ }
3526
+ return this.parseVersionRow(result);
3527
+ } catch (error) {
3528
+ throw new MastraError(
3529
+ {
3530
+ id: createStorageErrorId("PG", "GET_VERSION_BY_NUMBER", "FAILED"),
3531
+ domain: ErrorDomain.STORAGE,
3532
+ category: ErrorCategory.THIRD_PARTY,
3533
+ details: { agentId, versionNumber }
3534
+ },
3535
+ error
3536
+ );
3537
+ }
3538
+ }
3539
+ async getLatestVersion(agentId) {
3540
+ try {
3541
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3542
+ const result = await this.#db.client.oneOrNone(
3543
+ `SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
3544
+ [agentId]
3545
+ );
3546
+ if (!result) {
3547
+ return null;
3548
+ }
3549
+ return this.parseVersionRow(result);
3550
+ } catch (error) {
3551
+ throw new MastraError(
3552
+ {
3553
+ id: createStorageErrorId("PG", "GET_LATEST_VERSION", "FAILED"),
3554
+ domain: ErrorDomain.STORAGE,
3555
+ category: ErrorCategory.THIRD_PARTY,
3556
+ details: { agentId }
3557
+ },
3558
+ error
3559
+ );
3560
+ }
3561
+ }
3562
+ async listVersions(input) {
3563
+ const { agentId, page = 0, perPage: perPageInput, orderBy } = input;
3564
+ if (page < 0) {
3565
+ throw new MastraError(
3566
+ {
3567
+ id: createStorageErrorId("PG", "LIST_VERSIONS", "INVALID_PAGE"),
3568
+ domain: ErrorDomain.STORAGE,
3569
+ category: ErrorCategory.USER,
3570
+ details: { page }
3571
+ },
3572
+ new Error("page must be >= 0")
3573
+ );
3574
+ }
3575
+ const perPage = normalizePerPage(perPageInput, 20);
3576
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
3577
+ try {
3578
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
3579
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3580
+ const countResult = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [
3581
+ agentId
3582
+ ]);
3583
+ const total = parseInt(countResult.count, 10);
3584
+ if (total === 0) {
3585
+ return {
3586
+ versions: [],
3587
+ total: 0,
3588
+ page,
3589
+ perPage: perPageForResponse,
3590
+ hasMore: false
3591
+ };
3592
+ }
3593
+ const limitValue = perPageInput === false ? total : perPage;
3594
+ const dataResult = await this.#db.client.manyOrNone(
3595
+ `SELECT * FROM ${tableName} WHERE "agentId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
3596
+ [agentId, limitValue, offset]
3597
+ );
3598
+ const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
3599
+ return {
3600
+ versions,
3601
+ total,
3602
+ page,
3603
+ perPage: perPageForResponse,
3604
+ hasMore: perPageInput === false ? false : offset + perPage < total
3605
+ };
3606
+ } catch (error) {
3607
+ throw new MastraError(
3608
+ {
3609
+ id: createStorageErrorId("PG", "LIST_VERSIONS", "FAILED"),
3610
+ domain: ErrorDomain.STORAGE,
3611
+ category: ErrorCategory.THIRD_PARTY,
3612
+ details: { agentId }
3613
+ },
3614
+ error
3615
+ );
3616
+ }
3617
+ }
3618
+ async deleteVersion(id) {
3619
+ try {
3620
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3621
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
3622
+ } catch (error) {
3623
+ throw new MastraError(
3624
+ {
3625
+ id: createStorageErrorId("PG", "DELETE_VERSION", "FAILED"),
3626
+ domain: ErrorDomain.STORAGE,
3627
+ category: ErrorCategory.THIRD_PARTY,
3628
+ details: { versionId: id }
3629
+ },
3630
+ error
3631
+ );
3632
+ }
3633
+ }
3634
+ async deleteVersionsByAgentId(agentId) {
3635
+ try {
3636
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3637
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "agentId" = $1`, [agentId]);
3638
+ } catch (error) {
3639
+ throw new MastraError(
3640
+ {
3641
+ id: createStorageErrorId("PG", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
3642
+ domain: ErrorDomain.STORAGE,
3643
+ category: ErrorCategory.THIRD_PARTY,
3644
+ details: { agentId }
3645
+ },
3646
+ error
3647
+ );
3648
+ }
3649
+ }
3650
+ async countVersions(agentId) {
3651
+ try {
3652
+ const tableName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.#schema) });
3653
+ const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "agentId" = $1`, [
3654
+ agentId
3655
+ ]);
3656
+ return parseInt(result.count, 10);
3657
+ } catch (error) {
3658
+ throw new MastraError(
3659
+ {
3660
+ id: createStorageErrorId("PG", "COUNT_VERSIONS", "FAILED"),
3661
+ domain: ErrorDomain.STORAGE,
3662
+ category: ErrorCategory.THIRD_PARTY,
3663
+ details: { agentId }
3664
+ },
3665
+ error
3666
+ );
3667
+ }
3668
+ }
3669
+ // ==========================================================================
3670
+ // Private Helper Methods
3671
+ // ==========================================================================
3672
+ parseVersionRow(row) {
3673
+ return {
3674
+ id: row.id,
3675
+ agentId: row.agentId,
3676
+ versionNumber: row.versionNumber,
3677
+ name: row.name,
3678
+ snapshot: this.parseJson(row.snapshot, "snapshot"),
3679
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
3680
+ changeMessage: row.changeMessage,
3681
+ createdAt: row.createdAtZ || row.createdAt
3682
+ };
3683
+ }
3433
3684
  };
3434
3685
  function getSchemaName3(schema) {
3435
3686
  return schema ? `"${schema}"` : '"public"';
@@ -5016,11 +5267,13 @@ var ObservabilityPG = class _ObservabilityPG extends ObservabilityStorage {
5016
5267
  perPage,
5017
5268
  hasMore: (page + 1) * perPage < count
5018
5269
  },
5019
- spans: spans.map(
5020
- (span) => transformFromSqlRow({
5021
- tableName: TABLE_SPANS,
5022
- sqlRow: span
5023
- })
5270
+ spans: toTraceSpans(
5271
+ spans.map(
5272
+ (span) => transformFromSqlRow({
5273
+ tableName: TABLE_SPANS,
5274
+ sqlRow: span
5275
+ })
5276
+ )
5024
5277
  )
5025
5278
  };
5026
5279
  } catch (error) {