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