@ai.ntellect/core 0.7.7 → 1.0.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 (111) hide show
  1. package/README.md +158 -81
  2. package/index.ts +462 -22
  3. package/package copy.json +21 -0
  4. package/package.json +9 -44
  5. package/tsconfig.json +108 -22
  6. package/types.ts +62 -0
  7. package/utils/executor.ts +42 -0
  8. package/.mocharc.json +0 -5
  9. package/dist/graph/controller.d.ts +0 -31
  10. package/dist/graph/controller.d.ts.map +0 -1
  11. package/dist/graph/controller.js +0 -71
  12. package/dist/graph/controller.js.map +0 -1
  13. package/dist/graph/event-manager.d.ts +0 -92
  14. package/dist/graph/event-manager.d.ts.map +0 -1
  15. package/dist/graph/event-manager.js +0 -244
  16. package/dist/graph/event-manager.js.map +0 -1
  17. package/dist/graph/index.d.ts +0 -159
  18. package/dist/graph/index.d.ts.map +0 -1
  19. package/dist/graph/index.js +0 -303
  20. package/dist/graph/index.js.map +0 -1
  21. package/dist/graph/logger.d.ts +0 -46
  22. package/dist/graph/logger.d.ts.map +0 -1
  23. package/dist/graph/logger.js +0 -69
  24. package/dist/graph/logger.js.map +0 -1
  25. package/dist/graph/node.d.ts +0 -92
  26. package/dist/graph/node.d.ts.map +0 -1
  27. package/dist/graph/node.js +0 -249
  28. package/dist/graph/node.js.map +0 -1
  29. package/dist/graph/observer.d.ts +0 -113
  30. package/dist/graph/observer.d.ts.map +0 -1
  31. package/dist/graph/observer.js +0 -198
  32. package/dist/graph/observer.js.map +0 -1
  33. package/dist/index.d.ts +0 -26
  34. package/dist/index.d.ts.map +0 -1
  35. package/dist/index.js +0 -42
  36. package/dist/index.js.map +0 -1
  37. package/dist/interfaces/index.d.ts +0 -447
  38. package/dist/interfaces/index.d.ts.map +0 -1
  39. package/dist/interfaces/index.js +0 -75
  40. package/dist/interfaces/index.js.map +0 -1
  41. package/dist/modules/agenda/adapters/node-cron/index.d.ts +0 -17
  42. package/dist/modules/agenda/adapters/node-cron/index.d.ts.map +0 -1
  43. package/dist/modules/agenda/adapters/node-cron/index.js +0 -30
  44. package/dist/modules/agenda/adapters/node-cron/index.js.map +0 -1
  45. package/dist/modules/agenda/index.d.ts +0 -63
  46. package/dist/modules/agenda/index.d.ts.map +0 -1
  47. package/dist/modules/agenda/index.js +0 -141
  48. package/dist/modules/agenda/index.js.map +0 -1
  49. package/dist/modules/embedding/adapters/ai/index.d.ts +0 -29
  50. package/dist/modules/embedding/adapters/ai/index.d.ts.map +0 -1
  51. package/dist/modules/embedding/adapters/ai/index.js +0 -58
  52. package/dist/modules/embedding/adapters/ai/index.js.map +0 -1
  53. package/dist/modules/embedding/index.d.ts +0 -36
  54. package/dist/modules/embedding/index.d.ts.map +0 -1
  55. package/dist/modules/embedding/index.js +0 -60
  56. package/dist/modules/embedding/index.js.map +0 -1
  57. package/dist/modules/memory/adapters/in-memory/index.d.ts +0 -120
  58. package/dist/modules/memory/adapters/in-memory/index.d.ts.map +0 -1
  59. package/dist/modules/memory/adapters/in-memory/index.js +0 -211
  60. package/dist/modules/memory/adapters/in-memory/index.js.map +0 -1
  61. package/dist/modules/memory/adapters/meilisearch/index.d.ts +0 -110
  62. package/dist/modules/memory/adapters/meilisearch/index.d.ts.map +0 -1
  63. package/dist/modules/memory/adapters/meilisearch/index.js +0 -321
  64. package/dist/modules/memory/adapters/meilisearch/index.js.map +0 -1
  65. package/dist/modules/memory/adapters/redis/index.d.ts +0 -82
  66. package/dist/modules/memory/adapters/redis/index.d.ts.map +0 -1
  67. package/dist/modules/memory/adapters/redis/index.js +0 -159
  68. package/dist/modules/memory/adapters/redis/index.js.map +0 -1
  69. package/dist/modules/memory/index.d.ts +0 -67
  70. package/dist/modules/memory/index.d.ts.map +0 -1
  71. package/dist/modules/memory/index.js +0 -104
  72. package/dist/modules/memory/index.js.map +0 -1
  73. package/dist/types/index.d.ts +0 -166
  74. package/dist/types/index.d.ts.map +0 -1
  75. package/dist/types/index.js +0 -3
  76. package/dist/types/index.js.map +0 -1
  77. package/dist/utils/generate-action-schema.d.ts +0 -5
  78. package/dist/utils/generate-action-schema.d.ts.map +0 -1
  79. package/dist/utils/generate-action-schema.js +0 -44
  80. package/dist/utils/generate-action-schema.js.map +0 -1
  81. package/dist/utils/header-builder.d.ts +0 -12
  82. package/dist/utils/header-builder.d.ts.map +0 -1
  83. package/dist/utils/header-builder.js +0 -35
  84. package/dist/utils/header-builder.js.map +0 -1
  85. package/graph/controller.ts +0 -74
  86. package/graph/event-manager.ts +0 -295
  87. package/graph/index.ts +0 -397
  88. package/graph/logger.ts +0 -70
  89. package/graph/node.ts +0 -305
  90. package/graph/observer.ts +0 -368
  91. package/interfaces/index.ts +0 -545
  92. package/modules/agenda/adapters/node-cron/index.ts +0 -25
  93. package/modules/agenda/index.ts +0 -146
  94. package/modules/embedding/adapters/ai/index.ts +0 -42
  95. package/modules/embedding/index.ts +0 -45
  96. package/modules/memory/adapters/in-memory/index.ts +0 -207
  97. package/modules/memory/adapters/meilisearch/index.ts +0 -361
  98. package/modules/memory/adapters/redis/index.ts +0 -164
  99. package/modules/memory/index.ts +0 -93
  100. package/test/graph/controller.test.ts +0 -187
  101. package/test/graph/event-manager.test.ts +0 -72
  102. package/test/graph/index.test.ts +0 -768
  103. package/test/graph/node.test.ts +0 -510
  104. package/test/graph/observer.test.ts +0 -398
  105. package/test/modules/agenda/node-cron.test.ts +0 -307
  106. package/test/modules/memory/adapters/in-memory.test.ts +0 -153
  107. package/test/modules/memory/adapters/meilisearch.test.ts +0 -287
  108. package/test/modules/memory/base.test.ts +0 -230
  109. package/types/index.ts +0 -184
  110. package/utils/generate-action-schema.ts +0 -46
  111. package/utils/header-builder.ts +0 -40
