@ai.ntellect/core 0.3.3 โ†’ 0.4.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.
Files changed (85) hide show
  1. package/.nvmrc +1 -0
  2. package/README.FR.md +201 -261
  3. package/README.md +208 -260
  4. package/agent/index.ts +199 -216
  5. package/agent/tools/get-rss.ts +64 -0
  6. package/bull.ts +5 -0
  7. package/dist/agent/index.d.ts +29 -26
  8. package/dist/agent/index.js +123 -112
  9. package/dist/agent/tools/get-rss.d.ts +16 -0
  10. package/dist/agent/tools/get-rss.js +62 -0
  11. package/dist/bull.d.ts +1 -0
  12. package/dist/bull.js +9 -0
  13. package/dist/examples/index.d.ts +2 -0
  14. package/dist/examples/index.js +89 -0
  15. package/dist/llm/interpreter/context.d.ts +5 -22
  16. package/dist/llm/interpreter/context.js +8 -9
  17. package/dist/llm/interpreter/index.d.ts +9 -5
  18. package/dist/llm/interpreter/index.js +55 -48
  19. package/dist/llm/memory-manager/context.d.ts +2 -0
  20. package/dist/llm/memory-manager/context.js +22 -0
  21. package/dist/llm/memory-manager/index.d.ts +17 -0
  22. package/dist/llm/memory-manager/index.js +107 -0
  23. package/dist/llm/orchestrator/context.d.ts +2 -10
  24. package/dist/llm/orchestrator/context.js +19 -14
  25. package/dist/llm/orchestrator/index.d.ts +36 -21
  26. package/dist/llm/orchestrator/index.js +122 -88
  27. package/dist/llm/orchestrator/types.d.ts +12 -0
  28. package/dist/llm/orchestrator/types.js +2 -0
  29. package/dist/memory/cache.d.ts +6 -5
  30. package/dist/memory/cache.js +31 -21
  31. package/dist/memory/persistent.d.ts +5 -3
  32. package/dist/memory/persistent.js +89 -73
  33. package/dist/services/redis-cache.d.ts +37 -0
  34. package/dist/services/redis-cache.js +93 -0
  35. package/dist/services/scheduler.d.ts +39 -16
  36. package/dist/services/scheduler.js +81 -103
  37. package/dist/services/telegram-monitor.d.ts +0 -15
  38. package/dist/services/telegram-monitor.js +117 -101
  39. package/dist/test.js +106 -172
  40. package/dist/types.d.ts +38 -7
  41. package/dist/utils/generate-object.d.ts +12 -0
  42. package/dist/utils/generate-object.js +90 -0
  43. package/dist/utils/header-builder.d.ts +11 -0
  44. package/dist/utils/header-builder.js +34 -0
  45. package/dist/utils/inject-actions.js +2 -2
  46. package/dist/utils/queue-item-transformer.d.ts +2 -2
  47. package/dist/utils/schema-generator.d.ts +16 -0
  48. package/dist/utils/schema-generator.js +46 -0
  49. package/examples/index.ts +103 -0
  50. package/llm/interpreter/context.ts +20 -8
  51. package/llm/interpreter/index.ts +81 -54
  52. package/llm/memory-manager/context.ts +21 -0
  53. package/llm/memory-manager/index.ts +163 -0
  54. package/llm/orchestrator/context.ts +20 -13
  55. package/llm/orchestrator/index.ts +210 -130
  56. package/llm/orchestrator/types.ts +14 -0
  57. package/memory/cache.ts +37 -31
  58. package/memory/persistent.ts +121 -99
  59. package/package.json +11 -2
  60. package/services/redis-cache.ts +128 -0
  61. package/services/scheduler.ts +102 -141
  62. package/services/telegram-monitor.ts +138 -138
  63. package/t.py +79 -0
  64. package/t.spec +38 -0
  65. package/types.ts +40 -7
  66. package/utils/generate-object.ts +105 -0
  67. package/utils/header-builder.ts +40 -0
  68. package/utils/inject-actions.ts +4 -6
  69. package/utils/queue-item-transformer.ts +2 -1
  70. package/utils/schema-generator.ts +73 -0
  71. package/agent/handlers/ActionHandler.ts +0 -48
  72. package/agent/handlers/ConfirmationHandler.ts +0 -37
  73. package/agent/handlers/EventHandler.ts +0 -35
  74. package/dist/agent/handlers/ActionHandler.d.ts +0 -8
  75. package/dist/agent/handlers/ActionHandler.js +0 -36
  76. package/dist/agent/handlers/ConfirmationHandler.d.ts +0 -7
  77. package/dist/agent/handlers/ConfirmationHandler.js +0 -31
  78. package/dist/agent/handlers/EventHandler.d.ts +0 -10
  79. package/dist/agent/handlers/EventHandler.js +0 -34
  80. package/dist/llm/evaluator/context.d.ts +0 -10
  81. package/dist/llm/evaluator/context.js +0 -24
  82. package/dist/llm/evaluator/index.d.ts +0 -16
  83. package/dist/llm/evaluator/index.js +0 -150
  84. package/llm/evaluator/context.ts +0 -21
  85. package/llm/evaluator/index.ts +0 -193
