agents-library 0.1.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 (89) hide show
  1. package/dist/base-agent.d.ts +172 -0
  2. package/dist/base-agent.d.ts.map +1 -0
  3. package/dist/base-agent.js +255 -0
  4. package/dist/base-agent.js.map +1 -0
  5. package/dist/base-bot.d.ts +282 -0
  6. package/dist/base-bot.d.ts.map +1 -0
  7. package/dist/base-bot.js +375 -0
  8. package/dist/base-bot.js.map +1 -0
  9. package/dist/common/result.d.ts +51 -0
  10. package/dist/common/result.d.ts.map +1 -0
  11. package/dist/common/result.js +45 -0
  12. package/dist/common/result.js.map +1 -0
  13. package/dist/common/types.d.ts +57 -0
  14. package/dist/common/types.d.ts.map +1 -0
  15. package/dist/common/types.js +42 -0
  16. package/dist/common/types.js.map +1 -0
  17. package/dist/index.d.ts +94 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +108 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/kadi-event-publisher.d.ts +163 -0
  22. package/dist/kadi-event-publisher.d.ts.map +1 -0
  23. package/dist/kadi-event-publisher.js +286 -0
  24. package/dist/kadi-event-publisher.js.map +1 -0
  25. package/dist/memory/arcadedb-adapter.d.ts +159 -0
  26. package/dist/memory/arcadedb-adapter.d.ts.map +1 -0
  27. package/dist/memory/arcadedb-adapter.js +314 -0
  28. package/dist/memory/arcadedb-adapter.js.map +1 -0
  29. package/dist/memory/file-storage-adapter.d.ts +122 -0
  30. package/dist/memory/file-storage-adapter.d.ts.map +1 -0
  31. package/dist/memory/file-storage-adapter.js +352 -0
  32. package/dist/memory/file-storage-adapter.js.map +1 -0
  33. package/dist/memory/memory-service.d.ts +208 -0
  34. package/dist/memory/memory-service.d.ts.map +1 -0
  35. package/dist/memory/memory-service.js +410 -0
  36. package/dist/memory/memory-service.js.map +1 -0
  37. package/dist/memory/types.d.ts +126 -0
  38. package/dist/memory/types.d.ts.map +1 -0
  39. package/dist/memory/types.js +41 -0
  40. package/dist/memory/types.js.map +1 -0
  41. package/dist/producer-tool-utils.d.ts +474 -0
  42. package/dist/producer-tool-utils.d.ts.map +1 -0
  43. package/dist/producer-tool-utils.js +664 -0
  44. package/dist/producer-tool-utils.js.map +1 -0
  45. package/dist/providers/anthropic-provider.d.ts +160 -0
  46. package/dist/providers/anthropic-provider.d.ts.map +1 -0
  47. package/dist/providers/anthropic-provider.js +527 -0
  48. package/dist/providers/anthropic-provider.js.map +1 -0
  49. package/dist/providers/model-manager-provider.d.ts +91 -0
  50. package/dist/providers/model-manager-provider.d.ts.map +1 -0
  51. package/dist/providers/model-manager-provider.js +355 -0
  52. package/dist/providers/model-manager-provider.js.map +1 -0
  53. package/dist/providers/provider-manager.d.ts +111 -0
  54. package/dist/providers/provider-manager.d.ts.map +1 -0
  55. package/dist/providers/provider-manager.js +337 -0
  56. package/dist/providers/provider-manager.js.map +1 -0
  57. package/dist/providers/types.d.ts +145 -0
  58. package/dist/providers/types.d.ts.map +1 -0
  59. package/dist/providers/types.js +23 -0
  60. package/dist/providers/types.js.map +1 -0
  61. package/dist/shadow-agent-factory.d.ts +623 -0
  62. package/dist/shadow-agent-factory.d.ts.map +1 -0
  63. package/dist/shadow-agent-factory.js +1117 -0
  64. package/dist/shadow-agent-factory.js.map +1 -0
  65. package/dist/types/agent-config.d.ts +307 -0
  66. package/dist/types/agent-config.d.ts.map +1 -0
  67. package/dist/types/agent-config.js +15 -0
  68. package/dist/types/agent-config.js.map +1 -0
  69. package/dist/types/event-schemas.d.ts +358 -0
  70. package/dist/types/event-schemas.d.ts.map +1 -0
  71. package/dist/types/event-schemas.js +188 -0
  72. package/dist/types/event-schemas.js.map +1 -0
  73. package/dist/types/tool-schemas.d.ts +498 -0
  74. package/dist/types/tool-schemas.d.ts.map +1 -0
  75. package/dist/types/tool-schemas.js +457 -0
  76. package/dist/types/tool-schemas.js.map +1 -0
  77. package/dist/utils/logger.d.ts +135 -0
  78. package/dist/utils/logger.d.ts.map +1 -0
  79. package/dist/utils/logger.js +205 -0
  80. package/dist/utils/logger.js.map +1 -0
  81. package/dist/utils/timer.d.ts +186 -0
  82. package/dist/utils/timer.d.ts.map +1 -0
  83. package/dist/utils/timer.js +211 -0
  84. package/dist/utils/timer.js.map +1 -0
  85. package/dist/worker-agent-factory.d.ts +688 -0
  86. package/dist/worker-agent-factory.d.ts.map +1 -0
  87. package/dist/worker-agent-factory.js +1517 -0
  88. package/dist/worker-agent-factory.js.map +1 -0
  89. package/package.json +38 -0