@@ -1,42 +0,0 @@
1
- import { embed, EmbeddingModel, embedMany } from "ai";
2
- import { IEmbeddingModel } from "../../../../interfaces";
3
-
4
- /**
5
- * @module AIEmbeddingAdapter
6
- * @description Adapter implementation for AI-based embedding service.
7
- * Provides integration with AI models for text embedding generation.
8
- * @implements {IEmbeddingModel}
9
- */
10
- export class AIEmbeddingAdapter implements IEmbeddingModel {
11
- /**
12
- * Creates an instance of AIEmbeddingAdapter
13
- * @param {EmbeddingModel<string>} model - The AI embedding model to use
14
- */
15
- constructor(private readonly model: EmbeddingModel<string>) {}
16
-
17
- /**
18
- * Generates an embedding vector for a single text using the AI model
19
- * @param {string} text - The text to embed
20
- * @returns {Promise<number[]>} The generated embedding vector
21
- */
22
- async embed(text: string): Promise<number[]> {
23
- const { embedding } = await embed({
24
- model: this.model,
25
- value: text,
26
- });
27
- return embedding;
28
- }
29
-
30
- /**
31
- * Generates embedding vectors for multiple texts using the AI model
32
- * @param {string[]} texts - Array of texts to embed
33
- * @returns {Promise<number[][]>} Array of generated embedding vectors
34
- */
35
- async embedMany(texts: string[]): Promise<number[][]> {
36
- const { embeddings } = await embedMany({
37
- model: this.model,
38
- values: texts,
39
- });
40
- return embeddings;
41
- }
42
- }
@@ -1,45 +0,0 @@
1
- import { cosineSimilarity } from "ai";
2
- import { IEmbeddingModel, IEmbeddingModule } from "../../interfaces";
3
-
4
- /**
5
- * @module EmbeddingManager
6
- * @description A module for generating and managing text embeddings.
7
- * Provides functionality for converting text into vector representations
8
- * and calculating similarities between embeddings.
9
- * @implements {IEmbeddingModule}
10
- */
11
- export class EmbeddingManager implements IEmbeddingModule {
12
- /**
13
- * Creates an instance of EmbeddingManager
14
- * @param {IEmbeddingModel} embeddingModel - The embedding model implementation to use
15
- */
16
- constructor(private readonly embeddingModel: IEmbeddingModel) {}
17
-
18
- /**
19
- * Generates an embedding vector for a single text
20
- * @param {string} text - The text to embed
21
- * @returns {Promise<number[]>} The embedding vector
22
- */
23
- async embedText(text: string): Promise<number[]> {
24
- return this.embeddingModel.embed(text);
25
- }
26
-
27
- /**
28
- * Generates embedding vectors for multiple texts
29
- * @param {string[]} texts - Array of texts to embed
30
- * @returns {Promise<number[][]>} Array of embedding vectors
31
- */
32
- async embedMany(texts: string[]): Promise<number[][]> {
33
- return this.embeddingModel.embedMany(texts);
34
- }
35
-
36
- /**
37
- * Calculates the similarity score between two embeddings
38
- * @param {number[]} embedding1 - First embedding vector
39
- * @param {number[]} embedding2 - Second embedding vector
40
- * @returns {number} Similarity score between 0 and 100
41
- */
42
- calculateSimilarity(embedding1: number[], embedding2: number[]): number {
43
- return (cosineSimilarity(embedding1, embedding2) + 1) * 50;
44
- }
45
- }
@@ -1,207 +0,0 @@
1
- import { ICronJob, IMemoryAdapter } from "../../../../interfaces";
2
- import {
3
- BaseMemoryType,
4
- CreateMemoryInput,
5
- ScheduledRequest,
6
- } from "../../../../types";
7
-
8
- /**
9
- * @module InMemoryAdapter
10
- * @description In-memory implementation of the memory storage adapter.
11
- * Provides a simple Map-based storage solution
12
- * @implements {IMemoryAdapter}
13
- */
14
- export class InMemoryAdapter implements IMemoryAdapter {
15
- /** Internal storage using Map structure for jobs and requests */
16
- private jobs: Map<string, ICronJob>;
17
- /** Internal storage using Map structure for requests */
18
- private requests: Map<string, ScheduledRequest>;
19
- /** Internal storage using Map structure */
20
- private storage: Map<string, BaseMemoryType[]>;
21
-
22
- /**
23
- * Creates an instance of InMemoryAdapter
24
- */
25
- constructor() {
26
- this.storage = new Map();
27
- this.jobs = new Map();
28
- this.requests = new Map();
29
- }
30
-
31
- /**
32
- * Initializes storage for a room
33
- * @param {string} roomId - Room identifier
34
- * @returns {Promise<void>}
35
- */
36
- async init(roomId: string): Promise<void> {
37
- if (!this.storage.has(roomId)) {
38
- this.storage.set(roomId, []);
39
- }
40
- }
41
-
42
- /**
43
- * Creates a new memory entry
44
- * @param {CreateMemoryInput & { embedding?: number[] }} input - Memory data with optional embedding
45
- * @returns {Promise<BaseMemoryType | undefined>} Created memory or existing memory if duplicate
46
- */
47
- async createMemory(
48
- input: CreateMemoryInput & { embedding?: number[] }
49
- ): Promise<BaseMemoryType | undefined> {
50
- await this.init(input.roomId);
51
-
52
- // Check if memory already exists
53
- const memories = this.storage.get(input.roomId) || [];
54
- const existingMemory = memories.find((m) => m.data === input.data);
55
- if (existingMemory) {
56
- return existingMemory;
57
- }
58
-
59
- // Create new memory
60
- const memory: BaseMemoryType = {
61
- id: input.id || crypto.randomUUID(),
62
- data: input.data,
63
- embedding: input.embedding,
64
- roomId: input.roomId,
65
- createdAt: new Date(),
66
- };
67
-
68
- memories.push(memory);
69
- this.storage.set(input.roomId, memories);
70
- return memory;
71
- }
72
-
73
- /**
74
- * Retrieves a memory by ID and room ID
75
- * @param {string} id - Memory identifier
76
- * @param {string} roomId - Room identifier
77
- * @returns {Promise<BaseMemoryType | null>} Memory entry or null if not found
78
- */
79
- async getMemoryById(
80
- id: string,
81
- roomId: string
82
- ): Promise<BaseMemoryType | null> {
83
- const memories = this.storage.get(roomId) || [];
84
- return memories.find((m) => m.id === id) || null;
85
- }
86
-
87
- /**
88
- * Searches for memories based on query and options
89
- * @param {string} query - Search query
90
- * @param {Object} options - Search options
91
- * @param {string} options.roomId - Room identifier
92
- * @param {number} [options.limit] - Maximum number of results
93
- * @returns {Promise<BaseMemoryType[]>} Array of matching memories
94
- */
95
- async getMemoryByIndex(
96
- query: string,
97
- options: { roomId: string; limit?: number }
98
- ): Promise<BaseMemoryType[]> {
99
- const memories = this.storage.get(options.roomId) || [];
100
- const filtered = memories.filter((m) => m.data.includes(query));
101
- return filtered.slice(0, options.limit || filtered.length);
102
- }
103
-
104
- /**
105
- * Retrieves all memories for a room
106
- * @param {string} roomId - Room identifier
107
- * @returns {Promise<BaseMemoryType[]>} Array of all memories
108
- */
109
- async getAllMemories(roomId: string): Promise<BaseMemoryType[]> {
110
- return this.storage.get(roomId) || [];
111
- }
112
-
113
- /**
114
- * Deletes a specific memory
115
- * @param {string} id - Memory identifier
116
- * @param {string} roomId - Room identifier
117
- * @returns {Promise<void>}
118
- */
119
- async clearMemoryById(id: string, roomId: string): Promise<void> {
120
- const memories = this.storage.get(roomId) || [];
121
- const filtered = memories.filter((m) => m.id !== id);
122
- this.storage.set(roomId, filtered);
123
- }
124
-
125
- /**
126
- * Clears all memories across all rooms
127
- * @returns {Promise<void>}
128
- */
129
- async clearAllMemories(): Promise<void> {
130
- this.storage.clear();
131
- this.jobs.clear();
132
- this.requests.clear();
133
- }
134
-
135
- /**
136
- * Saves a job to the internal storage
137
- * @param {string} id - Job identifier
138
- * @param {ICronJob} job - Job data
139
- * @returns {Promise<void>}
140
- */
141
- async saveJob(id: string, job: ICronJob): Promise<void> {
142
- this.jobs.set(id, job);
143
- }
144
-
145
- /**
146
- * Saves a request to the internal storage
147
- * @param {string} id - Request identifier
148
- * @param {ScheduledRequest} request - Request data
149
- * @returns {Promise<void>}
150
- */
151
- async saveRequest(id: string, request: ScheduledRequest): Promise<void> {
152
- this.requests.set(id, request);
153
- }
154
-
155
- /**
156
- * Retrieves a job by ID
157
- * @param {string} id - Job identifier
158
- * @returns {Promise<ICronJob | undefined>} Job data or undefined if not found
159
- */
160
- async getJob(id: string): Promise<ICronJob | undefined> {
161
- return this.jobs.get(id);
162
- }
163
-
164
- /**
165
- * Retrieves a request by ID
166
- * @param {string} id - Request identifier
167
- * @returns {Promise<ScheduledRequest | undefined>} Request data or undefined if not found
168
- */
169
- async getRequest(id: string): Promise<ScheduledRequest | undefined> {
170
- return this.requests.get(id);
171
- }
172
-
173
- /**
174
- * Deletes a job by ID
175
- * @param {string} id - Job identifier
176
- * @returns {Promise<void>}
177
- */
178
- async deleteJob(id: string): Promise<void> {
179
- this.jobs.delete(id);
180
- }
181
-
182
- /**
183
- * Deletes a request by ID
184
- * @param {string} id - Request identifier
185
- * @returns {Promise<void>}
186
- */
187
- async deleteRequest(id: string): Promise<void> {
188
- this.requests.delete(id);
189
- }
190
-
191
- /**
192
- * Retrieves all requests
193
- * @returns {Promise<ScheduledRequest[]>} Array of all requests
194
- */
195
- async getAllRequests(): Promise<ScheduledRequest[]> {
196
- return Array.from(this.requests.values());
197
- }
198
-
199
- /**
200
- * Clears all jobs and requests
201
- * @returns {Promise<void>}
202
- */
203
- async clear(): Promise<void> {
204
- this.jobs.clear();
205
- this.requests.clear();
206
- }
207
- }
@@ -1,361 +0,0 @@
1
- import { IMemoryAdapter } from "../../../../interfaces";
2
- import {
3
- BaseMemoryType,
4
- CreateMemoryInput,
5
- MeilisearchConfig,
6
- } from "../../../../types";
7
-
8
- /**
9
- * @module MeilisearchAdapter
10
- * @description Adapter implementation for Meilisearch as a memory storage solution.
11
- * Provides integration with Meilisearch for storing and retrieving memory entries.
12
- * @implements {IMemoryAdapter}
13
- */
14
- export class MeilisearchAdapter implements IMemoryAdapter {
15
- /**
16
- * Creates an instance of MeilisearchAdapter
17
- * @param {MeilisearchConfig} config - Configuration for Meilisearch connection
18
- */
19
- constructor(private readonly config: MeilisearchConfig) {}
20
-
21
- /**
22
- * Makes an HTTP request to the Meilisearch API
23
- * @private
24
- * @param {string} path - API endpoint path
25
- * @param {RequestInit} [options] - Fetch request options
26
- * @returns {Promise<any>} Response data
27
- * @throws {Error} If the request fails
28
- */
29
- private async makeRequest(path: string, options?: RequestInit) {
30
- try {
31
- const url = `${this.config.host}${path}`;
32
- const response = await fetch(url, {
33
- ...options,
34
- headers: {
35
- "Content-Type": "application/json",
36
- Authorization: `Bearer ${this.config.apiKey}`,
37
- ...options?.headers,
38
- },
39
- });
40
-
41
- if (!response.ok) {
42
- const errorBody = await response.text();
43
- throw new Error(
44
- `HTTP ${response.status}: ${errorBody || response.statusText}`
45
- );
46
- }
47
-
48
- return response.json();
49
- } catch (error) {
50
- if (error instanceof TypeError && error.message === "Failed to fetch") {
51
- throw new Error(
52
- `Network error: Unable to connect to Meilisearch at ${this.config.host}`
53
- );
54
- }
55
- throw error;
56
- }
57
- }
58
-
59
- /**
60
- * Initializes a storage index for a room
61
- * @private
62
- * @param {string} roomId - Room identifier to create index for
63
- * @returns {Promise<void>}
64
- */
65
- private async initializeStorage(roomId: string): Promise<void> {
66
- try {
67
- let indexExists = false;
68
-
69
- try {
70
- await this.makeRequest(`/indexes/${roomId}`);
71
- indexExists = true;
72
- } catch (error) {
73
- if (!indexExists) {
74
- const createResponse = await this.makeRequest("/indexes", {
75
- method: "POST",
76
- body: JSON.stringify({
77
- uid: roomId,
78
- primaryKey: "id",
79
- }),
80
- });
81
-
82
- console.log("✅ Index creation response:", createResponse);
83
- }
84
- }
85
-
86
- // Appliquer les settings seulement si l'index existe bien
87
- await this.makeRequest(`/indexes/${roomId}/settings`, {
88
- method: "PATCH",
89
- body: JSON.stringify({
90
- searchableAttributes: this.config.searchableAttributes || [
91
- "data",
92
- "query",
93
- ],
94
- sortableAttributes: this.config.sortableAttributes || ["createdAt"],
95
- }),
96
- });
97
- } catch (error) {
98
- const errorMessage =
99
- error instanceof Error ? error.message : "Unknown error";
100
- console.error(
101
- `❌ Error initializing storage for index ${roomId}:`,
102
- errorMessage
103
- );
104
- throw new Error(
105
- `Failed to initialize storage for index ${roomId}: ${errorMessage}`
106
- );
107
- }
108
- }
109
-
110
- /**
111
- * Adds documents to the Meilisearch index
112
- * @private
113
- * @param {BaseMemoryType[]} documents - Documents to add
114
- * @param {string} roomId - Room identifier
115
- * @returns {Promise<void>}
116
- */
117
- private async addDocuments(
118
- documents: BaseMemoryType[],
119
- roomId: string
120
- ): Promise<void> {
121
- await this.makeRequest(`/indexes/${roomId}/documents`, {
122
- method: "POST",
123
- body: JSON.stringify(documents),
124
- });
125
- }
126
-
127
- /**
128
- * Deletes a storage index for a room
129
- * @private
130
- * @param {string} roomId - Room identifier
131
- * @returns {Promise<void>}
132
- */
133
- private async deleteStorage(roomId: string): Promise<void> {
134
- await this.makeRequest(`/indexes/${roomId}`, {
135
- method: "DELETE",
136
- });
137
- }
138
-
139
- /**
140
- * Initializes the adapter for a specific room
141
- * @param {string} roomId - Room identifier
142
- * @returns {Promise<void>}
143
- */
144
- async init(roomId: string): Promise<void> {
145
- try {
146
- // Initialize the default "memories" index
147
- await this.initializeStorage(roomId);
148
- } catch (error) {
149
- const errorMessage =
150
- error instanceof Error ? error.message : "Unknown error";
151
- console.error("Failed to initialize default index:", errorMessage);
152
- throw new Error(`Failed to initialize default index: ${errorMessage}`);
153
- }
154
- }
155
-
156
- /**
157
- * Performs a search in the Meilisearch index
158
- * @private
159
- * @param {string} query - Search query
160
- * @param {string} roomId - Room identifier
161
- * @param {Object} [options] - Search options
162
- * @param {number} [options.limit] - Maximum number of results
163
- * @param {number} [options.threshold] - Minimum score threshold
164
- * @returns {Promise<SearchResult[]>} Search results
165
- */
166
- private async search(
167
- query: string,
168
- roomId: string,
169
- options?: { limit?: number; threshold?: number }
170
- ): Promise<SearchResult[]> {
171
- const searchResults = await this.makeRequest(`/indexes/${roomId}/search`, {
172
- method: "POST",
173
- body: JSON.stringify({
174
- q: query,
175
- limit: options?.limit || 10,
176
- }),
177
- });
178
-
179
- if (!searchResults.hits) {
180
- return [];
181
- }
182
-
183
- return searchResults.hits.map((hit: any) => ({
184
- document: {
185
- id: hit.id,
186
- data: hit.data,
187
- embedding: hit.embedding,
188
- roomId: hit.roomId,
189
- createdAt: hit.createdAt,
190
- },
191
- score: hit._score || 0,
192
- }));
193
- }
194
-
195
- /**
196
- * Creates a new memory entry
197
- * @param {CreateMemoryInput & { embedding?: number[] }} input - Memory data with optional embedding
198
- * @returns {Promise<BaseMemoryType | undefined>} Created memory or undefined
199
- */
200
- async createMemory(
201
- input: CreateMemoryInput & { embedding?: number[] }
202
- ): Promise<BaseMemoryType | undefined> {
203
- // Initialize storage for this roomId if needed
204
- await this.initializeStorage(input.roomId);
205
-
206
- // Check if the memory already exists
207
- const existingMemory = await this.search(input.data, input.roomId, {
208
- limit: 1,
209
- });
210
- if (existingMemory.length > 0) {
211
- return existingMemory[0].document;
212
- }
213
-
214
- // If not found, create new memory
215
- const memory: BaseMemoryType = {
216
- id: input.id || crypto.randomUUID(),
217
- data: input.data,
218
- embedding: input.embedding,
219
- roomId: input.roomId,
220
- createdAt: new Date(),
221
- };
222
-
223
- await this.addDocuments([memory], input.roomId);
224
- return memory;
225
- }
226
-
227
- /**
228
- * Retrieves a memory by ID and room ID
229
- * @param {string} id - Memory identifier
230
- * @param {string} roomId - Room identifier
231
- * @returns {Promise<BaseMemoryType | null>} Memory entry or null if not found
232
- */
233
- async getMemoryById(
234
- id: string,
235
- roomId: string
236
- ): Promise<BaseMemoryType | null> {
237
- try {
238
- const result = await this.makeRequest(
239
- `/indexes/${roomId}/documents/${id}`
240
- );
241
- return result
242
- ? {
243
- id: result.id,
244
- data: result.data,
245
- embedding: result.embedding,
246
- roomId: result.roomId,
247
- createdAt: result.createdAt,
248
- }
249
- : null;
250
- } catch {
251
- return null;
252
- }
253
- }
254
-
255
- /**
256
- * Searches for memories based on query and options
257
- * @param {string} query - Search query
258
- * @param {Object} options - Search options
259
- * @param {string} options.roomId - Room identifier
260
- * @param {number} [options.limit] - Maximum number of results
261
- * @returns {Promise<BaseMemoryType[]>} Array of matching memories
262
- */
263
- async getMemoryByIndex(
264
- query: string,
265
- options: { roomId: string; limit?: number }
266
- ): Promise<BaseMemoryType[]> {
267
- const results = await this.search(query, options.roomId, {
268
- limit: options.limit,
269
- });
270
- return results
271
- .filter((result) => result.document.roomId === options.roomId)
272
- .map((result) => ({
273
- id: result.document.id,
274
- data: result.document.data,
275
- embedding: result.document.embedding,
276
- roomId: result.document.roomId,
277
- createdAt: result.document.createdAt,
278
- }));
279
- }
280
-
281
- /**
282
- * Retrieves all memories for a room
283
- * @param {string} roomId - Room identifier
284
- * @returns {Promise<BaseMemoryType[]>} Array of all memories
285
- */
286
- async getAllMemories(roomId: string): Promise<BaseMemoryType[]> {
287
- const results = await this.makeRequest(`/indexes/${roomId}/documents`);
288
- if (results.total === 0) {
289
- return [];
290
- }
291
-
292
- return results.results.map((doc: any) => ({
293
- id: doc.id,
294
- data: doc.data,
295
- embedding: doc.embedding,
296
- roomId: doc.roomId,
297
- createdAt: doc.createdAt,
298
- }));
299
- }
300
-
301
- /**
302
- * Deletes a specific memory
303
- * @param {string} id - Memory identifier
304
- * @param {string} roomId - Room identifier
305
- * @returns {Promise<void>}
306
- */
307
- async clearMemoryById(id: string, roomId: string): Promise<void> {
308
- try {
309
- // Ensure the index exists before attempting to delete
310
- await this.initializeStorage(roomId);
311
-
312
- await this.makeRequest(`/indexes/${roomId}/documents/${id}`, {
313
- method: "DELETE",
314
- });
315
- } catch (error) {
316
- const errorMessage =
317
- error instanceof Error ? error.message : "Unknown error";
318
- console.error(
319
- `Error clearing memory ${id} from index ${roomId}:`,
320
- errorMessage
321
- );
322
- throw new Error(
323
- `Failed to clear memory ${id} from index ${roomId}: ${errorMessage}`
324
- );
325
- }
326
- }
327
-
328
- /**
329
- * Clears all memories across all rooms
330
- * @returns {Promise<void>}
331
- */
332
- async clearAllMemories(): Promise<void> {
333
- try {
334
- // Get all indexes
335
- const response = await this.makeRequest("/indexes");
336
- const indexes = response.results || [];
337
-
338
- // Delete each index
339
- for (const index of indexes) {
340
- await this.deleteStorage(index.uid);
341
- }
342
- } catch (error) {
343
- const errorMessage =
344
- error instanceof Error ? error.message : "Unknown error";
345
- throw new Error(`Failed to clear all memories: ${errorMessage}`);
346
- }
347
- }
348
- }
349
-
350
- /**
351
- * @interface SearchResult
352
- * @description Interface for search results from Meilisearch
353
- */
354
- interface SearchResult {
355
- /** The matched document */
356
- document?: any;
357
- /** Relevance score of the match */
358
- score?: number;
359
- /** Array of additional results */
360
- results?: any[];
361
- }