@nxuss/lemma 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.
- package/LICENSE +21 -0
- package/README.md +311 -0
- package/dist/cloud/KeyManager.d.ts +29 -0
- package/dist/cloud/KeyManager.d.ts.map +1 -0
- package/dist/cloud/KeyManager.js +142 -0
- package/dist/cloud/KeyManager.js.map +1 -0
- package/dist/cloud/TenantCache.d.ts +29 -0
- package/dist/cloud/TenantCache.d.ts.map +1 -0
- package/dist/cloud/TenantCache.js +162 -0
- package/dist/cloud/TenantCache.js.map +1 -0
- package/dist/cloud/index.d.ts +4 -0
- package/dist/cloud/index.d.ts.map +1 -0
- package/dist/cloud/index.js +23 -0
- package/dist/cloud/index.js.map +1 -0
- package/dist/cloud/server.d.ts +17 -0
- package/dist/cloud/server.d.ts.map +1 -0
- package/dist/cloud/server.js +189 -0
- package/dist/cloud/server.js.map +1 -0
- package/dist/cloud/types.d.ts +35 -0
- package/dist/cloud/types.d.ts.map +1 -0
- package/dist/cloud/types.js +14 -0
- package/dist/cloud/types.js.map +1 -0
- package/dist/config/index.d.ts +44 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +161 -0
- package/dist/config/index.js.map +1 -0
- package/dist/consensus/ConsensusEngine.d.ts +119 -0
- package/dist/consensus/ConsensusEngine.d.ts.map +1 -0
- package/dist/consensus/ConsensusEngine.js +314 -0
- package/dist/consensus/ConsensusEngine.js.map +1 -0
- package/dist/consensus/ModelPool.d.ts +103 -0
- package/dist/consensus/ModelPool.d.ts.map +1 -0
- package/dist/consensus/ModelPool.js +276 -0
- package/dist/consensus/ModelPool.js.map +1 -0
- package/dist/consensus/index.d.ts +8 -0
- package/dist/consensus/index.d.ts.map +1 -0
- package/dist/consensus/index.js +13 -0
- package/dist/consensus/index.js.map +1 -0
- package/dist/core/AgentRegistry.d.ts +89 -0
- package/dist/core/AgentRegistry.d.ts.map +1 -0
- package/dist/core/AgentRegistry.js +264 -0
- package/dist/core/AgentRegistry.js.map +1 -0
- package/dist/core/DashboardBroadcaster.d.ts +67 -0
- package/dist/core/DashboardBroadcaster.d.ts.map +1 -0
- package/dist/core/DashboardBroadcaster.js +264 -0
- package/dist/core/DashboardBroadcaster.js.map +1 -0
- package/dist/core/OrchestrationEngine.d.ts +84 -0
- package/dist/core/OrchestrationEngine.d.ts.map +1 -0
- package/dist/core/OrchestrationEngine.js +455 -0
- package/dist/core/OrchestrationEngine.js.map +1 -0
- package/dist/core/SubconsciousEngine.d.ts +53 -0
- package/dist/core/SubconsciousEngine.d.ts.map +1 -0
- package/dist/core/SubconsciousEngine.js +273 -0
- package/dist/core/SubconsciousEngine.js.map +1 -0
- package/dist/core/WebSocketServer.d.ts +89 -0
- package/dist/core/WebSocketServer.d.ts.map +1 -0
- package/dist/core/WebSocketServer.js +416 -0
- package/dist/core/WebSocketServer.js.map +1 -0
- package/dist/core/index.d.ts +15 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +24 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/router.d.ts +105 -0
- package/dist/core/router.d.ts.map +1 -0
- package/dist/core/router.js +420 -0
- package/dist/core/router.js.map +1 -0
- package/dist/embed/index.d.ts +153 -0
- package/dist/embed/index.d.ts.map +1 -0
- package/dist/embed/index.js +408 -0
- package/dist/embed/index.js.map +1 -0
- package/dist/embed.d.ts +11 -0
- package/dist/embed.d.ts.map +1 -0
- package/dist/embed.js +19 -0
- package/dist/embed.js.map +1 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +176 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol/flows.d.ts +126 -0
- package/dist/protocol/flows.d.ts.map +1 -0
- package/dist/protocol/flows.js +347 -0
- package/dist/protocol/flows.js.map +1 -0
- package/dist/protocol/iap.d.ts +54 -0
- package/dist/protocol/iap.d.ts.map +1 -0
- package/dist/protocol/iap.js +108 -0
- package/dist/protocol/iap.js.map +1 -0
- package/dist/protocol/index.d.ts +23 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +45 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/protocol/types.d.ts +332 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +57 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/protocol/utils.d.ts +130 -0
- package/dist/protocol/utils.d.ts.map +1 -0
- package/dist/protocol/utils.js +292 -0
- package/dist/protocol/utils.js.map +1 -0
- package/dist/protocol/validators.d.ts +54 -0
- package/dist/protocol/validators.d.ts.map +1 -0
- package/dist/protocol/validators.js +344 -0
- package/dist/protocol/validators.js.map +1 -0
- package/dist/security/AuthManager.d.ts +73 -0
- package/dist/security/AuthManager.d.ts.map +1 -0
- package/dist/security/AuthManager.js +102 -0
- package/dist/security/AuthManager.js.map +1 -0
- package/dist/security/MessageSanitizer.d.ts +51 -0
- package/dist/security/MessageSanitizer.d.ts.map +1 -0
- package/dist/security/MessageSanitizer.js +166 -0
- package/dist/security/MessageSanitizer.js.map +1 -0
- package/dist/security/RateLimiter.d.ts +46 -0
- package/dist/security/RateLimiter.d.ts.map +1 -0
- package/dist/security/RateLimiter.js +133 -0
- package/dist/security/RateLimiter.js.map +1 -0
- package/dist/security/SecurityMiddleware.d.ts +88 -0
- package/dist/security/SecurityMiddleware.d.ts.map +1 -0
- package/dist/security/SecurityMiddleware.js +146 -0
- package/dist/security/SecurityMiddleware.js.map +1 -0
- package/dist/security/index.d.ts +35 -0
- package/dist/security/index.d.ts.map +1 -0
- package/dist/security/index.js +42 -0
- package/dist/security/index.js.map +1 -0
- package/dist/speculative/PredictionEngine.d.ts +99 -0
- package/dist/speculative/PredictionEngine.d.ts.map +1 -0
- package/dist/speculative/PredictionEngine.js +291 -0
- package/dist/speculative/PredictionEngine.js.map +1 -0
- package/dist/speculative/SpeculativeCache.d.ts +117 -0
- package/dist/speculative/SpeculativeCache.d.ts.map +1 -0
- package/dist/speculative/SpeculativeCache.js +292 -0
- package/dist/speculative/SpeculativeCache.js.map +1 -0
- package/dist/speculative/SpeculativeEngine.d.ts +114 -0
- package/dist/speculative/SpeculativeEngine.d.ts.map +1 -0
- package/dist/speculative/SpeculativeEngine.js +244 -0
- package/dist/speculative/SpeculativeEngine.js.map +1 -0
- package/dist/speculative/WorkerPool.d.ts +109 -0
- package/dist/speculative/WorkerPool.d.ts.map +1 -0
- package/dist/speculative/WorkerPool.js +327 -0
- package/dist/speculative/WorkerPool.js.map +1 -0
- package/dist/speculative/index.d.ts +10 -0
- package/dist/speculative/index.d.ts.map +1 -0
- package/dist/speculative/index.js +17 -0
- package/dist/speculative/index.js.map +1 -0
- package/dist/subconscious/EmbeddingService.d.ts +73 -0
- package/dist/subconscious/EmbeddingService.d.ts.map +1 -0
- package/dist/subconscious/EmbeddingService.js +196 -0
- package/dist/subconscious/EmbeddingService.js.map +1 -0
- package/dist/subconscious/SemanticCache.d.ts +82 -0
- package/dist/subconscious/SemanticCache.d.ts.map +1 -0
- package/dist/subconscious/SemanticCache.js +164 -0
- package/dist/subconscious/SemanticCache.js.map +1 -0
- package/dist/subconscious/SubconsciousEngine.d.ts +121 -0
- package/dist/subconscious/SubconsciousEngine.d.ts.map +1 -0
- package/dist/subconscious/SubconsciousEngine.js +241 -0
- package/dist/subconscious/SubconsciousEngine.js.map +1 -0
- package/dist/subconscious/VectorStore.d.ts +54 -0
- package/dist/subconscious/VectorStore.d.ts.map +1 -0
- package/dist/subconscious/VectorStore.js +168 -0
- package/dist/subconscious/VectorStore.js.map +1 -0
- package/dist/subconscious/cache.d.ts +34 -0
- package/dist/subconscious/cache.d.ts.map +1 -0
- package/dist/subconscious/cache.js +156 -0
- package/dist/subconscious/cache.js.map +1 -0
- package/dist/subconscious/embeddings.d.ts +25 -0
- package/dist/subconscious/embeddings.d.ts.map +1 -0
- package/dist/subconscious/embeddings.js +65 -0
- package/dist/subconscious/embeddings.js.map +1 -0
- package/dist/subconscious/index.d.ts +12 -0
- package/dist/subconscious/index.d.ts.map +1 -0
- package/dist/subconscious/index.js +19 -0
- package/dist/subconscious/index.js.map +1 -0
- package/dist/types/index.d.ts +286 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +43 -0
- package/dist/types/index.js.map +1 -0
- package/dist/utils/logger.d.ts +63 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +126 -0
- package/dist/utils/logger.js.map +1 -0
- package/package.json +99 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SubconsciousEngine = void 0;
|
|
4
|
+
const VectorStore_1 = require("./VectorStore");
|
|
5
|
+
const EmbeddingService_1 = require("./EmbeddingService");
|
|
6
|
+
const SemanticCache_1 = require("./SemanticCache");
|
|
7
|
+
const events_1 = require("events");
|
|
8
|
+
/**
|
|
9
|
+
* SubconsciousEngine is the main orchestrator for semantic caching.
|
|
10
|
+
* It intercepts tasks, checks for cached results, and manages background vectorization.
|
|
11
|
+
*/
|
|
12
|
+
class SubconsciousEngine extends events_1.EventEmitter {
|
|
13
|
+
constructor(config = {}) {
|
|
14
|
+
super();
|
|
15
|
+
this.isInitialized = false;
|
|
16
|
+
this.backgroundQueue = [];
|
|
17
|
+
this.isProcessingQueue = false;
|
|
18
|
+
this.cacheLatencies = [];
|
|
19
|
+
this.missLatencies = [];
|
|
20
|
+
// Set default configuration
|
|
21
|
+
this.config = {
|
|
22
|
+
chromaUrl: config.chromaUrl || 'http://localhost:8000',
|
|
23
|
+
ollamaUrl: config.ollamaUrl || 'http://localhost:11434',
|
|
24
|
+
model: config.model || 'llama3',
|
|
25
|
+
collectionName: config.collectionName || 'subconscious_cache',
|
|
26
|
+
threshold: config.threshold || 0.95,
|
|
27
|
+
enableBackgroundVectorization: config.enableBackgroundVectorization ?? true,
|
|
28
|
+
};
|
|
29
|
+
// Initialize components
|
|
30
|
+
this.vectorStore = new VectorStore_1.VectorStore(this.config.collectionName, this.config.chromaUrl);
|
|
31
|
+
this.embeddingService = new EmbeddingService_1.EmbeddingService(this.config.ollamaUrl, this.config.model);
|
|
32
|
+
this.semanticCache = new SemanticCache_1.SemanticCache(this.vectorStore, this.embeddingService, this.config.threshold);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Initialize the Subconscious Engine.
|
|
36
|
+
* Must be called before using the engine.
|
|
37
|
+
*/
|
|
38
|
+
async initialize() {
|
|
39
|
+
if (this.isInitialized) {
|
|
40
|
+
console.log('[SubconsciousEngine] Already initialized');
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
console.log('[SubconsciousEngine] Initializing...');
|
|
44
|
+
try {
|
|
45
|
+
// Initialize vector store
|
|
46
|
+
await this.vectorStore.initialize();
|
|
47
|
+
// Health check for Ollama
|
|
48
|
+
const health = await this.embeddingService.healthCheck();
|
|
49
|
+
if (!health.available) {
|
|
50
|
+
console.warn(`[SubconsciousEngine] Warning: Ollama not available - ${health.error}`);
|
|
51
|
+
console.warn('[SubconsciousEngine] Engine will operate in degraded mode');
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
console.log(`[SubconsciousEngine] Ollama connected (model: ${health.model})`);
|
|
55
|
+
}
|
|
56
|
+
this.isInitialized = true;
|
|
57
|
+
this.emit('initialized');
|
|
58
|
+
console.log('[SubconsciousEngine] ✓ Initialization complete');
|
|
59
|
+
console.log(`[SubconsciousEngine] Threshold: ${this.config.threshold}`);
|
|
60
|
+
console.log(`[SubconsciousEngine] Background vectorization: ${this.config.enableBackgroundVectorization ? 'enabled' : 'disabled'}`);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
console.error('[SubconsciousEngine] Initialization failed:', error);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Intercept a task and check for cached results.
|
|
69
|
+
* This is the main entry point for the semantic short-circuit.
|
|
70
|
+
*
|
|
71
|
+
* @param task - Task to intercept
|
|
72
|
+
* @returns CacheResult indicating if a cached result was found
|
|
73
|
+
*/
|
|
74
|
+
async interceptTask(task) {
|
|
75
|
+
if (!this.isInitialized) {
|
|
76
|
+
throw new Error('SubconsciousEngine not initialized. Call initialize() first.');
|
|
77
|
+
}
|
|
78
|
+
console.log(`[SubconsciousEngine] Intercepting task: ${task.id}`);
|
|
79
|
+
const cacheResult = await this.semanticCache.check(task.description);
|
|
80
|
+
// Track latencies for metrics
|
|
81
|
+
if (cacheResult.hit) {
|
|
82
|
+
this.cacheLatencies.push(cacheResult.latencyMs);
|
|
83
|
+
this.emit('cacheHit', {
|
|
84
|
+
taskId: task.id,
|
|
85
|
+
similarity: cacheResult.similarity,
|
|
86
|
+
latencyMs: cacheResult.latencyMs,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
this.missLatencies.push(cacheResult.latencyMs);
|
|
91
|
+
this.emit('cacheMiss', {
|
|
92
|
+
taskId: task.id,
|
|
93
|
+
latencyMs: cacheResult.latencyMs,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return cacheResult;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Store a task result for future caching.
|
|
100
|
+
* If background vectorization is enabled, queues the task for async processing.
|
|
101
|
+
*
|
|
102
|
+
* @param task - Original task
|
|
103
|
+
* @param result - Result to cache
|
|
104
|
+
*/
|
|
105
|
+
async storeResult(task, result) {
|
|
106
|
+
if (!this.isInitialized) {
|
|
107
|
+
throw new Error('SubconsciousEngine not initialized. Call initialize() first.');
|
|
108
|
+
}
|
|
109
|
+
if (this.config.enableBackgroundVectorization) {
|
|
110
|
+
// Queue for background processing
|
|
111
|
+
this.backgroundQueue.push({
|
|
112
|
+
taskId: task.id,
|
|
113
|
+
description: task.description,
|
|
114
|
+
result,
|
|
115
|
+
metadata: task.metadata || {},
|
|
116
|
+
});
|
|
117
|
+
console.log(`[SubconsciousEngine] Queued task ${task.id} for background vectorization ` +
|
|
118
|
+
`(queue size: ${this.backgroundQueue.length})`);
|
|
119
|
+
// Start processing queue if not already running
|
|
120
|
+
if (!this.isProcessingQueue) {
|
|
121
|
+
this.processBackgroundQueue();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
// Store immediately
|
|
126
|
+
await this.semanticCache.store(task.id, task.description, result, task.metadata || {});
|
|
127
|
+
}
|
|
128
|
+
this.emit('resultStored', { taskId: task.id });
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Process the background vectorization queue.
|
|
132
|
+
* Runs asynchronously without blocking the main thread.
|
|
133
|
+
*/
|
|
134
|
+
async processBackgroundQueue() {
|
|
135
|
+
if (this.isProcessingQueue || this.backgroundQueue.length === 0) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
this.isProcessingQueue = true;
|
|
139
|
+
console.log('[SubconsciousEngine] Starting background vectorization...');
|
|
140
|
+
while (this.backgroundQueue.length > 0) {
|
|
141
|
+
const item = this.backgroundQueue.shift();
|
|
142
|
+
if (!item)
|
|
143
|
+
continue;
|
|
144
|
+
try {
|
|
145
|
+
await this.semanticCache.store(item.taskId, item.description, item.result, item.metadata);
|
|
146
|
+
this.emit('backgroundVectorized', { taskId: item.taskId });
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
console.error(`[SubconsciousEngine] Failed to vectorize task ${item.taskId}:`, error);
|
|
150
|
+
this.emit('vectorizationError', { taskId: item.taskId, error });
|
|
151
|
+
}
|
|
152
|
+
// Small delay to avoid overwhelming the system
|
|
153
|
+
await this.sleep(10);
|
|
154
|
+
}
|
|
155
|
+
this.isProcessingQueue = false;
|
|
156
|
+
console.log('[SubconsciousEngine] Background vectorization complete');
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Get comprehensive engine metrics.
|
|
160
|
+
*/
|
|
161
|
+
async getMetrics() {
|
|
162
|
+
const cacheMetrics = this.semanticCache.getMetrics();
|
|
163
|
+
const totalCachedTasks = await this.semanticCache.getCacheSize();
|
|
164
|
+
const avgCacheLatency = this.cacheLatencies.length > 0
|
|
165
|
+
? this.cacheLatencies.reduce((a, b) => a + b, 0) / this.cacheLatencies.length
|
|
166
|
+
: 0;
|
|
167
|
+
const avgMissLatency = this.missLatencies.length > 0
|
|
168
|
+
? this.missLatencies.reduce((a, b) => a + b, 0) / this.missLatencies.length
|
|
169
|
+
: 0;
|
|
170
|
+
return {
|
|
171
|
+
totalTasks: cacheMetrics.total,
|
|
172
|
+
cacheHits: cacheMetrics.hits,
|
|
173
|
+
cacheMisses: cacheMetrics.misses,
|
|
174
|
+
hitRate: cacheMetrics.hitRate,
|
|
175
|
+
avgCacheLatencyMs: Math.round(avgCacheLatency),
|
|
176
|
+
avgMissLatencyMs: Math.round(avgMissLatency),
|
|
177
|
+
totalCachedTasks,
|
|
178
|
+
backgroundQueueSize: this.backgroundQueue.length,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Reset all metrics.
|
|
183
|
+
*/
|
|
184
|
+
resetMetrics() {
|
|
185
|
+
this.semanticCache.resetMetrics();
|
|
186
|
+
this.cacheLatencies = [];
|
|
187
|
+
this.missLatencies = [];
|
|
188
|
+
console.log('[SubconsciousEngine] Metrics reset');
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Update the similarity threshold.
|
|
192
|
+
*/
|
|
193
|
+
setThreshold(threshold) {
|
|
194
|
+
this.semanticCache.setThreshold(threshold);
|
|
195
|
+
this.config.threshold = threshold;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Get the current configuration.
|
|
199
|
+
*/
|
|
200
|
+
getConfig() {
|
|
201
|
+
return { ...this.config };
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Clear all cached tasks and reset metrics.
|
|
205
|
+
*/
|
|
206
|
+
async clear() {
|
|
207
|
+
await this.semanticCache.clear();
|
|
208
|
+
this.backgroundQueue = [];
|
|
209
|
+
this.resetMetrics();
|
|
210
|
+
console.log('[SubconsciousEngine] Engine cleared');
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Shutdown the engine gracefully.
|
|
214
|
+
* Waits for background queue to finish processing.
|
|
215
|
+
*/
|
|
216
|
+
async shutdown() {
|
|
217
|
+
console.log('[SubconsciousEngine] Shutting down...');
|
|
218
|
+
// Wait for background queue to finish
|
|
219
|
+
while (this.isProcessingQueue || this.backgroundQueue.length > 0) {
|
|
220
|
+
console.log(`[SubconsciousEngine] Waiting for background queue (${this.backgroundQueue.length} items)...`);
|
|
221
|
+
await this.sleep(100);
|
|
222
|
+
}
|
|
223
|
+
this.isInitialized = false;
|
|
224
|
+
this.emit('shutdown');
|
|
225
|
+
console.log('[SubconsciousEngine] Shutdown complete');
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Check if the engine is ready to use.
|
|
229
|
+
*/
|
|
230
|
+
isReady() {
|
|
231
|
+
return this.isInitialized && this.vectorStore.isReady();
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Sleep for specified milliseconds.
|
|
235
|
+
*/
|
|
236
|
+
sleep(ms) {
|
|
237
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
exports.SubconsciousEngine = SubconsciousEngine;
|
|
241
|
+
//# sourceMappingURL=SubconsciousEngine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SubconsciousEngine.js","sourceRoot":"","sources":["../../src/subconscious/SubconsciousEngine.ts"],"names":[],"mappings":";;;AAAA,+CAA4C;AAC5C,yDAAsD;AACtD,mDAA6D;AAC7D,mCAAsC;AAiDtC;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,qBAAY;IAgBlD,YAAY,SAA6B,EAAE;QACzC,KAAK,EAAE,CAAC;QAZF,kBAAa,GAAY,KAAK,CAAC;QAC/B,oBAAe,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C;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;IAC1D,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,EAAU;QACtB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3D,CAAC;CACF;AAhTD,gDAgTC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VectorStore manages the ChromaDB client and collection for semantic caching.
|
|
3
|
+
* It provides methods to insert task vectors and search for similar tasks.
|
|
4
|
+
*/
|
|
5
|
+
export declare class VectorStore {
|
|
6
|
+
private client;
|
|
7
|
+
private collection;
|
|
8
|
+
private collectionName;
|
|
9
|
+
private isInitialized;
|
|
10
|
+
constructor(collectionName?: string, chromaUrl?: string);
|
|
11
|
+
/**
|
|
12
|
+
* Initialize the ChromaDB collection.
|
|
13
|
+
* Creates a new collection if it doesn't exist.
|
|
14
|
+
*/
|
|
15
|
+
initialize(): Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Insert a task vector with its result into the collection.
|
|
18
|
+
*
|
|
19
|
+
* @param taskId - Unique identifier for the task
|
|
20
|
+
* @param embedding - Vector embedding of the task
|
|
21
|
+
* @param taskDescription - Original task description
|
|
22
|
+
* @param result - Cached result to return on cache hit
|
|
23
|
+
* @param metadata - Additional metadata (agent, timestamp, etc.)
|
|
24
|
+
*/
|
|
25
|
+
insertVector(taskId: string, embedding: number[], taskDescription: string, result: any, metadata?: Record<string, any>): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* Search for similar tasks using semantic similarity.
|
|
28
|
+
*
|
|
29
|
+
* @param queryEmbedding - Vector embedding of the query task
|
|
30
|
+
* @param threshold - Minimum similarity score (0-1, default 0.95)
|
|
31
|
+
* @param topK - Number of results to return (default 1)
|
|
32
|
+
* @returns Array of similar tasks with their results and similarity scores
|
|
33
|
+
*/
|
|
34
|
+
searchSimilar(queryEmbedding: number[], threshold?: number, topK?: number): Promise<Array<{
|
|
35
|
+
id: string;
|
|
36
|
+
similarity: number;
|
|
37
|
+
result: any;
|
|
38
|
+
taskDescription: string;
|
|
39
|
+
metadata: Record<string, any>;
|
|
40
|
+
}>>;
|
|
41
|
+
/**
|
|
42
|
+
* Get the total count of cached tasks.
|
|
43
|
+
*/
|
|
44
|
+
getCount(): Promise<number>;
|
|
45
|
+
/**
|
|
46
|
+
* Clear all cached tasks from the collection.
|
|
47
|
+
*/
|
|
48
|
+
clear(): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Check if the VectorStore is ready to use.
|
|
51
|
+
*/
|
|
52
|
+
isReady(): boolean;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=VectorStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VectorStore.d.ts","sourceRoot":"","sources":["../../src/subconscious/VectorStore.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,aAAa,CAAkB;gBAGrC,cAAc,GAAE,MAA6B,EAC7C,SAAS,GAAE,MAAgC;IAM7C;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBjC;;;;;;;;OAQG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EAAE,EACnB,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,GAAG,EACX,QAAQ,GAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAM,GACjC,OAAO,CAAC,IAAI,CAAC;IAwBhB;;;;;;;OAOG;IACG,aAAa,CACjB,cAAc,EAAE,MAAM,EAAE,EACxB,SAAS,GAAE,MAAa,EACxB,IAAI,GAAE,MAAU,GACf,OAAO,CAAC,KAAK,CAAC;QACf,EAAE,EAAE,MAAM,CAAC;QACX,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,GAAG,CAAC;QACZ,eAAe,EAAE,MAAM,CAAC;QACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KAC/B,CAAC,CAAC;IAyDH;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAcjC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAiB5B;;OAEG;IACH,OAAO,IAAI,OAAO;CAGnB"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VectorStore = void 0;
|
|
4
|
+
const chromadb_1 = require("chromadb");
|
|
5
|
+
/**
|
|
6
|
+
* VectorStore manages the ChromaDB client and collection for semantic caching.
|
|
7
|
+
* It provides methods to insert task vectors and search for similar tasks.
|
|
8
|
+
*/
|
|
9
|
+
class VectorStore {
|
|
10
|
+
constructor(collectionName = 'subconscious_cache', chromaUrl = 'http://localhost:8000') {
|
|
11
|
+
this.collection = null;
|
|
12
|
+
this.isInitialized = false;
|
|
13
|
+
this.collectionName = collectionName;
|
|
14
|
+
this.client = new chromadb_1.ChromaClient({ path: chromaUrl });
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Initialize the ChromaDB collection.
|
|
18
|
+
* Creates a new collection if it doesn't exist.
|
|
19
|
+
*/
|
|
20
|
+
async initialize() {
|
|
21
|
+
if (this.isInitialized) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
// Try to get existing collection
|
|
26
|
+
this.collection = await this.client.getOrCreateCollection({
|
|
27
|
+
name: this.collectionName,
|
|
28
|
+
metadata: {
|
|
29
|
+
description: 'Semantic cache for agent task results',
|
|
30
|
+
'hnsw:space': 'cosine', // Use cosine similarity
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
this.isInitialized = true;
|
|
34
|
+
console.log(`[VectorStore] Initialized collection: ${this.collectionName}`);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
console.error('[VectorStore] Failed to initialize collection:', error);
|
|
38
|
+
throw new Error(`VectorStore initialization failed: ${error}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Insert a task vector with its result into the collection.
|
|
43
|
+
*
|
|
44
|
+
* @param taskId - Unique identifier for the task
|
|
45
|
+
* @param embedding - Vector embedding of the task
|
|
46
|
+
* @param taskDescription - Original task description
|
|
47
|
+
* @param result - Cached result to return on cache hit
|
|
48
|
+
* @param metadata - Additional metadata (agent, timestamp, etc.)
|
|
49
|
+
*/
|
|
50
|
+
async insertVector(taskId, embedding, taskDescription, result, metadata = {}) {
|
|
51
|
+
if (!this.collection) {
|
|
52
|
+
throw new Error('VectorStore not initialized. Call initialize() first.');
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
await this.collection.add({
|
|
56
|
+
ids: [taskId],
|
|
57
|
+
embeddings: [embedding],
|
|
58
|
+
documents: [taskDescription],
|
|
59
|
+
metadatas: [{
|
|
60
|
+
result: JSON.stringify(result),
|
|
61
|
+
timestamp: new Date().toISOString(),
|
|
62
|
+
...metadata,
|
|
63
|
+
}],
|
|
64
|
+
});
|
|
65
|
+
console.log(`[VectorStore] Inserted vector for task: ${taskId}`);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
console.error('[VectorStore] Failed to insert vector:', error);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Search for similar tasks using semantic similarity.
|
|
74
|
+
*
|
|
75
|
+
* @param queryEmbedding - Vector embedding of the query task
|
|
76
|
+
* @param threshold - Minimum similarity score (0-1, default 0.95)
|
|
77
|
+
* @param topK - Number of results to return (default 1)
|
|
78
|
+
* @returns Array of similar tasks with their results and similarity scores
|
|
79
|
+
*/
|
|
80
|
+
async searchSimilar(queryEmbedding, threshold = 0.95, topK = 1) {
|
|
81
|
+
if (!this.collection) {
|
|
82
|
+
throw new Error('VectorStore not initialized. Call initialize() first.');
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const results = await this.collection.query({
|
|
86
|
+
queryEmbeddings: [queryEmbedding],
|
|
87
|
+
nResults: topK,
|
|
88
|
+
include: [
|
|
89
|
+
chromadb_1.IncludeEnum.Documents,
|
|
90
|
+
chromadb_1.IncludeEnum.Metadatas,
|
|
91
|
+
chromadb_1.IncludeEnum.Distances,
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
const matches = [];
|
|
95
|
+
if (results.ids && results.ids[0]) {
|
|
96
|
+
for (let i = 0; i < results.ids[0].length; i++) {
|
|
97
|
+
// ChromaDB returns distances, convert to similarity (1 - distance for cosine)
|
|
98
|
+
const distance = results.distances?.[0]?.[i] ?? 1;
|
|
99
|
+
const similarity = 1 - distance;
|
|
100
|
+
// Only include results above threshold
|
|
101
|
+
if (similarity >= threshold) {
|
|
102
|
+
const metadata = results.metadatas?.[0]?.[i] || {};
|
|
103
|
+
const resultStr = metadata.result || '{}';
|
|
104
|
+
matches.push({
|
|
105
|
+
id: results.ids[0][i],
|
|
106
|
+
similarity,
|
|
107
|
+
result: JSON.parse(resultStr),
|
|
108
|
+
taskDescription: results.documents?.[0]?.[i] || '',
|
|
109
|
+
metadata: {
|
|
110
|
+
...metadata,
|
|
111
|
+
result: undefined, // Remove result from metadata to avoid duplication
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
console.log(`[VectorStore] Found ${matches.length} matches above threshold ${threshold}`);
|
|
118
|
+
return matches;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
console.error('[VectorStore] Search failed:', error);
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Get the total count of cached tasks.
|
|
127
|
+
*/
|
|
128
|
+
async getCount() {
|
|
129
|
+
if (!this.collection) {
|
|
130
|
+
throw new Error('VectorStore not initialized. Call initialize() first.');
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const count = await this.collection.count();
|
|
134
|
+
return count;
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
console.error('[VectorStore] Failed to get count:', error);
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Clear all cached tasks from the collection.
|
|
143
|
+
*/
|
|
144
|
+
async clear() {
|
|
145
|
+
if (!this.collection) {
|
|
146
|
+
throw new Error('VectorStore not initialized. Call initialize() first.');
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
await this.client.deleteCollection({ name: this.collectionName });
|
|
150
|
+
this.collection = null;
|
|
151
|
+
this.isInitialized = false;
|
|
152
|
+
await this.initialize();
|
|
153
|
+
console.log('[VectorStore] Collection cleared and reinitialized');
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
console.error('[VectorStore] Failed to clear collection:', error);
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Check if the VectorStore is ready to use.
|
|
162
|
+
*/
|
|
163
|
+
isReady() {
|
|
164
|
+
return this.isInitialized && this.collection !== null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
exports.VectorStore = VectorStore;
|
|
168
|
+
//# sourceMappingURL=VectorStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VectorStore.js","sourceRoot":"","sources":["../../src/subconscious/VectorStore.ts"],"names":[],"mappings":";;;AAAA,uCAAiE;AAEjE;;;GAGG;AACH,MAAa,WAAW;IAMtB,YACE,iBAAyB,oBAAoB,E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AAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YAC5C,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;YAC3D,OAAO,CAAC,CAAC;QACX,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC3E,CAAC;QAED,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC;YAClE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;YACvB,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;YAC3B,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;YACxB,OAAO,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAC;QACpE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;YAClE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,UAAU,KAAK,IAAI,CAAC;IACxD,CAAC;CACF;AAtMD,kCAsMC"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Semantic cache using ChromaDB for vector storage
|
|
3
|
+
*/
|
|
4
|
+
import { TaskRequest, TaskResponse, SemanticCacheEntry } from '../types/index.js';
|
|
5
|
+
import { EmbeddingService } from './embeddings.js';
|
|
6
|
+
export declare class SemanticCache {
|
|
7
|
+
private client;
|
|
8
|
+
private collection;
|
|
9
|
+
private collectionName;
|
|
10
|
+
private embeddingService;
|
|
11
|
+
private similarityThreshold;
|
|
12
|
+
constructor(host: string, port: number, collectionName: string, embeddingService: EmbeddingService, similarityThreshold?: number);
|
|
13
|
+
/**
|
|
14
|
+
* Initialize the ChromaDB collection
|
|
15
|
+
*/
|
|
16
|
+
initialize(): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Search for similar cached tasks
|
|
19
|
+
*/
|
|
20
|
+
search(taskRequest: TaskRequest): Promise<SemanticCacheEntry | null>;
|
|
21
|
+
/**
|
|
22
|
+
* Store a new task-response pair in the cache
|
|
23
|
+
*/
|
|
24
|
+
store(taskRequest: TaskRequest, taskResponse: TaskResponse): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Update access count for a cache entry
|
|
27
|
+
*/
|
|
28
|
+
private updateAccessCount;
|
|
29
|
+
/**
|
|
30
|
+
* Clear old cache entries (TTL cleanup)
|
|
31
|
+
*/
|
|
32
|
+
cleanup(ttl: number): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/subconscious/cache.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,gBAAgB,CAAmB;IAC3C,OAAO,CAAC,mBAAmB,CAAS;gBAGlC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,gBAAgB,EAAE,gBAAgB,EAClC,mBAAmB,GAAE,MAAa;IAQpC;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAajC;;OAEG;IACG,MAAM,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAsD1E;;OAEG;IACG,KAAK,CAAC,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BhF;;OAEG;YACW,iBAAiB;IAmB/B;;OAEG;IACG,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAwB1C"}
|