@ainetwork/adk-provider-memory-mongodb 0.2.4 → 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.
@@ -0,0 +1,17 @@
1
+ // models/agent.model.ts
2
+ import { Schema } from "mongoose";
3
+ import mongoose from "mongoose";
4
+ var AgentObjectSchema = new Schema(
5
+ {
6
+ agent_prompt: {
7
+ type: String
8
+ }
9
+ }
10
+ );
11
+ var AgentModel = mongoose.model("Agent", AgentObjectSchema);
12
+
13
+ export {
14
+ AgentObjectSchema,
15
+ AgentModel
16
+ };
17
+ //# sourceMappingURL=chunk-OWGGE5EW.js.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,SAAwB,cAAc;AACtC,OAAO,cAAc;AAEd,IAAM,oBAAoB,IAAI;AAAA,EACpC;AAAA,IACC,cAAc;AAAA,MACb,MAAM;AAAA,IACP;AAAA,EACD;AACD;AAMO,IAAM,aAAa,SAAS,MAAqB,SAAS,iBAAiB;","names":[]}
package/dist/index.cjs CHANGED
@@ -30,191 +30,147 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- MongoDBIntent: () => MongoDBIntent,
34
- MongoDBMemory: () => MongoDBMemory,
35
- MongoDBThread: () => MongoDBThread
33
+ MongoDBMemory: () => MongoDBMemory
36
34
  });
37
35
  module.exports = __toCommonJS(index_exports);
38
36
 
39
37
  // implements/base.memory.ts
