@snap-agent/core 0.1.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,801 @@
1
+ // src/storage/MongoDBStorage.ts
2
+ import { MongoClient, ObjectId } from "mongodb";
3
+ var MongoDBStorage = class {
4
+ constructor(config) {
5
+ this.db = null;
6
+ if (typeof config === "string") {
7
+ this.config = {
8
+ uri: config,
9
+ dbName: "agentStudio",
10
+ agentsCollection: "v2_agents",
11
+ threadsCollection: "v2_threads"
12
+ };
13
+ } else {
14
+ this.config = {
15
+ uri: config.uri,
16
+ dbName: config.dbName || "agentStudio",
17
+ agentsCollection: config.agentsCollection || "v2_agents",
18
+ threadsCollection: config.threadsCollection || "v2_threads"
19
+ };
20
+ }
21
+ this.client = new MongoClient(this.config.uri);
22
+ }
23
+ async ensureConnection() {
24
+ if (!this.db) {
25
+ await this.client.connect();
26
+ this.db = this.client.db(this.config.dbName);
27
+ }
28
+ return this.db;
29
+ }
30
+ async disconnect() {
31
+ await this.client.close();
32
+ this.db = null;
33
+ }
34
+ // ============================================================================
35
+ // Agent Operations
36
+ // ============================================================================
37
+ async createAgent(config) {
38
+ const db = await this.ensureConnection();
39
+ const collection = db.collection(
40
+ this.config.agentsCollection
41
+ );
42
+ const doc = {
43
+ organizationId: config.organizationId,
44
+ userId: config.userId,
45
+ phone: config.phone,
46
+ name: config.name,
47
+ description: config.description,
48
+ instructions: config.instructions,
49
+ provider: config.provider,
50
+ model: config.model,
51
+ createdAt: /* @__PURE__ */ new Date(),
52
+ updatedAt: /* @__PURE__ */ new Date(),
53
+ files: [],
54
+ metadata: config.metadata || {}
55
+ };
56
+ const result = await collection.insertOne(doc);
57
+ return result.insertedId.toString();
58
+ }
59
+ async getAgent(agentId) {
60
+ const db = await this.ensureConnection();
61
+ const collection = db.collection(
62
+ this.config.agentsCollection
63
+ );
64
+ const doc = await collection.findOne({ _id: new ObjectId(agentId) });
65
+ if (!doc) return null;
66
+ return this.agentDocToData(doc);
67
+ }
68
+ async updateAgent(agentId, updates) {
69
+ const db = await this.ensureConnection();
70
+ const collection = db.collection(
71
+ this.config.agentsCollection
72
+ );
73
+ await collection.updateOne(
74
+ { _id: new ObjectId(agentId) },
75
+ {
76
+ $set: {
77
+ ...updates,
78
+ updatedAt: /* @__PURE__ */ new Date()
79
+ }
80
+ }
81
+ );
82
+ }
83
+ async deleteAgent(agentId) {
84
+ const db = await this.ensureConnection();
85
+ const collection = db.collection(
86
+ this.config.agentsCollection
87
+ );
88
+ await collection.deleteOne({ _id: new ObjectId(agentId) });
89
+ }
90
+ async listAgents(userId, organizationId) {
91
+ const db = await this.ensureConnection();
92
+ const collection = db.collection(
93
+ this.config.agentsCollection
94
+ );
95
+ const query = { userId };
96
+ if (organizationId) {
97
+ query.organizationId = organizationId;
98
+ }
99
+ const docs = await collection.find(query).sort({ updatedAt: -1 }).toArray();
100
+ return docs.map((doc) => this.agentDocToData(doc));
101
+ }
102
+ // ============================================================================
103
+ // Thread Operations
104
+ // ============================================================================
105
+ async createThread(config) {
106
+ const db = await this.ensureConnection();
107
+ const collection = db.collection(
108
+ this.config.threadsCollection
109
+ );
110
+ const doc = {
111
+ organizationId: config.organizationId,
112
+ agentId: config.agentId,
113
+ userId: config.userId,
114
+ endUserId: config.endUserId,
115
+ name: config.name,
116
+ createdAt: /* @__PURE__ */ new Date(),
117
+ updatedAt: /* @__PURE__ */ new Date(),
118
+ messages: [],
119
+ isPendingThread: true,
120
+ metadata: config.metadata || {}
121
+ };
122
+ const result = await collection.insertOne(doc);
123
+ return result.insertedId.toString();
124
+ }
125
+ async getThread(threadId) {
126
+ const db = await this.ensureConnection();
127
+ const collection = db.collection(
128
+ this.config.threadsCollection
129
+ );
130
+ const doc = await collection.findOne({ _id: new ObjectId(threadId) });
131
+ if (!doc) return null;
132
+ return this.threadDocToData(doc);
133
+ }
134
+ async updateThread(threadId, updates) {
135
+ const db = await this.ensureConnection();
136
+ const collection = db.collection(
137
+ this.config.threadsCollection
138
+ );
139
+ await collection.updateOne(
140
+ { _id: new ObjectId(threadId) },
141
+ {
142
+ $set: {
143
+ ...updates,
144
+ updatedAt: /* @__PURE__ */ new Date()
145
+ }
146
+ }
147
+ );
148
+ }
149
+ async deleteThread(threadId) {
150
+ const db = await this.ensureConnection();
151
+ const collection = db.collection(
152
+ this.config.threadsCollection
153
+ );
154
+ await collection.deleteOne({ _id: new ObjectId(threadId) });
155
+ }
156
+ async listThreads(filters) {
157
+ const db = await this.ensureConnection();
158
+ const collection = db.collection(
159
+ this.config.threadsCollection
160
+ );
161
+ const query = {};
162
+ if (filters.userId) query.userId = filters.userId;
163
+ if (filters.agentId) query.agentId = filters.agentId;
164
+ if (filters.organizationId) query.organizationId = filters.organizationId;
165
+ const docs = await collection.find(query).sort({ updatedAt: -1 }).toArray();
166
+ return docs.map((doc) => this.threadDocToData(doc));
167
+ }
168
+ // ============================================================================
169
+ // Message Operations
170
+ // ============================================================================
171
+ async addMessage(threadId, role, content, attachments) {
172
+ const db = await this.ensureConnection();
173
+ const collection = db.collection(
174
+ this.config.threadsCollection
175
+ );
176
+ const messageId = new ObjectId();
177
+ const message = {
178
+ _id: messageId,
179
+ role,
180
+ content,
181
+ timestamp: /* @__PURE__ */ new Date(),
182
+ attachments
183
+ };
184
+ await collection.updateOne(
185
+ { _id: new ObjectId(threadId) },
186
+ {
187
+ $push: { messages: message },
188
+ $set: { updatedAt: /* @__PURE__ */ new Date() }
189
+ }
190
+ );
191
+ return messageId.toString();
192
+ }
193
+ async getMessages(threadId, limit) {
194
+ const db = await this.ensureConnection();
195
+ const collection = db.collection(
196
+ this.config.threadsCollection
197
+ );
198
+ const doc = await collection.findOne({ _id: new ObjectId(threadId) });
199
+ if (!doc) return [];
200
+ let messages = doc.messages.map((msg) => ({
201
+ id: msg._id?.toString() || "",
202
+ role: msg.role,
203
+ content: msg.content,
204
+ timestamp: msg.timestamp,
205
+ metadata: msg.metadata,
206
+ attachments: msg.attachments
207
+ }));
208
+ if (limit) {
209
+ messages = messages.slice(-limit);
210
+ }
211
+ return messages;
212
+ }
213
+ async getConversationContext(threadId, maxMessages = 20) {
214
+ const messages = await this.getMessages(threadId, maxMessages);
215
+ return messages.map((msg) => ({
216
+ role: msg.role,
217
+ content: msg.content
218
+ }));
219
+ }
220
+ // ============================================================================
221
+ // Helper Methods
222
+ // ============================================================================
223
+ agentDocToData(doc) {
224
+ return {
225
+ id: doc._id.toString(),
226
+ organizationId: doc.organizationId,
227
+ userId: doc.userId,
228
+ phone: doc.phone,
229
+ name: doc.name,
230
+ description: doc.description,
231
+ instructions: doc.instructions,
232
+ provider: doc.provider,
233
+ model: doc.model,
234
+ createdAt: doc.createdAt,
235
+ updatedAt: doc.updatedAt,
236
+ files: doc.files,
237
+ metadata: doc.metadata
238
+ };
239
+ }
240
+ threadDocToData(doc) {
241
+ return {
242
+ id: doc._id.toString(),
243
+ organizationId: doc.organizationId,
244
+ agentId: doc.agentId,
245
+ userId: doc.userId,
246
+ endUserId: doc.endUserId,
247
+ name: doc.name,
248
+ createdAt: doc.createdAt,
249
+ updatedAt: doc.updatedAt,
250
+ messages: doc.messages.map((msg) => ({
251
+ id: msg._id?.toString() || "",
252
+ role: msg.role,
253
+ content: msg.content,
254
+ timestamp: msg.timestamp,
255
+ metadata: msg.metadata,
256
+ attachments: msg.attachments
257
+ })),
258
+ isPendingThread: doc.isPendingThread,
259
+ metadata: doc.metadata
260
+ };
261
+ }
262
+ };
263
+
264
+ // src/storage/MemoryStorage.ts
265
+ var MemoryStorage = class {
266
+ constructor() {
267
+ this.agents = /* @__PURE__ */ new Map();
268
+ this.threads = /* @__PURE__ */ new Map();
269
+ this.idCounter = 0;
270
+ }
271
+ generateId() {
272
+ return `${Date.now()}-${++this.idCounter}`;
273
+ }
274
+ // ============================================================================
275
+ // Agent Operations
276
+ // ============================================================================
277
+ async createAgent(config) {
278
+ const id = this.generateId();
279
+ const agent = {
280
+ id,
281
+ ...config,
282
+ createdAt: /* @__PURE__ */ new Date(),
283
+ updatedAt: /* @__PURE__ */ new Date(),
284
+ files: []
285
+ };
286
+ this.agents.set(id, agent);
287
+ return id;
288
+ }
289
+ async getAgent(agentId) {
290
+ return this.agents.get(agentId) || null;
291
+ }
292
+ async updateAgent(agentId, updates) {
293
+ const agent = this.agents.get(agentId);
294
+ if (!agent) return;
295
+ Object.assign(agent, updates, { updatedAt: /* @__PURE__ */ new Date() });
296
+ this.agents.set(agentId, agent);
297
+ }
298
+ async deleteAgent(agentId) {
299
+ this.agents.delete(agentId);
300
+ const threadsToDelete = [];
301
+ for (const [threadId, thread] of this.threads.entries()) {
302
+ if (thread.agentId === agentId) {
303
+ threadsToDelete.push(threadId);
304
+ }
305
+ }
306
+ for (const threadId of threadsToDelete) {
307
+ this.threads.delete(threadId);
308
+ }
309
+ }
310
+ async listAgents(userId, organizationId) {
311
+ const agents = Array.from(this.agents.values()).filter((agent) => {
312
+ if (agent.userId !== userId) return false;
313
+ if (organizationId && agent.organizationId !== organizationId) return false;
314
+ return true;
315
+ });
316
+ return agents.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
317
+ }
318
+ // ============================================================================
319
+ // Thread Operations
320
+ // ============================================================================
321
+ async createThread(config) {
322
+ const id = this.generateId();
323
+ const thread = {
324
+ id,
325
+ ...config,
326
+ createdAt: /* @__PURE__ */ new Date(),
327
+ updatedAt: /* @__PURE__ */ new Date(),
328
+ messages: [],
329
+ isPendingThread: true
330
+ };
331
+ this.threads.set(id, thread);
332
+ return id;
333
+ }
334
+ async getThread(threadId) {
335
+ return this.threads.get(threadId) || null;
336
+ }
337
+ async updateThread(threadId, updates) {
338
+ const thread = this.threads.get(threadId);
339
+ if (!thread) return;
340
+ Object.assign(thread, updates, { updatedAt: /* @__PURE__ */ new Date() });
341
+ this.threads.set(threadId, thread);
342
+ }
343
+ async deleteThread(threadId) {
344
+ this.threads.delete(threadId);
345
+ }
346
+ async listThreads(filters) {
347
+ const threads = Array.from(this.threads.values()).filter((thread) => {
348
+ if (filters.userId && thread.userId !== filters.userId) return false;
349
+ if (filters.agentId && thread.agentId !== filters.agentId) return false;
350
+ if (filters.organizationId && thread.organizationId !== filters.organizationId) return false;
351
+ return true;
352
+ });
353
+ return threads.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
354
+ }
355
+ // ============================================================================
356
+ // Message Operations
357
+ // ============================================================================
358
+ async addMessage(threadId, role, content, attachments) {
359
+ const thread = this.threads.get(threadId);
360
+ if (!thread) {
361
+ throw new Error(`Thread not found: ${threadId}`);
362
+ }
363
+ const messageId = this.generateId();
364
+ const message = {
365
+ id: messageId,
366
+ role,
367
+ content,
368
+ timestamp: /* @__PURE__ */ new Date(),
369
+ attachments
370
+ };
371
+ thread.messages.push(message);
372
+ thread.updatedAt = /* @__PURE__ */ new Date();
373
+ this.threads.set(threadId, thread);
374
+ return messageId;
375
+ }
376
+ async getMessages(threadId, limit) {
377
+ const thread = this.threads.get(threadId);
378
+ if (!thread) return [];
379
+ const messages = [...thread.messages];
380
+ if (limit) {
381
+ return messages.slice(-limit);
382
+ }
383
+ return messages;
384
+ }
385
+ async getConversationContext(threadId, maxMessages = 20) {
386
+ const messages = await this.getMessages(threadId, maxMessages);
387
+ return messages.map((msg) => ({
388
+ role: msg.role,
389
+ content: msg.content
390
+ }));
391
+ }
392
+ // ============================================================================
393
+ // Utility Methods
394
+ // ============================================================================
395
+ /**
396
+ * Clear all stored data
397
+ */
398
+ clear() {
399
+ this.agents.clear();
400
+ this.threads.clear();
401
+ this.idCounter = 0;
402
+ }
403
+ /**
404
+ * Get statistics about stored data
405
+ */
406
+ getStats() {
407
+ return {
408
+ agents: this.agents.size,
409
+ threads: this.threads.size,
410
+ messages: Array.from(this.threads.values()).reduce(
411
+ (sum, thread) => sum + thread.messages.length,
412
+ 0
413
+ )
414
+ };
415
+ }
416
+ };
417
+
418
+ // src/storage/UpstashStorage.ts
419
+ var UpstashStorage = class {
420
+ constructor(config) {
421
+ this.url = config.url.replace(/\/$/, "");
422
+ this.token = config.token;
423
+ this.prefix = config.prefix || "snap-agent";
424
+ }
425
+ // ============================================================================
426
+ // Redis Commands via REST API
427
+ // ============================================================================
428
+ async command(cmd, ...args) {
429
+ const body = [cmd, ...args];
430
+ const response = await fetch(`${this.url}`, {
431
+ method: "POST",
432
+ headers: {
433
+ Authorization: `Bearer ${this.token}`,
434
+ "Content-Type": "application/json"
435
+ },
436
+ body: JSON.stringify(body)
437
+ });
438
+ if (!response.ok) {
439
+ const text = await response.text();
440
+ throw new Error(`Upstash Redis error: ${response.status} - ${text}`);
441
+ }
442
+ const data = await response.json();
443
+ if (data.error) {
444
+ throw new Error(`Upstash Redis error: ${data.error}`);
445
+ }
446
+ return data.result;
447
+ }
448
+ async pipeline(commands) {
449
+ const response = await fetch(`${this.url}/pipeline`, {
450
+ method: "POST",
451
+ headers: {
452
+ Authorization: `Bearer ${this.token}`,
453
+ "Content-Type": "application/json"
454
+ },
455
+ body: JSON.stringify(commands)
456
+ });
457
+ if (!response.ok) {
458
+ const text = await response.text();
459
+ throw new Error(`Upstash Redis pipeline error: ${response.status} - ${text}`);
460
+ }
461
+ const data = await response.json();
462
+ return data.map((item) => {
463
+ if (item.error) {
464
+ throw new Error(`Upstash Redis error: ${item.error}`);
465
+ }
466
+ return item.result;
467
+ });
468
+ }
469
+ // ============================================================================
470
+ // Key Generation
471
+ // ============================================================================
472
+ key(...parts) {
473
+ return `${this.prefix}:${parts.join(":")}`;
474
+ }
475
+ generateId() {
476
+ const timestamp = Date.now().toString(36);
477
+ const random = Math.random().toString(36).substring(2, 10);
478
+ return `${timestamp}${random}`;
479
+ }
480
+ // ============================================================================
481
+ // Agent Operations
482
+ // ============================================================================
483
+ async createAgent(config) {
484
+ const id = this.generateId();
485
+ const now = (/* @__PURE__ */ new Date()).toISOString();
486
+ const stored = {
487
+ id,
488
+ organizationId: config.organizationId,
489
+ userId: config.userId,
490
+ phone: config.phone,
491
+ name: config.name,
492
+ description: config.description,
493
+ instructions: config.instructions,
494
+ provider: config.provider,
495
+ model: config.model,
496
+ createdAt: now,
497
+ updatedAt: now,
498
+ files: JSON.stringify([]),
499
+ metadata: config.metadata ? JSON.stringify(config.metadata) : void 0
500
+ };
501
+ const fields = [];
502
+ for (const [key, value] of Object.entries(stored)) {
503
+ if (value !== void 0) {
504
+ fields.push(key, String(value));
505
+ }
506
+ }
507
+ await this.pipeline([
508
+ ["HSET", this.key("agent", id), ...fields],
509
+ ["SADD", this.key("agents:user", config.userId), id],
510
+ ...config.organizationId ? [["SADD", this.key("agents:org", config.organizationId), id]] : []
511
+ ]);
512
+ return id;
513
+ }
514
+ async getAgent(agentId) {
515
+ const data = await this.command(
516
+ "HGETALL",
517
+ this.key("agent", agentId)
518
+ );
519
+ if (!data || Object.keys(data).length === 0) {
520
+ return null;
521
+ }
522
+ return this.parseStoredAgent(data);
523
+ }
524
+ async updateAgent(agentId, updates) {
525
+ const fields = ["updatedAt", (/* @__PURE__ */ new Date()).toISOString()];
526
+ for (const [key, value] of Object.entries(updates)) {
527
+ if (value !== void 0) {
528
+ if (key === "metadata") {
529
+ fields.push(key, JSON.stringify(value));
530
+ } else {
531
+ fields.push(key, String(value));
532
+ }
533
+ }
534
+ }
535
+ await this.command("HSET", this.key("agent", agentId), ...fields);
536
+ }
537
+ async deleteAgent(agentId) {
538
+ const agent = await this.getAgent(agentId);
539
+ if (!agent) return;
540
+ const threadIds = await this.command(
541
+ "SMEMBERS",
542
+ this.key("threads:agent", agentId)
543
+ );
544
+ const commands = [
545
+ ["DEL", this.key("agent", agentId)],
546
+ ["SREM", this.key("agents:user", agent.userId), agentId]
547
+ ];
548
+ if (agent.organizationId) {
549
+ commands.push(["SREM", this.key("agents:org", agent.organizationId), agentId]);
550
+ }
551
+ for (const threadId of threadIds || []) {
552
+ commands.push(["DEL", this.key("thread", threadId)]);
553
+ }
554
+ commands.push(["DEL", this.key("threads:agent", agentId)]);
555
+ await this.pipeline(commands);
556
+ }
557
+ async listAgents(userId, organizationId) {
558
+ const indexKey = organizationId ? this.key("agents:org", organizationId) : this.key("agents:user", userId);
559
+ const agentIds = await this.command("SMEMBERS", indexKey);
560
+ if (!agentIds || agentIds.length === 0) {
561
+ return [];
562
+ }
563
+ const agents = [];
564
+ for (const id of agentIds) {
565
+ const agent = await this.getAgent(id);
566
+ if (agent) {
567
+ if (!organizationId || agent.userId === userId) {
568
+ agents.push(agent);
569
+ }
570
+ }
571
+ }
572
+ return agents.sort(
573
+ (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()
574
+ );
575
+ }
576
+ // ============================================================================
577
+ // Thread Operations
578
+ // ============================================================================
579
+ async createThread(config) {
580
+ const id = this.generateId();
581
+ const now = (/* @__PURE__ */ new Date()).toISOString();
582
+ const stored = {
583
+ id,
584
+ organizationId: config.organizationId,
585
+ agentId: config.agentId,
586
+ userId: config.userId,
587
+ endUserId: config.endUserId,
588
+ name: config.name,
589
+ createdAt: now,
590
+ updatedAt: now,
591
+ messages: JSON.stringify([]),
592
+ isPendingThread: "true",
593
+ metadata: config.metadata ? JSON.stringify(config.metadata) : void 0
594
+ };
595
+ const fields = [];
596
+ for (const [key, value] of Object.entries(stored)) {
597
+ if (value !== void 0) {
598
+ fields.push(key, String(value));
599
+ }
600
+ }
601
+ await this.pipeline([
602
+ ["HSET", this.key("thread", id), ...fields],
603
+ ["SADD", this.key("threads:agent", config.agentId), id],
604
+ ["SADD", this.key("threads:user", config.userId), id],
605
+ ...config.organizationId ? [["SADD", this.key("threads:org", config.organizationId), id]] : []
606
+ ]);
607
+ return id;
608
+ }
609
+ async getThread(threadId) {
610
+ const data = await this.command(
611
+ "HGETALL",
612
+ this.key("thread", threadId)
613
+ );
614
+ if (!data || Object.keys(data).length === 0) {
615
+ return null;
616
+ }
617
+ return this.parseStoredThread(data);
618
+ }
619
+ async updateThread(threadId, updates) {
620
+ const fields = ["updatedAt", (/* @__PURE__ */ new Date()).toISOString()];
621
+ for (const [key, value] of Object.entries(updates)) {
622
+ if (value !== void 0) {
623
+ if (key === "metadata") {
624
+ fields.push(key, JSON.stringify(value));
625
+ } else {
626
+ fields.push(key, String(value));
627
+ }
628
+ }
629
+ }
630
+ await this.command("HSET", this.key("thread", threadId), ...fields);
631
+ }
632
+ async deleteThread(threadId) {
633
+ const thread = await this.getThread(threadId);
634
+ if (!thread) return;
635
+ const commands = [
636
+ ["DEL", this.key("thread", threadId)],
637
+ ["SREM", this.key("threads:agent", thread.agentId), threadId],
638
+ ["SREM", this.key("threads:user", thread.userId), threadId]
639
+ ];
640
+ if (thread.organizationId) {
641
+ commands.push(["SREM", this.key("threads:org", thread.organizationId), threadId]);
642
+ }
643
+ await this.pipeline(commands);
644
+ }
645
+ async listThreads(filters) {
646
+ let indexKey;
647
+ if (filters.agentId) {
648
+ indexKey = this.key("threads:agent", filters.agentId);
649
+ } else if (filters.organizationId) {
650
+ indexKey = this.key("threads:org", filters.organizationId);
651
+ } else if (filters.userId) {
652
+ indexKey = this.key("threads:user", filters.userId);
653
+ } else {
654
+ return [];
655
+ }
656
+ const threadIds = await this.command("SMEMBERS", indexKey);
657
+ if (!threadIds || threadIds.length === 0) {
658
+ return [];
659
+ }
660
+ const threads = [];
661
+ for (const id of threadIds) {
662
+ const thread = await this.getThread(id);
663
+ if (thread) {
664
+ if (filters.userId && thread.userId !== filters.userId) continue;
665
+ if (filters.agentId && thread.agentId !== filters.agentId) continue;
666
+ if (filters.organizationId && thread.organizationId !== filters.organizationId) continue;
667
+ threads.push(thread);
668
+ }
669
+ }
670
+ return threads.sort(
671
+ (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()
672
+ );
673
+ }
674
+ // ============================================================================
675
+ // Message Operations
676
+ // ============================================================================
677
+ async addMessage(threadId, role, content, attachments) {
678
+ const thread = await this.getThread(threadId);
679
+ if (!thread) {
680
+ throw new Error(`Thread not found: ${threadId}`);
681
+ }
682
+ const messageId = this.generateId();
683
+ const message = {
684
+ id: messageId,
685
+ role,
686
+ content,
687
+ timestamp: /* @__PURE__ */ new Date(),
688
+ attachments
689
+ };
690
+ thread.messages.push(message);
691
+ await this.command(
692
+ "HSET",
693
+ this.key("thread", threadId),
694
+ "messages",
695
+ JSON.stringify(thread.messages),
696
+ "updatedAt",
697
+ (/* @__PURE__ */ new Date()).toISOString(),
698
+ "isPendingThread",
699
+ "false"
700
+ );
701
+ return messageId;
702
+ }
703
+ async getMessages(threadId, limit) {
704
+ const thread = await this.getThread(threadId);
705
+ if (!thread) return [];
706
+ const messages = [...thread.messages];
707
+ if (limit) {
708
+ return messages.slice(-limit);
709
+ }
710
+ return messages;
711
+ }
712
+ async getConversationContext(threadId, maxMessages = 20) {
713
+ const messages = await this.getMessages(threadId, maxMessages);
714
+ return messages.map((msg) => ({
715
+ role: msg.role,
716
+ content: msg.content
717
+ }));
718
+ }
719
+ // ============================================================================
720
+ // Helper Methods
721
+ // ============================================================================
722
+ parseStoredAgent(stored) {
723
+ return {
724
+ id: stored.id,
725
+ organizationId: stored.organizationId,
726
+ userId: stored.userId,
727
+ phone: stored.phone,
728
+ name: stored.name,
729
+ description: stored.description,
730
+ instructions: stored.instructions,
731
+ provider: stored.provider,
732
+ model: stored.model,
733
+ createdAt: new Date(stored.createdAt),
734
+ updatedAt: new Date(stored.updatedAt),
735
+ files: stored.files ? JSON.parse(stored.files) : [],
736
+ metadata: stored.metadata ? JSON.parse(stored.metadata) : void 0
737
+ };
738
+ }
739
+ parseStoredThread(stored) {
740
+ const messages = stored.messages ? JSON.parse(stored.messages) : [];
741
+ const parsedMessages = messages.map((msg) => ({
742
+ ...msg,
743
+ timestamp: new Date(msg.timestamp)
744
+ }));
745
+ return {
746
+ id: stored.id,
747
+ organizationId: stored.organizationId,
748
+ agentId: stored.agentId,
749
+ userId: stored.userId,
750
+ endUserId: stored.endUserId,
751
+ name: stored.name,
752
+ createdAt: new Date(stored.createdAt),
753
+ updatedAt: new Date(stored.updatedAt),
754
+ messages: parsedMessages,
755
+ isPendingThread: stored.isPendingThread === "true",
756
+ metadata: stored.metadata ? JSON.parse(stored.metadata) : void 0
757
+ };
758
+ }
759
+ // ============================================================================
760
+ // Utility Methods
761
+ // ============================================================================
762
+ /**
763
+ * Test connection to Upstash Redis
764
+ */
765
+ async ping() {
766
+ try {
767
+ const result = await this.command("PING");
768
+ return result === "PONG";
769
+ } catch {
770
+ return false;
771
+ }
772
+ }
773
+ /**
774
+ * Clear all data with this prefix (use with caution!)
775
+ */
776
+ async clear() {
777
+ const keys = await this.command("KEYS", `${this.prefix}:*`);
778
+ if (keys && keys.length > 0) {
779
+ await this.command("DEL", ...keys);
780
+ }
781
+ }
782
+ /**
783
+ * Get storage statistics
784
+ */
785
+ async getStats() {
786
+ const [agentKeys, threadKeys] = await this.pipeline([
787
+ ["KEYS", `${this.prefix}:agent:*`],
788
+ ["KEYS", `${this.prefix}:thread:*`]
789
+ ]);
790
+ return {
791
+ agents: agentKeys?.length || 0,
792
+ threads: threadKeys?.length || 0
793
+ };
794
+ }
795
+ };
796
+
797
+ export {
798
+ MongoDBStorage,
799
+ MemoryStorage,
800
+ UpstashStorage
801
+ };