@ainetwork/adk-provider-memory-mongodb 0.2.3 → 0.3.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,3 +1,6 @@
1
+ import {
2
+ AgentModel
3
+ } from "./chunk-OWGGE5EW.js";
1
4
  import {
2
5
  IntentModel
3
6
  } from "./chunk-YFW7JXII.js";
@@ -10,164 +13,377 @@ import {
10
13
 
11
14
  // implements/base.memory.ts
12
15
  import mongoose from "mongoose";
13
- import { loggers } from "@ainetwork/adk/utils/logger";
14
- var MongoDBMemory = class {
15
- _isConnected = false;
16
- _uri;
17
- constructor(uri) {
18
- this._uri = uri;
16
+ import { loggers as loggers2 } from "@ainetwork/adk/utils/logger";
17
+
18
+ // implements/agent.memory.ts
19
+ var MongoDBAgent = class {
20
+ executeWithRetry;
21
+ getOperationTimeout;
22
+ constructor(executeWithRetry, getOperationTimeout) {
23
+ this.executeWithRetry = executeWithRetry;
24
+ this.getOperationTimeout = getOperationTimeout;
19
25
  }
20
- async connect() {
21
- if (this._isConnected) {
22
- return;
23
- }
24
- try {
25
- await mongoose.connect(this._uri, {
26
- maxPoolSize: 1,
27
- serverSelectionTimeoutMS: 3e4,
28
- socketTimeoutMS: 45e3,
29
- connectTimeoutMS: 3e4,
30
- bufferCommands: false
31
- });
32
- this._isConnected = true;
33
- loggers.agent.info("MongoDB connected successfully");
34
- } catch (error) {
35
- loggers.agent.error("Failed to connect to MongoDB:", error);
36
- throw error;
37
- }
26
+ async getAgentPrompt() {
27
+ return this.executeWithRetry(async () => {
28
+ const timeout = this.getOperationTimeout();
29
+ const metadata = await AgentModel.findOne({
30
+ id: "agent_metadata"
31
+ }).maxTimeMS(timeout).lean();
32
+ return metadata?.agent_prompt || "";
33
+ }, "getAgentPrompt()");
38
34
  }
39
- async disconnect() {
40
- if (!this.isConnected) {
41
- return;
42
- }
43
- try {
44
- await mongoose.disconnect();
45
- this._isConnected = false;
46
- loggers.agent.info("MongoDB disconnected successfully");
47
- } catch (error) {
48
- loggers.agent.error("Failed to disconnect from MongoDB:", error);
49
- throw error;
50
- }
35
+ async updateAgentPrompt(prompt) {
36
+ return this.executeWithRetry(async () => {
37
+ const timeout = this.getOperationTimeout();
38
+ await AgentModel.updateOne({
39
+ id: "agent_metadata"
40
+ }, { "agent_prompt": prompt }).maxTimeMS(timeout);
41
+ }, "updateAgentPrompt()");
51
42
  }
52
- isConnected() {
53
- return this._isConnected;
43
+ };
44
+
45
+ // implements/intent.memory.ts
46
+ var MongoDBIntent = class {
47
+ executeWithRetry;
48
+ getOperationTimeout;
49
+ constructor(executeWithRetry, getOperationTimeout) {
50
+ this.executeWithRetry = executeWithRetry;
51
+ this.getOperationTimeout = getOperationTimeout;
52
+ }
53
+ async getIntent(intentId) {
54
+ return this.executeWithRetry(async () => {
55
+ const timeout = this.getOperationTimeout();
56
+ const intent = await IntentModel.findOne({ id: intentId }).maxTimeMS(timeout).lean();
57
+ return intent || void 0;
58
+ }, `getIntent(${intentId})`);
59
+ }
60
+ async getIntentByName(intentName) {
61
+ return this.executeWithRetry(async () => {
62
+ const timeout = this.getOperationTimeout();
63
+ const intent = await IntentModel.findOne({ name: intentName }).maxTimeMS(timeout).lean();
64
+ return intent || void 0;
65
+ }, `getIntentByName(${intentName})`);
66
+ }
67
+ async saveIntent(intent) {
68
+ return this.executeWithRetry(async () => {
69
+ await IntentModel.create(intent);
70
+ }, `saveIntent(${intent.id})`);
71
+ }
72
+ async updateIntent(intentId, intent) {
73
+ return this.executeWithRetry(async () => {
74
+ const timeout = this.getOperationTimeout();
75
+ await IntentModel.updateOne({
76
+ id: intentId
77
+ }, intent).maxTimeMS(timeout);
78
+ }, `updateIntent(${intentId})`);
79
+ }
80
+ async deleteIntent(intentId) {
81
+ return this.executeWithRetry(async () => {
82
+ const timeout = this.getOperationTimeout();
83
+ await IntentModel.deleteOne({ id: intentId }).maxTimeMS(timeout);
84
+ }, `deleteIntent(${intentId})`);
85
+ }
86
+ async listIntents() {
87
+ return this.executeWithRetry(async () => {
88
+ const timeout = this.getOperationTimeout();
89
+ const intents = await IntentModel.find().maxTimeMS(timeout).lean();
90
+ return intents;
91
+ }, `listIntents()`);
54
92
  }
55
93
  };
56
94
 
57
95
  // implements/thread.memory.ts
58
- import { loggers as loggers2 } from "@ainetwork/adk/utils/logger";
59
- var MongoDBThread = class extends MongoDBMemory {
60
- constructor(uri) {
61
- super(uri);
96
+ import { loggers } from "@ainetwork/adk/utils/logger";
97
+ var MongoDBThread = class {
98
+ executeWithRetry;
99
+ getOperationTimeout;
100
+ constructor(executeWithRetry, getOperationTimeout) {
101
+ this.executeWithRetry = executeWithRetry;
102
+ this.getOperationTimeout = getOperationTimeout;
62
103
  }
63
104
  async getThread(userId, threadId) {
64
- const thread = await ThreadModel.findOne({ threadId, userId });
65
- const messages = await MessageModel.find({ threadId, userId }).sort({
66
- timestamp: 1
67
- });
68
- if (!thread) return void 0;
69
- loggers2.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);
70
- const threadObject = {
71
- threadId: thread.threadId,
72
- userId: thread.userId,
73
- type: thread.type,
74
- title: thread.title || "New thread",
75
- messages: []
76
- };
77
- messages.forEach((message) => {
78
- threadObject.messages.push({
79
- messageId: message.messageId,
80
- role: message.role,
81
- content: message.content,
82
- timestamp: message.timestamp,
83
- metadata: message.metadata
105
+ return this.executeWithRetry(async () => {
106
+ const timeout = this.getOperationTimeout();
107
+ const thread = await ThreadModel.findOne({ threadId, userId }).maxTimeMS(timeout);
108
+ const messages = await MessageModel.find({ threadId, userId }).sort({ timestamp: 1 }).maxTimeMS(timeout);
109
+ if (!thread) return void 0;
110
+ loggers.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);
111
+ const threadObject = {
112
+ threadId: thread.threadId,
113
+ userId: thread.userId,
114
+ type: thread.type,
115
+ title: thread.title || "New thread",
116
+ messages: []
117
+ };
118
+ messages.forEach((message) => {
119
+ threadObject.messages.push({
120
+ messageId: message.messageId,
121
+ role: message.role,
122
+ content: message.content,
123
+ timestamp: message.timestamp,
124
+ metadata: message.metadata
125
+ });
84
126
  });
85
- });
86
- return threadObject;
127
+ return threadObject;
128
+ }, `getThread(${userId}, ${threadId})`);
87
129
  }
88
130
  async createThread(type, userId, threadId, title) {
89
- const now = Date.now();
90
- await ThreadModel.create({
91
- type,
92
- userId,
93
- threadId,
94
- title,
95
- updated_at: now,
96
- created_at: now
97
- });
98
- return { type, userId, threadId, title, messages: [] };
131
+ return this.executeWithRetry(async () => {
132
+ const now = Date.now();
133
+ await ThreadModel.create({
134
+ type,
135
+ userId,
136
+ threadId,
137
+ title,
138
+ updated_at: now,
139
+ created_at: now
140
+ });
141
+ return { type, userId, threadId, title, messages: [] };
142
+ }, `createThread(${userId}, ${threadId})`);
99
143
  }
100
144
  async addMessagesToThread(userId, threadId, messages) {
101
- await ThreadModel.updateOne({ threadId, userId }, {
102
- updated_at: Date.now()
103
- });
104
- for (const message of messages) {
105
- await MessageModel.create({
106
- threadId,
107
- messageId: message.messageId,
108
- userId,
109
- role: message.role,
110
- content: message.content,
111
- timestamp: message.timestamp,
112
- metadata: message.metadata
145
+ return this.executeWithRetry(async () => {
146
+ await ThreadModel.updateOne({ threadId, userId }, {
147
+ updated_at: Date.now()
113
148
  });
114
- }
149
+ for (const message of messages) {
150
+ await MessageModel.create({
151
+ threadId,
152
+ messageId: message.messageId,
153
+ userId,
154
+ role: message.role,
155
+ content: message.content,
156
+ timestamp: message.timestamp,
157
+ metadata: message.metadata
158
+ });
159
+ }
160
+ }, `addMessagesToThread(${userId}, ${threadId})`);
115
161
  }
116
162
  async deleteThread(userId, threadId) {
117
- const messages = await MessageModel.find({ userId, threadId }).sort({
118
- timestamp: 1
119
- });
120
- messages?.forEach((message) => {
121
- message.deleteOne();
122
- });
123
- const thread = await ThreadModel.findOne({ userId, threadId });
124
- thread?.deleteOne();
163
+ return this.executeWithRetry(async () => {
164
+ const timeout = this.getOperationTimeout();
165
+ const messages = await MessageModel.find({ userId, threadId }).sort({ timestamp: 1 }).maxTimeMS(timeout);
166
+ messages?.forEach((message) => {
167
+ message.deleteOne();
168
+ });
169
+ const thread = await ThreadModel.findOne({ userId, threadId }).maxTimeMS(timeout);
170
+ thread?.deleteOne();
171
+ }, `deleteThread(${userId}, ${threadId})`);
125
172
  }
126
173
  async listThreads(userId) {
127
- const threads = await ThreadModel.find({ userId }).sort({
128
- updated_at: -1
129
- });
130
- const data = threads.map((thread) => {
131
- return {
132
- type: thread.type,
133
- userId,
134
- threadId: thread.threadId,
135
- title: thread.title,
136
- updatedAt: thread.updated_at
137
- };
138
- });
139
- return data;
174
+ return this.executeWithRetry(async () => {
175
+ const timeout = this.getOperationTimeout();
176
+ const threads = await ThreadModel.find({ userId }).sort({ updated_at: -1 }).maxTimeMS(timeout);
177
+ const data = threads.map((thread) => {
178
+ return {
179
+ type: thread.type,
180
+ userId,
181
+ threadId: thread.threadId,
182
+ title: thread.title,
183
+ updatedAt: thread.updated_at
184
+ };
185
+ });
186
+ return data;
187
+ }, `listThreads(${userId})`);
140
188
  }
141
189
  };
142
190
 
143
- // implements/intent.memory.ts
144
- var MongoDBIntent = class extends MongoDBMemory {
145
- async getIntent(intentId) {
146
- const intent = await IntentModel.findOne({ id: intentId }).lean();
147
- return intent || void 0;
191
+ // implements/base.memory.ts
192
+ var MongoDBMemory = class _MongoDBMemory {
193
+ static instance;
194
+ uri;
195
+ connected = false;
196
+ reconnectAttempts = 0;
197
+ maxReconnectAttempts;
198
+ reconnectInterval;
199
+ reconnecting = false;
200
+ connectionConfig;
201
+ eventListenersSetup = false;
202
+ operationTimeoutMS;
203
+ agentMemory;
204
+ intentMemory;
205
+ threadMemory;
206
+ constructor(config) {
207
+ const cfg = typeof config === "string" ? { uri: config } : config;
208
+ this.uri = cfg.uri;
209
+ this.maxReconnectAttempts = cfg.maxReconnectAttempts ?? 5;
210
+ this.reconnectInterval = cfg.reconnectInterval ?? 5e3;
211
+ this.operationTimeoutMS = cfg.operationTimeoutMS ?? 1e4;
212
+ this.connectionConfig = {
213
+ maxPoolSize: cfg.maxPoolSize ?? 1,
214
+ serverSelectionTimeoutMS: cfg.serverSelectionTimeoutMS ?? 3e4,
215
+ socketTimeoutMS: cfg.socketTimeoutMS ?? 45e3,
216
+ connectTimeoutMS: cfg.connectTimeoutMS ?? 3e4,
217
+ bufferCommands: false
218
+ };
219
+ if (!_MongoDBMemory.instance) {
220
+ _MongoDBMemory.instance = this;
221
+ this.setupMongooseEventListeners();
222
+ } else {
223
+ this.connected = _MongoDBMemory.instance.connected;
224
+ this.operationTimeoutMS = _MongoDBMemory.instance.operationTimeoutMS;
225
+ }
226
+ this.agentMemory = new MongoDBAgent(
227
+ this.executeWithRetry.bind(this),
228
+ this.getOperationTimeout.bind(this)
229
+ );
230
+ this.threadMemory = new MongoDBThread(
231
+ this.executeWithRetry.bind(this),
232
+ this.getOperationTimeout.bind(this)
233
+ );
234
+ this.intentMemory = new MongoDBIntent(
235
+ this.executeWithRetry.bind(this),
236
+ this.getOperationTimeout.bind(this)
237
+ );
148
238
  }
149
- async getIntentByName(intentName) {
150
- const intent = await IntentModel.findOne({ name: intentName }).lean();
151
- return intent || void 0;
239
+ getAgentMemory() {
240
+ return this.agentMemory;
152
241
  }
153
- async saveIntent(intent) {
154
- await IntentModel.create(intent);
242
+ getThreadMemory() {
243
+ return this.threadMemory;
155
244
  }
156
- async updateIntent(intentId, intent) {
157
- await IntentModel.updateOne({
158
- id: intentId
159
- }, intent);
245
+ getIntentMemory() {
246
+ return this.intentMemory;
160
247
  }
161
- async deleteIntent(intentId) {
162
- await IntentModel.deleteOne({ id: intentId });
248
+ setupMongooseEventListeners() {
249
+ if (this.eventListenersSetup) return;
250
+ this.eventListenersSetup = true;
251
+ mongoose.connection.on("connected", () => {
252
+ this.connected = true;
253
+ this.reconnectAttempts = 0;
254
+ this.reconnecting = false;
255
+ loggers2.agent.info("MongoDB connected successfully");
256
+ });
257
+ mongoose.connection.on("disconnected", () => {
258
+ this.connected = false;
259
+ loggers2.agent.warn("MongoDB disconnected");
260
+ this.handleDisconnection();
261
+ });
262
+ mongoose.connection.on("error", (error) => {
263
+ this.connected = false;
264
+ loggers2.agent.error("MongoDB connection error:", error);
265
+ this.handleDisconnection();
266
+ });
267
+ mongoose.connection.on("reconnected", () => {
268
+ this.connected = true;
269
+ this.reconnectAttempts = 0;
270
+ this.reconnecting = false;
271
+ loggers2.agent.info("MongoDB reconnected successfully");
272
+ });
163
273
  }
164
- async listIntents() {
165
- const intents = await IntentModel.find().lean();
166
- return intents;
274
+ async handleDisconnection() {
275
+ if (this.reconnecting) {
276
+ return;
277
+ }
278
+ this.reconnecting = true;
279
+ while (this.reconnectAttempts < this.maxReconnectAttempts && !this.isConnected) {
280
+ this.reconnectAttempts++;
281
+ loggers2.agent.info(
282
+ `Attempting to reconnect to MongoDB (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`
283
+ );
284
+ try {
285
+ await mongoose.connect(this.uri, this.connectionConfig);
286
+ this.connected = true;
287
+ this.reconnectAttempts = 0;
288
+ this.reconnecting = false;
289
+ loggers2.agent.info("MongoDB reconnection successful");
290
+ return;
291
+ } catch (error) {
292
+ loggers2.agent.error(
293
+ `Reconnection attempt ${this.reconnectAttempts} failed:`,
294
+ error
295
+ );
296
+ if (this.reconnectAttempts < this.maxReconnectAttempts) {
297
+ await new Promise(
298
+ (resolve) => setTimeout(resolve, this.reconnectInterval)
299
+ );
300
+ }
301
+ }
302
+ }
303
+ this.reconnecting = false;
304
+ if (!this.isConnected) {
305
+ loggers2.agent.error(
306
+ `Failed to reconnect to MongoDB after ${this.maxReconnectAttempts} attempts`
307
+ );
308
+ }
309
+ }
310
+ async connect() {
311
+ if (this.connected) {
312
+ return;
313
+ }
314
+ try {
315
+ await mongoose.connect(this.uri, this.connectionConfig);
316
+ this.connected = true;
317
+ this.reconnectAttempts = 0;
318
+ } catch (error) {
319
+ loggers2.agent.error("Failed to connect to MongoDB:", error);
320
+ throw error;
321
+ }
322
+ }
323
+ async disconnect() {
324
+ if (!this.isConnected) {
325
+ return;
326
+ }
327
+ try {
328
+ await mongoose.disconnect();
329
+ this.connected = false;
330
+ } catch (error) {
331
+ loggers2.agent.error("Failed to disconnect from MongoDB:", error);
332
+ throw error;
333
+ }
334
+ }
335
+ isConnected() {
336
+ return this.connected;
337
+ }
338
+ async ensureConnection() {
339
+ if (!this.isConnected && !this.reconnecting) {
340
+ await this.connect();
341
+ }
342
+ const maxWaitTime = 3e4;
343
+ const startTime = Date.now();
344
+ while (this.reconnecting && Date.now() - startTime < maxWaitTime) {
345
+ await new Promise((resolve) => setTimeout(resolve, 100));
346
+ }
347
+ if (!this.isConnected) {
348
+ throw new Error("MongoDB is not connected and reconnection failed");
349
+ }
350
+ }
351
+ /**
352
+ * Get the operation timeout in milliseconds
353
+ */
354
+ getOperationTimeout() {
355
+ return this.operationTimeoutMS;
356
+ }
357
+ /**
358
+ * Execute a database operation with automatic retry on connection errors
359
+ * Note: Use mongoose's maxTimeMS option in queries for timeout control
360
+ */
361
+ async executeWithRetry(operation, operationName = "Database operation") {
362
+ await this.ensureConnection();
363
+ try {
364
+ return await operation();
365
+ } catch (error) {
366
+ if (error.code === 50 || error.message?.includes("operation exceeded time limit")) {
367
+ loggers2.agent.error(`${operationName} exceeded time limit`);
368
+ throw error;
369
+ }
370
+ if (error.name === "MongoNetworkError" || error.name === "MongoServerError" || error.message?.includes("connection") || error.message?.includes("disconnect")) {
371
+ loggers2.agent.warn(
372
+ `${operationName} failed due to connection issue, attempting reconnection...`
373
+ );
374
+ await this.ensureConnection();
375
+ try {
376
+ return await operation();
377
+ } catch (retryError) {
378
+ loggers2.agent.error(`${operationName} failed after retry:`, retryError);
379
+ throw retryError;
380
+ }
381
+ }
382
+ throw error;
383
+ }
167
384
  }
168
385
  };
169
386
  export {
170
- MongoDBIntent,
171
- MongoDBThread
387
+ MongoDBMemory
172
388
  };
173
389
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../implements/base.memory.ts","../implements/thread.memory.ts","../implements/intent.memory.ts"],"sourcesContent":["import { IMemory } from \"node_modules/@ainetwork/adk/dist/esm/modules/memory/base.memory\";\nimport mongoose from \"mongoose\";\nimport { loggers } from \"@ainetwork/adk/utils/logger\";\n\nexport class MongoDBMemory implements IMemory {\n private _isConnected: boolean = false;\n private _uri: string;\n\n constructor(uri: string) {\n this._uri = uri;\n }\n\n public async connect(): Promise<void> {\n\t\tif (this._isConnected) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n await mongoose.connect(this._uri, {\n maxPoolSize: 1,\n serverSelectionTimeoutMS: 30000,\n socketTimeoutMS: 45000,\n connectTimeoutMS: 30000,\n bufferCommands: false,\n });\n\t\t\tthis._isConnected = true;\n\t\t\tloggers.agent.info(\"MongoDB connected successfully\");\n\t\t} catch (error) {\n\t\t\tloggers.agent.error(\"Failed to connect to MongoDB:\", error);\n\t\t\tthrow error;\n\t\t}\n }\n\n public async disconnect(): Promise<void> {\n\t\tif (!this.isConnected) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait mongoose.disconnect();\n\t\t\tthis._isConnected = false;\n\t\t\tloggers.agent.info(\"MongoDB disconnected successfully\");\n\t\t} catch (error) {\n\t\t\tloggers.agent.error(\"Failed to disconnect from MongoDB:\", error);\n\t\t\tthrow error;\n\t\t}\n }\n\n public isConnected(): boolean {\n return this._isConnected;\n }\n}","import type { MessageObject, ThreadMetadata, ThreadObject, ThreadType } from \"@ainetwork/adk/types/memory\";\nimport { MessageRole } from \"@ainetwork/adk/types/memory\";\nimport { IThreadMemory } from \"@ainetwork/adk/modules\";\nimport { MongoDBMemory } from \"./base.memory\";\nimport { ThreadDocument, ThreadModel } from \"../models/threads.model\";\nimport { MessageDocument, MessageModel } from \"../models/messages.model\";\nimport { loggers } from \"@ainetwork/adk/utils/logger\";\n\nexport class MongoDBThread extends MongoDBMemory implements IThreadMemory {\n constructor(uri: string) {\n super(uri);\n }\n\n public async getThread(\n userId: string,\n threadId: string\n ): Promise<ThreadObject | undefined> {\n const thread = await ThreadModel.findOne({ threadId, userId });\n\t\tconst messages = await MessageModel.find({ threadId, userId }).sort({\n\t\t\ttimestamp: 1,\n\t\t});\n\n if (!thread) return undefined;\n\n\t\tloggers.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);\n\n\t\tconst threadObject: ThreadObject = { \n threadId: thread.threadId, \n userId: thread.userId,\n type: thread.type as ThreadType,\n title: thread.title || \"New thread\",\n messages: []\n };\n\t\tmessages.forEach((message: MessageDocument) => {\n\t\t\tthreadObject.messages.push({\n messageId: message.messageId,\n\t\t\t\trole: message.role as MessageRole,\n\t\t\t\tcontent: message.content,\n\t\t\t\ttimestamp: message.timestamp,\n\t\t\t\tmetadata: message.metadata,\n\t\t\t});\n\t\t});\n\n\t\treturn threadObject;\n };\n\n\tpublic async createThread(\n\t\ttype: ThreadType,\n\t\tuserId: string,\n\t\tthreadId: string,\n\t\ttitle: string,\n ): Promise<ThreadObject> {\n const now = Date.now();\n await ThreadModel.create({\n type,\n userId,\n threadId,\n title,\n updated_at: now,\n created_at: now,\n });\n\n return { type, userId, threadId, title, messages: []};\n };\n\n\tpublic async addMessagesToThread(\n userId: string,\n threadId: string,\n messages: MessageObject[]\n ): Promise<void> {\n await ThreadModel.updateOne({ threadId, userId }, {\n updated_at: Date.now(),\n });\n for (const message of messages) {\n await MessageModel.create({\n threadId,\n messageId: message.messageId,\n userId,\n role: message.role,\n content: message.content,\n timestamp: message.timestamp,\n metadata: message.metadata,\n });\n }\n };\n\n\tpublic async deleteThread(userId: string, threadId: string): Promise<void> {\n\t\tconst messages = await MessageModel.find({ userId, threadId }).sort({\n\t\t\ttimestamp: 1,\n\t\t});\n\n\t\tmessages?.forEach((message: MessageDocument) => {\n message.deleteOne();\n\t\t});\n \n const thread = await ThreadModel.findOne({ userId, threadId });\n thread?.deleteOne();\n };\n\n\tpublic async listThreads(userId: string): Promise<ThreadMetadata[]> {\n const threads = await ThreadModel.find({ userId }).sort({\n updated_at: -1,\n });\n const data: ThreadMetadata[] = threads.map((thread: ThreadDocument) => {\n return {\n type: thread.type,\n userId,\n threadId: thread.threadId,\n title: thread.title,\n updatedAt: thread.updated_at\n } as ThreadMetadata;\n })\n return data;\n };\n}","import type { Intent } from \"@ainetwork/adk/types/memory\";\nimport { IIntentMemory } from \"@ainetwork/adk/modules\";\nimport { MongoDBMemory } from \"./base.memory\";\nimport { IntentModel } from \"../models/intent.model\";\n\nexport class MongoDBIntent extends MongoDBMemory implements IIntentMemory {\n public async getIntent(intentId: string): Promise<Intent | undefined> {\n const intent = await IntentModel.findOne({ id: intentId }).lean<Intent>();\n return intent || undefined;\n };\n\n\tpublic async getIntentByName(intentName: string): Promise<Intent | undefined> {\n\t\tconst intent = await IntentModel.findOne({ name: intentName }).lean<Intent>();\n return intent || undefined;\n\t}\n\n\tpublic async saveIntent(intent: Intent): Promise<void> {\n await IntentModel.create(intent);\n };\n\n\tpublic async updateIntent(intentId: string, intent: Intent): Promise<void> {\n await IntentModel.updateOne({\n id: intentId,\n }, intent);\n };\n\n\tpublic async deleteIntent(intentId: string): Promise<void> {\n await IntentModel.deleteOne({ id: intentId });\n };\n\n\tpublic async listIntents(): Promise<Intent[]> {\n const intents = await IntentModel.find().lean<Intent[]>();\n return intents;\n };\n}"],"mappings":";;;;;;;;;;;AACA,OAAO,cAAc;AACrB,SAAS,eAAe;AAEjB,IAAM,gBAAN,MAAuC;AAAA,EACpC,eAAwB;AAAA,EACxB;AAAA,EAER,YAAY,KAAa;AACvB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,MAAa,UAAyB;AACtC,QAAI,KAAK,cAAc;AACtB;AAAA,IACD;AAEA,QAAI;AACA,YAAM,SAAS,QAAQ,KAAK,MAAM;AAAA,QAChC,aAAa;AAAA,QACb,0BAA0B;AAAA,QAC1B,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,gBAAgB;AAAA,MAClB,CAAC;AACJ,W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AO;AAAA,QACjB,OAAO,OAAO;AAAA,QACd,WAAW,OAAO;AAAA,MACpB;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AACF;;;AC7GO,IAAM,gBAAN,cAA4B,cAAuC;AAAA,EACxE,MAAa,UAAU,UAA+C;AACpE,UAAM,SAAS,MAAM,YAAY,QAAQ,EAAE,IAAI,SAAS,CAAC,EAAE,KAAa;AACxE,WAAO,UAAU;AAAA,EACnB;AAAA,EAED,MAAa,gBAAgB,YAAiD;AAC7E,UAAM,SAAS,MAAM,YAAY,QAAQ,EAAE,MAAM,WAAW,CAAC,EAAE,KAAa;AAC1E,WAAO,UAAU;AAAA,EACpB;AAAA,EAEA,MAAa,WAAW,QAA+B;AACpD,UAAM,YAAY,OAAO,MAAM;AAAA,EACjC;AAAA,EAED,MAAa,aAAa,UAAkB,QAA+B;AACxE,UAAM,YAAY,UAAU;AAAA,MAC1B,IAAI;AAAA,IACN,GAAG,MAAM;AAAA,EACX;AAAA,EAED,MAAa,aAAa,UAAiC;AACxD,UAAM,YAAY,UAAU,EAAE,IAAI,SAAS,CAAC;AAAA,EAC9C;AAAA,EAED,MAAa,cAAiC;AAC3C,UAAM,UAAU,MAAM,YAAY,KAAK,EAAE,KAAe;AACxD,WAAO;AAAA,EACT;AACF;","names":["loggers"]}
1
+ {"version":3,"sources":["../implements/base.memory.ts","../implements/agent.memory.ts","../implements/intent.memory.ts","../implements/thread.memory.ts"],"sourcesContent":["import { IAgentMemory, IIntentMemory, IMemory, IThreadMemory } from \"node_modules/@ainetwork/adk/dist/esm/modules/memory/base.memory\";\nimport mongoose from \"mongoose\";\nimport { loggers } from \"@ainetwork/adk/utils/logger\";\nimport { MongoDBAgent } from \"./agent.memory\";\nimport { MongoDBIntent } from \"./intent.memory\";\nimport { MongoDBThread } from \"./thread.memory\";\n\nexport interface MongoDBMemoryConfig {\n uri: string;\n maxReconnectAttempts?: number;\n reconnectInterval?: number;\n maxPoolSize?: number;\n serverSelectionTimeoutMS?: number;\n socketTimeoutMS?: number;\n connectTimeoutMS?: number;\n operationTimeoutMS?: number; // Timeout for database operations\n}\n\nexport class MongoDBMemory implements IMemory {\n private static instance: MongoDBMemory;\n private uri: string;\n private connected: boolean = false;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number;\n private reconnectInterval: number;\n private reconnecting: boolean = false;\n private connectionConfig: mongoose.ConnectOptions;\n private eventListenersSetup: boolean = false;\n private operationTimeoutMS: number;\n\n private agentMemory: MongoDBAgent;\n private intentMemory: MongoDBIntent;\n private threadMemory: MongoDBThread;\n\n constructor(config: string | MongoDBMemoryConfig) {\n const cfg = typeof config === 'string' ? { uri: config } : config;\n\n this.uri = cfg.uri;\n this.maxReconnectAttempts = cfg.maxReconnectAttempts ?? 5;\n this.reconnectInterval = cfg.reconnectInterval ?? 5000;\n this.operationTimeoutMS = cfg.operationTimeoutMS ?? 10000; // Default 10 seconds\n this.connectionConfig = {\n maxPoolSize: cfg.maxPoolSize ?? 1,\n serverSelectionTimeoutMS: cfg.serverSelectionTimeoutMS ?? 30000,\n socketTimeoutMS: cfg.socketTimeoutMS ?? 45000,\n connectTimeoutMS: cfg.connectTimeoutMS ?? 30000,\n bufferCommands: false,\n };\n\n if (!MongoDBMemory.instance) {\n MongoDBMemory.instance = this;\n this.setupMongooseEventListeners();\n } else {\n // Use existing instance's connection state\n this.connected = MongoDBMemory.instance.connected;\n this.operationTimeoutMS = MongoDBMemory.instance.operationTimeoutMS;\n }\n\n\t\tthis.agentMemory = new MongoDBAgent(\n\t\t\tthis.executeWithRetry.bind(this),\n\t\t\tthis.getOperationTimeout.bind(this)\n\t\t);\n\n\t\tthis.threadMemory = new MongoDBThread(\n\t\t\tthis.executeWithRetry.bind(this),\n\t\t\tthis.getOperationTimeout.bind(this)\n\t\t);\n\n\t\tthis.intentMemory = new MongoDBIntent(\n\t\t\tthis.executeWithRetry.bind(this),\n\t\t\tthis.getOperationTimeout.bind(this)\n\t\t);\n }\n\n public getAgentMemory(): IAgentMemory {\n return this.agentMemory;\n }\n\n public getThreadMemory(): IThreadMemory {\n return this.threadMemory;\n }\n\n public getIntentMemory(): IIntentMemory {\n return this.intentMemory;\n }\n\n private setupMongooseEventListeners(): void {\n if (this.eventListenersSetup) return;\n\n this.eventListenersSetup = true;\n\n mongoose.connection.on(\"connected\", () => {\n this.connected = true;\n this.reconnectAttempts = 0;\n this.reconnecting = false;\n loggers.agent.info(\"MongoDB connected successfully\");\n });\n\n mongoose.connection.on(\"disconnected\", () => {\n this.connected = false;\n loggers.agent.warn(\"MongoDB disconnected\");\n this.handleDisconnection();\n });\n\n mongoose.connection.on(\"error\", (error) => {\n this.connected = false;\n loggers.agent.error(\"MongoDB connection error:\", error);\n this.handleDisconnection();\n });\n\n mongoose.connection.on(\"reconnected\", () => {\n this.connected = true;\n this.reconnectAttempts = 0;\n this.reconnecting = false;\n loggers.agent.info(\"MongoDB reconnected successfully\");\n });\n }\n\n private async handleDisconnection(): Promise<void> {\n if (this.reconnecting) {\n return;\n }\n\n this.reconnecting = true;\n\n while (this.reconnectAttempts < this.maxReconnectAttempts && !this.isConnected) {\n this.reconnectAttempts++;\n loggers.agent.info(\n `Attempting to reconnect to MongoDB (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`\n );\n\n try {\n await mongoose.connect(this.uri, this.connectionConfig);\n this.connected = true;\n this.reconnectAttempts = 0;\n this.reconnecting = false;\n loggers.agent.info(\"MongoDB reconnection successful\");\n return;\n } catch (error) {\n loggers.agent.error(\n `Reconnection attempt ${this.reconnectAttempts} failed:`,\n error\n );\n\n if (this.reconnectAttempts < this.maxReconnectAttempts) {\n await new Promise((resolve) =>\n setTimeout(resolve, this.reconnectInterval)\n );\n }\n }\n }\n\n this.reconnecting = false;\n\n if (!this.isConnected) {\n loggers.agent.error(\n `Failed to reconnect to MongoDB after ${this.maxReconnectAttempts} attempts`\n );\n }\n }\n\n public async connect(): Promise<void> {\n if (this.connected) {\n return;\n }\n\n try {\n await mongoose.connect(this.uri, this.connectionConfig);\n this.connected = true;\n this.reconnectAttempts = 0;\n } catch (error) {\n loggers.agent.error(\"Failed to connect to MongoDB:\", error);\n throw error;\n }\n }\n\n public async disconnect(): Promise<void> {\n if (!this.isConnected) {\n return;\n }\n\n try {\n await mongoose.disconnect();\n this.connected = false;\n } catch (error) {\n loggers.agent.error(\"Failed to disconnect from MongoDB:\", error);\n throw error;\n }\n }\n\n public isConnected(): boolean {\n return this.connected;\n }\n\n private async ensureConnection(): Promise<void> {\n if (!this.isConnected && !this.reconnecting) {\n await this.connect();\n }\n\n // Wait for reconnection if in progress\n const maxWaitTime = 30000; // 30 seconds\n const startTime = Date.now();\n while (this.reconnecting && Date.now() - startTime < maxWaitTime) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n if (!this.isConnected) {\n throw new Error(\"MongoDB is not connected and reconnection failed\");\n }\n }\n\n /**\n * Get the operation timeout in milliseconds\n */\n protected getOperationTimeout(): number {\n return this.operationTimeoutMS;\n }\n\n /**\n * Execute a database operation with automatic retry on connection errors\n * Note: Use mongoose's maxTimeMS option in queries for timeout control\n */\n protected async executeWithRetry<T>(\n operation: () => Promise<T>,\n operationName: string = \"Database operation\"\n ): Promise<T> {\n await this.ensureConnection();\n\n try {\n return await operation();\n } catch (error: any) {\n // Check if it's a timeout error from MongoDB\n if (error.code === 50 || error.message?.includes(\"operation exceeded time limit\")) {\n loggers.agent.error(`${operationName} exceeded time limit`);\n throw error;\n }\n\n // Check if it's a connection-related error\n if (\n error.name === \"MongoNetworkError\" ||\n error.name === \"MongoServerError\" ||\n error.message?.includes(\"connection\") ||\n error.message?.includes(\"disconnect\")\n ) {\n loggers.agent.warn(\n `${operationName} failed due to connection issue, attempting reconnection...`\n );\n\n await this.ensureConnection();\n\n // Retry the operation once after reconnection\n try {\n return await operation();\n } catch (retryError: any) {\n loggers.agent.error(`${operationName} failed after retry:`, retryError);\n throw retryError;\n }\n }\n\n // If it's not a connection error, just throw it\n throw error;\n }\n }\n}\n","import { IAgentMemory } from \"@ainetwork/adk/modules\";\nimport { AgentModel } from \"../models/agent.model\";\n\nexport type ExecuteWithRetryFn = <T>(\n operation: () => Promise<T>,\n operationName?: string\n) => Promise<T>;\n\nexport type GetOperationTimeoutFn = () => number;\n\ntype AgentMetadata = {\n agent_prompt: string;\n}\n\nexport class MongoDBAgent implements IAgentMemory {\n private executeWithRetry: ExecuteWithRetryFn;\n private getOperationTimeout: GetOperationTimeoutFn;\n\n constructor(\n executeWithRetry: ExecuteWithRetryFn,\n getOperationTimeout: GetOperationTimeoutFn\n ) {\n this.executeWithRetry = executeWithRetry;\n this.getOperationTimeout = getOperationTimeout;\n }\n\n public async getAgentPrompt(): Promise<string> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const metadata = await AgentModel.findOne({\n id: \"agent_metadata\"\n }).maxTimeMS(timeout)\n .lean<AgentMetadata>();\n return metadata?.agent_prompt || \"\";\n }, \"getAgentPrompt()\");\n };\n \n public async updateAgentPrompt(prompt: string): Promise<void> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n await AgentModel.updateOne({\n id: \"agent_metadata\",\n }, { \"agent_prompt\": prompt }).maxTimeMS(timeout);\n }, \"updateAgentPrompt()\");\n };\n}\n","import type { Intent } from \"@ainetwork/adk/types/memory\";\nimport { IIntentMemory } from \"@ainetwork/adk/modules\";\nimport { IntentModel } from \"../models/intent.model\";\n\nexport type ExecuteWithRetryFn = <T>(\n operation: () => Promise<T>,\n operationName?: string\n) => Promise<T>;\n\nexport type GetOperationTimeoutFn = () => number;\n\nexport class MongoDBIntent implements IIntentMemory {\n private executeWithRetry: ExecuteWithRetryFn;\n private getOperationTimeout: GetOperationTimeoutFn;\n\n constructor(\n executeWithRetry: ExecuteWithRetryFn,\n getOperationTimeout: GetOperationTimeoutFn\n ) {\n this.executeWithRetry = executeWithRetry;\n this.getOperationTimeout = getOperationTimeout;\n }\n\n public async getIntent(intentId: string): Promise<Intent | undefined> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const intent = await IntentModel.findOne({ id: intentId })\n .maxTimeMS(timeout)\n .lean<Intent>();\n return intent || undefined;\n }, `getIntent(${intentId})`);\n };\n\n public async getIntentByName(intentName: string): Promise<Intent | undefined> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const intent = await IntentModel.findOne({ name: intentName })\n .maxTimeMS(timeout)\n .lean<Intent>();\n return intent || undefined;\n }, `getIntentByName(${intentName})`);\n }\n\n public async saveIntent(intent: Intent): Promise<void> {\n return this.executeWithRetry(async () => {\n await IntentModel.create(intent);\n }, `saveIntent(${intent.id})`);\n };\n\n public async updateIntent(intentId: string, intent: Intent): Promise<void> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n await IntentModel.updateOne({\n id: intentId,\n }, intent).maxTimeMS(timeout);\n }, `updateIntent(${intentId})`);\n };\n\n public async deleteIntent(intentId: string): Promise<void> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n await IntentModel.deleteOne({ id: intentId }).maxTimeMS(timeout);\n }, `deleteIntent(${intentId})`);\n };\n\n public async listIntents(): Promise<Intent[]> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const intents = await IntentModel.find()\n .maxTimeMS(timeout)\n .lean<Intent[]>();\n return intents;\n }, `listIntents()`);\n };\n}\n","import type { MessageObject, ThreadMetadata, ThreadObject, ThreadType } from \"@ainetwork/adk/types/memory\";\nimport { MessageRole } from \"@ainetwork/adk/types/memory\";\nimport { IThreadMemory } from \"@ainetwork/adk/modules\";\nimport { ThreadDocument, ThreadModel } from \"../models/threads.model\";\nimport { MessageDocument, MessageModel } from \"../models/messages.model\";\nimport { loggers } from \"@ainetwork/adk/utils/logger\";\n\nexport type ExecuteWithRetryFn = <T>(\n operation: () => Promise<T>,\n operationName?: string\n) => Promise<T>;\n\nexport type GetOperationTimeoutFn = () => number;\n\nexport class MongoDBThread implements IThreadMemory {\n private executeWithRetry: ExecuteWithRetryFn;\n private getOperationTimeout: GetOperationTimeoutFn;\n\n constructor(\n executeWithRetry: ExecuteWithRetryFn,\n getOperationTimeout: GetOperationTimeoutFn\n ) {\n this.executeWithRetry = executeWithRetry;\n this.getOperationTimeout = getOperationTimeout;\n }\n\n public async getThread(\n userId: string,\n threadId: string\n ): Promise<ThreadObject | undefined> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const thread = await ThreadModel.findOne({ threadId, userId }).maxTimeMS(timeout);\n const messages = await MessageModel.find({ threadId, userId })\n .sort({ timestamp: 1 })\n .maxTimeMS(timeout);\n\n if (!thread) return undefined;\n\n loggers.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);\n\n const threadObject: ThreadObject = {\n threadId: thread.threadId,\n userId: thread.userId,\n type: thread.type as ThreadType,\n title: thread.title || \"New thread\",\n messages: []\n };\n messages.forEach((message: MessageDocument) => {\n threadObject.messages.push({\n messageId: message.messageId,\n role: message.role as MessageRole,\n content: message.content,\n timestamp: message.timestamp,\n metadata: message.metadata,\n });\n });\n\n return threadObject;\n }, `getThread(${userId}, ${threadId})`);\n };\n\n public async createThread(\n type: ThreadType,\n userId: string,\n threadId: string,\n title: string,\n ): Promise<ThreadObject> {\n return this.executeWithRetry(async () => {\n const now = Date.now();\n await ThreadModel.create({\n type,\n userId,\n threadId,\n title,\n updated_at: now,\n created_at: now,\n });\n\n return { type, userId, threadId, title, messages: []};\n }, `createThread(${userId}, ${threadId})`);\n };\n\n public async addMessagesToThread(\n userId: string,\n threadId: string,\n messages: MessageObject[]\n ): Promise<void> {\n return this.executeWithRetry(async () => {\n await ThreadModel.updateOne({ threadId, userId }, {\n updated_at: Date.now(),\n });\n for (const message of messages) {\n await MessageModel.create({\n threadId,\n messageId: message.messageId,\n userId,\n role: message.role,\n content: message.content,\n timestamp: message.timestamp,\n metadata: message.metadata,\n });\n }\n }, `addMessagesToThread(${userId}, ${threadId})`);\n };\n\n public async deleteThread(userId: string, threadId: string): Promise<void> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const messages = await MessageModel.find({ userId, threadId })\n .sort({ timestamp: 1 })\n .maxTimeMS(timeout);\n\n messages?.forEach((message: MessageDocument) => {\n message.deleteOne();\n });\n\n const thread = await ThreadModel.findOne({ userId, threadId }).maxTimeMS(timeout);\n thread?.deleteOne();\n }, `deleteThread(${userId}, ${threadId})`);\n };\n\n public async listThreads(userId: string): Promise<ThreadMetadata[]> {\n return this.executeWithRetry(async () => {\n const timeout = this.getOperationTimeout();\n const threads = await ThreadModel.find({ userId })\n .sort({ updated_at: -1 })\n .maxTimeMS(timeout);\n const data: ThreadMetadata[] = threads.map((thread: ThreadDocument) => {\n return {\n type: thread.type,\n userId,\n threadId: thread.threadId,\n title: thread.title,\n updatedAt: thread.updated_at\n } as ThreadMetadata;\n })\n return data;\n }, `listThreads(${userId})`);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AACA,OAAO,cAAc;AACrB,SAAS,WAAAA,gBAAe;;;ACYjB,IAAM,eAAN,MAA2C;AAAA,EACxC;AAAA,EACA;AAAA,EAER,YACE,kBACA,qBACA;AACA,SAAK,mBAAmB;AACxB,SAAK,sBAAsB;AAAA,EAC7B;AAAA,EAEA,MAAa,iBAAkC;AAC7C,WAAO,KAAK,iBAAiB,YAAY;AACvC,YAAM,UAAU,KAAK,oBAAoB;AACzC,YAAM,WAAW,MAAM,WAAW,QAAQ;AAAA,QACxC,IAAI;AAAA,MACN,CAAC,EAAE,UAAU,OAAO,EACjB,KAAoB;AACvB,aAAO,UAAU,gBAAgB;AAAA,IACnC,GAAG,kBAAkB;AAAA,EACvB;AAAA,EAEA,MAAa,kBAAkB,QAA+B;AAC5D,WAAO,KAAK,iBAAiB,YAAY;AACvC,YAAM,UAAU,KAAK,oBAAoB;AACzC,YAAM,WAAW,UAAU;AAAA,QACzB,IAAI;AAAA,MACN,GAAG,EAAE,gBAAgB,OAAO,CAAC,EAAE,UAAU,OAAO;AAAA,IAClD,GAAG,qB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QACR;AAAA,MACF;AAGA,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":["loggers","loggers"]}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // models/agent.model.ts
31
+ var agent_model_exports = {};
32
+ __export(agent_model_exports, {
33
+ AgentModel: () => AgentModel,
34
+ AgentObjectSchema: () => AgentObjectSchema
35
+ });
36
+ module.exports = __toCommonJS(agent_model_exports);
37
+ var import_mongoose = require("mongoose");
38
+ var import_mongoose2 = __toESM(require("mongoose"), 1);
39
+ var AgentObjectSchema = new import_mongoose.Schema(
40
+ {
41
+ agent_prompt: {
42
+ type: String
43
+ }
44
+ }
45
+ );
46
+ var AgentModel = import_mongoose2.default.model("Agent", AgentObjectSchema);
47
+ // Annotate the CommonJS export names for ESM import in node:
48
+ 0 && (module.exports = {
49
+ AgentModel,
50
+ AgentObjectSchema
51
+ });
52
+ //# sourceMappingURL=agent.model.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../models/agent.model.ts"],"sourcesContent":["import { type Document, Schema } from \"mongoose\";\nimport mongoose from \"mongoose\";\n\nexport const AgentObjectSchema = new Schema(\n\t{\n\t\tagent_prompt: {\n\t\t\ttype: String,\n\t\t},\n\t},\n);\n\nexport interface AgentDocument extends Document {\n\tagent_prompt: string;\n}\n\nexport const AgentModel = mongoose.model<AgentDocument>(\"Agent\", AgentObjectSchema);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAsC;AACtC,IAAAA,mBAAqB;AAEd,IAAM,oBAAoB,IAAI;AAAA,EACpC;AAAA,IACC,cAAc;AAAA,MACb,MAAM;AAAA,IACP;AAAA,EACD;AACD;AAMO,IAAM,aAAa,iBAAAC,QAAS,MAAqB,SAAS,iBAAiB;","names":["import_mongoose","mongoose"]}