40
- var import_mongoose = __toESM(require("mongoose"), 1);
41
- var import_logger = require("@ainetwork/adk/utils/logger");
42
- var MongoDBMemory = class _MongoDBMemory {
43
- static instance;
44
- uri;
45
- connected = false;
46
- reconnectAttempts = 0;
47
- maxReconnectAttempts;
48
- reconnectInterval;
49
- reconnecting = false;
50
- connectionConfig;
51
- eventListenersSetup = false;
52
- operationTimeoutMS;
53
- constructor(config) {
54
- const cfg = typeof config === "string" ? { uri: config } : config;
55
- this.uri = cfg.uri;
56
- this.maxReconnectAttempts = cfg.maxReconnectAttempts ?? 5;
57
- this.reconnectInterval = cfg.reconnectInterval ?? 5e3;
58
- this.operationTimeoutMS = cfg.operationTimeoutMS ?? 1e4;
59
- this.connectionConfig = {
60
- maxPoolSize: cfg.maxPoolSize ?? 1,
61
- serverSelectionTimeoutMS: cfg.serverSelectionTimeoutMS ?? 3e4,
62
- socketTimeoutMS: cfg.socketTimeoutMS ?? 45e3,
63
- connectTimeoutMS: cfg.connectTimeoutMS ?? 3e4,
64
- bufferCommands: false
65
- };
66
- if (!_MongoDBMemory.instance) {
67
- _MongoDBMemory.instance = this;
68
- this.setupMongooseEventListeners();
69
- } else {
70
- this.connected = _MongoDBMemory.instance.connected;
71
- this.operationTimeoutMS = _MongoDBMemory.instance.operationTimeoutMS;
38
+ var import_mongoose8 = __toESM(require("mongoose"), 1);
39
+ var import_logger2 = require("@ainetwork/adk/utils/logger");
40
+
41
+ // models/agent.model.ts
42
+ var import_mongoose = require("mongoose");
43
+ var import_mongoose2 = __toESM(require("mongoose"), 1);
44
+ var AgentObjectSchema = new import_mongoose.Schema(
45
+ {
46
+ agent_prompt: {
47
+ type: String
72
48
  }
73
49
  }
74
- setupMongooseEventListeners() {
75
- if (this.eventListenersSetup) return;
76
- this.eventListenersSetup = true;
77
- import_mongoose.default.connection.on("connected", () => {
78
- this.connected = true;
79
- this.reconnectAttempts = 0;
80
- this.reconnecting = false;
81
- import_logger.loggers.agent.info("MongoDB connected successfully");
82
- });
83
- import_mongoose.default.connection.on("disconnected", () => {
84
- this.connected = false;
85
- import_logger.loggers.agent.warn("MongoDB disconnected");
86
- this.handleDisconnection();
87
- });
88
- import_mongoose.default.connection.on("error", (error) => {
89
- this.connected = false;
90
- import_logger.loggers.agent.error("MongoDB connection error:", error);
91
- this.handleDisconnection();
92
- });
93
- import_mongoose.default.connection.on("reconnected", () => {
94
- this.connected = true;
95
- this.reconnectAttempts = 0;
96
- this.reconnecting = false;
97
- import_logger.loggers.agent.info("MongoDB reconnected successfully");
98
- });
50
+ );
51
+ var AgentModel = import_mongoose2.default.model("Agent", AgentObjectSchema);
52
+
53
+ // implements/agent.memory.ts
54
+ var MongoDBAgent = class {
55
+ executeWithRetry;
56
+ getOperationTimeout;
57
+ constructor(executeWithRetry, getOperationTimeout) {
58
+ this.executeWithRetry = executeWithRetry;
59
+ this.getOperationTimeout = getOperationTimeout;
99
60
  }
100
- async handleDisconnection() {
101
- if (this.reconnecting) {
102
- return;
103
- }
104
- this.reconnecting = true;
105
- while (this.reconnectAttempts < this.maxReconnectAttempts && !this.isConnected) {
106
- this.reconnectAttempts++;
107
- import_logger.loggers.agent.info(
108
- `Attempting to reconnect to MongoDB (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`
109
- );
110
- try {
111
- await import_mongoose.default.connect(this.uri, this.connectionConfig);
112
- this.connected = true;
113
- this.reconnectAttempts = 0;
114
- this.reconnecting = false;
115
- import_logger.loggers.agent.info("MongoDB reconnection successful");
116
- return;
117
- } catch (error) {
118
- import_logger.loggers.agent.error(
119
- `Reconnection attempt ${this.reconnectAttempts} failed:`,
120
- error
121
- );
122
- if (this.reconnectAttempts < this.maxReconnectAttempts) {
123
- await new Promise(
124
- (resolve) => setTimeout(resolve, this.reconnectInterval)
125
- );
126
- }
127
- }
128
- }
129
- this.reconnecting = false;
130
- if (!this.isConnected) {
131
- import_logger.loggers.agent.error(
132
- `Failed to reconnect to MongoDB after ${this.maxReconnectAttempts} attempts`
133
- );
134
- }
61
+ async getAgentPrompt() {
62
+ return this.executeWithRetry(async () => {
63
+ const timeout = this.getOperationTimeout();
64
+ const metadata = await AgentModel.findOne({
65
+ id: "agent_metadata"
66
+ }).maxTimeMS(timeout).lean();
67
+ return metadata?.agent_prompt || "";
68
+ }, "getAgentPrompt()");
135
69
  }
136
- async connect() {
137
- if (this.connected) {
138
- return;
139
- }
140
- try {
141
- await import_mongoose.default.connect(this.uri, this.connectionConfig);
142
- this.connected = true;
143
- this.reconnectAttempts = 0;
144
- } catch (error) {
145
- import_logger.loggers.agent.error("Failed to connect to MongoDB:", error);
146
- throw error;
147
- }
70
+ async updateAgentPrompt(prompt) {
71
+ return this.executeWithRetry(async () => {
72
+ const timeout = this.getOperationTimeout();
73
+ await AgentModel.updateOne({
74
+ id: "agent_metadata"
75
+ }, { "agent_prompt": prompt }).maxTimeMS(timeout);
76
+ }, "updateAgentPrompt()");
148
77
  }
149
- async disconnect() {
150
- if (!this.isConnected) {
151
- return;
152
- }
153
- try {
154
- await import_mongoose.default.disconnect();
155
- this.connected = false;
156
- } catch (error) {
157
- import_logger.loggers.agent.error("Failed to disconnect from MongoDB:", error);
158
- throw error;
78
+ };
79
+
80
+ // models/intent.model.ts
81
+ var import_mongoose3 = __toESM(require("mongoose"), 1);
82
+ var IntentObjectSchema = new import_mongoose3.Schema(
83
+ {
84
+ id: {
85
+ type: String,
86
+ required: true,
87
+ index: true,
88
+ unique: true
89
+ },
90
+ name: {
91
+ type: String,
92
+ required: true,
93
+ index: true
94
+ },
95
+ description: {
96
+ type: String,
97
+ required: true
98
+ },
99
+ prompt: {
100
+ type: String,
101
+ required: false
102
+ },
103
+ status: {
104
+ type: String,
105
+ required: true
106
+ },
107
+ triggeringSentences: {
108
+ type: [String],
109
+ required: false
110
+ },
111
+ tags: {
112
+ type: [String],
113
+ required: false
159
114
  }
160
115
  }
161
- isConnected() {
162
- return this.connected;
116
+ );
117
+ var IntentModel = import_mongoose3.default.model("Intent", IntentObjectSchema);
118
+
119
+ // implements/intent.memory.ts
120
+ var MongoDBIntent = class {
121
+ executeWithRetry;
122
+ getOperationTimeout;
123
+ constructor(executeWithRetry, getOperationTimeout) {
124
+ this.executeWithRetry = executeWithRetry;
125
+ this.getOperationTimeout = getOperationTimeout;
163
126
  }
164
- async ensureConnection() {
165
- if (!this.isConnected && !this.reconnecting) {
166
- await this.connect();
167
- }
168
- const maxWaitTime = 3e4;
169
- const startTime = Date.now();
170
- while (this.reconnecting && Date.now() - startTime < maxWaitTime) {
171
- await new Promise((resolve) => setTimeout(resolve, 100));
172
- }
173
- if (!this.isConnected) {
174
- throw new Error("MongoDB is not connected and reconnection failed");
175
- }
127
+ async getIntent(intentId) {
128
+ return this.executeWithRetry(async () => {
129
+ const timeout = this.getOperationTimeout();
130
+ const intent = await IntentModel.findOne({ id: intentId }).maxTimeMS(timeout).lean();
131
+ return intent || void 0;
132
+ }, `getIntent(${intentId})`);
176
133
  }
177
- /**
178
- * Get the operation timeout in milliseconds
179
- */
180
- getOperationTimeout() {
181
- return this.operationTimeoutMS;
134
+ async getIntentByName(intentName) {
135
+ return this.executeWithRetry(async () => {
136
+ const timeout = this.getOperationTimeout();
137
+ const intent = await IntentModel.findOne({ name: intentName }).maxTimeMS(timeout).lean();
138
+ return intent || void 0;
139
+ }, `getIntentByName(${intentName})`);
182
140
  }
183
- /**
184
- * Execute a database operation with automatic retry on connection errors
185
- * Note: Use mongoose's maxTimeMS option in queries for timeout control
186
- */
187
- async executeWithRetry(operation, operationName = "Database operation") {
188
- await this.ensureConnection();
189
- try {
190
- return await operation();
191
- } catch (error) {
192
- if (error.code === 50 || error.message?.includes("operation exceeded time limit")) {
193
- import_logger.loggers.agent.error(`${operationName} exceeded time limit`);
194
- throw error;
195
- }
196
- if (error.name === "MongoNetworkError" || error.name === "MongoServerError" || error.message?.includes("connection") || error.message?.includes("disconnect")) {
197
- import_logger.loggers.agent.warn(
198
- `${operationName} failed due to connection issue, attempting reconnection...`
199
- );
200
- await this.ensureConnection();
201
- try {
202
- return await operation();
203
- } catch (retryError) {
204
- import_logger.loggers.agent.error(`${operationName} failed after retry:`, retryError);
205
- throw retryError;
206
- }
207
- }
208
- throw error;
209
- }
141
+ async saveIntent(intent) {
142
+ return this.executeWithRetry(async () => {
143
+ await IntentModel.create(intent);
144
+ }, `saveIntent(${intent.id})`);
145
+ }
146
+ async updateIntent(intentId, intent) {
147
+ return this.executeWithRetry(async () => {
148
+ const timeout = this.getOperationTimeout();
149
+ await IntentModel.updateOne({
150
+ id: intentId
151
+ }, intent).maxTimeMS(timeout);
152
+ }, `updateIntent(${intentId})`);
153
+ }
154
+ async deleteIntent(intentId) {
155
+ return this.executeWithRetry(async () => {
156
+ const timeout = this.getOperationTimeout();
157
+ await IntentModel.deleteOne({ id: intentId }).maxTimeMS(timeout);
158
+ }, `deleteIntent(${intentId})`);
159
+ }
160
+ async listIntents() {
161
+ return this.executeWithRetry(async () => {
162
+ const timeout = this.getOperationTimeout();
163
+ const intents = await IntentModel.find().maxTimeMS(timeout).lean();
164
+ return intents;
165
+ }, `listIntents()`);
210
166
  }
211
167
  };
212
168
 
213
169
  // models/threads.model.ts
214
170
  var import_memory = require("@ainetwork/adk/types/memory");
215
- var import_mongoose2 = require("mongoose");
216
- var import_mongoose3 = __toESM(require("mongoose"), 1);
217
- var ThreadObjectSchema = new import_mongoose2.Schema(
171
+ var import_mongoose4 = require("mongoose");
172
+ var import_mongoose5 = __toESM(require("mongoose"), 1);
173
+ var ThreadObjectSchema = new import_mongoose4.Schema(
218
174
  {
219
175
  type: {
220
176
  type: String,
@@ -245,20 +201,20 @@ var ThreadObjectSchema = new import_mongoose2.Schema(
245
201
  }
246
202
  }
247
203
  );
248
- var ThreadModel = import_mongoose3.default.model("Thread", ThreadObjectSchema);
204
+ var ThreadModel = import_mongoose5.default.model("Thread", ThreadObjectSchema);
249
205
 
250
206
  // models/messages.model.ts
251
207
  var import_memory2 = require("@ainetwork/adk/types/memory");
252
- var import_mongoose4 = require("mongoose");
253
- var import_mongoose5 = __toESM(require("mongoose"), 1);
254
- var MessageContentObjectSchema = new import_mongoose4.Schema(
208
+ var import_mongoose6 = require("mongoose");
209
+ var import_mongoose7 = __toESM(require("mongoose"), 1);
210
+ var MessageContentObjectSchema = new import_mongoose6.Schema(
255
211
  {
256
212
  type: { type: String, required: true },
257
- parts: { type: [import_mongoose4.Schema.Types.Mixed], required: true }
213
+ parts: { type: [import_mongoose6.Schema.Types.Mixed], required: true }
258
214
  },
259
215
  { _id: false }
260
216
  );
261
- var MessageObjectSchema = new import_mongoose4.Schema(
217
+ var MessageObjectSchema = new import_mongoose6.Schema(
262
218
  {
263
219
  messageId: {
264
220
  type: String,
@@ -289,18 +245,21 @@ var MessageObjectSchema = new import_mongoose4.Schema(
289
245
  required: true
290
246
  },
291
247
  metadata: {
292
- type: import_mongoose4.Schema.Types.Mixed,
248
+ type: import_mongoose6.Schema.Types.Mixed,
293
249
  default: {}
294
250
  }
295
251
  }
296
252
  );
297
- var MessageModel = import_mongoose5.default.model("Message", MessageObjectSchema);
253
+ var MessageModel = import_mongoose7.default.model("Message", MessageObjectSchema);
298
254
 
299
255
  // implements/thread.memory.ts
300
- var import_logger2 = require("@ainetwork/adk/utils/logger");
301
- var MongoDBThread = class extends MongoDBMemory {
302
- constructor(uri) {
303
- super(uri);
256
+ var import_logger = require("@ainetwork/adk/utils/logger");
257
+ var MongoDBThread = class {
258
+ executeWithRetry;
259
+ getOperationTimeout;
260
+ constructor(executeWithRetry, getOperationTimeout) {
261
+ this.executeWithRetry = executeWithRetry;
262
+ this.getOperationTimeout = getOperationTimeout;
304
263
  }
305
264
  async getThread(userId, threadId) {
306
265
  return this.executeWithRetry(async () => {
@@ -308,7 +267,7 @@ var MongoDBThread = class extends MongoDBMemory {
308
267
  const thread = await ThreadModel.findOne({ threadId, userId }).maxTimeMS(timeout);
309
268
  const messages = await MessageModel.find({ threadId, userId }).sort({ timestamp: 1 }).maxTimeMS(timeout);
310
269
  if (!thread) return void 0;
311
- import_logger2.loggers.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);
270
+ import_logger.loggers.agent.debug(`Found ${messages.length} messages for thread ${threadId}`);
312
271
  const threadObject = {
313
272
  threadId: thread.threadId,
314
273
  userId: thread.userId,
@@ -389,92 +348,203 @@ var MongoDBThread = class extends MongoDBMemory {
389
348
  }
390
349
  };
391
350
 
392
- // models/intent.model.ts
393
- var import_mongoose6 = __toESM(require("mongoose"), 1);
394
- var IntentObjectSchema = new import_mongoose6.Schema(
395
- {
396
- id: {
397
- type: String,
398
- required: true,
399
- index: true,
400
- unique: true
401
- },
402
- name: {
403
- type: String,
404
- required: true,
405
- index: true
406
- },
407
- description: {
408
- type: String,
409
- required: true
410
- },
411
- prompt: {
412
- type: String,
413
- required: false
414
- },
415
- status: {
416
- type: String,
417
- required: true
418
- },
419
- triggeringSentences: {
420
- type: [String],
421
- required: false
422
- },
423
- tags: {
424
- type: [String],
425
- required: false
351
+ // implements/base.memory.ts
352
+ var MongoDBMemory = class _MongoDBMemory {
353
+ static instance;
354
+ uri;
355
+ connected = false;
356
+ reconnectAttempts = 0;
357
+ maxReconnectAttempts;
358
+ reconnectInterval;
359
+ reconnecting = false;
360
+ connectionConfig;
361
+ eventListenersSetup = false;
362
+ operationTimeoutMS;
363
+ agentMemory;
364
+ intentMemory;
365
+ threadMemory;
366
+ constructor(config) {
367
+ const cfg = typeof config === "string" ? { uri: config } : config;
368
+ this.uri = cfg.uri;
369
+ this.maxReconnectAttempts = cfg.maxReconnectAttempts ?? 5;
370
+ this.reconnectInterval = cfg.reconnectInterval ?? 5e3;
371
+ this.operationTimeoutMS = cfg.operationTimeoutMS ?? 1e4;
372
+ this.connectionConfig = {
373
+ maxPoolSize: cfg.maxPoolSize ?? 1,
374
+ serverSelectionTimeoutMS: cfg.serverSelectionTimeoutMS ?? 3e4,
375
+ socketTimeoutMS: cfg.socketTimeoutMS ?? 45e3,
376
+ connectTimeoutMS: cfg.connectTimeoutMS ?? 3e4,
377
+ bufferCommands: false
378
+ };
379
+ if (!_MongoDBMemory.instance) {
380
+ _MongoDBMemory.instance = this;
381
+ this.setupMongooseEventListeners();
382
+ } else {
383
+ this.connected = _MongoDBMemory.instance.connected;
384
+ this.operationTimeoutMS = _MongoDBMemory.instance.operationTimeoutMS;
426
385
  }
386
+ this.agentMemory = new MongoDBAgent(
387
+ this.executeWithRetry.bind(this),
388
+ this.getOperationTimeout.bind(this)
389
+ );
390
+ this.threadMemory = new MongoDBThread(
391
+ this.executeWithRetry.bind(this),
392
+ this.getOperationTimeout.bind(this)
393
+ );
394
+ this.intentMemory = new MongoDBIntent(
395
+ this.executeWithRetry.bind(this),
396
+ this.getOperationTimeout.bind(this)
397
+ );
427
398
  }
428
- );
429
- var IntentModel = import_mongoose6.default.model("Intent", IntentObjectSchema);
430
-
431
- // implements/intent.memory.ts
432
- var MongoDBIntent = class extends MongoDBMemory {
433
- async getIntent(intentId) {
434
- return this.executeWithRetry(async () => {
435
- const timeout = this.getOperationTimeout();
436
- const intent = await IntentModel.findOne({ id: intentId }).maxTimeMS(timeout).lean();
437
- return intent || void 0;
438
- }, `getIntent(${intentId})`);
399
+ getAgentMemory() {
400
+ return this.agentMemory;
439
401
  }
440
- async getIntentByName(intentName) {
441
- return this.executeWithRetry(async () => {
442
- const timeout = this.getOperationTimeout();
443
- const intent = await IntentModel.findOne({ name: intentName }).maxTimeMS(timeout).lean();
444
- return intent || void 0;
445
- }, `getIntentByName(${intentName})`);
402
+ getThreadMemory() {
403
+ return this.threadMemory;
446
404
  }
447
- async saveIntent(intent) {
448
- return this.executeWithRetry(async () => {
449
- await IntentModel.create(intent);
450
- }, `saveIntent(${intent.id})`);
405
+ getIntentMemory() {
406
+ return this.intentMemory;
451
407
  }
452
- async updateIntent(intentId, intent) {
453
- return this.executeWithRetry(async () => {
454
- const timeout = this.getOperationTimeout();
455
- await IntentModel.updateOne({
456
- id: intentId
457
- }, intent).maxTimeMS(timeout);
458
- }, `updateIntent(${intentId})`);
408
+ setupMongooseEventListeners() {
409
+ if (this.eventListenersSetup) return;
410
+ this.eventListenersSetup = true;
411
+ import_mongoose8.default.connection.on("connected", () => {
412
+ this.connected = true;
413
+ this.reconnectAttempts = 0;
414
+ this.reconnecting = false;
415
+ import_logger2.loggers.agent.info("MongoDB connected successfully");
416
+ });
417
+ import_mongoose8.default.connection.on("disconnected", () => {
418
+ this.connected = false;
419
+ import_logger2.loggers.agent.warn("MongoDB disconnected");
420
+ this.handleDisconnection();
421
+ });
422
+ import_mongoose8.default.connection.on("error", (error) => {
423
+ this.connected = false;
424
+ import_logger2.loggers.agent.error("MongoDB connection error:", error);
425
+ this.handleDisconnection();
426
+ });
427
+ import_mongoose8.default.connection.on("reconnected", () => {
428
+ this.connected = true;
429
+ this.reconnectAttempts = 0;
430
+ this.reconnecting = false;
431
+ import_logger2.loggers.agent.info("MongoDB reconnected successfully");
432
+ });
459
433
  }
460
- async deleteIntent(intentId) {
461
- return this.executeWithRetry(async () => {
462
- const timeout = this.getOperationTimeout();
463
- await IntentModel.deleteOne({ id: intentId }).maxTimeMS(timeout);
464
- }, `deleteIntent(${intentId})`);
434
+ async handleDisconnection() {
435
+ if (this.reconnecting) {
436
+ return;
437
+ }
438
+ this.reconnecting = true;
439
+ while (this.reconnectAttempts < this.maxReconnectAttempts && !this.isConnected) {
440
+ this.reconnectAttempts++;
441
+ import_logger2.loggers.agent.info(
442
+ `Attempting to reconnect to MongoDB (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`
443
+ );
444
+ try {
445
+ await import_mongoose8.default.connect(this.uri, this.connectionConfig);
446
+ this.connected = true;
447
+ this.reconnectAttempts = 0;
448
+ this.reconnecting = false;
449
+ import_logger2.loggers.agent.info("MongoDB reconnection successful");
450
+ return;
451
+ } catch (error) {
452
+ import_logger2.loggers.agent.error(
453
+ `Reconnection attempt ${this.reconnectAttempts} failed:`,
454
+ error
455
+ );
456
+ if (this.reconnectAttempts < this.maxReconnectAttempts) {
457
+ await new Promise(
458
+ (resolve) => setTimeout(resolve, this.reconnectInterval)
459
+ );
460
+ }
461
+ }
462
+ }
463
+ this.reconnecting = false;
464
+ if (!this.isConnected) {
465
+ import_logger2.loggers.agent.error(
466
+ `Failed to reconnect to MongoDB after ${this.maxReconnectAttempts} attempts`
467
+ );
468
+ }
465
469
  }
466
- async listIntents() {
467
- return this.executeWithRetry(async () => {
468
- const timeout = this.getOperationTimeout();
469
- const intents = await IntentModel.find().maxTimeMS(timeout).lean();
470
- return intents;
471
- }, `listIntents()`);
470
+ async connect() {
471
+ if (this.connected) {
472
+ return;
473
+ }
474
+ try {
475
+ await import_mongoose8.default.connect(this.uri, this.connectionConfig);
476
+ this.connected = true;
477
+ this.reconnectAttempts = 0;
478
+ } catch (error) {
479
+ import_logger2.loggers.agent.error("Failed to connect to MongoDB:", error);
480
+ throw error;
481
+ }
482
+ }
483
+ async disconnect() {
484
+ if (!this.isConnected) {
485
+ return;
486
+ }
487
+ try {
488
+ await import_mongoose8.default.disconnect();
489
+ this.connected = false;
490
+ } catch (error) {
491
+ import_logger2.loggers.agent.error("Failed to disconnect from MongoDB:", error);
492
+ throw error;
493
+ }
494
+ }
495
+ isConnected() {
496
+ return this.connected;
497
+ }
498
+ async ensureConnection() {
499
+ if (!this.isConnected && !this.reconnecting) {
500
+ await this.connect();
501
+ }
502
+ const maxWaitTime = 3e4;
503
+ const startTime = Date.now();
504
+ while (this.reconnecting && Date.now() - startTime < maxWaitTime) {
505
+ await new Promise((resolve) => setTimeout(resolve, 100));
506
+ }
507
+ if (!this.isConnected) {
508
+ throw new Error("MongoDB is not connected and reconnection failed");
509
+ }
510
+ }
511
+ /**
512
+ * Get the operation timeout in milliseconds
513
+ */
514
+ getOperationTimeout() {
515
+ return this.operationTimeoutMS;
516
+ }
517
+ /**
518
+ * Execute a database operation with automatic retry on connection errors
519
+ * Note: Use mongoose's maxTimeMS option in queries for timeout control
520
+ */
521
+ async executeWithRetry(operation, operationName = "Database operation") {
522
+ await this.ensureConnection();
523
+ try {
524
+ return await operation();
525
+ } catch (error) {
526
+ if (error.code === 50 || error.message?.includes("operation exceeded time limit")) {
527
+ import_logger2.loggers.agent.error(`${operationName} exceeded time limit`);
528
+ throw error;
529
+ }
530
+ if (error.name === "MongoNetworkError" || error.name === "MongoServerError" || error.message?.includes("connection") || error.message?.includes("disconnect")) {
531
+ import_logger2.loggers.agent.warn(
532
+ `${operationName} failed due to connection issue, attempting reconnection...`
533
+ );
534
+ await this.ensureConnection();
535
+ try {
536
+ return await operation();
537
+ } catch (retryError) {
538
+ import_logger2.loggers.agent.error(`${operationName} failed after retry:`, retryError);
539
+ throw retryError;
540
+ }
541
+ }
542
+ throw error;
543
+ }
472
544
  }
473
545
  };
474
546
  // Annotate the CommonJS export names for ESM import in node:
475
547
  0 && (module.exports = {
476
- MongoDBIntent,
477
- MongoDBMemory,
478
- MongoDBThread
548
+ MongoDBMemory
479
549
  });
480
550
  //# sourceMappingURL=index.cjs.map