@nxuss/lemma 1.18.1 → 1.19.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/bin/init.js +104 -0
- package/dist/cjs/mcp/tools/context-tools.d.ts.map +1 -1
- package/dist/cjs/mcp/tools/context-tools.js +11 -2
- package/dist/cjs/mcp/tools/context-tools.js.map +1 -1
- package/dist/cjs/mcp/tools/squeeze-cache.d.ts.map +1 -1
- package/dist/cjs/mcp/tools/squeeze-cache.js +2 -0
- package/dist/cjs/mcp/tools/squeeze-cache.js.map +1 -1
- package/dist/cjs/mcp/tools/workspace.d.ts.map +1 -1
- package/dist/cjs/mcp/tools/workspace.js +13 -1
- package/dist/cjs/mcp/tools/workspace.js.map +1 -1
- package/dist/cjs/mcp/tools.js +10 -0
- package/dist/cjs/mcp/tools.js.map +1 -1
- package/dist/cjs/mcp/utils.d.ts +22 -2
- package/dist/cjs/mcp/utils.d.ts.map +1 -1
- package/dist/cjs/mcp/utils.js +98 -10
- package/dist/cjs/mcp/utils.js.map +1 -1
- package/dist/cjs/utils/ExecAuditLog.d.ts +27 -0
- package/dist/cjs/utils/ExecAuditLog.d.ts.map +1 -0
- package/dist/cjs/utils/ExecAuditLog.js +53 -0
- package/dist/cjs/utils/ExecAuditLog.js.map +1 -0
- package/dist/esm/mcp/tools/context-tools.d.ts.map +1 -1
- package/dist/esm/mcp/tools/context-tools.js +11 -2
- package/dist/esm/mcp/tools/context-tools.js.map +1 -1
- package/dist/esm/mcp/tools/squeeze-cache.d.ts.map +1 -1
- package/dist/esm/mcp/tools/squeeze-cache.js +3 -1
- package/dist/esm/mcp/tools/squeeze-cache.js.map +1 -1
- package/dist/esm/mcp/tools/workspace.d.ts.map +1 -1
- package/dist/esm/mcp/tools/workspace.js +13 -1
- package/dist/esm/mcp/tools/workspace.js.map +1 -1
- package/dist/esm/mcp/tools.js +11 -1
- package/dist/esm/mcp/tools.js.map +1 -1
- package/dist/esm/mcp/utils.d.ts +22 -2
- package/dist/esm/mcp/utils.d.ts.map +1 -1
- package/dist/esm/mcp/utils.js +97 -10
- package/dist/esm/mcp/utils.js.map +1 -1
- package/dist/esm/utils/ExecAuditLog.d.ts +27 -0
- package/dist/esm/utils/ExecAuditLog.d.ts.map +1 -0
- package/dist/esm/utils/ExecAuditLog.js +45 -0
- package/dist/esm/utils/ExecAuditLog.js.map +1 -0
- package/package.json +3 -1
- package/sdks/crewai/dist/crewai/src/index.d.ts +131 -0
- package/sdks/crewai/dist/crewai/src/index.js +325 -0
- package/sdks/crewai/dist/crewai/src/memory.d.ts +36 -0
- package/sdks/crewai/dist/crewai/src/memory.js +61 -0
- package/sdks/crewai/dist/ts/src/client.d.ts +39 -0
- package/sdks/crewai/dist/ts/src/client.js +124 -0
- package/sdks/crewai/dist/ts/src/errors.d.ts +19 -0
- package/sdks/crewai/dist/ts/src/errors.js +18 -0
- package/sdks/crewai/dist/ts/src/evidence.d.ts +30 -0
- package/sdks/crewai/dist/ts/src/evidence.js +175 -0
- package/sdks/crewai/dist/ts/src/index.d.ts +4 -0
- package/sdks/crewai/dist/ts/src/index.js +27 -0
- package/sdks/crewai/dist/ts/src/types.d.ts +112 -0
- package/sdks/crewai/dist/ts/src/types.js +11 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
+
};
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.LemmaCrew = exports.LemmaCrewAgent = void 0;
|
|
21
|
+
const ws_1 = __importDefault(require("ws"));
|
|
22
|
+
const uuid_1 = require("uuid");
|
|
23
|
+
/**
|
|
24
|
+
* CrewAI Agent integrated with Lemma Router
|
|
25
|
+
*/
|
|
26
|
+
class LemmaCrewAgent {
|
|
27
|
+
constructor(config) {
|
|
28
|
+
this.ws = null;
|
|
29
|
+
this.connected = false;
|
|
30
|
+
this.pendingTasks = new Map();
|
|
31
|
+
this.config = {
|
|
32
|
+
routerUrl: config.routerUrl,
|
|
33
|
+
agentId: config.agentId,
|
|
34
|
+
role: config.role,
|
|
35
|
+
goal: config.goal,
|
|
36
|
+
backstory: config.backstory || '',
|
|
37
|
+
capabilities: config.capabilities || ['crewai'],
|
|
38
|
+
verbose: config.verbose || false,
|
|
39
|
+
allowDelegation: config.allowDelegation !== false,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Connect to Lemma router
|
|
44
|
+
*/
|
|
45
|
+
async connect() {
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
this.ws = new ws_1.default(this.config.routerUrl);
|
|
48
|
+
this.ws.on('open', () => {
|
|
49
|
+
this.log('Connected to Lemma router');
|
|
50
|
+
// Send handshake
|
|
51
|
+
this.send({
|
|
52
|
+
type: 'HANDSHAKE',
|
|
53
|
+
messageId: (0, uuid_1.v4)(),
|
|
54
|
+
timestamp: Date.now(),
|
|
55
|
+
payload: {
|
|
56
|
+
agentId: this.config.agentId,
|
|
57
|
+
agentName: `${this.config.role} (CrewAI)`,
|
|
58
|
+
version: '1.0.0',
|
|
59
|
+
capabilities: this.config.capabilities.map(name => ({
|
|
60
|
+
name,
|
|
61
|
+
version: '1.0.0',
|
|
62
|
+
})),
|
|
63
|
+
metadata: {
|
|
64
|
+
role: this.config.role,
|
|
65
|
+
goal: this.config.goal,
|
|
66
|
+
backstory: this.config.backstory,
|
|
67
|
+
framework: 'crewai',
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
this.ws.on('message', (data) => {
|
|
73
|
+
try {
|
|
74
|
+
const message = JSON.parse(data.toString());
|
|
75
|
+
this.handleMessage(message);
|
|
76
|
+
if (message.type === 'HANDSHAKE_ACK') {
|
|
77
|
+
this.connected = true;
|
|
78
|
+
this.log('Handshake acknowledged');
|
|
79
|
+
resolve();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
console.error('Error parsing message:', error);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
this.ws.on('error', (error) => {
|
|
87
|
+
console.error('WebSocket error:', error);
|
|
88
|
+
if (!this.connected) {
|
|
89
|
+
reject(error);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
this.ws.on('close', () => {
|
|
93
|
+
this.connected = false;
|
|
94
|
+
this.log('Disconnected from router');
|
|
95
|
+
});
|
|
96
|
+
// Connection timeout
|
|
97
|
+
setTimeout(() => {
|
|
98
|
+
if (!this.connected) {
|
|
99
|
+
reject(new Error('Connection timeout'));
|
|
100
|
+
}
|
|
101
|
+
}, 10000);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Disconnect from router
|
|
106
|
+
*/
|
|
107
|
+
disconnect() {
|
|
108
|
+
if (this.ws) {
|
|
109
|
+
this.ws.close();
|
|
110
|
+
this.ws = null;
|
|
111
|
+
this.connected = false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Execute a task
|
|
116
|
+
*/
|
|
117
|
+
async execute(task) {
|
|
118
|
+
if (!this.connected) {
|
|
119
|
+
throw new Error('Not connected to router. Call connect() first.');
|
|
120
|
+
}
|
|
121
|
+
const taskId = (0, uuid_1.v4)();
|
|
122
|
+
this.log(`Executing task: ${task.description}`);
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
this.pendingTasks.set(taskId, { resolve, reject });
|
|
125
|
+
// Send task request to router
|
|
126
|
+
this.send({
|
|
127
|
+
type: 'TASK_REQUEST',
|
|
128
|
+
messageId: (0, uuid_1.v4)(),
|
|
129
|
+
timestamp: Date.now(),
|
|
130
|
+
payload: {
|
|
131
|
+
taskId,
|
|
132
|
+
description: task.description,
|
|
133
|
+
requiredCapabilities: this.config.capabilities,
|
|
134
|
+
parameters: {
|
|
135
|
+
expectedOutput: task.expectedOutput,
|
|
136
|
+
context: task.context,
|
|
137
|
+
allowDelegation: task.allowDelegation ?? this.config.allowDelegation,
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Handle incoming message from router
|
|
145
|
+
*/
|
|
146
|
+
handleMessage(message) {
|
|
147
|
+
switch (message.type) {
|
|
148
|
+
case 'TASK_ASSIGN':
|
|
149
|
+
this.handleTaskAssign(message);
|
|
150
|
+
break;
|
|
151
|
+
case 'TASK_RESPONSE':
|
|
152
|
+
this.handleTaskResponse(message);
|
|
153
|
+
break;
|
|
154
|
+
case 'PING':
|
|
155
|
+
this.send({
|
|
156
|
+
type: 'PONG',
|
|
157
|
+
messageId: (0, uuid_1.v4)(),
|
|
158
|
+
timestamp: Date.now(),
|
|
159
|
+
payload: {
|
|
160
|
+
originalMessageId: message.messageId,
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Handle task assignment from router
|
|
168
|
+
*/
|
|
169
|
+
async handleTaskAssign(message) {
|
|
170
|
+
const { taskId, description, parameters } = message.payload;
|
|
171
|
+
const startTime = Date.now();
|
|
172
|
+
this.log(`Received task assignment: ${description}`);
|
|
173
|
+
try {
|
|
174
|
+
// Execute the task (override this method in subclasses)
|
|
175
|
+
const output = await this.performTask(description, parameters);
|
|
176
|
+
// Send response back to router
|
|
177
|
+
this.send({
|
|
178
|
+
type: 'TASK_RESPONSE',
|
|
179
|
+
messageId: (0, uuid_1.v4)(),
|
|
180
|
+
timestamp: Date.now(),
|
|
181
|
+
payload: {
|
|
182
|
+
taskId,
|
|
183
|
+
success: true,
|
|
184
|
+
result: output,
|
|
185
|
+
executionTime: Date.now() - startTime,
|
|
186
|
+
taskDescription: description,
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
this.send({
|
|
192
|
+
type: 'TASK_RESPONSE',
|
|
193
|
+
messageId: (0, uuid_1.v4)(),
|
|
194
|
+
timestamp: Date.now(),
|
|
195
|
+
payload: {
|
|
196
|
+
taskId,
|
|
197
|
+
success: false,
|
|
198
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
199
|
+
executionTime: Date.now() - startTime,
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Handle task response from router
|
|
206
|
+
*/
|
|
207
|
+
handleTaskResponse(message) {
|
|
208
|
+
const { taskId, success, result, error, executionTime, cached, similarity } = message.payload;
|
|
209
|
+
const pending = this.pendingTasks.get(taskId);
|
|
210
|
+
if (!pending) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this.pendingTasks.delete(taskId);
|
|
214
|
+
if (success) {
|
|
215
|
+
this.log(`Task completed in ${executionTime}ms${cached ? ' (cached)' : ''}`);
|
|
216
|
+
pending.resolve({
|
|
217
|
+
success: true,
|
|
218
|
+
output: result,
|
|
219
|
+
executionTime,
|
|
220
|
+
cached,
|
|
221
|
+
similarity,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
pending.reject(new Error(error || 'Task failed'));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Perform task (override in subclasses)
|
|
230
|
+
*/
|
|
231
|
+
async performTask(description, parameters) {
|
|
232
|
+
// Default implementation - subclasses should override
|
|
233
|
+
return `Task completed: ${description}`;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Send message to router
|
|
237
|
+
*/
|
|
238
|
+
send(message) {
|
|
239
|
+
if (!this.ws || !this.connected) {
|
|
240
|
+
throw new Error('Not connected to router');
|
|
241
|
+
}
|
|
242
|
+
this.ws.send(JSON.stringify(message));
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Log message if verbose
|
|
246
|
+
*/
|
|
247
|
+
log(message) {
|
|
248
|
+
if (this.config.verbose) {
|
|
249
|
+
console.log(`[${this.config.role}] ${message}`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Get agent info
|
|
254
|
+
*/
|
|
255
|
+
getInfo() {
|
|
256
|
+
return {
|
|
257
|
+
agentId: this.config.agentId,
|
|
258
|
+
role: this.config.role,
|
|
259
|
+
goal: this.config.goal,
|
|
260
|
+
backstory: this.config.backstory,
|
|
261
|
+
capabilities: this.config.capabilities,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
exports.LemmaCrewAgent = LemmaCrewAgent;
|
|
266
|
+
class LemmaCrew {
|
|
267
|
+
constructor(config) {
|
|
268
|
+
this.agents = [];
|
|
269
|
+
this.config = config;
|
|
270
|
+
// Create agents
|
|
271
|
+
this.agents = config.agents.map(agentConfig => new LemmaCrewAgent({
|
|
272
|
+
...agentConfig,
|
|
273
|
+
routerUrl: config.routerUrl,
|
|
274
|
+
verbose: config.verbose,
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Connect all agents
|
|
279
|
+
*/
|
|
280
|
+
async connect() {
|
|
281
|
+
await Promise.all(this.agents.map(agent => agent.connect()));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Disconnect all agents
|
|
285
|
+
*/
|
|
286
|
+
disconnect() {
|
|
287
|
+
this.agents.forEach(agent => agent.disconnect());
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Execute a multi-agent workflow
|
|
291
|
+
*/
|
|
292
|
+
async kickoff(options) {
|
|
293
|
+
const { task, process = 'sequential' } = options;
|
|
294
|
+
if (process === 'sequential') {
|
|
295
|
+
// Execute tasks sequentially through agents
|
|
296
|
+
let result = task;
|
|
297
|
+
for (const agent of this.agents) {
|
|
298
|
+
const taskResult = await agent.execute({
|
|
299
|
+
description: result,
|
|
300
|
+
});
|
|
301
|
+
result = taskResult.output || result;
|
|
302
|
+
}
|
|
303
|
+
return result;
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
// Hierarchical - first agent coordinates others
|
|
307
|
+
const manager = this.agents[0];
|
|
308
|
+
return await manager.execute({
|
|
309
|
+
description: task,
|
|
310
|
+
allowDelegation: true,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Get all agents
|
|
316
|
+
*/
|
|
317
|
+
getAgents() {
|
|
318
|
+
return this.agents;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
exports.LemmaCrew = LemmaCrew;
|
|
322
|
+
exports.default = LemmaCrewAgent;
|
|
323
|
+
// Lemma /v2 Verifiable Memory API — a separate surface from LemmaCrewAgent
|
|
324
|
+
// above (that talks to the WebSocket orchestration router). See memory.ts.
|
|
325
|
+
__exportStar(require("./memory"), exports);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { LemmaClientOptions } from '../../ts/src/index';
|
|
2
|
+
import type { MemoryState, VerifiedResult } from '../../ts/src/types';
|
|
3
|
+
export interface LemmaMemoryToolConfig extends Omit<LemmaClientOptions, 'apiKey'> {
|
|
4
|
+
apiKey: string;
|
|
5
|
+
rootDir?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface LemmaMemoryRecallResult {
|
|
8
|
+
state: MemoryState;
|
|
9
|
+
staleFiles?: string[];
|
|
10
|
+
results: VerifiedResult[];
|
|
11
|
+
}
|
|
12
|
+
export type LemmaMemoryToolInput = {
|
|
13
|
+
action: 'remember';
|
|
14
|
+
text: string;
|
|
15
|
+
filePaths?: string[];
|
|
16
|
+
} | {
|
|
17
|
+
action: 'recall';
|
|
18
|
+
query: string;
|
|
19
|
+
filePaths?: string[];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* A CrewAI-style tool: `name`, `description`, and an async `func` an agent
|
|
23
|
+
* calls directly. `func` never collapses the result to a string — a
|
|
24
|
+
* `'recall'` call returns `{ state, staleFiles, results }`, so the crew can
|
|
25
|
+
* branch on `state === 'stale'` instead of parsing prose.
|
|
26
|
+
*/
|
|
27
|
+
export declare class LemmaMemoryTool {
|
|
28
|
+
readonly name = "lemma_memory";
|
|
29
|
+
readonly description: string;
|
|
30
|
+
private readonly client;
|
|
31
|
+
private readonly rootDir;
|
|
32
|
+
constructor(config: LemmaMemoryToolConfig);
|
|
33
|
+
func(input: LemmaMemoryToolInput): Promise<{
|
|
34
|
+
id: string;
|
|
35
|
+
} | LemmaMemoryRecallResult>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LemmaMemoryTool = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Lemma memory tool for CrewAI (Lane H).
|
|
6
|
+
*
|
|
7
|
+
* Separate surface from `LemmaCrewConfig`/task-execution code in `index.ts`
|
|
8
|
+
* (that talks to the WebSocket orchestration router, an unrelated pre-existing
|
|
9
|
+
* product surface) — this wraps the `/v2` Verifiable Memory API on top of
|
|
10
|
+
* `@nxuss/lemma-sdk`. Shaped as a CrewAI-style tool: `name` + `description`
|
|
11
|
+
* + an async `func`, the calling convention CrewAI tools use so an agent can
|
|
12
|
+
* invoke it directly — and, per the plan, `func('recall', ...)` returns
|
|
13
|
+
* `state` as a first-class field, never hidden behind prose the agent has to
|
|
14
|
+
* re-interpret.
|
|
15
|
+
*/
|
|
16
|
+
const index_1 = require("../../ts/src/index");
|
|
17
|
+
const STATE_SEVERITY = {
|
|
18
|
+
contradicted: 3,
|
|
19
|
+
stale: 2,
|
|
20
|
+
unverified: 1,
|
|
21
|
+
fresh: 0,
|
|
22
|
+
};
|
|
23
|
+
function worstState(results) {
|
|
24
|
+
if (results.length === 0)
|
|
25
|
+
return 'unverified';
|
|
26
|
+
return results.reduce((worst, r) => (STATE_SEVERITY[r.state] > STATE_SEVERITY[worst] ? r.state : worst), 'fresh');
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A CrewAI-style tool: `name`, `description`, and an async `func` an agent
|
|
30
|
+
* calls directly. `func` never collapses the result to a string — a
|
|
31
|
+
* `'recall'` call returns `{ state, staleFiles, results }`, so the crew can
|
|
32
|
+
* branch on `state === 'stale'` instead of parsing prose.
|
|
33
|
+
*/
|
|
34
|
+
class LemmaMemoryTool {
|
|
35
|
+
constructor(config) {
|
|
36
|
+
this.name = 'lemma_memory';
|
|
37
|
+
this.description = 'Store and recall verifiable memories about this codebase. Every recall returns a `state` ' +
|
|
38
|
+
'(fresh/stale/unverified/contradicted) proven against the current code — never a guess.';
|
|
39
|
+
const { rootDir, ...clientOptions } = config;
|
|
40
|
+
this.client = new index_1.LemmaClient(clientOptions);
|
|
41
|
+
this.rootDir = rootDir ?? process.cwd();
|
|
42
|
+
}
|
|
43
|
+
async func(input) {
|
|
44
|
+
if (input.action === 'remember') {
|
|
45
|
+
const evidence = (0, index_1.collectEvidence)({ rootDir: this.rootDir, files: input.filePaths ?? [] });
|
|
46
|
+
const res = await this.client.remember({
|
|
47
|
+
claims: [{ text: input.text, filePaths: input.filePaths }],
|
|
48
|
+
evidence,
|
|
49
|
+
});
|
|
50
|
+
return { id: res.id };
|
|
51
|
+
}
|
|
52
|
+
const evidence = (0, index_1.collectEvidence)({ rootDir: this.rootDir, files: input.filePaths ?? [] });
|
|
53
|
+
const res = await this.client.recall({ query: input.query, currentEvidence: evidence });
|
|
54
|
+
return {
|
|
55
|
+
state: worstState(res.results),
|
|
56
|
+
staleFiles: res.results.flatMap((r) => r.staleFiles ?? []),
|
|
57
|
+
results: res.results,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
exports.LemmaMemoryTool = LemmaMemoryTool;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { CreateMemoryRequest, CreateMemoryResponse, RecallRequest, RecallResponse, VerifyRequest, VerifyResponse, ForgetResponse, ScrubRequest, ScrubResponse, UsageResponse } from './types';
|
|
2
|
+
export interface LemmaClientOptions {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
/** Defaults to the production /v2 base URL. Point at a local server in dev. */
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
/** Per-request timeout. Defaults to 10s. */
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
/** Retries for 429 (honoring Retry-After) and transient network/5xx failures. Defaults to 3. */
|
|
9
|
+
maxRetries?: number;
|
|
10
|
+
/** Injectable for tests; defaults to the global fetch. */
|
|
11
|
+
fetchImpl?: typeof fetch;
|
|
12
|
+
/** Injectable for tests; avoids real sleeps in the backoff test. */
|
|
13
|
+
sleep?: (ms: number) => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare class LemmaClient {
|
|
16
|
+
private readonly apiKey;
|
|
17
|
+
private readonly baseUrl;
|
|
18
|
+
private readonly timeoutMs;
|
|
19
|
+
private readonly maxRetries;
|
|
20
|
+
private readonly fetchImpl;
|
|
21
|
+
private readonly sleep;
|
|
22
|
+
constructor(options: LemmaClientOptions);
|
|
23
|
+
/** Store a memory: claims + the evidence they're grounded in (see `collectEvidence`). */
|
|
24
|
+
remember(request: CreateMemoryRequest): Promise<CreateMemoryResponse>;
|
|
25
|
+
/** Search; every result comes back with a verified `state`, never a guess. */
|
|
26
|
+
recall(request: RecallRequest): Promise<RecallResponse>;
|
|
27
|
+
/** Batch-resolve freshness for known ids without a search round-trip. */
|
|
28
|
+
verify(request: VerifyRequest): Promise<VerifyResponse>;
|
|
29
|
+
/** Permanently forget a memory, scoped to your tenant. */
|
|
30
|
+
forget(id: string): Promise<ForgetResponse>;
|
|
31
|
+
/** Stateless secret-scrubbing pass over text or a serialized tool-call. */
|
|
32
|
+
scrub(request: ScrubRequest): Promise<ScrubResponse>;
|
|
33
|
+
/** Real, counted usage for your tenant — never an estimate. */
|
|
34
|
+
usage(): Promise<UsageResponse>;
|
|
35
|
+
/** Masked — never prints the raw key, including via `console.log`. */
|
|
36
|
+
toString(): string;
|
|
37
|
+
private request;
|
|
38
|
+
}
|
|
39
|
+
export default LemmaClient;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LemmaClient = void 0;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const DEFAULT_BASE_URL = 'https://api.lemma.dev/v2';
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 10000;
|
|
7
|
+
const DEFAULT_MAX_RETRIES = 3;
|
|
8
|
+
/** Cap for exponential backoff on transient (network/5xx) failures. */
|
|
9
|
+
const MAX_BACKOFF_MS = 8000;
|
|
10
|
+
function defaultSleep(ms) {
|
|
11
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
|
+
}
|
|
13
|
+
function isRetryableStatus(status) {
|
|
14
|
+
return status === 429 || status >= 500;
|
|
15
|
+
}
|
|
16
|
+
/** LemmaClient never logs or exposes the raw key past construction. */
|
|
17
|
+
function maskKey(key) {
|
|
18
|
+
if (key.length <= 12)
|
|
19
|
+
return '***';
|
|
20
|
+
return `${key.slice(0, 8)}...${key.slice(-4)}`;
|
|
21
|
+
}
|
|
22
|
+
class LemmaClient {
|
|
23
|
+
constructor(options) {
|
|
24
|
+
if (!options.apiKey) {
|
|
25
|
+
throw new errors_1.LemmaSdkError({ code: 'invalid_request', message: 'apiKey is required' });
|
|
26
|
+
}
|
|
27
|
+
this.apiKey = options.apiKey;
|
|
28
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
29
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
30
|
+
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
31
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
32
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
33
|
+
}
|
|
34
|
+
/** Store a memory: claims + the evidence they're grounded in (see `collectEvidence`). */
|
|
35
|
+
async remember(request) {
|
|
36
|
+
return this.request('POST', '/memories', request);
|
|
37
|
+
}
|
|
38
|
+
/** Search; every result comes back with a verified `state`, never a guess. */
|
|
39
|
+
async recall(request) {
|
|
40
|
+
return this.request('POST', '/recall', request);
|
|
41
|
+
}
|
|
42
|
+
/** Batch-resolve freshness for known ids without a search round-trip. */
|
|
43
|
+
async verify(request) {
|
|
44
|
+
return this.request('POST', '/verify', request);
|
|
45
|
+
}
|
|
46
|
+
/** Permanently forget a memory, scoped to your tenant. */
|
|
47
|
+
async forget(id) {
|
|
48
|
+
return this.request('DELETE', `/memories/${encodeURIComponent(id)}`);
|
|
49
|
+
}
|
|
50
|
+
/** Stateless secret-scrubbing pass over text or a serialized tool-call. */
|
|
51
|
+
async scrub(request) {
|
|
52
|
+
return this.request('POST', '/scrub', request);
|
|
53
|
+
}
|
|
54
|
+
/** Real, counted usage for your tenant — never an estimate. */
|
|
55
|
+
async usage() {
|
|
56
|
+
return this.request('GET', '/usage');
|
|
57
|
+
}
|
|
58
|
+
/** Masked — never prints the raw key, including via `console.log`. */
|
|
59
|
+
toString() {
|
|
60
|
+
return `LemmaClient(baseUrl=${this.baseUrl}, apiKey=${maskKey(this.apiKey)})`;
|
|
61
|
+
}
|
|
62
|
+
/** Node's console.log/util.inspect path — masked for the same reason as toString(). */
|
|
63
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
64
|
+
return this.toString();
|
|
65
|
+
}
|
|
66
|
+
async request(method, path, body) {
|
|
67
|
+
let attempt = 0;
|
|
68
|
+
while (true) {
|
|
69
|
+
const controller = new AbortController();
|
|
70
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
71
|
+
let res;
|
|
72
|
+
try {
|
|
73
|
+
res = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
74
|
+
method,
|
|
75
|
+
headers: {
|
|
76
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
},
|
|
79
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
80
|
+
signal: controller.signal,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
const isAbort = err instanceof Error && err.name === 'AbortError';
|
|
86
|
+
if (attempt < this.maxRetries) {
|
|
87
|
+
await this.sleep(backoffMs(attempt));
|
|
88
|
+
attempt++;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
throw new errors_1.LemmaSdkError({
|
|
92
|
+
code: isAbort ? 'timeout' : 'network_error',
|
|
93
|
+
message: isAbort ? `request timed out after ${this.timeoutMs}ms` : `network error: ${err.message}`,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
if (res.ok) {
|
|
98
|
+
return (await res.json());
|
|
99
|
+
}
|
|
100
|
+
const bodyJson = (await res.json().catch(() => null));
|
|
101
|
+
const apiError = bodyJson?.error;
|
|
102
|
+
if (isRetryableStatus(res.status) && attempt < this.maxRetries) {
|
|
103
|
+
const retryAfterHeader = res.headers.get('Retry-After');
|
|
104
|
+
const waitMs = retryAfterHeader ? Number(retryAfterHeader) * 1000 : backoffMs(attempt);
|
|
105
|
+
await this.sleep(Number.isFinite(waitMs) && waitMs > 0 ? waitMs : backoffMs(attempt));
|
|
106
|
+
attempt++;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
throw new errors_1.LemmaSdkError({
|
|
110
|
+
code: apiError?.code ?? 'internal',
|
|
111
|
+
message: apiError?.message ?? `request failed with status ${res.status}`,
|
|
112
|
+
status: res.status,
|
|
113
|
+
field: apiError?.field,
|
|
114
|
+
retryAfter: res.headers.get('Retry-After') ? Number(res.headers.get('Retry-After')) : undefined,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.LemmaClient = LemmaClient;
|
|
120
|
+
/** Exponential backoff (200ms, 400ms, 800ms, ...) capped at MAX_BACKOFF_MS. */
|
|
121
|
+
function backoffMs(attempt) {
|
|
122
|
+
return Math.min(200 * 2 ** attempt, MAX_BACKOFF_MS);
|
|
123
|
+
}
|
|
124
|
+
exports.default = LemmaClient;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { LemmaErrorCode } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Typed error thrown by every LemmaClient method. Carries the API's stable
|
|
4
|
+
* `code` so callers can branch on it instead of parsing `message`.
|
|
5
|
+
*/
|
|
6
|
+
export declare class LemmaSdkError extends Error {
|
|
7
|
+
readonly code: LemmaErrorCode | 'network_error' | 'timeout';
|
|
8
|
+
readonly status?: number;
|
|
9
|
+
readonly field?: string;
|
|
10
|
+
/** Present on `rate_limited` — seconds the server asked the client to wait. */
|
|
11
|
+
readonly retryAfter?: number;
|
|
12
|
+
constructor(opts: {
|
|
13
|
+
code: LemmaErrorCode | 'network_error' | 'timeout';
|
|
14
|
+
message: string;
|
|
15
|
+
status?: number;
|
|
16
|
+
field?: string;
|
|
17
|
+
retryAfter?: number;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LemmaSdkError = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Typed error thrown by every LemmaClient method. Carries the API's stable
|
|
6
|
+
* `code` so callers can branch on it instead of parsing `message`.
|
|
7
|
+
*/
|
|
8
|
+
class LemmaSdkError extends Error {
|
|
9
|
+
constructor(opts) {
|
|
10
|
+
super(opts.message);
|
|
11
|
+
this.name = 'LemmaSdkError';
|
|
12
|
+
this.code = opts.code;
|
|
13
|
+
this.status = opts.status;
|
|
14
|
+
this.field = opts.field;
|
|
15
|
+
this.retryAfter = opts.retryAfter;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.LemmaSdkError = LemmaSdkError;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Evidence } from './types';
|
|
2
|
+
/** sha256 of a whole file's utf8 content. `'MISSING'` if it can't be read. */
|
|
3
|
+
export declare function hashFile(rootDir: string, relPath: string): string;
|
|
4
|
+
/** Token-stream normalization: strips comments/whitespace, keeps semantics. */
|
|
5
|
+
export declare function normalizeForFreshness(source: string): string;
|
|
6
|
+
/** Raw + normalized sha256 pair for one symbol. `'MISSING'`/`'MISSING'` if unreadable or not found. */
|
|
7
|
+
export declare function hashSymbol(rootDir: string, relPath: string, symbolName: string): {
|
|
8
|
+
raw: string;
|
|
9
|
+
normalized: string;
|
|
10
|
+
};
|
|
11
|
+
export interface CollectEvidenceOptions {
|
|
12
|
+
/** Directory relative paths are resolved against. Defaults to `process.cwd()`. */
|
|
13
|
+
rootDir?: string;
|
|
14
|
+
/** Relative file paths to hash whole. */
|
|
15
|
+
files?: string[];
|
|
16
|
+
/** Symbols to hash (raw + normalized), one file per symbol. */
|
|
17
|
+
symbols?: Array<{
|
|
18
|
+
filePath: string;
|
|
19
|
+
symbolName: string;
|
|
20
|
+
}>;
|
|
21
|
+
branch?: string;
|
|
22
|
+
commit?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Builds an `Evidence` bundle the way a client is expected to: hash the files
|
|
26
|
+
* and symbols it's about to make claims about, right before sending them.
|
|
27
|
+
* Identical algorithm to the local MCP Brain's `LocalFsResolver` — see the
|
|
28
|
+
* module doc.
|
|
29
|
+
*/
|
|
30
|
+
export declare function collectEvidence(options: CollectEvidenceOptions): Evidence;
|