@mastra/mongodb 1.0.0 → 1.1.0-alpha.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,107 @@
1
1
  # @mastra/mongodb
2
2
 
3
+ ## 1.1.0-alpha.1
4
+
5
+ ### Minor Changes
6
+
7
+ - Restructured stored agents to use a thin metadata record with versioned configuration snapshots. ([#12488](https://github.com/mastra-ai/mastra/pull/12488))
8
+
9
+ The agent record now only stores metadata fields (id, status, activeVersionId, authorId, metadata, timestamps). All configuration fields (name, instructions, model, tools, etc.) live exclusively in version snapshot rows, enabling full version history and rollback.
10
+
11
+ **Key changes:**
12
+ - Stored Agent records are now thin metadata-only (StorageAgentType)
13
+ - All config lives in version snapshots (StorageAgentSnapshotType)
14
+ - New resolved type (StorageResolvedAgentType) merges agent record + active version config
15
+ - Renamed `ownerId` to `authorId` for multi-tenant filtering
16
+ - Changed `memory` field type from `string` to `Record<string, unknown>`
17
+ - Added `status` field ('draft' | 'published') to agent records
18
+ - Flattened CreateAgent/UpdateAgent input types (config fields at top level, no nested snapshot)
19
+ - Version config columns are top-level in the agent_versions table (no single snapshot jsonb column)
20
+ - List endpoints return resolved agents (thin record + active version config)
21
+ - Auto-versioning on update with retention limits and race condition handling
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies [[`b99ceac`](https://github.com/mastra-ai/mastra/commit/b99ceace2c830dbdef47c8692d56a91954aefea2), [`deea43e`](https://github.com/mastra-ai/mastra/commit/deea43eb1366d03a864c5e597d16a48592b9893f), [`ac9ec66`](https://github.com/mastra-ai/mastra/commit/ac9ec6672779b2e6d4344e415481d1a6a7d4911a)]:
26
+ - @mastra/core@1.1.0-alpha.1
27
+
28
+ ## 1.1.0-alpha.0
29
+
30
+ ### Minor Changes
31
+
32
+ - Added dynamic agent management with CRUD operations and version tracking ([#12038](https://github.com/mastra-ai/mastra/pull/12038))
33
+
34
+ **New Features:**
35
+ - Create, edit, and delete agents directly from the Mastra Studio UI
36
+ - Full version history for agents with compare and restore capabilities
37
+ - Visual diff viewer to compare agent configurations across versions
38
+ - Agent creation modal with comprehensive configuration options (model selection, instructions, tools, workflows, sub-agents, memory)
39
+ - AI-powered instruction enhancement
40
+
41
+ **Storage:**
42
+ - New storage interfaces for stored agents and agent versions
43
+ - PostgreSQL, LibSQL, and MongoDB implementations included
44
+ - In-memory storage for development and testing
45
+
46
+ **API:**
47
+ - RESTful endpoints for agent CRUD operations
48
+ - Version management endpoints (create, list, activate, restore, delete, compare)
49
+ - Automatic versioning on agent updates when enabled
50
+
51
+ **Client SDK:**
52
+ - JavaScript client with full support for stored agents and versions
53
+ - Type-safe methods for all CRUD and version operations
54
+
55
+ **Usage Example:**
56
+
57
+ ```typescript
58
+ // Server-side: Configure storage
59
+ import { Mastra } from '@mastra/core';
60
+ import { PgAgentsStorage } from '@mastra/pg';
61
+
62
+ const mastra = new Mastra({
63
+ agents: { agentOne },
64
+ storage: {
65
+ agents: new PgAgentsStorage({
66
+ connectionString: process.env.DATABASE_URL,
67
+ }),
68
+ },
69
+ });
70
+
71
+ // Client-side: Use the SDK
72
+ import { MastraClient } from '@mastra/client-js';
73
+
74
+ const client = new MastraClient({ baseUrl: 'http://localhost:3000' });
75
+
76
+ // Create a stored agent
77
+ const agent = await client.createStoredAgent({
78
+ name: 'Customer Support Agent',
79
+ description: 'Handles customer inquiries',
80
+ model: { provider: 'ANTHROPIC', name: 'claude-sonnet-4-5' },
81
+ instructions: 'You are a helpful customer support agent...',
82
+ tools: ['search', 'email'],
83
+ });
84
+
85
+ // Create a version snapshot
86
+ await client.storedAgent(agent.id).createVersion({
87
+ name: 'v1.0 - Initial release',
88
+ changeMessage: 'First production version',
89
+ });
90
+
91
+ // Compare versions
92
+ const diff = await client.storedAgent(agent.id).compareVersions('version-1', 'version-2');
93
+ ```
94
+
95
+ **Why:**
96
+ This feature enables teams to manage agents dynamically without code changes, making it easier to iterate on agent configurations and maintain a complete audit trail of changes.
97
+
98
+ - Added `status` field to `listTraces` response. The status field indicates the trace state: `success` (completed without error), `error` (has error), or `running` (still in progress). This makes it easier to filter and display traces by their current state without having to derive it from the `error` and `endedAt` fields. ([#12213](https://github.com/mastra-ai/mastra/pull/12213))
99
+
100
+ ### Patch Changes
101
+
102
+ - Updated dependencies [[`90fc0e5`](https://github.com/mastra-ai/mastra/commit/90fc0e5717cb280c2d4acf4f0410b510bb4c0a72), [`1cf5d2e`](https://github.com/mastra-ai/mastra/commit/1cf5d2ea1b085be23e34fb506c80c80a4e6d9c2b), [`833ae96`](https://github.com/mastra-ai/mastra/commit/833ae96c3e34370e58a1e979571c41f39a720592), [`943772b`](https://github.com/mastra-ai/mastra/commit/943772b4378f625f0f4e19ea2b7c392bd8e71786), [`b5c711b`](https://github.com/mastra-ai/mastra/commit/b5c711b281dd1fb81a399a766bc9f86c55efc13e), [`3efbe5a`](https://github.com/mastra-ai/mastra/commit/3efbe5ae20864c4f3143457f4f3ee7dc2fa5ca76), [`1e49e7a`](https://github.com/mastra-ai/mastra/commit/1e49e7ab5f173582154cb26b29d424de67d09aef), [`751eaab`](https://github.com/mastra-ai/mastra/commit/751eaab4e0d3820a94e4c3d39a2ff2663ded3d91), [`69d8156`](https://github.com/mastra-ai/mastra/commit/69d81568bcf062557c24471ce26812446bec465d), [`60d9d89`](https://github.com/mastra-ai/mastra/commit/60d9d899e44b35bc43f1bcd967a74e0ce010b1af), [`5c544c8`](https://github.com/mastra-ai/mastra/commit/5c544c8d12b08ab40d64d8f37b3c4215bee95b87), [`771ad96`](https://github.com/mastra-ai/mastra/commit/771ad962441996b5c43549391a3e6a02c6ddedc2), [`2b0936b`](https://github.com/mastra-ai/mastra/commit/2b0936b0c9a43eeed9bef63e614d7e02ee803f7e), [`3b04f30`](https://github.com/mastra-ai/mastra/commit/3b04f3010604f3cdfc8a0674731700ad66471cee), [`97e26de`](https://github.com/mastra-ai/mastra/commit/97e26deaebd9836647a67b96423281d66421ca07), [`10523f4`](https://github.com/mastra-ai/mastra/commit/10523f4882d9b874b40ce6e3715f66dbcd4947d2), [`cb72d20`](https://github.com/mastra-ai/mastra/commit/cb72d2069d7339bda8a0e76d4f35615debb07b84), [`42856b1`](https://github.com/mastra-ai/mastra/commit/42856b1c8aeea6371c9ee77ae2f5f5fe34400933), [`66f33ff`](https://github.com/mastra-ai/mastra/commit/66f33ff68620018513e499c394411d1d39b3aa5c), [`ab3c190`](https://github.com/mastra-ai/mastra/commit/ab3c1901980a99910ca9b96a7090c22e24060113), [`d4f06c8`](https://github.com/mastra-ai/mastra/commit/d4f06c85ffa5bb0da38fb82ebf3b040cc6b4ec4e), [`0350626`](https://github.com/mastra-ai/mastra/commit/03506267ec41b67add80d994c0c0fcce93bbc75f), [`bc9fa00`](https://github.com/mastra-ai/mastra/commit/bc9fa00859c5c4a796d53a0a5cae46ab4a3072e4), [`f46a478`](https://github.com/mastra-ai/mastra/commit/f46a4782f595949c696569e891f81c8d26338508), [`90fc0e5`](https://github.com/mastra-ai/mastra/commit/90fc0e5717cb280c2d4acf4f0410b510bb4c0a72), [`f05a3a5`](https://github.com/mastra-ai/mastra/commit/f05a3a5cf2b9a9c2d40c09cb8c762a4b6cd5d565), [`a291da9`](https://github.com/mastra-ai/mastra/commit/a291da9363efd92dafd8775dccb4f2d0511ece7a), [`c5d71da`](https://github.com/mastra-ai/mastra/commit/c5d71da1c680ce5640b1a7f8ca0e024a4ab1cfed), [`07042f9`](https://github.com/mastra-ai/mastra/commit/07042f9f89080f38b8f72713ba1c972d5b1905b8), [`0423442`](https://github.com/mastra-ai/mastra/commit/0423442b7be2dfacba95890bea8f4a810db4d603)]:
103
+ - @mastra/core@1.1.0-alpha.0
104
+
3
105
  ## 1.0.0
4
106
 
5
107
  ### Major Changes
@@ -31,4 +31,4 @@ docs/
31
31
  ## Version
32
32
 
33
33
  Package: @mastra/mongodb
34
- Version: 1.0.0
34
+ Version: 1.1.0-alpha.1
@@ -5,7 +5,7 @@ description: Documentation for @mastra/mongodb. Includes links to type definitio
5
5
 
6
6
  # @mastra/mongodb Documentation
7
7
 
8
- > **Version**: 1.0.0
8
+ > **Version**: 1.1.0-alpha.1
9
9
  > **Package**: @mastra/mongodb
10
10
 
11
11
  ## Quick Navigation
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0",
2
+ "version": "1.1.0-alpha.1",
3
3
  "package": "@mastra/mongodb",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Working Memory
4
4
 
5
- While [message history](https://mastra.ai/docs/v1/memory/message-history) and [semantic recall](./semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
5
+ While [message history](https://mastra.ai/docs/memory/message-history) and [semantic recall](./semantic-recall) help agents remember conversations, working memory allows them to maintain persistent information about users across interactions.
6
6
 
7
7
  Think of it as the agent's active thoughts or scratchpad – the key information they keep available about the user or task. It's similar to how a person would naturally remember someone's name, preferences, or important details during a conversation.
8
8
 
@@ -383,6 +383,27 @@ await memory.updateWorkingMemory({
383
383
  });
384
384
  ```
385
385
 
386
+ ## Read-Only Working Memory
387
+
388
+ In some scenarios, you may want an agent to have access to working memory data without the ability to modify it. This is useful for:
389
+
390
+ - **Routing agents** that need context but shouldn't update user profiles
391
+ - **Sub agents** in a multi-agent system that should reference but not own the memory
392
+
393
+ To enable read-only mode, set `readOnly: true` in the memory options:
394
+
395
+ ```typescript
396
+ const response = await agent.generate("What do you know about me?", {
397
+ memory: {
398
+ thread: "conversation-123",
399
+ resource: "user-alice-456",
400
+ options: {
401
+ readOnly: true, // Working memory is provided but cannot be updated
402
+ },
403
+ },
404
+ });
405
+ ```
406
+
386
407
  ## Examples
387
408
 
388
409
  - [Working memory with template](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-template)
@@ -376,7 +376,7 @@ The dimension size must match the output dimension of your chosen embedding mode
376
376
 
377
377
  - OpenAI text-embedding-3-small: 1536 dimensions (or custom, e.g., 256)
378
378
  - Cohere embed-multilingual-v3: 1024 dimensions
379
- - Google text-embedding-004: 768 dimensions (or custom)
379
+ - Google gemini-embedding-001: 768 dimensions (or custom)
380
380
 
381
381
  > **Note:**
382
382
  Index dimensions cannot be changed after creation. To use a different model, delete and recreate the index with the new dimension size.
@@ -73,7 +73,7 @@ Filter results based on metadata fields to narrow down the search space. This ap
73
73
 
74
74
  This is useful when you have documents from different sources, time periods, or with specific attributes. Mastra provides a unified MongoDB-style query syntax that works across all supported vector stores.
75
75
 
76
- For detailed information about available operators and syntax, see the [Metadata Filters Reference](https://mastra.ai/reference/v1/rag/metadata-filters).
76
+ For detailed information about available operators and syntax, see the [Metadata Filters Reference](https://mastra.ai/reference/rag/metadata-filters).
77
77
 
78
78
  Basic filtering examples:
79
79
 
@@ -264,7 +264,7 @@ await pineconeQueryTool.execute(
264
264
  );
265
265
  ```
266
266
 
267
- For detailed configuration options and advanced usage, see the [Vector Query Tool Reference](https://mastra.ai/reference/v1/tools/vector-query-tool).
267
+ For detailed configuration options and advanced usage, see the [Vector Query Tool Reference](https://mastra.ai/reference/tools/vector-query-tool).
268
268
 
269
269
  ### Vector Store Prompts
270
270
 
@@ -543,6 +543,6 @@ const relevanceProvider = new ZeroEntropyRelevanceScorer("zerank-1");
543
543
 
544
544
  The re-ranked results combine vector similarity with semantic understanding to improve retrieval quality.
545
545
 
546
- For more details about re-ranking, see the [rerank()](https://mastra.ai/reference/v1/rag/rerankWithScorer) method.
546
+ For more details about re-ranking, see the [rerank()](https://mastra.ai/reference/rag/rerankWithScorer) method.
547
547
 
548
- For graph-based retrieval that follows connections between chunks, see the [GraphRAG](https://mastra.ai/docs/v1/rag/graph-rag) documentation.
548
+ For graph-based retrieval that follows connections between chunks, see the [GraphRAG](https://mastra.ai/docs/rag/graph-rag) documentation.
@@ -13,8 +13,8 @@ The MongoDB storage implementation provides a scalable storage solution using Mo
13
13
 
14
14
  ## Installation
15
15
 
16
- ```bash
17
- npm install @mastra/mongodb@beta
16
+ ```bash npm2yarn
17
+ npm install @mastra/mongodb@latest
18
18
  ```
19
19
 
20
20
  ## Usage
@@ -13,8 +13,8 @@ The `MongoDBVector` class provides vector search using [MongoDB Atlas Vector Sea
13
13
 
14
14
  ## Installation
15
15
 
16
- ```bash
17
- npm install @mastra/mongodb@beta
16
+ ```bash npm2yarn
17
+ npm install @mastra/mongodb@latest
18
18
  ```
19
19
 
20
20
  ## Usage Example
@@ -154,8 +154,8 @@ Embeddings are numeric vectors used by memory's `semanticRecall` to retrieve rel
154
154
  This setup uses FastEmbed, a local embedding model, to generate vector embeddings.
155
155
  To use this, install `@mastra/fastembed`:
156
156
 
157
- ```bash
158
- npm install @mastra/fastembed@beta
157
+ ```bash npm2yarn
158
+ npm install @mastra/fastembed@latest
159
159
  ```
160
160
 
161
161
  Add the following to your agent:
package/dist/index.cjs CHANGED
@@ -13,7 +13,7 @@ var evals = require('@mastra/core/evals');
13
13
 
14
14
  // package.json
15
15
  var package_default = {
16
- version: "1.0.0"};
16
+ version: "1.1.0-alpha.1"};
17
17
  var MongoDBFilterTranslator = class extends filter.BaseFilterTranslator {
18
18
  getSupportedOperators() {
19
19
  return {
@@ -894,12 +894,27 @@ function resolveMongoDBConfig(config) {
894
894
  );
895
895
  }
896
896
  }
897
+ var SNAPSHOT_FIELDS = [
898
+ "name",
899
+ "description",
900
+ "instructions",
901
+ "model",
902
+ "tools",
903
+ "defaultOptions",
904
+ "workflows",
905
+ "agents",
906
+ "integrationTools",
907
+ "inputProcessors",
908
+ "outputProcessors",
909
+ "memory",
910
+ "scorers"
911
+ ];
897
912
  var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsStorage {
898
913
  #connector;
899
914
  #skipDefaultIndexes;
900
915
  #indexes;
901
916
  /** Collections managed by this domain */
902
- static MANAGED_COLLECTIONS = [storage.TABLE_AGENTS];
917
+ static MANAGED_COLLECTIONS = [storage.TABLE_AGENTS, storage.TABLE_AGENT_VERSIONS];
903
918
  constructor(config) {
904
919
  super();
905
920
  this.#connector = resolveMongoDBConfig(config);
@@ -919,7 +934,10 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
919
934
  return [
920
935
  { collection: storage.TABLE_AGENTS, keys: { id: 1 }, options: { unique: true } },
921
936
  { collection: storage.TABLE_AGENTS, keys: { createdAt: -1 } },
922
- { collection: storage.TABLE_AGENTS, keys: { updatedAt: -1 } }
937
+ { collection: storage.TABLE_AGENTS, keys: { updatedAt: -1 } },
938
+ { collection: storage.TABLE_AGENT_VERSIONS, keys: { id: 1 }, options: { unique: true } },
939
+ { collection: storage.TABLE_AGENT_VERSIONS, keys: { agentId: 1, versionNumber: -1 }, options: { unique: true } },
940
+ { collection: storage.TABLE_AGENT_VERSIONS, keys: { agentId: 1, createdAt: -1 } }
923
941
  ];
924
942
  }
925
943
  async createDefaultIndexes() {
@@ -956,8 +974,10 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
956
974
  await this.createCustomIndexes();
957
975
  }
958
976
  async dangerouslyClearAll() {
959
- const collection = await this.getCollection(storage.TABLE_AGENTS);
960
- await collection.deleteMany({});
977
+ const versionsCollection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
978
+ await versionsCollection.deleteMany({});
979
+ const agentsCollection = await this.getCollection(storage.TABLE_AGENTS);
980
+ await agentsCollection.deleteMany({});
961
981
  }
962
982
  async getAgentById({ id }) {
963
983
  try {
@@ -994,11 +1014,28 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
994
1014
  }
995
1015
  const now = /* @__PURE__ */ new Date();
996
1016
  const newAgent = {
997
- ...agent,
1017
+ id: agent.id,
1018
+ status: "draft",
1019
+ activeVersionId: void 0,
1020
+ authorId: agent.authorId,
1021
+ metadata: agent.metadata,
998
1022
  createdAt: now,
999
1023
  updatedAt: now
1000
1024
  };
1001
1025
  await collection.insertOne(this.serializeAgent(newAgent));
1026
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = agent;
1027
+ const versionId = crypto.randomUUID();
1028
+ await this.createVersion({
1029
+ id: versionId,
1030
+ agentId: agent.id,
1031
+ versionNumber: 1,
1032
+ ...snapshotConfig,
1033
+ changedFields: Object.keys(snapshotConfig),
1034
+ changeMessage: "Initial version"
1035
+ });
1036
+ newAgent.activeVersionId = versionId;
1037
+ newAgent.status = "published";
1038
+ await collection.updateOne({ id: agent.id }, { $set: { activeVersionId: versionId, status: "published" } });
1002
1039
  return newAgent;
1003
1040
  } catch (error$1) {
1004
1041
  if (error$1 instanceof error.MastraError) {
@@ -1031,18 +1068,11 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1031
1068
  const updateDoc = {
1032
1069
  updatedAt: /* @__PURE__ */ new Date()
1033
1070
  };
1034
- if (updates.name !== void 0) updateDoc.name = updates.name;
1035
- if (updates.description !== void 0) updateDoc.description = updates.description;
1036
- if (updates.instructions !== void 0) updateDoc.instructions = updates.instructions;
1037
- if (updates.model !== void 0) updateDoc.model = updates.model;
1038
- if (updates.tools !== void 0) updateDoc.tools = updates.tools;
1039
- if (updates.defaultOptions !== void 0) updateDoc.defaultOptions = updates.defaultOptions;
1040
- if (updates.workflows !== void 0) updateDoc.workflows = updates.workflows;
1041
- if (updates.agents !== void 0) updateDoc.agents = updates.agents;
1042
- if (updates.inputProcessors !== void 0) updateDoc.inputProcessors = updates.inputProcessors;
1043
- if (updates.outputProcessors !== void 0) updateDoc.outputProcessors = updates.outputProcessors;
1044
- if (updates.memory !== void 0) updateDoc.memory = updates.memory;
1045
- if (updates.scorers !== void 0) updateDoc.scorers = updates.scorers;
1071
+ if (updates.authorId !== void 0) updateDoc.authorId = updates.authorId;
1072
+ if (updates.activeVersionId !== void 0) {
1073
+ updateDoc.activeVersionId = updates.activeVersionId;
1074
+ updateDoc.status = "published";
1075
+ }
1046
1076
  if (updates.metadata !== void 0) {
1047
1077
  const existingMetadata = existingAgent.metadata || {};
1048
1078
  updateDoc.metadata = { ...existingMetadata, ...updates.metadata };
@@ -1076,6 +1106,7 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1076
1106
  }
1077
1107
  async deleteAgent({ id }) {
1078
1108
  try {
1109
+ await this.deleteVersionsByAgentId(id);
1079
1110
  const collection = await this.getCollection(storage.TABLE_AGENTS);
1080
1111
  await collection.deleteOne({ id });
1081
1112
  } catch (error$1) {
@@ -1146,18 +1177,259 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1146
1177
  );
1147
1178
  }
1148
1179
  }
1180
+ /**
1181
+ * Transforms a raw MongoDB document into a thin StorageAgentType record.
1182
+ * Only returns metadata-level fields (no config/snapshot fields).
1183
+ */
1149
1184
  transformAgent(doc) {
1150
- const { _id, ...agent } = doc;
1185
+ const { _id, ...rest } = doc;
1151
1186
  return {
1152
- ...agent,
1153
- createdAt: agent.createdAt instanceof Date ? agent.createdAt : new Date(agent.createdAt),
1154
- updatedAt: agent.updatedAt instanceof Date ? agent.updatedAt : new Date(agent.updatedAt)
1187
+ id: rest.id,
1188
+ status: rest.status,
1189
+ activeVersionId: rest.activeVersionId,
1190
+ authorId: rest.authorId,
1191
+ metadata: rest.metadata,
1192
+ createdAt: rest.createdAt instanceof Date ? rest.createdAt : new Date(rest.createdAt),
1193
+ updatedAt: rest.updatedAt instanceof Date ? rest.updatedAt : new Date(rest.updatedAt)
1155
1194
  };
1156
1195
  }
1196
+ /**
1197
+ * Serializes a thin StorageAgentType record for MongoDB insertion.
1198
+ * Only persists metadata-level fields.
1199
+ */
1157
1200
  serializeAgent(agent) {
1158
1201
  return {
1159
- ...agent
1202
+ id: agent.id,
1203
+ status: agent.status,
1204
+ activeVersionId: agent.activeVersionId,
1205
+ authorId: agent.authorId,
1206
+ metadata: agent.metadata,
1207
+ createdAt: agent.createdAt,
1208
+ updatedAt: agent.updatedAt
1209
+ };
1210
+ }
1211
+ // ==========================================================================
1212
+ // Agent Version Methods
1213
+ // ==========================================================================
1214
+ async createVersion(input) {
1215
+ try {
1216
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1217
+ const now = /* @__PURE__ */ new Date();
1218
+ const versionDoc = {
1219
+ id: input.id,
1220
+ agentId: input.agentId,
1221
+ versionNumber: input.versionNumber,
1222
+ changedFields: input.changedFields ?? void 0,
1223
+ changeMessage: input.changeMessage ?? void 0,
1224
+ createdAt: now
1225
+ };
1226
+ for (const field of SNAPSHOT_FIELDS) {
1227
+ if (input[field] !== void 0) {
1228
+ versionDoc[field] = input[field];
1229
+ }
1230
+ }
1231
+ await collection.insertOne(versionDoc);
1232
+ return {
1233
+ ...input,
1234
+ createdAt: now
1235
+ };
1236
+ } catch (error$1) {
1237
+ throw new error.MastraError(
1238
+ {
1239
+ id: storage.createStorageErrorId("MONGODB", "CREATE_VERSION", "FAILED"),
1240
+ domain: error.ErrorDomain.STORAGE,
1241
+ category: error.ErrorCategory.THIRD_PARTY,
1242
+ details: { versionId: input.id, agentId: input.agentId }
1243
+ },
1244
+ error$1
1245
+ );
1246
+ }
1247
+ }
1248
+ async getVersion(id) {
1249
+ try {
1250
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1251
+ const result = await collection.findOne({ id });
1252
+ if (!result) {
1253
+ return null;
1254
+ }
1255
+ return this.transformVersion(result);
1256
+ } catch (error$1) {
1257
+ throw new error.MastraError(
1258
+ {
1259
+ id: storage.createStorageErrorId("MONGODB", "GET_VERSION", "FAILED"),
1260
+ domain: error.ErrorDomain.STORAGE,
1261
+ category: error.ErrorCategory.THIRD_PARTY,
1262
+ details: { versionId: id }
1263
+ },
1264
+ error$1
1265
+ );
1266
+ }
1267
+ }
1268
+ async getVersionByNumber(agentId, versionNumber) {
1269
+ try {
1270
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1271
+ const result = await collection.findOne({ agentId, versionNumber });
1272
+ if (!result) {
1273
+ return null;
1274
+ }
1275
+ return this.transformVersion(result);
1276
+ } catch (error$1) {
1277
+ throw new error.MastraError(
1278
+ {
1279
+ id: storage.createStorageErrorId("MONGODB", "GET_VERSION_BY_NUMBER", "FAILED"),
1280
+ domain: error.ErrorDomain.STORAGE,
1281
+ category: error.ErrorCategory.THIRD_PARTY,
1282
+ details: { agentId, versionNumber }
1283
+ },
1284
+ error$1
1285
+ );
1286
+ }
1287
+ }
1288
+ async getLatestVersion(agentId) {
1289
+ try {
1290
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1291
+ const result = await collection.find({ agentId }).sort({ versionNumber: -1 }).limit(1).toArray();
1292
+ if (!result || result.length === 0) {
1293
+ return null;
1294
+ }
1295
+ return this.transformVersion(result[0]);
1296
+ } catch (error$1) {
1297
+ throw new error.MastraError(
1298
+ {
1299
+ id: storage.createStorageErrorId("MONGODB", "GET_LATEST_VERSION", "FAILED"),
1300
+ domain: error.ErrorDomain.STORAGE,
1301
+ category: error.ErrorCategory.THIRD_PARTY,
1302
+ details: { agentId }
1303
+ },
1304
+ error$1
1305
+ );
1306
+ }
1307
+ }
1308
+ async listVersions(input) {
1309
+ const { agentId, page = 0, perPage: perPageInput, orderBy } = input;
1310
+ if (page < 0) {
1311
+ throw new error.MastraError(
1312
+ {
1313
+ id: storage.createStorageErrorId("MONGODB", "LIST_VERSIONS", "INVALID_PAGE"),
1314
+ domain: error.ErrorDomain.STORAGE,
1315
+ category: error.ErrorCategory.USER,
1316
+ details: { page }
1317
+ },
1318
+ new Error("page must be >= 0")
1319
+ );
1320
+ }
1321
+ const perPage = storage.normalizePerPage(perPageInput, 20);
1322
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1323
+ try {
1324
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
1325
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1326
+ const total = await collection.countDocuments({ agentId });
1327
+ if (total === 0 || perPage === 0) {
1328
+ return {
1329
+ versions: [],
1330
+ total,
1331
+ page,
1332
+ perPage: perPageForResponse,
1333
+ hasMore: false
1334
+ };
1335
+ }
1336
+ const sortOrder = direction === "ASC" ? 1 : -1;
1337
+ let cursor = collection.find({ agentId }).sort({ [field]: sortOrder }).skip(offset);
1338
+ if (perPageInput !== false) {
1339
+ cursor = cursor.limit(perPage);
1340
+ }
1341
+ const results = await cursor.toArray();
1342
+ const versions = results.map((doc) => this.transformVersion(doc));
1343
+ return {
1344
+ versions,
1345
+ total,
1346
+ page,
1347
+ perPage: perPageForResponse,
1348
+ hasMore: perPageInput !== false && offset + perPage < total
1349
+ };
1350
+ } catch (error$1) {
1351
+ throw new error.MastraError(
1352
+ {
1353
+ id: storage.createStorageErrorId("MONGODB", "LIST_VERSIONS", "FAILED"),
1354
+ domain: error.ErrorDomain.STORAGE,
1355
+ category: error.ErrorCategory.THIRD_PARTY,
1356
+ details: { agentId }
1357
+ },
1358
+ error$1
1359
+ );
1360
+ }
1361
+ }
1362
+ async deleteVersion(id) {
1363
+ try {
1364
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1365
+ await collection.deleteOne({ id });
1366
+ } catch (error$1) {
1367
+ throw new error.MastraError(
1368
+ {
1369
+ id: storage.createStorageErrorId("MONGODB", "DELETE_VERSION", "FAILED"),
1370
+ domain: error.ErrorDomain.STORAGE,
1371
+ category: error.ErrorCategory.THIRD_PARTY,
1372
+ details: { versionId: id }
1373
+ },
1374
+ error$1
1375
+ );
1376
+ }
1377
+ }
1378
+ async deleteVersionsByAgentId(agentId) {
1379
+ try {
1380
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1381
+ await collection.deleteMany({ agentId });
1382
+ } catch (error$1) {
1383
+ throw new error.MastraError(
1384
+ {
1385
+ id: storage.createStorageErrorId("MONGODB", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
1386
+ domain: error.ErrorDomain.STORAGE,
1387
+ category: error.ErrorCategory.THIRD_PARTY,
1388
+ details: { agentId }
1389
+ },
1390
+ error$1
1391
+ );
1392
+ }
1393
+ }
1394
+ async countVersions(agentId) {
1395
+ try {
1396
+ const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1397
+ return await collection.countDocuments({ agentId });
1398
+ } catch (error$1) {
1399
+ throw new error.MastraError(
1400
+ {
1401
+ id: storage.createStorageErrorId("MONGODB", "COUNT_VERSIONS", "FAILED"),
1402
+ domain: error.ErrorDomain.STORAGE,
1403
+ category: error.ErrorCategory.THIRD_PARTY,
1404
+ details: { agentId }
1405
+ },
1406
+ error$1
1407
+ );
1408
+ }
1409
+ }
1410
+ // ==========================================================================
1411
+ // Private Helper Methods
1412
+ // ==========================================================================
1413
+ /**
1414
+ * Transforms a raw MongoDB version document into an AgentVersion.
1415
+ * Config fields are returned directly (no nested snapshot object).
1416
+ */
1417
+ transformVersion(doc) {
1418
+ const { _id, ...version } = doc;
1419
+ const result = {
1420
+ id: version.id,
1421
+ agentId: version.agentId,
1422
+ versionNumber: version.versionNumber,
1423
+ changedFields: version.changedFields,
1424
+ changeMessage: version.changeMessage,
1425
+ createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
1160
1426
  };
1427
+ for (const field of SNAPSHOT_FIELDS) {
1428
+ if (version[field] !== void 0) {
1429
+ result[field] = version[field];
1430
+ }
1431
+ }
1432
+ return result;
1161
1433
  }
1162
1434
  };
1163
1435
  function formatDateForMongoDB(date) {
@@ -2492,7 +2764,7 @@ Note: This migration may take some time for large collections.
2492
2764
  perPage,
2493
2765
  hasMore: (page + 1) * perPage < count2
2494
2766
  },
2495
- spans: spans2.map((span) => this.transformSpanFromMongo(span))
2767
+ spans: storage.toTraceSpans(spans2.map((span) => this.transformSpanFromMongo(span)))
2496
2768
  };
2497
2769
  }
2498
2770
  const count = await collection.countDocuments(mongoFilter);
@@ -2535,7 +2807,7 @@ Note: This migration may take some time for large collections.
2535
2807
  perPage,
2536
2808
  hasMore: (page + 1) * perPage < count
2537
2809
  },
2538
- spans: spans.map((span) => this.transformSpanFromMongo(span))
2810
+ spans: storage.toTraceSpans(spans.map((span) => this.transformSpanFromMongo(span)))
2539
2811
  };
2540
2812
  } catch (error$1) {
2541
2813
  throw new error.MastraError(