@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,420 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Router = void 0;
|
|
4
|
+
const events_1 = require("events");
|
|
5
|
+
const types_1 = require("../types");
|
|
6
|
+
/**
|
|
7
|
+
* Core routing engine for Inter-Agent Protocol (I.A.P.) messages
|
|
8
|
+
* Handles message reception, agent selection, and error management
|
|
9
|
+
*/
|
|
10
|
+
class Router extends events_1.EventEmitter {
|
|
11
|
+
constructor(wsServer, agentRegistry, config) {
|
|
12
|
+
super();
|
|
13
|
+
this.pendingTasks = new Map();
|
|
14
|
+
this.taskTimeouts = new Map();
|
|
15
|
+
this.wsServer = wsServer;
|
|
16
|
+
this.agentRegistry = agentRegistry;
|
|
17
|
+
this.config = {
|
|
18
|
+
defaultTimeout: config.defaultTimeout || 30000,
|
|
19
|
+
maxRetries: config.maxRetries || 3,
|
|
20
|
+
retryDelay: config.retryDelay || 1000,
|
|
21
|
+
...config,
|
|
22
|
+
};
|
|
23
|
+
this.setupEventHandlers();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Setup event handlers for WebSocket server
|
|
27
|
+
*/
|
|
28
|
+
setupEventHandlers() {
|
|
29
|
+
// Handle incoming messages
|
|
30
|
+
this.wsServer.on('message', ({ connectionId, agentId, message }) => {
|
|
31
|
+
this.handleMessage(connectionId, agentId, message);
|
|
32
|
+
});
|
|
33
|
+
// Handle new connections
|
|
34
|
+
this.wsServer.on('connection', (connection) => {
|
|
35
|
+
console.log(`New connection established: ${connection.id}`);
|
|
36
|
+
});
|
|
37
|
+
// Handle disconnections
|
|
38
|
+
this.wsServer.on('disconnection', ({ connectionId, agentId }) => {
|
|
39
|
+
if (agentId) {
|
|
40
|
+
this.handleAgentDisconnection(agentId);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Handle incoming I.A.P. message
|
|
46
|
+
*/
|
|
47
|
+
async handleMessage(connectionId, agentId, message) {
|
|
48
|
+
try {
|
|
49
|
+
// Validate message structure
|
|
50
|
+
if (!this.validateMessage(message)) {
|
|
51
|
+
const msgId = message?.id || message?.messageId;
|
|
52
|
+
this.sendError(connectionId, 'Invalid message format', msgId);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
console.log(`Received ${message.type} from ${agentId || connectionId}`);
|
|
56
|
+
// Route based on message type
|
|
57
|
+
switch (message.type) {
|
|
58
|
+
case types_1.IAPMessageType.HANDSHAKE:
|
|
59
|
+
await this.handleHandshake(connectionId, message);
|
|
60
|
+
break;
|
|
61
|
+
case types_1.IAPMessageType.TASK_REQUEST:
|
|
62
|
+
await this.handleTaskRequest(connectionId, agentId, message);
|
|
63
|
+
break;
|
|
64
|
+
case types_1.IAPMessageType.TASK_RESPONSE:
|
|
65
|
+
await this.handleTaskResponse(agentId, message);
|
|
66
|
+
break;
|
|
67
|
+
case types_1.IAPMessageType.CAPABILITY_QUERY:
|
|
68
|
+
await this.handleCapabilityQuery(connectionId, message);
|
|
69
|
+
break;
|
|
70
|
+
case types_1.IAPMessageType.HEARTBEAT:
|
|
71
|
+
await this.handleHeartbeat(connectionId, agentId);
|
|
72
|
+
break;
|
|
73
|
+
case types_1.IAPMessageType.ERROR:
|
|
74
|
+
await this.handleErrorMessage(agentId, message);
|
|
75
|
+
break;
|
|
76
|
+
default:
|
|
77
|
+
this.sendError(connectionId, `Unknown message type: ${message.type}`, message.id || message.messageId);
|
|
78
|
+
}
|
|
79
|
+
this.emit('messageProcessed', { connectionId, agentId, message });
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
console.error('Error handling message:', error);
|
|
83
|
+
const msgId = message?.id || message?.messageId;
|
|
84
|
+
this.sendError(connectionId, 'Internal routing error', msgId);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Handle agent handshake (registration)
|
|
89
|
+
*/
|
|
90
|
+
async handleHandshake(connectionId, message) {
|
|
91
|
+
const { agentId, capabilities, metadata } = message.payload;
|
|
92
|
+
if (!agentId || !capabilities) {
|
|
93
|
+
this.sendError(connectionId, 'Handshake requires agentId and capabilities', message.id);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
// Register agent in registry
|
|
97
|
+
const agentInfo = this.agentRegistry.registerAgent(agentId, connectionId, capabilities, metadata);
|
|
98
|
+
// Update WebSocket connection with agent info
|
|
99
|
+
this.wsServer.updateAgentInfo(connectionId, agentId, capabilities.map((c) => c.name));
|
|
100
|
+
// Send handshake acknowledgment
|
|
101
|
+
this.wsServer.sendToConnection(connectionId, {
|
|
102
|
+
type: types_1.IAPMessageType.HANDSHAKE_ACK,
|
|
103
|
+
id: this.generateMessageId(),
|
|
104
|
+
timestamp: Date.now(),
|
|
105
|
+
payload: {
|
|
106
|
+
success: true,
|
|
107
|
+
agentId,
|
|
108
|
+
registeredCapabilities: capabilities.length,
|
|
109
|
+
serverInfo: {
|
|
110
|
+
version: '1.0.0-alpha',
|
|
111
|
+
protocol: 'I.A.P. v1',
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
console.log(`Agent ${agentId} handshake completed`);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Handle task request from agent or external source
|
|
119
|
+
*/
|
|
120
|
+
async handleTaskRequest(connectionId, agentId, message) {
|
|
121
|
+
const taskRequest = message.payload;
|
|
122
|
+
if (!taskRequest.requiredCapabilities || taskRequest.requiredCapabilities.length === 0) {
|
|
123
|
+
this.sendError(connectionId, 'Task request requires capabilities', message.id);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
// Find best agent for the task
|
|
127
|
+
const routingDecision = this.selectAgent(taskRequest);
|
|
128
|
+
if (!routingDecision.success || !routingDecision.selectedAgent) {
|
|
129
|
+
this.sendError(connectionId, `No agent available with capabilities: ${taskRequest.requiredCapabilities.join(', ')}`, message.id);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
// Store pending task
|
|
133
|
+
const taskId = message.id || this.generateMessageId();
|
|
134
|
+
this.pendingTasks.set(taskId, {
|
|
135
|
+
taskId,
|
|
136
|
+
requestorConnectionId: connectionId,
|
|
137
|
+
requestorAgentId: agentId,
|
|
138
|
+
targetAgentId: routingDecision.selectedAgent.agentId,
|
|
139
|
+
request: taskRequest,
|
|
140
|
+
startTime: Date.now(),
|
|
141
|
+
retries: 0,
|
|
142
|
+
});
|
|
143
|
+
// Set timeout for task
|
|
144
|
+
this.setTaskTimeout(taskId);
|
|
145
|
+
// Forward task to selected agent
|
|
146
|
+
const success = this.wsServer.sendToAgent(routingDecision.selectedAgent.agentId, {
|
|
147
|
+
type: types_1.IAPMessageType.TASK_REQUEST,
|
|
148
|
+
id: taskId,
|
|
149
|
+
timestamp: Date.now(),
|
|
150
|
+
payload: taskRequest,
|
|
151
|
+
});
|
|
152
|
+
if (!success) {
|
|
153
|
+
this.handleTaskFailure(taskId, 'Failed to send task to agent');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
// Update agent metrics
|
|
157
|
+
this.agentRegistry.recordTaskStart(routingDecision.selectedAgent.agentId);
|
|
158
|
+
console.log(`Task ${taskId} routed to agent ${routingDecision.selectedAgent.agentId}`);
|
|
159
|
+
this.emit('taskRouted', { taskId, routingDecision });
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Handle task response from agent
|
|
163
|
+
*/
|
|
164
|
+
async handleTaskResponse(agentId, message) {
|
|
165
|
+
const taskId = message.id || message.messageId;
|
|
166
|
+
if (!taskId) {
|
|
167
|
+
console.warn('Received task response without task ID');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const pendingTask = this.pendingTasks.get(taskId);
|
|
171
|
+
if (!pendingTask) {
|
|
172
|
+
console.warn(`Received response for unknown task: ${taskId}`);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
// Clear timeout
|
|
176
|
+
this.clearTaskTimeout(taskId);
|
|
177
|
+
const responseTime = Date.now() - pendingTask.startTime;
|
|
178
|
+
const taskResponse = message.payload;
|
|
179
|
+
// Update agent metrics
|
|
180
|
+
if (agentId) {
|
|
181
|
+
this.agentRegistry.recordTaskCompletion(agentId, responseTime, taskResponse.success);
|
|
182
|
+
}
|
|
183
|
+
// Forward response to requestor
|
|
184
|
+
this.wsServer.sendToConnection(pendingTask.requestorConnectionId, {
|
|
185
|
+
type: types_1.IAPMessageType.TASK_RESPONSE,
|
|
186
|
+
id: taskId,
|
|
187
|
+
timestamp: Date.now(),
|
|
188
|
+
payload: {
|
|
189
|
+
...taskResponse,
|
|
190
|
+
responseTime,
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
// Clean up
|
|
194
|
+
this.pendingTasks.delete(taskId);
|
|
195
|
+
console.log(`Task ${taskId} completed in ${responseTime}ms`);
|
|
196
|
+
this.emit('taskCompleted', { taskId, responseTime, success: taskResponse.success });
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Handle capability query
|
|
200
|
+
*/
|
|
201
|
+
async handleCapabilityQuery(connectionId, message) {
|
|
202
|
+
const { capability } = message.payload;
|
|
203
|
+
let agents;
|
|
204
|
+
if (capability) {
|
|
205
|
+
agents = this.agentRegistry.findAgentsByCapability(capability);
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
agents = this.agentRegistry.getOnlineAgents();
|
|
209
|
+
}
|
|
210
|
+
this.wsServer.sendToConnection(connectionId, {
|
|
211
|
+
type: types_1.IAPMessageType.CAPABILITY_RESPONSE,
|
|
212
|
+
id: this.generateMessageId(),
|
|
213
|
+
timestamp: Date.now(),
|
|
214
|
+
payload: {
|
|
215
|
+
capability,
|
|
216
|
+
agents: agents.map(agent => ({
|
|
217
|
+
agentId: agent.agentId,
|
|
218
|
+
capabilities: agent.capabilities,
|
|
219
|
+
status: agent.status,
|
|
220
|
+
metrics: agent.metrics,
|
|
221
|
+
})),
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Handle heartbeat message
|
|
227
|
+
*/
|
|
228
|
+
async handleHeartbeat(connectionId, agentId) {
|
|
229
|
+
if (agentId) {
|
|
230
|
+
const agent = this.agentRegistry.getAgent(agentId);
|
|
231
|
+
if (agent) {
|
|
232
|
+
agent.lastSeen = Date.now();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
this.wsServer.sendToConnection(connectionId, {
|
|
236
|
+
type: types_1.IAPMessageType.HEARTBEAT_ACK,
|
|
237
|
+
id: this.generateMessageId(),
|
|
238
|
+
timestamp: Date.now(),
|
|
239
|
+
payload: {},
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Handle error message from agent
|
|
244
|
+
*/
|
|
245
|
+
async handleErrorMessage(agentId, message) {
|
|
246
|
+
console.error(`Error from agent ${agentId}:`, message.payload);
|
|
247
|
+
const taskId = message.payload.taskId;
|
|
248
|
+
if (taskId) {
|
|
249
|
+
this.handleTaskFailure(taskId, message.payload.error);
|
|
250
|
+
}
|
|
251
|
+
this.emit('agentError', { agentId, error: message.payload });
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Select best agent for a task
|
|
255
|
+
*/
|
|
256
|
+
selectAgent(taskRequest) {
|
|
257
|
+
const startTime = Date.now();
|
|
258
|
+
// Find agents with required capabilities
|
|
259
|
+
const selectedAgent = this.agentRegistry.findBestAgent(taskRequest.requiredCapabilities);
|
|
260
|
+
if (!selectedAgent) {
|
|
261
|
+
return {
|
|
262
|
+
success: false,
|
|
263
|
+
reason: 'No suitable agent found',
|
|
264
|
+
selectionTime: Date.now() - startTime,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
success: true,
|
|
269
|
+
selectedAgent,
|
|
270
|
+
selectionTime: Date.now() - startTime,
|
|
271
|
+
reason: 'Agent selected based on capabilities and load',
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Handle agent disconnection
|
|
276
|
+
*/
|
|
277
|
+
handleAgentDisconnection(agentId) {
|
|
278
|
+
console.log(`Agent disconnected: ${agentId}`);
|
|
279
|
+
// Unregister agent
|
|
280
|
+
this.agentRegistry.unregisterAgent(agentId);
|
|
281
|
+
// Handle pending tasks for this agent
|
|
282
|
+
this.pendingTasks.forEach((task, taskId) => {
|
|
283
|
+
if (task.targetAgentId === agentId) {
|
|
284
|
+
this.handleTaskFailure(taskId, 'Agent disconnected');
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Handle task failure
|
|
290
|
+
*/
|
|
291
|
+
handleTaskFailure(taskId, reason) {
|
|
292
|
+
const pendingTask = this.pendingTasks.get(taskId);
|
|
293
|
+
if (!pendingTask)
|
|
294
|
+
return;
|
|
295
|
+
this.clearTaskTimeout(taskId);
|
|
296
|
+
// Check if we should retry
|
|
297
|
+
if (pendingTask.retries < this.config.maxRetries) {
|
|
298
|
+
console.log(`Retrying task ${taskId} (attempt ${pendingTask.retries + 1})`);
|
|
299
|
+
pendingTask.retries++;
|
|
300
|
+
setTimeout(() => {
|
|
301
|
+
this.retryTask(taskId);
|
|
302
|
+
}, this.config.retryDelay);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
// Send failure response
|
|
306
|
+
this.wsServer.sendToConnection(pendingTask.requestorConnectionId, {
|
|
307
|
+
type: types_1.IAPMessageType.TASK_RESPONSE,
|
|
308
|
+
id: taskId,
|
|
309
|
+
timestamp: Date.now(),
|
|
310
|
+
payload: {
|
|
311
|
+
success: false,
|
|
312
|
+
error: reason,
|
|
313
|
+
retries: pendingTask.retries,
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
// Update metrics
|
|
317
|
+
this.agentRegistry.recordTaskCompletion(pendingTask.targetAgentId, 0, false);
|
|
318
|
+
// Clean up
|
|
319
|
+
this.pendingTasks.delete(taskId);
|
|
320
|
+
console.error(`Task ${taskId} failed: ${reason}`);
|
|
321
|
+
this.emit('taskFailed', { taskId, reason });
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Retry a failed task
|
|
325
|
+
*/
|
|
326
|
+
async retryTask(taskId) {
|
|
327
|
+
const pendingTask = this.pendingTasks.get(taskId);
|
|
328
|
+
if (!pendingTask)
|
|
329
|
+
return;
|
|
330
|
+
// Find new agent
|
|
331
|
+
const routingDecision = this.selectAgent(pendingTask.request);
|
|
332
|
+
if (!routingDecision.success || !routingDecision.selectedAgent) {
|
|
333
|
+
this.handleTaskFailure(taskId, 'No agent available for retry');
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
// Update target agent
|
|
337
|
+
pendingTask.targetAgentId = routingDecision.selectedAgent.agentId;
|
|
338
|
+
this.setTaskTimeout(taskId);
|
|
339
|
+
// Send task to new agent
|
|
340
|
+
const success = this.wsServer.sendToAgent(routingDecision.selectedAgent.agentId, {
|
|
341
|
+
type: types_1.IAPMessageType.TASK_REQUEST,
|
|
342
|
+
id: taskId,
|
|
343
|
+
timestamp: Date.now(),
|
|
344
|
+
payload: pendingTask.request,
|
|
345
|
+
});
|
|
346
|
+
if (!success) {
|
|
347
|
+
this.handleTaskFailure(taskId, 'Failed to send retry');
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Set timeout for a task
|
|
352
|
+
*/
|
|
353
|
+
setTaskTimeout(taskId) {
|
|
354
|
+
this.clearTaskTimeout(taskId);
|
|
355
|
+
const timeout = setTimeout(() => {
|
|
356
|
+
this.handleTaskFailure(taskId, 'Task timeout');
|
|
357
|
+
}, this.config.defaultTimeout);
|
|
358
|
+
this.taskTimeouts.set(taskId, timeout);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Clear timeout for a task
|
|
362
|
+
*/
|
|
363
|
+
clearTaskTimeout(taskId) {
|
|
364
|
+
const timeout = this.taskTimeouts.get(taskId);
|
|
365
|
+
if (timeout) {
|
|
366
|
+
clearTimeout(timeout);
|
|
367
|
+
this.taskTimeouts.delete(taskId);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Send error message to connection
|
|
372
|
+
*/
|
|
373
|
+
sendError(connectionId, error, messageId) {
|
|
374
|
+
this.wsServer.sendToConnection(connectionId, {
|
|
375
|
+
type: types_1.IAPMessageType.ERROR,
|
|
376
|
+
id: messageId || this.generateMessageId(),
|
|
377
|
+
timestamp: Date.now(),
|
|
378
|
+
payload: {
|
|
379
|
+
error,
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Validate I.A.P. message structure
|
|
385
|
+
*/
|
|
386
|
+
validateMessage(message) {
|
|
387
|
+
return (message &&
|
|
388
|
+
typeof message === 'object' &&
|
|
389
|
+
typeof message.type === 'string' &&
|
|
390
|
+
typeof message.timestamp === 'number' &&
|
|
391
|
+
message.payload !== undefined);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Generate unique message ID
|
|
395
|
+
*/
|
|
396
|
+
generateMessageId() {
|
|
397
|
+
return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Get router statistics
|
|
401
|
+
*/
|
|
402
|
+
getStats() {
|
|
403
|
+
return {
|
|
404
|
+
pendingTasks: this.pendingTasks.size,
|
|
405
|
+
agentStats: this.agentRegistry.getStats(),
|
|
406
|
+
connectionStats: this.wsServer.getStats(),
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Stop the router
|
|
411
|
+
*/
|
|
412
|
+
stop() {
|
|
413
|
+
// Clear all timeouts
|
|
414
|
+
this.taskTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
415
|
+
this.taskTimeouts.clear();
|
|
416
|
+
this.pendingTasks.clear();
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
exports.Router = Router;
|
|
420
|
+
//# sourceMappingURL=router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/core/router.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AAGtC,oCAOkB;AAElB;;;GAGG;AACH,MAAa,MAAO,SAAQ,qBAAY;IAOtC,YACE,QAAyB,EACzB,aAA4B,EAC5B,MAAoB;QAEpB,KAAK,EAAE,CAAC;QARF,iBAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;QACnD,iBAAY,GAAgC,IAAI,GAAG,EAAE,CAAC;QAQ5D,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG;YACZ,cAAc,EAAE,MAAM,CAAC,cAAc,IAAI,KAAK;YAC9C,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,CAAC;YAClC,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,IAAI;YACrC,GAAG,MAAM;SACV,CAAC;QAEF,IAAI,CAAC,kBAAkB,EAAE,CAAC;IAC5B,CAAC;IAED;;OAEG;IACK,kBAAkB;QACxB,2BAA2B;QAC3B,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE;YACjE,IAAI,CAAC,aAAa,CAAC,YAAY,EAAE,OAAO,EAAE,O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SACF,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACK,eAAe,CAAC,OAAY;QAClC,OAAO,CACL,OAAO;YACP,OAAO,OAAO,KAAK,QAAQ;YAC3B,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ;YAChC,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ;YACrC,OAAO,CAAC,OAAO,KAAK,SAAS,CAC9B,CAAC;IACJ,CAAC;IAED;;OAEG;IACK,iBAAiB;QACvB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;IACxE,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,OAAO;YACL,YAAY,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI;YACpC,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE;YACzC,eAAe,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE;SAC1C,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,IAAI;QACT,qBAAqB;QACrB,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;QAC5D,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;QAC1B,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;IAC5B,CAAC;CACF;AA/fD,wBA+fC"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lemma Embedded Mode
|
|
3
|
+
*
|
|
4
|
+
* Zero-config semantic cache for any project.
|
|
5
|
+
* No separate server, no WebSocket, no agents required.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { Lemma } from 'lemma/embed';
|
|
9
|
+
*
|
|
10
|
+
* const lemma = await Lemma.create();
|
|
11
|
+
* const suggest = lemma.wrap(myOpenAIFunction);
|
|
12
|
+
* const result = await suggest('pollo y arroz'); // cached after first call
|
|
13
|
+
*/
|
|
14
|
+
import { EventEmitter } from 'events';
|
|
15
|
+
export interface LemmaConfig {
|
|
16
|
+
/**
|
|
17
|
+
* Storage backend.
|
|
18
|
+
* - 'memory': in-process Map, zero dependencies, resets on restart (default)
|
|
19
|
+
* - 'chroma': ChromaDB + Ollama for persistent semantic cache
|
|
20
|
+
* - 'cloud': Lemma Cloud — managed semantic cache, just add an API key
|
|
21
|
+
*/
|
|
22
|
+
storage?: 'memory' | 'chroma' | 'cloud';
|
|
23
|
+
/**
|
|
24
|
+
* Lemma Cloud API key. Required when storage='cloud'.
|
|
25
|
+
* Get yours at https://lemma.dev
|
|
26
|
+
*/
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Lemma Cloud API URL. Default: 'https://api.lemma.dev'
|
|
30
|
+
*/
|
|
31
|
+
cloudUrl?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Similarity threshold for semantic matching (0–1).
|
|
34
|
+
* Higher = stricter matching. Default: 0.92
|
|
35
|
+
*/
|
|
36
|
+
threshold?: number;
|
|
37
|
+
/**
|
|
38
|
+
* ChromaDB URL. Only used when storage='chroma'.
|
|
39
|
+
* Default: 'http://localhost:8000'
|
|
40
|
+
*/
|
|
41
|
+
chromaUrl?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Ollama URL for embeddings. Only used when storage='chroma'.
|
|
44
|
+
* Default: 'http://localhost:11434'
|
|
45
|
+
*/
|
|
46
|
+
ollamaUrl?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Ollama model for embeddings. Default: 'llama3'
|
|
49
|
+
*/
|
|
50
|
+
ollamaModel?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Collection name in ChromaDB. Default: 'lemma_cache'
|
|
53
|
+
*/
|
|
54
|
+
collection?: string;
|
|
55
|
+
/**
|
|
56
|
+
* TTL in milliseconds. 0 = no expiry. Default: 0
|
|
57
|
+
*/
|
|
58
|
+
ttl?: number;
|
|
59
|
+
/**
|
|
60
|
+
* Max entries in memory cache. Default: 10000
|
|
61
|
+
*/
|
|
62
|
+
maxSize?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Log cache hits/misses to console. Default: false
|
|
65
|
+
*/
|
|
66
|
+
debug?: boolean;
|
|
67
|
+
}
|
|
68
|
+
export interface CacheResult<T = any> {
|
|
69
|
+
data: T;
|
|
70
|
+
fromCache: boolean;
|
|
71
|
+
similarity?: number;
|
|
72
|
+
latencyMs: number;
|
|
73
|
+
}
|
|
74
|
+
export interface LemmaMetrics {
|
|
75
|
+
hits: number;
|
|
76
|
+
misses: number;
|
|
77
|
+
total: number;
|
|
78
|
+
hitRate: number;
|
|
79
|
+
avgLatencyMs: number;
|
|
80
|
+
cacheSize: number;
|
|
81
|
+
}
|
|
82
|
+
export declare class Lemma extends EventEmitter {
|
|
83
|
+
private backend;
|
|
84
|
+
private config;
|
|
85
|
+
private metrics;
|
|
86
|
+
private ready;
|
|
87
|
+
private constructor();
|
|
88
|
+
/**
|
|
89
|
+
* Create and initialize a Lemma instance.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* // Zero config — in-memory cache
|
|
93
|
+
* const lemma = await Lemma.create();
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* // Persistent semantic cache with ChromaDB
|
|
97
|
+
* const lemma = await Lemma.create({
|
|
98
|
+
* storage: 'chroma',
|
|
99
|
+
* threshold: 0.90,
|
|
100
|
+
* });
|
|
101
|
+
*/
|
|
102
|
+
static create(config?: LemmaConfig): Promise<Lemma>;
|
|
103
|
+
private init;
|
|
104
|
+
/**
|
|
105
|
+
* Wrap any async function with semantic caching.
|
|
106
|
+
* The first argument of the function is used as the cache key.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* const cachedSuggest = lemma.wrap(async (ingredients: string) => {
|
|
110
|
+
* return await openai.chat.completions.create({ ... });
|
|
111
|
+
* });
|
|
112
|
+
*
|
|
113
|
+
* await cachedSuggest('pollo y arroz'); // calls OpenAI
|
|
114
|
+
* await cachedSuggest('arroz con pollo'); // returns from cache ⚡
|
|
115
|
+
*/
|
|
116
|
+
wrap<TArgs extends [string, ...any[]], TReturn>(fn: (...args: TArgs) => Promise<TReturn>): (...args: TArgs) => Promise<CacheResult<TReturn>>;
|
|
117
|
+
/**
|
|
118
|
+
* Manually check cache and run function if miss.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* const result = await lemma.run(
|
|
122
|
+
* userMessage,
|
|
123
|
+
* () => openai.chat.completions.create({ ... })
|
|
124
|
+
* );
|
|
125
|
+
* if (result.fromCache) console.log('⚡ Saved an API call!');
|
|
126
|
+
*/
|
|
127
|
+
run<T>(input: string, fn: () => Promise<T>): Promise<CacheResult<T>>;
|
|
128
|
+
/**
|
|
129
|
+
* Manually get a value from cache.
|
|
130
|
+
* Returns null if not found.
|
|
131
|
+
*/
|
|
132
|
+
get(input: string): Promise<CacheResult<any> | null>;
|
|
133
|
+
/**
|
|
134
|
+
* Manually store a value in cache.
|
|
135
|
+
*/
|
|
136
|
+
set(input: string, data: any): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* Get performance metrics.
|
|
139
|
+
*/
|
|
140
|
+
getMetrics(): LemmaMetrics;
|
|
141
|
+
/**
|
|
142
|
+
* Clear all cached entries and reset metrics.
|
|
143
|
+
*/
|
|
144
|
+
clear(): void;
|
|
145
|
+
/**
|
|
146
|
+
* Update similarity threshold at runtime.
|
|
147
|
+
*/
|
|
148
|
+
setThreshold(threshold: number): void;
|
|
149
|
+
private assertReady;
|
|
150
|
+
private log;
|
|
151
|
+
}
|
|
152
|
+
export default Lemma;
|
|
153
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/embed/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;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