@ai.ntellect/core 0.4.1 → 0.5.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,298 @@
1
+ import { type CoreMessage } from "ai";
2
+ import Redis from "ioredis";
3
+ import cron from "node-cron";
4
+
5
+ export interface CacheConfig {
6
+ host: string;
7
+ port: number;
8
+ password?: string;
9
+ ttl?: number; // Time to live in seconds (default 30 minutes)
10
+ cleanupInterval?: string; // Cron expression (default every 30 minutes)
11
+ }
12
+
13
+ export class RedisCache {
14
+ private redis: Redis;
15
+ private readonly defaultTTL: number;
16
+ private readonly cleanupJob: cron.ScheduledTask;
17
+
18
+ constructor(config: CacheConfig) {
19
+ this.redis = new Redis({
20
+ host: config.host,
21
+ port: config.port,
22
+ password: config.password,
23
+ });
24
+
25
+ this.defaultTTL = config.ttl || 1800; // 30 minutes in seconds
26
+ // Setup cleanup job (default: every 30 minutes)
27
+
28
+ // this.cleanupEverything();
29
+
30
+ this.cleanupJob = cron.schedule(
31
+ config.cleanupInterval || "*/30 * * * *",
32
+ () => this.cleanup()
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Store previous actions for a specific request
38
+ */
39
+ async storePreviousActions(requestId: string, actions: any[]): Promise<void> {
40
+ const key = `previous_actions:${requestId}`;
41
+ await this.redis.setex(
42
+ key,
43
+ this.defaultTTL,
44
+ JSON.stringify({
45
+ timestamp: new Date().toISOString(),
46
+ actions,
47
+ })
48
+ );
49
+ }
50
+
51
+ /**
52
+ * Get previous actions for a specific request
53
+ */
54
+ async getPreviousActions(requestId: string): Promise<any[]> {
55
+ const key = `previous_actions:${requestId}`;
56
+ const data = await this.redis.get(key);
57
+ if (!data) return [];
58
+
59
+ const parsed = JSON.parse(data);
60
+ return parsed.actions;
61
+ }
62
+
63
+ async storeMessage(
64
+ role: "user" | "assistant" | "system",
65
+ message: string
66
+ ): Promise<void> {
67
+ const id = crypto.randomUUID();
68
+ const key = `recent_messages:${id}`;
69
+ const coreMessage: CoreMessage = {
70
+ role,
71
+ content: message,
72
+ };
73
+ await this.redis.setex(
74
+ key,
75
+ this.defaultTTL,
76
+ JSON.stringify({ ...coreMessage, timestamp: new Date().toISOString() })
77
+ );
78
+ console.log("🔍 Message stored successfully", { key, message });
79
+ }
80
+
81
+ /**
82
+ * Store a recent message following CoreMessage structure
83
+ */
84
+ async storeRecentMessage(
85
+ message: string,
86
+ metadata?: {
87
+ socialResponse?: string;
88
+ agentName?: string;
89
+ agentResponse?: string;
90
+ actions?: any[];
91
+ }
92
+ ): Promise<void> {
93
+ console.log("🔍 Storing recent message:", message);
94
+ const id = crypto.randomUUID();
95
+ const key = `recent_messages:${id}`;
96
+
97
+ // Create CoreMessage structure
98
+ const coreMessage: CoreMessage[] = [
99
+ {
100
+ role: "user",
101
+ content: message,
102
+ },
103
+ ];
104
+
105
+ // Add assistant response if available
106
+ if (metadata?.socialResponse || metadata?.agentResponse) {
107
+ coreMessage.push({
108
+ role: "assistant",
109
+ content:
110
+ metadata.socialResponse || metadata.agentResponse
111
+ ? `Agent ${metadata.agentName ? metadata.agentName : "Main"}: ${
112
+ metadata.socialResponse || metadata.agentResponse
113
+ }`
114
+ : "",
115
+ });
116
+ }
117
+
118
+ await this.redis.setex(
119
+ key,
120
+ this.defaultTTL,
121
+ JSON.stringify({
122
+ timestamp: new Date().toISOString(),
123
+ messages: coreMessage,
124
+ actions: metadata?.actions || [],
125
+ })
126
+ );
127
+ console.log("🔍 Recent message stored successfully", {
128
+ key,
129
+ message,
130
+ });
131
+ }
132
+
133
+ /**
134
+ * Get previous actions
135
+ */
136
+ async getRecentPreviousActions(limit: number = 10): Promise<any[]> {
137
+ const keys = await this.redis.keys("previous_actions:*");
138
+ if (!keys.length) return [];
139
+
140
+ const actions = await Promise.all(
141
+ keys.map(async (key) => {
142
+ const data = await this.redis.get(key);
143
+ return data ? JSON.parse(data) : null;
144
+ })
145
+ );
146
+ return actions.slice(0, limit);
147
+ }
148
+
149
+ /**
150
+ * Get recent messages in CoreMessage format
151
+ */
152
+ async getRecentMessages(limit: number = 10): Promise<CoreMessage[]> {
153
+ const keys = await this.redis.keys("recent_messages:*");
154
+ if (!keys.length) return [];
155
+
156
+ const messages = await Promise.all(
157
+ keys.map(async (key) => {
158
+ const data = await this.redis.get(key);
159
+ return data ? JSON.parse(data) : null;
160
+ })
161
+ );
162
+
163
+ const formattedMessages = messages
164
+ .sort(
165
+ (a, b) =>
166
+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
167
+ ) // Tri par timestamp
168
+ .map((message) => {
169
+ return {
170
+ role: message.role,
171
+ content: message.content,
172
+ };
173
+ }) // Extraire les messages de chaque entrée
174
+ .slice(0, limit); // Limiter le nombre de messages
175
+ return formattedMessages;
176
+ }
177
+ /**
178
+ * Cleanup expired keys
179
+ */
180
+ private async cleanup(): Promise<void> {
181
+ console.log("🧹 Starting cache cleanup...");
182
+ try {
183
+ // Redis automatically removes expired keys
184
+ // This is just for logging purposes
185
+ const actionKeys = await this.redis.keys("previous_actions:*");
186
+ const messageKeys = await this.redis.keys("recent_messages:*");
187
+ console.log(
188
+ `Cache status: ${actionKeys.length} actions, ${messageKeys.length} messages`
189
+ );
190
+ } catch (error) {
191
+ console.error("❌ Cache cleanup error:", error);
192
+ }
193
+ }
194
+ async cleanupEverything(): Promise<void> {
195
+ const keys = await this.redis.keys("*");
196
+ console.log("🔍 Cleaning up messages with TTL:", keys);
197
+
198
+ for (const key of keys) {
199
+ console.log(`🧹 Suppression de la clé expirée ou invalide: ${key}`);
200
+ await this.redis.del(key);
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Stop the cleanup job and close Redis connection
206
+ */
207
+ async close(): Promise<void> {
208
+ this.cleanupJob.stop();
209
+ await this.redis.quit();
210
+ }
211
+
212
+ /**
213
+ * Store a memory with tags and categories
214
+ */
215
+ async storeMemory(
216
+ data: string,
217
+ category: string,
218
+ tags: string[],
219
+ ttl?: number
220
+ ): Promise<void> {
221
+ const id = crypto.randomUUID();
222
+ const key = `memory:${id}`;
223
+ const memoryData = {
224
+ data,
225
+ category,
226
+ tags,
227
+ timestamp: new Date().toISOString(),
228
+ };
229
+
230
+ // Enregistrer la mémoire avec TTL
231
+ await this.redis.setex(
232
+ key,
233
+ ttl || this.defaultTTL,
234
+ JSON.stringify(memoryData)
235
+ );
236
+
237
+ // Indexer les tags
238
+ for (const tag of tags) {
239
+ const tagKey = `tag:${tag}`;
240
+ await this.redis.sadd(tagKey, key);
241
+ }
242
+
243
+ // Indexer les catégories
244
+ const categoryKey = `category:${category}`;
245
+ await this.redis.sadd(categoryKey, key);
246
+ console.log("🔍 Memory stored successfully", { key, memoryData });
247
+ }
248
+
249
+ /**
250
+ * Get memories by a specific tag
251
+ */
252
+ async getMemoriesByTag(tag: string): Promise<any[]> {
253
+ const tagKey = `tag:${tag}`;
254
+ const keys = await this.redis.smembers(tagKey);
255
+
256
+ const memories = await Promise.all(
257
+ keys.map(async (key) => {
258
+ const data = await this.redis.get(key);
259
+ return data ? JSON.parse(data) : null;
260
+ })
261
+ );
262
+
263
+ return memories.filter(Boolean); // Filtrer les valeurs nulles
264
+ }
265
+
266
+ /**
267
+ * Get memories by a specific category
268
+ */
269
+ async getMemoriesByCategory(category: string): Promise<any[]> {
270
+ const categoryKey = `category:${category}`;
271
+ const keys = await this.redis.smembers(categoryKey);
272
+
273
+ const memories = await Promise.all(
274
+ keys.map(async (key) => {
275
+ const data = await this.redis.get(key);
276
+ return data ? JSON.parse(data) : null;
277
+ })
278
+ );
279
+
280
+ return memories.filter(Boolean); // Filtrer les valeurs nulles
281
+ }
282
+
283
+ /**
284
+ * Get all available tags
285
+ */
286
+ async getAllTags(): Promise<string[]> {
287
+ const keys = await this.redis.keys("tag:*");
288
+ return keys.map((key) => key.replace("tag:", ""));
289
+ }
290
+
291
+ /**
292
+ * Get all available categories
293
+ */
294
+ async getAllCategories(): Promise<string[]> {
295
+ const keys = await this.redis.keys("category:*");
296
+ return keys.map((key) => key.replace("category:", ""));
297
+ }
298
+ }
package/services/queue.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  QueueResult,
7
7
  } from "../types";
8
8
 
9
- export class ActionQueueManager {
9
+ export class Queue {
10
10
  private queue: QueueItem[] = [];
11
11
  private results: QueueResult[] = [];
12
12
  private callbacks: QueueCallbacks;
@@ -18,7 +18,7 @@ export class ActionQueueManager {
18
18
  this.callbacks = callbacks;
19
19
  }
20
20
 
21
- addToQueue(actions: QueueItem | QueueItem[]) {
21
+ add(actions: QueueItem | QueueItem[]) {
22
22
  if (Array.isArray(actions)) {
23
23
  console.log("\n📋 Adding actions to queue:");
24
24
  actions.forEach((action, index) => {
@@ -31,7 +31,7 @@ export class ActionQueueManager {
31
31
  }
32
32
  }
33
33
 
34
- async processQueue() {
34
+ async execute() {
35
35
  if (this.isProcessing) {
36
36
  console.log("\n⚠️ Queue is already being processed");
37
37
  return;