@snap-agent/core 0.1.3 → 0.1.5

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