@@ -0,0 +1,352 @@
1
+ /**
2
+ * File Storage Adapter
3
+ *
4
+ * Provides low-level file operations for JSON and Markdown files with:
5
+ * - Atomic writes (write to temp → rename)
6
+ * - File locking with exponential backoff
7
+ * - Error handling with Result<T, FileError> pattern
8
+ * - Graceful ENOENT handling (returns null instead of error)
9
+ */
10
+ import { promises as fs } from 'fs';
11
+ import { join, dirname } from 'path';
12
+ import { ok, err } from '../common/result.js';
13
+ import { FileErrorType } from '../common/types.js';
14
+ /**
15
+ * File Storage Adapter
16
+ *
17
+ * Manages low-level file operations with atomic writes and error handling
18
+ */
19
+ export class FileStorageAdapter {
20
+ dataPath;
21
+ /**
22
+ * In-memory locks for file operations to prevent race conditions
23
+ */
24
+ fileLocks = new Map();
25
+ /**
26
+ * Create File Storage Adapter
27
+ *
28
+ * @param dataPath - Base directory for file storage
29
+ */
30
+ constructor(dataPath) {
31
+ this.dataPath = dataPath;
32
+ }
33
+ /**
34
+ * Read JSON file
35
+ *
36
+ * @param filePath - Path to JSON file (relative to dataPath)
37
+ * @returns Result with parsed JSON data or null if file doesn't exist
38
+ */
39
+ async readJSON(filePath) {
40
+ const fullPath = join(this.dataPath, filePath);
41
+ try {
42
+ const content = await fs.readFile(fullPath, 'utf-8');
43
+ const data = JSON.parse(content);
44
+ return ok(data);
45
+ }
46
+ catch (error) {
47
+ // Gracefully handle file not found
48
+ if (error.code === 'ENOENT') {
49
+ return ok(null);
50
+ }
51
+ // Handle JSON parse errors
52
+ if (error instanceof SyntaxError) {
53
+ return err({
54
+ type: FileErrorType.PARSE_ERROR,
55
+ message: `Failed to parse JSON from ${filePath}: ${error.message}`,
56
+ filePath: fullPath,
57
+ });
58
+ }
59
+ // Other file system errors
60
+ return err({
61
+ type: FileErrorType.READ_ERROR,
62
+ message: `Failed to read file ${filePath}: ${error.message}`,
63
+ filePath: fullPath,
64
+ });
65
+ }
66
+ }
67
+ /**
68
+ * Write JSON file with atomic write pattern
69
+ *
70
+ * Atomic pattern: write to temp file → rename to final file
71
+ * This prevents partial writes and corruption
72
+ *
73
+ * @param filePath - Path to JSON file (relative to dataPath)
74
+ * @param data - Data to serialize and write
75
+ * @returns Result indicating success or error
76
+ */
77
+ async writeJSON(filePath, data) {
78
+ const fullPath = join(this.dataPath, filePath);
79
+ const tempPath = `${fullPath}.tmp`;
80
+ try {
81
+ // Ensure parent directory exists
82
+ const dirResult = await this.ensureDirectory(dirname(filePath));
83
+ if (!dirResult.success) {
84
+ return dirResult;
85
+ }
86
+ // Serialize data
87
+ const content = JSON.stringify(data, null, 2);
88
+ // Write to temp file
89
+ await fs.writeFile(tempPath, content, 'utf-8');
90
+ // Atomic rename
91
+ await fs.rename(tempPath, fullPath);
92
+ return ok(undefined);
93
+ }
94
+ catch (error) {
95
+ // Clean up temp file on error
96
+ try {
97
+ await fs.unlink(tempPath);
98
+ }
99
+ catch {
100
+ // Ignore cleanup errors
101
+ }
102
+ return err({
103
+ type: FileErrorType.WRITE_ERROR,
104
+ message: `Failed to write JSON file ${filePath}: ${error.message}`,
105
+ filePath: fullPath,
106
+ });
107
+ }
108
+ }
109
+ /**
110
+ * Acquire lock for a file path and execute operation
111
+ *
112
+ * Ensures only one operation at a time per file path
113
+ *
114
+ * @param filePath - Path to lock
115
+ * @param operation - Async operation to execute while locked
116
+ * @returns Result of the operation
117
+ */
118
+ async withFileLock(filePath, operation) {
119
+ // Wait for any existing lock on this file
120
+ const existingLock = this.fileLocks.get(filePath);
121
+ if (existingLock) {
122
+ await existingLock;
123
+ // After waiting, recursively try again (in case another operation grabbed the lock)
124
+ return this.withFileLock(filePath, operation);
125
+ }
126
+ // Create new lock
127
+ let releaseLock;
128
+ const lockPromise = new Promise((resolve) => {
129
+ releaseLock = resolve;
130
+ });
131
+ this.fileLocks.set(filePath, lockPromise);
132
+ try {
133
+ // Execute operation
134
+ return await operation();
135
+ }
136
+ finally {
137
+ // Release lock
138
+ releaseLock();
139
+ this.fileLocks.delete(filePath);
140
+ }
141
+ }
142
+ /**
143
+ * Append item to JSON array file
144
+ *
145
+ * Reads existing array, appends item, writes back atomically with file locking
146
+ *
147
+ * @param filePath - Path to JSON array file
148
+ * @param item - Item to append
149
+ * @returns Result indicating success or error
150
+ */
151
+ async appendToJSONArray(filePath, item) {
152
+ return this.withFileLock(filePath, async () => {
153
+ // Read existing array
154
+ const result = await this.readJSON(filePath);
155
+ if (!result.success) {
156
+ return result;
157
+ }
158
+ // Initialize empty array if file doesn't exist
159
+ const array = result.data || [];
160
+ // Append item
161
+ array.push(item);
162
+ // Write back atomically
163
+ return this.writeJSON(filePath, array);
164
+ });
165
+ }
166
+ /**
167
+ * Trim JSON array to keep only last N items
168
+ *
169
+ * Reads array, keeps last N items, returns removed items
170
+ *
171
+ * @param filePath - Path to JSON array file
172
+ * @param keepLast - Number of items to keep
173
+ * @returns Result with removed items or error
174
+ */
175
+ async trimJSONArray(filePath, keepLast) {
176
+ return this.withFileLock(filePath, async () => {
177
+ // Read existing array
178
+ const result = await this.readJSON(filePath);
179
+ if (!result.success) {
180
+ return result;
181
+ }
182
+ // Return empty array if file doesn't exist
183
+ if (result.data === null) {
184
+ return ok([]);
185
+ }
186
+ const array = result.data;
187
+ // No trimming needed if array is small enough
188
+ if (array.length <= keepLast) {
189
+ return ok([]);
190
+ }
191
+ // Calculate split point
192
+ const removeCount = array.length - keepLast;
193
+ const removed = array.slice(0, removeCount);
194
+ const kept = array.slice(removeCount);
195
+ // Write back kept items
196
+ const writeResult = await this.writeJSON(filePath, kept);
197
+ if (!writeResult.success) {
198
+ return writeResult;
199
+ }
200
+ return ok(removed);
201
+ });
202
+ }
203
+ /**
204
+ * Ensure directory exists (create if needed)
205
+ *
206
+ * @param dirPath - Directory path (relative to dataPath)
207
+ * @returns Result indicating success or error
208
+ */
209
+ async ensureDirectory(dirPath) {
210
+ const fullPath = join(this.dataPath, dirPath);
211
+ try {
212
+ await fs.mkdir(fullPath, { recursive: true });
213
+ return ok(undefined);
214
+ }
215
+ catch (error) {
216
+ return err({
217
+ type: FileErrorType.WRITE_ERROR,
218
+ message: `Failed to create directory ${dirPath}: ${error.message}`,
219
+ filePath: fullPath,
220
+ });
221
+ }
222
+ }
223
+ /**
224
+ * List files in directory
225
+ *
226
+ * @param dirPath - Directory path (relative to dataPath)
227
+ * @returns Result with array of filenames or error
228
+ */
229
+ async listFiles(dirPath) {
230
+ const fullPath = join(this.dataPath, dirPath);
231
+ try {
232
+ const files = await fs.readdir(fullPath);
233
+ return ok(files);
234
+ }
235
+ catch (error) {
236
+ // Return empty array if directory doesn't exist
237
+ if (error.code === 'ENOENT') {
238
+ return ok([]);
239
+ }
240
+ return err({
241
+ type: FileErrorType.READ_ERROR,
242
+ message: `Failed to list directory ${dirPath}: ${error.message}`,
243
+ filePath: fullPath,
244
+ });
245
+ }
246
+ }
247
+ /**
248
+ * Delete file
249
+ *
250
+ * @param filePath - File path (relative to dataPath)
251
+ * @returns Result indicating success or error
252
+ */
253
+ async deleteFile(filePath) {
254
+ const fullPath = join(this.dataPath, filePath);
255
+ try {
256
+ await fs.unlink(fullPath);
257
+ return ok(undefined);
258
+ }
259
+ catch (error) {
260
+ // Succeed silently if file doesn't exist
261
+ if (error.code === 'ENOENT') {
262
+ return ok(undefined);
263
+ }
264
+ return err({
265
+ type: FileErrorType.WRITE_ERROR,
266
+ message: `Failed to delete file ${filePath}: ${error.message}`,
267
+ filePath: fullPath,
268
+ });
269
+ }
270
+ }
271
+ /**
272
+ * Read Markdown file
273
+ *
274
+ * @param filePath - Path to Markdown file (relative to dataPath)
275
+ * @returns Result with file content or null if file doesn't exist
276
+ */
277
+ async readMarkdown(filePath) {
278
+ const fullPath = join(this.dataPath, filePath);
279
+ try {
280
+ const content = await fs.readFile(fullPath, 'utf-8');
281
+ return ok(content);
282
+ }
283
+ catch (error) {
284
+ // Gracefully handle file not found
285
+ if (error.code === 'ENOENT') {
286
+ return ok(null);
287
+ }
288
+ return err({
289
+ type: FileErrorType.READ_ERROR,
290
+ message: `Failed to read Markdown file ${filePath}: ${error.message}`,
291
+ filePath: fullPath,
292
+ });
293
+ }
294
+ }
295
+ /**
296
+ * Write Markdown file with atomic write pattern
297
+ *
298
+ * @param filePath - Path to Markdown file (relative to dataPath)
299
+ * @param content - Markdown content to write
300
+ * @returns Result indicating success or error
301
+ */
302
+ async writeMarkdown(filePath, content) {
303
+ const fullPath = join(this.dataPath, filePath);
304
+ const tempPath = `${fullPath}.tmp`;
305
+ try {
306
+ // Ensure parent directory exists
307
+ const dirResult = await this.ensureDirectory(dirname(filePath));
308
+ if (!dirResult.success) {
309
+ return dirResult;
310
+ }
311
+ // Write to temp file
312
+ await fs.writeFile(tempPath, content, 'utf-8');
313
+ // Atomic rename
314
+ await fs.rename(tempPath, fullPath);
315
+ return ok(undefined);
316
+ }
317
+ catch (error) {
318
+ // Clean up temp file on error
319
+ try {
320
+ await fs.unlink(tempPath);
321
+ }
322
+ catch {
323
+ // Ignore cleanup errors
324
+ }
325
+ return err({
326
+ type: FileErrorType.WRITE_ERROR,
327
+ message: `Failed to write Markdown file ${filePath}: ${error.message}`,
328
+ filePath: fullPath,
329
+ });
330
+ }
331
+ }
332
+ /**
333
+ * Append content to Markdown file
334
+ *
335
+ * @param filePath - Path to Markdown file
336
+ * @param content - Content to append
337
+ * @returns Result indicating success or error
338
+ */
339
+ async appendToMarkdown(filePath, content) {
340
+ // Read existing content
341
+ const result = await this.readMarkdown(filePath);
342
+ if (!result.success) {
343
+ return result;
344
+ }
345
+ // Concatenate with newline
346
+ const existing = result.data || '';
347
+ const updated = existing ? `${existing}\n${content}` : content;
348
+ // Write back atomically
349
+ return this.writeMarkdown(filePath, updated);
350
+ }
351
+ }
352
+ //# sourceMappingURL=file-storage-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-storage-adapter.js","sourceRoot":"","sources":["../../src/memory/file-storage-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAErC,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAWA;IAV7B;;OAEG;IACK,SAAS,GAA+B,IAAI,GAAG,EAAE,CAAC;IAE1D;;;;OAIG;IACH,YAA6B,QAAgB;QAAhB,aAAQ,GAAR,QAAQ,CAAQ;IAAG,CAAC;IAEjD;;;;;OAKG;IACH,KAAK,CAAC,QAAQ,CAAI,QAAgB;QAChC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QAE/C,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACrD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAM,CAAC;YACtC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;QAClB,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,mCAAmC;YACnC,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC5B,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;YAClB,CAAC;YAED,2BAA2B;YAC3B,IAAI,KAAK,YA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AC,gBAAgB,CACpB,QAAgB,EAChB,OAAe;QAEf,wBAAwB;QACxB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QACjD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,2BAA2B;QAC3B,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAE/D,wBAAwB;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;CACF"}
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Memory Service - Hybrid Storage Orchestration
3
+ *
4
+ * Orchestrates hybrid memory system:
5
+ * - Short-term: Conversation context in JSON files (FileStorageAdapter)
6
+ * - Long-term: Summarized history in ArcadeDB (ArcadeDBAdapter)
7
+ * - Private: User preferences in JSON files
8
+ * - Public: Shared knowledge base in JSON files
9
+ *
10
+ * Features:
11
+ * - Automatic archival when conversation exceeds 20 messages
12
+ * - LLM-based summarization before archival
13
+ * - Graceful degradation if ArcadeDB unavailable
14
+ */
15
+ import type { Result } from '../common/result.js';
16
+ import type { ProviderManager } from '../providers/provider-manager.js';
17
+ /**
18
+ * Message in conversation history
19
+ */
20
+ export interface ConversationMessage {
21
+ role: 'user' | 'assistant' | 'system';
22
+ content: string;
23
+ timestamp: number;
24
+ }
25
+ /**
26
+ * Conversation context with metadata
27
+ */
28
+ export interface ConversationContext {
29
+ userId: string;
30
+ channelId: string;
31
+ messages: ConversationMessage[];
32
+ lastUpdated: number;
33
+ }
34
+ /**
35
+ * User preference storage
36
+ */
37
+ export interface UserPreference {
38
+ key: string;
39
+ value: any;
40
+ updatedAt: number;
41
+ }
42
+ /**
43
+ * Knowledge base entry
44
+ */
45
+ export interface KnowledgeEntry {
46
+ id: string;
47
+ topic: string;
48
+ content: string;
49
+ tags: string[];
50
+ createdAt: number;
51
+ updatedAt: number;
52
+ }
53
+ /**
54
+ * Archived conversation summary
55
+ */
56
+ export interface ArchivedSummary {
57
+ userId: string;
58
+ channelId: string;
59
+ summary: string;
60
+ messageCount: number;
61
+ startTime: number;
62
+ endTime: number;
63
+ }
64
+ /**
65
+ * Memory Service Error
66
+ */
67
+ export interface MemoryError {
68
+ type: 'FILE_ERROR' | 'DATABASE_ERROR' | 'PROVIDER_ERROR' | 'VALIDATION_ERROR';
69
+ message: string;
70
+ originalError?: unknown;
71
+ }
72
+ /**
73
+ * Memory Service
74
+ *
75
+ * Manages hybrid memory storage with automatic archival and graceful degradation
76
+ */
77
+ export declare class MemoryService {
78
+ private readonly providerManager?;
79
+ private fileStorage;
80
+ private dbAdapter;
81
+ private isDbAvailable;
82
+ private readonly archiveThreshold;
83
+ /**
84
+ * Create Memory Service
85
+ *
86
+ * @param memoryDataPath - Base directory for file storage
87
+ * @param arcadedbUrl - ArcadeDB connection URL (optional)
88
+ * @param arcadedbPassword - ArcadeDB root password (optional, defaults to 'root')
89
+ * @param providerManager - LLM provider for summarization (optional)
90
+ */
91
+ constructor(memoryDataPath: string, arcadedbUrl?: string, arcadedbPassword?: string, providerManager?: ProviderManager | undefined);
92
+ /**
93
+ * Initialize memory service
94
+ *
95
+ * Attempts to connect to ArcadeDB, logs warning if unavailable but continues
96
+ *
97
+ * @returns Result indicating initialization success
98
+ */
99
+ initialize(): Promise<Result<void, MemoryError>>;
100
+ /**
101
+ * Store message in conversation history
102
+ *
103
+ * Appends message to short-term storage and checks if archival is needed
104
+ *
105
+ * @param userId - User identifier
106
+ * @param channelId - Channel/conversation identifier
107
+ * @param message - Message to store
108
+ * @returns Result indicating success or error
109
+ */
110
+ storeMessage(userId: string, channelId: string, message: ConversationMessage): Promise<Result<void, MemoryError>>;
111
+ /**
112
+ * Retrieve conversation context
113
+ *
114
+ * Reads recent messages from short-term storage
115
+ *
116
+ * @param userId - User identifier
117
+ * @param channelId - Channel/conversation identifier
118
+ * @param limit - Maximum number of messages to retrieve (default: 20)
119
+ * @returns Result with conversation messages or error
120
+ */
121
+ retrieveContext(userId: string, channelId: string, limit?: number): Promise<Result<ConversationMessage[], MemoryError>>;
122
+ /**
123
+ * Store user preference
124
+ *
125
+ * Saves preference to user's preference file
126
+ *
127
+ * @param userId - User identifier
128
+ * @param key - Preference key
129
+ * @param value - Preference value
130
+ * @returns Result indicating success or error
131
+ */
132
+ storePreference(userId: string, key: string, value: any): Promise<Result<void, MemoryError>>;
133
+ /**
134
+ * Get user preference
135
+ *
136
+ * Retrieves preference value from user's preference file
137
+ *
138
+ * @param userId - User identifier
139
+ * @param key - Preference key
140
+ * @returns Result with preference value or null if not found
141
+ */
142
+ getPreference(userId: string, key: string): Promise<Result<any | null, MemoryError>>;
143
+ /**
144
+ * Store knowledge in public knowledge base
145
+ *
146
+ * Adds entry to shared knowledge base
147
+ *
148
+ * @param entry - Knowledge entry
149
+ * @returns Result indicating success or error
150
+ */
151
+ storeKnowledge(entry: KnowledgeEntry): Promise<Result<void, MemoryError>>;
152
+ /**
153
+ * Get knowledge from public knowledge base
154
+ *
155
+ * Retrieves entry by ID
156
+ *
157
+ * @param id - Knowledge entry ID
158
+ * @returns Result with knowledge entry or null if not found
159
+ */
160
+ getKnowledge(id: string): Promise<Result<KnowledgeEntry | null, MemoryError>>;
161
+ /**
162
+ * Check if conversation exceeds archival threshold
163
+ *
164
+ * If threshold exceeded, triggers archival to long-term storage
165
+ *
166
+ * @param userId - User identifier
167
+ * @param channelId - Channel identifier
168
+ */
169
+ private checkArchiveThreshold;
170
+ /**
171
+ * Archive conversation to long-term storage
172
+ *
173
+ * Summarizes conversation using LLM and stores in ArcadeDB
174
+ * Trims short-term storage to keep only recent messages
175
+ *
176
+ * @param userId - User identifier
177
+ * @param channelId - Channel identifier
178
+ * @param messages - Messages to archive
179
+ */
180
+ private archiveToLongTerm;
181
+ /**
182
+ * Summarize conversation using LLM
183
+ *
184
+ * @param messages - Messages to summarize
185
+ * @returns Result with summary text
186
+ */
187
+ private summarizeConversation;
188
+ /**
189
+ * Search long-term storage
190
+ *
191
+ * Queries ArcadeDB for archived conversations matching criteria
192
+ *
193
+ * @param userId - User identifier
194
+ * @param searchTerm - Search term for summary content
195
+ * @param limit - Maximum results to return (default: 10)
196
+ * @returns Result with archived summaries or error
197
+ */
198
+ searchLongTerm(userId: string, searchTerm: string, limit?: number): Promise<Result<ArchivedSummary[], MemoryError>>;
199
+ /**
200
+ * Dispose of memory service
201
+ *
202
+ * Disconnects from ArcadeDB and performs cleanup
203
+ *
204
+ * @returns Result indicating success or error
205
+ */
206
+ dispose(): Promise<Result<void, MemoryError>>;
207
+ }
208
+ //# sourceMappingURL=memory-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-service.d.ts","sourceRoot":"","sources":["../../src/memory/memory-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAKlD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAExE;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,QAAQ,CAAC;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,mBAAmB,EAAE,CAAC;IAChC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,GAAG,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;CACnB;A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