@@ -1,20 +1,21 @@
1
- import { CacheMemoryOptions, CacheMemoryType, CreateMemoryInput, MatchOptions, MemoryScope, QueueResult } from "../types";
1
+ import { CacheMemoryOptions, CacheMemoryType, CreateMemoryInput, MatchOptions, MemoryScope } from "../types";
2
2
  export declare class CacheMemory {
3
3
  private redis;
4
4
  private readonly CACHE_PREFIX;
5
5
  private readonly CACHE_TTL;
6
- constructor(options?: CacheMemoryOptions);
6
+ private readonly embeddingModel;
7
+ constructor(options: CacheMemoryOptions);
7
8
  private initRedis;
8
9
  private storeMemory;
9
10
  findSimilarActions(query: string, options?: MatchOptions & {
10
11
  userId?: string;
11
12
  scope?: MemoryScope;
12
13
  }): Promise<{
13
- actions: QueueResult[];
14
- similarityPercentage: number;
14
+ data: any;
15
15
  query: string;
16
+ createdAt: Date;
16
17
  }[]>;
17
- getAllMemories(scope?: MemoryScope, userId?: string): Promise<CacheMemoryType[]>;
18
+ getAllMemories(): Promise<CacheMemoryType[]>;
18
19
  private getMemoriesFromKeys;
19
20
  createMemory(input: CreateMemoryInput): Promise<CacheMemoryType | undefined>;
20
21
  private createSingleMemory;
@@ -6,7 +6,8 @@ const ai_1 = require("ai");
6
6
  const redis_1 = require("redis");
7
7
  const types_1 = require("../types");
8
8
  class CacheMemory {
9
- constructor(options = {}) {
9
+ constructor(options) {
10
+ this.embeddingModel = options.embeddingModel;
10
11
  const ttlInHours = options.cacheTTL ?? 1;
11
12
  this.CACHE_TTL = ttlInHours * 60 * 60;
12
13
  this.CACHE_PREFIX = options.cachePrefix ?? "memory:";
@@ -31,11 +32,11 @@ class CacheMemory {
31
32
  console.error("โŒ Failed to connect to Redis:", error);
32
33
  }
33
34
  }
34
- async storeMemory(memory) {
35
+ async storeMemory(memory, ttl) {
35
36
  const prefix = this.CACHE_PREFIX;
36
37
  const key = `${prefix}${memory.id}`;
37
38
  const result = await this.redis.set(key, JSON.stringify(memory), {
38
- EX: this.CACHE_TTL,
39
+ EX: ttl || this.CACHE_TTL,
39
40
  });
40
41
  console.log("๐Ÿ’พ Cache memory created:", result);
41
42
  }
@@ -47,14 +48,14 @@ class CacheMemory {
47
48
  model: openai_1.openai.embedding("text-embedding-3-small"),
48
49
  value: query,
49
50
  });
50
- const memories = await this.getAllMemories(options.scope, options.userId);
51
+ const memories = await this.getAllMemories();
51
52
  console.log(`\n๐Ÿ“š Found ${memories.length} cached queries to compare`);
52
53
  const matches = memories
53
54
  .map((memory) => {
54
55
  const similarity = (0, ai_1.cosineSimilarity)(embedding, memory.embedding);
55
56
  const similarityPercentage = (similarity + 1) * 50;
56
57
  return {
57
- actions: memory.data,
58
+ data: memory.data,
58
59
  query: memory.query,
59
60
  similarityPercentage,
60
61
  createdAt: memory.createdAt,
@@ -71,6 +72,7 @@ class CacheMemory {
71
72
  results.forEach((match, index) => {
72
73
  console.log(`\n${index + 1}. Match Details:`);
73
74
  console.log(` Query: ${match.query}`);
75
+ console.log(` Data: ${JSON.stringify(match.data)}`);
74
76
  console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
75
77
  console.log("โ”€".repeat(50));
76
78
  });
@@ -78,9 +80,15 @@ class CacheMemory {
78
80
  else {
79
81
  console.log("\nโŒ No similar queries found in cache");
80
82
  }
81
- return results;
83
+ return results.map((match) => {
84
+ return {
85
+ data: match.data,
86
+ query: match.query,
87
+ createdAt: match.createdAt,
88
+ };
89
+ });
82
90
  }
83
- async getAllMemories(scope, userId) {
91
+ async getAllMemories() {
84
92
  const keys = await this.redis.keys(`${this.CACHE_PREFIX}*`);
85
93
  const memories = await this.getMemoriesFromKeys(keys);
86
94
  return memories;
@@ -97,10 +105,9 @@ class CacheMemory {
97
105
  }
98
106
  async createMemory(input) {
99
107
  console.log("\n๐Ÿ“ Processing new memory creation");
100
- console.log("Content:", input.content);
101
- console.log("Type:", input.type);
102
- console.log("Scope:", input.scope);
103
- const existingPattern = await this.findSimilarActions(input.content, {
108
+ console.log("Content:", input.query);
109
+ console.log("TTL:", input.ttl ? `${input.ttl} seconds` : "default");
110
+ const existingPattern = await this.findSimilarActions(input.query, {
104
111
  similarityThreshold: 95,
105
112
  userId: input.userId,
106
113
  scope: input.scope,
@@ -111,7 +118,8 @@ class CacheMemory {
111
118
  existingPattern.forEach((match, index) => {
112
119
  console.log(`\n${index + 1}. Existing Match:`);
113
120
  console.log(` Query: ${match.query}`);
114
- console.log(` Similarity: ${match.similarityPercentage.toFixed(2)}%`);
121
+ console.log(` Data: ${JSON.stringify(match.data)}`);
122
+ console.log(` Created At: ${match.createdAt}`);
115
123
  });
116
124
  console.log("\nโญ๏ธ Skipping creation of new memory");
117
125
  return;
@@ -119,36 +127,38 @@ class CacheMemory {
119
127
  console.log("\n๐Ÿ†• No similar memory found - creating new one");
120
128
  const memory = await this.createSingleMemory({
121
129
  id: crypto.randomUUID(),
122
- content: input.content,
123
- type: input.type,
130
+ query: input.query,
124
131
  data: input.data,
125
132
  userId: input.userId,
126
133
  scope: input.scope,
134
+ ttl: input.ttl,
127
135
  });
128
136
  return memory;
129
137
  }
130
138
  async createSingleMemory(params) {
131
139
  console.log("\n๐Ÿ—๏ธ Creating new cache memory");
132
140
  console.log("ID:", params.id);
133
- console.log("Content:", params.content);
141
+ console.log("Content:", params.query);
134
142
  console.log("\n๐Ÿงฎ Generating embedding...");
135
143
  const { embedding } = await (0, ai_1.embed)({
136
- model: openai_1.openai.embedding("text-embedding-3-small"),
137
- value: params.content,
144
+ model: this.embeddingModel,
145
+ value: params.query,
138
146
  });
139
147
  console.log("โœ… Embedding generated successfully");
140
148
  const memory = {
141
149
  id: params.id,
142
- type: params.type,
143
150
  data: params.data,
144
- query: params.content,
151
+ query: params.query,
145
152
  embedding,
146
153
  userId: params.userId,
147
154
  scope: params.scope || (params.userId ? types_1.MemoryScope.USER : types_1.MemoryScope.GLOBAL),
148
155
  createdAt: new Date(),
149
156
  };
150
- await this.storeMemory(memory);
151
- console.log("โœ… Memory created and stored successfully");
157
+ await this.storeMemory(memory, params.ttl);
158
+ console.log("โœ… Short-term memory created and stored successfully", {
159
+ ...memory,
160
+ ttl: params.ttl || this.CACHE_TTL,
161
+ });
152
162
  return memory;
153
163
  }
154
164
  }
@@ -1,4 +1,5 @@
1
- import { Memory, MemoryScope } from "../types";
1
+ import { EmbeddingModel } from "ai";
2
+ import { LongTermMemory, MemoryScope } from "../types";
2
3
  interface SearchOptions {
3
4
  scope?: MemoryScope;
4
5
  userId?: string;
@@ -16,10 +17,12 @@ export declare class PersistentMemory {
16
17
  private readonly host;
17
18
  private readonly apiKey;
18
19
  private readonly INDEX_PREFIX;
20
+ private readonly embeddingModel;
19
21
  constructor(options: {
20
22
  host: string;
21
23
  apiKey: string;
22
24
  indexPrefix?: string;
25
+ embeddingModel: EmbeddingModel<string>;
23
26
  });
24
27
  /**
25
28
  * Initialize indexes
@@ -37,14 +40,13 @@ export declare class PersistentMemory {
37
40
  /**
38
41
  * Store a memory in the database
39
42
  */
40
- createMemory(memory: Memory): Promise<unknown>;
43
+ createMemory(memory: LongTermMemory): Promise<unknown>;
41
44
  /**
42
45
  * Find best matching memories
43
46
  */
44
47
  findRelevantDocuments(query: string, options?: SearchOptions): Promise<{
45
48
  query: string;
46
49
  data: any;
47
- similarityPercentage: number;
48
50
  createdAt: string;
49
51
  }[]>;
50
52
  /**
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PersistentMemory = void 0;
4
- const openai_1 = require("@ai-sdk/openai");
5
4
  const ai_1 = require("ai");
6
5
  const text_splitter_1 = require("langchain/text_splitter");
7
6
  /**
@@ -12,19 +11,28 @@ class PersistentMemory {
12
11
  this.host = options.host;
13
12
  this.apiKey = options.apiKey;
14
13
  this.INDEX_PREFIX = options.indexPrefix || "memory";
14
+ this.embeddingModel = options.embeddingModel;
15
15
  }
16
16
  /**
17
17
  * Initialize indexes
18
18
  */
19
19
  async init() {
20
- // Create global index
21
- await this._getOrCreateIndex(this.INDEX_PREFIX);
20
+ try {
21
+ // Create or get main index
22
+ await this._getOrCreateIndex(this.INDEX_PREFIX);
23
+ console.log(`โœ… Index '${this.INDEX_PREFIX}' initialized successfully`);
24
+ }
25
+ catch (error) {
26
+ console.error(`โŒ Failed to initialize index: ${error}`);
27
+ throw error;
28
+ }
22
29
  }
23
30
  /**
24
31
  * Make API request to Meilisearch
25
32
  */
26
33
  async _makeRequest(path, options = {}) {
27
34
  const url = `${this.host}${path}`;
35
+ console.log("๐Ÿ” Making request to Meilisearch:", url);
28
36
  const response = await fetch(url, {
29
37
  ...options,
30
38
  headers: {
@@ -44,14 +52,20 @@ class PersistentMemory {
44
52
  */
45
53
  async _getOrCreateIndex(indexName) {
46
54
  try {
47
- // Try to create index
48
- await this._makeRequest("/indexes", {
49
- method: "POST",
50
- body: JSON.stringify({
51
- uid: indexName,
52
- primaryKey: "id",
53
- }),
54
- });
55
+ // Check if index exists first
56
+ const indexExists = await this._makeRequest(`/indexes/${indexName}`, {
57
+ method: "GET",
58
+ }).catch(() => false);
59
+ if (!indexExists) {
60
+ console.log(`Creating new index: ${indexName}`);
61
+ await this._makeRequest("/indexes", {
62
+ method: "POST",
63
+ body: JSON.stringify({
64
+ uid: indexName,
65
+ primaryKey: "id",
66
+ }),
67
+ });
68
+ }
55
69
  // Update index settings
56
70
  const settings = {
57
71
  searchableAttributes: ["query", "purpose", "chunks.content"],
@@ -61,12 +75,11 @@ class PersistentMemory {
61
75
  method: "PATCH",
62
76
  body: JSON.stringify(settings),
63
77
  });
78
+ console.log(`Index ${indexName} configured successfully`);
64
79
  }
65
80
  catch (error) {
66
- // Index might already exist, which is fine
67
- if (!error.message.includes("already exists")) {
68
- throw error;
69
- }
81
+ console.error(`Failed to configure index ${indexName}:`, error);
82
+ throw error;
70
83
  }
71
84
  }
72
85
  async processContent(content) {
@@ -77,7 +90,7 @@ class PersistentMemory {
77
90
  const chunks = await textSplitter.createDocuments([content]);
78
91
  // Generate embeddings for all chunks
79
92
  const { embeddings } = await (0, ai_1.embedMany)({
80
- model: openai_1.openai.embedding("text-embedding-3-small"),
93
+ model: this.embeddingModel,
81
94
  values: chunks.map((chunk) => chunk.pageContent),
82
95
  });
83
96
  // Create processed chunks with embeddings
@@ -90,76 +103,79 @@ class PersistentMemory {
90
103
  * Store a memory in the database
91
104
  */
92
105
  async createMemory(memory) {
93
- await this._getOrCreateIndex(memory.roomId);
94
- const chunks = await this.processContent(memory.data);
95
- const document = {
96
- ...memory,
97
- chunks,
98
- createdAt: memory.createdAt.toISOString(),
99
- };
100
- const response = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/documents`, {
101
- method: "POST",
102
- body: JSON.stringify([document]),
103
- });
104
- console.log("Stored persistent memory response:", response);
105
- return response;
106
+ try {
107
+ console.log(`๐Ÿ“ Creating memory in index: ${this.INDEX_PREFIX}`);
108
+ // Process content into chunks with embeddings
109
+ const chunks = await this.processContent(memory.data);
110
+ // Generate unique ID if not provided
111
+ const id = memory.id || crypto.randomUUID();
112
+ const document = {
113
+ ...memory,
114
+ chunks,
115
+ createdAt: memory.createdAt.toISOString(),
116
+ };
117
+ const response = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/documents`, {
118
+ method: "POST",
119
+ body: JSON.stringify([document]),
120
+ });
121
+ console.log("โœ… Memory created successfully", { id });
122
+ return response;
123
+ }
124
+ catch (error) {
125
+ console.error("โŒ Failed to create memory:", error);
126
+ throw error;
127
+ }
106
128
  }
107
129
  /**
108
130
  * Find best matching memories
109
131
  */
110
132
  async findRelevantDocuments(query, options = {}) {
111
- console.log("\n๐Ÿ” Searching in persistent memory");
133
+ console.log(`\n๐Ÿ” Searching in index: ${this.INDEX_PREFIX}`);
112
134
  console.log("Query:", query);
113
- console.log("Options:", JSON.stringify(options, null, 2));
114
- // Generate embedding for the query
115
- const { embedding: queryEmbedding } = await (0, ai_1.embed)({
116
- model: openai_1.openai.embedding("text-embedding-3-small"),
117
- value: query,
118
- });
119
- const searchResults = [];
120
- console.log("\n๐Ÿ“š Searching in global index:", this.INDEX_PREFIX);
121
135
  try {
122
- const globalResults = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/search`, {
136
+ // Generate embedding for the query
137
+ const { embedding: queryEmbedding } = await (0, ai_1.embed)({
138
+ model: this.embeddingModel,
139
+ value: query,
140
+ });
141
+ // Search in the index
142
+ const searchResults = await this._makeRequest(`/indexes/${this.INDEX_PREFIX}/search`, {
123
143
  method: "POST",
124
- body: JSON.stringify({ q: query }),
144
+ body: JSON.stringify({
145
+ q: query,
146
+ limit: options.maxResults || 10,
147
+ }),
125
148
  });
126
- if (globalResults?.hits) {
127
- searchResults.push(...globalResults.hits);
149
+ if (!searchResults?.hits?.length) {
150
+ console.log("โŒ No matches found");
151
+ return [];
128
152
  }
129
- }
130
- catch (error) {
131
- console.error("โŒ Error searching global index:", error);
132
- }
133
- const totalResults = searchResults.length;
134
- console.log(`\n๐Ÿ“Š Found ${totalResults} total matches`);
135
- // Process and filter results using cosine similarity
136
- const results = searchResults
137
- .flatMap((hit) => {
138
- const chunkSimilarities = hit.chunks.map((chunk) => ({
139
- query: hit.query,
140
- data: hit.data,
141
- similarityPercentage: ((0, ai_1.cosineSimilarity)(queryEmbedding, chunk.embedding) + 1) * 50,
142
- createdAt: hit.createdAt,
153
+ // Process and filter results using cosine similarity
154
+ const results = searchResults.hits
155
+ .flatMap((hit) => {
156
+ const chunkSimilarities = hit.chunks.map((chunk) => ({
157
+ query: hit.query,
158
+ data: hit.data,
159
+ similarityPercentage: ((0, ai_1.cosineSimilarity)(queryEmbedding, chunk.embedding) + 1) * 50,
160
+ createdAt: hit.createdAt,
161
+ }));
162
+ return chunkSimilarities.reduce((best, current) => current.similarityPercentage > best.similarityPercentage
163
+ ? current
164
+ : best, chunkSimilarities[0]);
165
+ })
166
+ .filter((match) => match.similarityPercentage >= (options.similarityThreshold || 70))
167
+ .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
168
+ console.log(`โœจ Found ${results.length} relevant matches`);
169
+ return results.map((result) => ({
170
+ query: result.query,
171
+ data: result.data,
172
+ createdAt: result.createdAt,
143
173
  }));
144
- return chunkSimilarities.reduce((best, current) => current.similarityPercentage > best.similarityPercentage
145
- ? current
146
- : best, chunkSimilarities[0]);
147
- })
148
- .filter((match) => match.similarityPercentage >= (options.similarityThreshold || 70))
149
- .sort((a, b) => b.similarityPercentage - a.similarityPercentage);
150
- // Log filtered results in a more structured way
151
- if (results.length > 0) {
152
- console.log("\nโœจ Relevant matches found:");
153
- console.log("โ”€".repeat(50));
154
- results.forEach((match, index) => {
155
- console.log(`\n${index + 1}. Match Details:`);
156
- console.log(` Query: ${match.query}`);
157
- });
158
174
  }
159
- else {
160
- console.log("\nโŒ No relevant matches found");
175
+ catch (error) {
176
+ console.error("โŒ Search failed:", error);
177
+ return [];
161
178
  }
162
- return results;
163
179
  }
164
180
  /**
165
181
  * Delete memories for a given scope and user
@@ -0,0 +1,37 @@
1
+ export interface CacheConfig {
2
+ host: string;
3
+ port: number;
4
+ password?: string;
5
+ ttl?: number;
6
+ cleanupInterval?: string;
7
+ }
8
+ export declare class RedisCache {
9
+ private redis;
10
+ private readonly defaultTTL;
11
+ private readonly cleanupJob;
12
+ constructor(config: CacheConfig);
13
+ /**
14
+ * Store previous actions for a specific request
15
+ */
16
+ storePreviousActions(requestId: string, actions: any[]): Promise<void>;
17
+ /**
18
+ * Get previous actions for a specific request
19
+ */
20
+ getPreviousActions(requestId: string): Promise<any[]>;
21
+ /**
22
+ * Store a recent message
23
+ */
24
+ storeRecentMessage(message: string, metadata?: Record<string, any>): Promise<void>;
25
+ /**
26
+ * Get recent messages
27
+ */
28
+ getRecentMessages(limit?: number): Promise<any[]>;
29
+ /**
30
+ * Cleanup expired keys
31
+ */
32
+ private cleanup;
33
+ /**
34
+ * Stop the cleanup job and close Redis connection
35
+ */
36
+ close(): Promise<void>;
37
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RedisCache = void 0;
7
+ const ioredis_1 = __importDefault(require("ioredis"));
8
+ const node_cron_1 = __importDefault(require("node-cron"));
9
+ class RedisCache {
10
+ constructor(config) {
11
+ this.redis = new ioredis_1.default({
12
+ host: config.host,
13
+ port: config.port,
14
+ password: config.password,
15
+ });
16
+ this.defaultTTL = config.ttl || 1800; // 30 minutes in seconds
17
+ // Setup cleanup job (default: every 30 minutes)
18
+ this.cleanupJob = node_cron_1.default.schedule(config.cleanupInterval || "*/30 * * * *", () => this.cleanup());
19
+ }
20
+ /**
21
+ * Store previous actions for a specific request
22
+ */
23
+ async storePreviousActions(requestId, actions) {
24
+ const key = `previous_actions:${requestId}`;
25
+ await this.redis.setex(key, this.defaultTTL, JSON.stringify({
26
+ timestamp: new Date().toISOString(),
27
+ actions,
28
+ }));
29
+ }
30
+ /**
31
+ * Get previous actions for a specific request
32
+ */
33
+ async getPreviousActions(requestId) {
34
+ const key = `previous_actions:${requestId}`;
35
+ const data = await this.redis.get(key);
36
+ if (!data)
37
+ return [];
38
+ const parsed = JSON.parse(data);
39
+ return parsed.actions;
40
+ }
41
+ /**
42
+ * Store a recent message
43
+ */
44
+ async storeRecentMessage(message, metadata) {
45
+ const id = crypto.randomUUID();
46
+ const key = `recent_messages:${id}`;
47
+ await this.redis.setex(key, this.defaultTTL, JSON.stringify({
48
+ timestamp: new Date().toISOString(),
49
+ message,
50
+ metadata,
51
+ }));
52
+ }
53
+ /**
54
+ * Get recent messages
55
+ */
56
+ async getRecentMessages(limit = 10) {
57
+ const keys = await this.redis.keys("recent_messages:*");
58
+ if (!keys.length)
59
+ return [];
60
+ const messages = await Promise.all(keys.map(async (key) => {
61
+ const data = await this.redis.get(key);
62
+ return data ? JSON.parse(data) : null;
63
+ }));
64
+ return messages
65
+ .filter(Boolean)
66
+ .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
67
+ .slice(0, limit);
68
+ }
69
+ /**
70
+ * Cleanup expired keys
71
+ */
72
+ async cleanup() {
73
+ console.log("๐Ÿงน Starting cache cleanup...");
74
+ try {
75
+ // Redis automatically removes expired keys
76
+ // This is just for logging purposes
77
+ const actionKeys = await this.redis.keys("previous_actions:*");
78
+ const messageKeys = await this.redis.keys("recent_messages:*");
79
+ console.log(`Cache status: ${actionKeys.length} actions, ${messageKeys.length} messages`);
80
+ }
81
+ catch (error) {
82
+ console.error("โŒ Cache cleanup error:", error);
83
+ }
84
+ }
85
+ /**
86
+ * Stop the cleanup job and close Redis connection
87
+ */
88
+ async close() {
89
+ this.cleanupJob.stop();
90
+ await this.redis.quit();
91
+ }
92
+ }
93
+ exports.RedisCache = RedisCache;
@@ -1,17 +1,40 @@
1
- import { Orchestrator } from "../llm/orchestrator";
2
- import { ActionSchema, ScheduledAction, ScheduledActionEvents } from "../types";
3
- import { ActionQueueManager } from "./queue";
4
- export declare class ActionScheduler {
5
- private actionQueueManager;
6
- private orchestrator;
7
- private scheduledActions;
8
- private storage;
9
- private events;
10
- constructor(actionQueueManager: ActionQueueManager, orchestrator: Orchestrator, events?: ScheduledActionEvents);
11
- scheduleAction(action: ActionSchema, scheduledTime: Date, userId: string, recurrence?: ScheduledAction["recurrence"]): Promise<string>;
12
- private initializeScheduledActions;
13
- private scheduleExecution;
14
- private executeScheduledAction;
15
- private calculateNextExecutionTime;
16
- cancelScheduledAction(actionId: string): Promise<boolean>;
1
+ import { AgentRuntime } from "../llm/orchestrator";
2
+ import { RedisCache } from "./redis-cache";
3
+ interface ScheduledRequest {
4
+ id: string;
5
+ originalRequest: string;
6
+ cronExpression: string;
7
+ isRecurring: boolean;
8
+ createdAt: Date;
17
9
  }
10
+ export declare class TaskScheduler {
11
+ private scheduledRequests;
12
+ private cronJobs;
13
+ private readonly agentRuntime;
14
+ private readonly cache;
15
+ constructor(agentRuntime: AgentRuntime, cache: RedisCache);
16
+ /**
17
+ * Schedule a new request to be processed later
18
+ */
19
+ scheduleRequest(request: {
20
+ originalRequest: string;
21
+ cronExpression: string;
22
+ }): Promise<string>;
23
+ /**
24
+ * Execute a scheduled request by launching a new process
25
+ */
26
+ private executeScheduledRequest;
27
+ /**
28
+ * Cancel a scheduled request
29
+ */
30
+ cancelScheduledRequest(requestId: string): boolean;
31
+ /**
32
+ * Get all scheduled requests
33
+ */
34
+ getScheduledRequests(): ScheduledRequest[];
35
+ /**
36
+ * Stop all cron jobs
37
+ */
38
+ stopAll(): void;
39
+ }
40
+ export {};