@nxuss/lemma 0.7.9 → 0.8.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/README.md +31 -5
- package/dist/cjs/cli/lemma-proxy.d.ts.map +1 -1
- package/dist/cjs/cli/lemma-proxy.js +53 -7
- package/dist/cjs/cli/lemma-proxy.js.map +1 -1
- package/dist/cjs/mcp/index.js +1 -0
- package/dist/cjs/mcp/index.js.map +1 -1
- package/dist/cjs/mcp/prompts.d.ts +1 -0
- package/dist/cjs/mcp/prompts.d.ts.map +1 -1
- package/dist/cjs/mcp/prompts.js +58 -1
- package/dist/cjs/mcp/prompts.js.map +1 -1
- package/dist/cjs/mcp/resources.d.ts.map +1 -1
- package/dist/cjs/mcp/resources.js +3 -2
- package/dist/cjs/mcp/resources.js.map +1 -1
- package/dist/cjs/mcp/tools.d.ts.map +1 -1
- package/dist/cjs/mcp/tools.js +288 -10
- package/dist/cjs/mcp/tools.js.map +1 -1
- package/dist/cjs/mcp/utils.d.ts.map +1 -1
- package/dist/cjs/mcp/utils.js +2 -2
- package/dist/cjs/mcp/utils.js.map +1 -1
- package/dist/cjs/utils/reportSavings.d.ts.map +1 -1
- package/dist/cjs/utils/reportSavings.js +2 -2
- package/dist/cjs/utils/reportSavings.js.map +1 -1
- package/dist/esm/cli/lemma-proxy.d.ts.map +1 -1
- package/dist/esm/cli/lemma-proxy.js +53 -7
- package/dist/esm/cli/lemma-proxy.js.map +1 -1
- package/dist/esm/mcp/index.js +2 -1
- package/dist/esm/mcp/index.js.map +1 -1
- package/dist/esm/mcp/prompts.d.ts +1 -0
- package/dist/esm/mcp/prompts.d.ts.map +1 -1
- package/dist/esm/mcp/prompts.js +57 -0
- package/dist/esm/mcp/prompts.js.map +1 -1
- package/dist/esm/mcp/resources.d.ts.map +1 -1
- package/dist/esm/mcp/resources.js +3 -2
- package/dist/esm/mcp/resources.js.map +1 -1
- package/dist/esm/mcp/tools.d.ts.map +1 -1
- package/dist/esm/mcp/tools.js +288 -10
- package/dist/esm/mcp/tools.js.map +1 -1
- package/dist/esm/mcp/utils.d.ts.map +1 -1
- package/dist/esm/mcp/utils.js +2 -2
- package/dist/esm/mcp/utils.js.map +1 -1
- package/dist/esm/utils/reportSavings.d.ts.map +1 -1
- package/dist/esm/utils/reportSavings.js +2 -2
- package/dist/esm/utils/reportSavings.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/mcp/prompts.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LEMMA_SYSTEM_PROMPT = void 0;
|
|
3
|
+
exports.LEMMA_TURBOMODE_PROMPT = exports.LEMMA_SYSTEM_PROMPT = void 0;
|
|
4
4
|
exports.setupPromptsHandlers = setupPromptsHandlers;
|
|
5
5
|
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
6
6
|
exports.LEMMA_SYSTEM_PROMPT = `You are connected to Lemma — an intelligent local-first AI gateway.
|
|
@@ -51,6 +51,44 @@ You never need to manually sanitize file content.
|
|
|
51
51
|
- \`lemma://stats/usage\` — token savings report.
|
|
52
52
|
|
|
53
53
|
Remember: the user hired YOU to be autonomous. Act like it.`;
|
|
54
|
+
exports.LEMMA_TURBOMODE_PROMPT = `You are operating in LEMMA TURBOMODE. Your goal: multiply the user's LLM membership 50x by spending 50x fewer tokens per task. Every token counts. Every cache hit is a membership extension.
|
|
55
|
+
|
|
56
|
+
## MANDATORY TURBOMODE RULES — VIOLATE THESE AND YOU WASTE THE USER'S MONEY
|
|
57
|
+
|
|
58
|
+
### 0. Before ANYTHING → check token_budget
|
|
59
|
+
Every 5 turns, call \`token_budget\` to check your consumption. If multiplier drops below 10x, optimize harder.
|
|
60
|
+
|
|
61
|
+
### 1. Before sending ANY code → call turbosqueeze
|
|
62
|
+
BEFORE including ANY code block in your response, run it through \`turbosqueeze\` first. Strip comments, collapse whitespace, remove imports. A 500-line file becomes 50 lines. This is your #1 token saver.
|
|
63
|
+
|
|
64
|
+
### 2. Before reasoning → call smarter_cache (threshold 0.75)
|
|
65
|
+
NEVER reason from scratch. Call \`smarter_cache\` with the user's exact question. If similarity >= 75%, return the cached answer INSTANTLY. Zero cloud tokens spent. Only reason if you get a MISS.
|
|
66
|
+
|
|
67
|
+
### 3. Before every new turn → call compress_context
|
|
68
|
+
At the start of any extended interaction, call \`compress_context\` on the full message history. Keep only the last 3 turns intact. Summarize everything before that into 2 sentences. This keeps your context window lean.
|
|
69
|
+
|
|
70
|
+
### 4. Before reading files → call get_ast_hologram
|
|
71
|
+
NEVER read files blindly. Always call \`get_ast_hologram\` first to locate the exact symbols you need. Then read only those specific files. Each unnecessary file read wastes 1000+ tokens.
|
|
72
|
+
|
|
73
|
+
### 5. After every solution → call store_memory automatically
|
|
74
|
+
Every bug fix, feature, or answer MUST be stored via \`store_memory\`. This creates a permanent cache hit for future sessions. The first time costs tokens; every time after is FREE.
|
|
75
|
+
|
|
76
|
+
### 6. Answer concisely — no fluff
|
|
77
|
+
- No "Sure, I can help you with that" — just do it.
|
|
78
|
+
- No explanation of what you did — unless asked.
|
|
79
|
+
- No markdown formatting in internal responses.
|
|
80
|
+
- No repeating the user's question back to them.
|
|
81
|
+
|
|
82
|
+
### 7. Use batch_tool_calls aggressively
|
|
83
|
+
Any set of independent operations (read 3 files, search 2 patterns, check cache for 2 questions) — use \`batch_tool_calls\` to run them in parallel. Single round-trip > multiple sequential calls.
|
|
84
|
+
|
|
85
|
+
## TURBOMODE SCORING
|
|
86
|
+
- Cache HIT = perfect score (0 tokens spent)
|
|
87
|
+
- Cache MISS + compress = good score (< 100 tokens spent on overhead)
|
|
88
|
+
- Reasoning from scratch = bad score (only when absolutely necessary)
|
|
89
|
+
- Reading full files without hologram = FAIL (wasteful)
|
|
90
|
+
|
|
91
|
+
Remember: this user has a deadline. Every token you save is time and money. Make every token count.`;
|
|
54
92
|
function setupPromptsHandlers(server) {
|
|
55
93
|
server.setRequestHandler(types_js_1.ListPromptsRequestSchema, async () => {
|
|
56
94
|
return {
|
|
@@ -60,6 +98,11 @@ function setupPromptsHandlers(server) {
|
|
|
60
98
|
description: "Lemma Autopilot: mandatory behavioral instructions for the AI assistant. Load this prompt to make all Lemma tools fire automatically with zero user friction.",
|
|
61
99
|
arguments: [],
|
|
62
100
|
},
|
|
101
|
+
{
|
|
102
|
+
name: "lemma-turbomode",
|
|
103
|
+
description: "⚠️ LEMMA TURBOMODE: Extreme token optimization. Load this prompt to multiply your LLM membership 50x by aggressively compressing prompts, caching everything, and minimizing every token spent. Use for long/deadline-driven projects.",
|
|
104
|
+
arguments: [],
|
|
105
|
+
},
|
|
63
106
|
],
|
|
64
107
|
};
|
|
65
108
|
});
|
|
@@ -78,6 +121,20 @@ function setupPromptsHandlers(server) {
|
|
|
78
121
|
],
|
|
79
122
|
};
|
|
80
123
|
}
|
|
124
|
+
if (request.params.name === "lemma-turbomode") {
|
|
125
|
+
return {
|
|
126
|
+
description: "Lemma TurboMode — Extreme Token Optimization",
|
|
127
|
+
messages: [
|
|
128
|
+
{
|
|
129
|
+
role: "user",
|
|
130
|
+
content: {
|
|
131
|
+
type: "text",
|
|
132
|
+
text: exports.LEMMA_TURBOMODE_PROMPT,
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
],
|
|
136
|
+
};
|
|
137
|
+
}
|
|
81
138
|
throw new Error(`Unknown prompt: ${request.params.name}`);
|
|
82
139
|
});
|
|
83
140
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/mcp/prompts.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/mcp/prompts.ts"],"names":[],"mappings":";;;AA2FA,oDAiDC;AA3ID,iEAAsG;AAEzF,QAAA,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4D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
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/mcp/resources.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;
|
|
1
|
+
{"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/mcp/resources.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAQnE,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CA2D3D"}
|
|
@@ -7,6 +7,7 @@ exports.setupResourcesHandlers = setupResourcesHandlers;
|
|
|
7
7
|
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
8
8
|
const fs_1 = __importDefault(require("fs"));
|
|
9
9
|
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const os_1 = __importDefault(require("os"));
|
|
10
11
|
const axios_1 = __importDefault(require("axios"));
|
|
11
12
|
const utils_1 = require("./utils");
|
|
12
13
|
function setupResourcesHandlers(server) {
|
|
@@ -127,7 +128,7 @@ async function handleProjectContext(uri) {
|
|
|
127
128
|
let memoryCount = 0;
|
|
128
129
|
let monthlyTokens = 'N/A';
|
|
129
130
|
try {
|
|
130
|
-
const statsFile = path_1.default.join(
|
|
131
|
+
const statsFile = path_1.default.join(os_1.default.homedir(), '.lemma-cache/stats.json');
|
|
131
132
|
const stats = JSON.parse(fs_1.default.readFileSync(statsFile, 'utf8'));
|
|
132
133
|
monthlyTokens = String(stats.monthlyTokens || stats.totalTokens || 'N/A');
|
|
133
134
|
}
|
|
@@ -154,7 +155,7 @@ async function handleProjectContext(uri) {
|
|
|
154
155
|
};
|
|
155
156
|
}
|
|
156
157
|
async function handleStatsUsage(uri) {
|
|
157
|
-
const statsFile = path_1.default.join(
|
|
158
|
+
const statsFile = path_1.default.join(os_1.default.homedir(), ".lemma-cache/stats.json");
|
|
158
159
|
try {
|
|
159
160
|
const stats = JSON.parse(fs_1.default.readFileSync(statsFile, "utf8"));
|
|
160
161
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/mcp/resources.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"resources.js","sourceRoot":"","sources":["../../../src/mcp/resources.ts"],"names":[],"mappings":";;;;;AAQA,wDA2DC;AAlED,iEAA2G;AAC3G,4CAAoB;AACpB,gDAAwB;AACxB,4CAAoB;AACpB,kDAA0B;AAC1B,mCAAiD;AAEjD,SAAgB,sBAAsB,CAAC,MAAc;IACnD,MAAM,CAAC,iBAAiB,CAAC,qCAA0B,EAAE,KAAK,IAAI,EAAE;QAC9D,OAAO;YACL,SAAS,EAAE;gBACT;oBACE,GAAG,EAAE,yBAAyB;oBAC9B,IAAI,EAAE,oBAAoB;oBAC1B,WAAW,EAAE,kFAAkF;oBAC/F,QAAQ,EAAE,eAAe;iBAC1B;gBACD;oBACE,GAAG,EAAE,qBAAqB;oBAC1B,IAAI,EAAE,0BAA0B;oBAChC,WAAW,EAAE,qEAAqE;oBAClF,QAAQ,EAAE,kBAAkB;iBAC7B;gBACD;oBACE,GAAG,EAAE,yBAAyB;oBAC9B,IAAI,EAAE,uBAAuB;oBAC7B,WAAW,EAAE,2FAA2F;oBACxG,QAAQ,EAAE,eAAe;iBAC1B;gBACD;oBACE,GAAG,EAAE,4BAA4B;oBACjC,IAAI,EAAE,uCAAuC;oBAC7C,WAAW,EAAE,oHAAoH;oBACjI,QAAQ,EAAE,eAAe;iBAC1B;gBACD;oBACE,GAAG,EAAE,6BAA6B;oBAClC,IAAI,EAAE,wCAAwC;oBAC9C,WAAW,EAAE,4HAA4H;oBACzI,QAAQ,EAAE,eAAe;iBAC1B;aACF;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,iBAAiB,CAAC,oCAAyB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QACpE,MAAM,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,MAA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,CAAC,CAAC,CAAC;QACL,CAAC;QAED,OAAO;YACL,QAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;SAC/D,CAAC;IACJ,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,IAAA,gBAAQ,EAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;QACvC,OAAO;YACL,QAAQ,EAAE;gBACR;oBACE,GAAG;oBACH,QAAQ,EAAE,eAAe;oBACzB,IAAI,EAAE,0DAA0D,KAAK,CAAC,OAAO,2BAA2B;iBACzG;aACF;SACF,CAAC;IACJ,CAAC;AACH,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/mcp/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;
|
|
1
|
+
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/mcp/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAqXnE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC1B,MAAM,EAAE,IAAI,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,GAC1C,IAAI,CA2CN"}
|
package/dist/cjs/mcp/tools.js
CHANGED
|
@@ -313,6 +313,57 @@ const toolDefinitions = [
|
|
|
313
313
|
required: ["calls"],
|
|
314
314
|
},
|
|
315
315
|
},
|
|
316
|
+
{
|
|
317
|
+
name: "turbosqueeze",
|
|
318
|
+
description: "COMPRIME prompts hasta 90%. Elimina comentarios, imports redundantes, whitespace excesivo, y compacta JSON. Usar ANTES de enviar código largo al LLM para maximizar ahorro de tokens.",
|
|
319
|
+
inputSchema: {
|
|
320
|
+
type: "object",
|
|
321
|
+
properties: {
|
|
322
|
+
text: { type: "string", description: "El texto/prompt a comprimir" },
|
|
323
|
+
stripComments: { type: "boolean", description: "Eliminar comentarios del código", default: true },
|
|
324
|
+
stripImports: { type: "boolean", description: "Eliminar imports/requires", default: true },
|
|
325
|
+
compactJson: { type: "boolean", description: "Compactar JSON a 1 línea", default: true },
|
|
326
|
+
},
|
|
327
|
+
required: ["text"],
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
{
|
|
331
|
+
name: "compress_context",
|
|
332
|
+
description: "Comprime el historial de conversación: resume turns antiguos vía Ollama, mantiene solo los últimos N intactos. Reduce contexto 70-80%. USAR antes de cada turno extendido.",
|
|
333
|
+
inputSchema: {
|
|
334
|
+
type: "object",
|
|
335
|
+
properties: {
|
|
336
|
+
messages: {
|
|
337
|
+
type: "array",
|
|
338
|
+
items: { type: "object" },
|
|
339
|
+
description: "Array de mensajes del historial con role + content",
|
|
340
|
+
},
|
|
341
|
+
keepRecent: { type: "number", description: "Número de turns recientes a mantener intactos", default: 3 },
|
|
342
|
+
},
|
|
343
|
+
required: ["messages"],
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
name: "smarter_cache",
|
|
348
|
+
description: "Cache predictivo con threshold bajo (75%). Busca en The Brain antes de cualquier razonamiento. Si hay hit >= 75%, devuelve respuesta instantánea sin gastar tokens en LLM.",
|
|
349
|
+
inputSchema: {
|
|
350
|
+
type: "object",
|
|
351
|
+
properties: {
|
|
352
|
+
query: { type: "string", description: "La pregunta o task description" },
|
|
353
|
+
context: { type: "string", description: "Contexto adicional opcional" },
|
|
354
|
+
threshold: { type: "number", description: "Threshold de similitud (0.0-1.0, default: 0.75)", default: 0.75 },
|
|
355
|
+
},
|
|
356
|
+
required: ["query"],
|
|
357
|
+
},
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
name: "token_budget",
|
|
361
|
+
description: "Muestra el dashboard de consumo: multiplicador actual de membresía, tokens ahorrados, tools usadas, y recomendaciones para optimizar más. Consultar periódicamente para auto-regular consumo.",
|
|
362
|
+
inputSchema: {
|
|
363
|
+
type: "object",
|
|
364
|
+
properties: {},
|
|
365
|
+
},
|
|
366
|
+
},
|
|
316
367
|
];
|
|
317
368
|
const toolHandlers = {
|
|
318
369
|
scrub_privacy: handleScrubPrivacy,
|
|
@@ -336,6 +387,10 @@ const toolHandlers = {
|
|
|
336
387
|
prune_conversation_history: handlePruneConversationHistory,
|
|
337
388
|
diff_only: handleDiffOnly,
|
|
338
389
|
batch_tool_calls: handleBatchToolCalls,
|
|
390
|
+
turbosqueeze: handleTurboSqueeze,
|
|
391
|
+
compress_context: handleCompressContext,
|
|
392
|
+
smarter_cache: handleSmarterCache,
|
|
393
|
+
token_budget: handleTokenBudget,
|
|
339
394
|
};
|
|
340
395
|
function setupToolsHandlers(server, onToolCall) {
|
|
341
396
|
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
|
|
@@ -903,7 +958,7 @@ async function handleValidatePatchSandbox(args) {
|
|
|
903
958
|
try {
|
|
904
959
|
fs_1.default.mkdirSync(sandboxDir, { recursive: true });
|
|
905
960
|
fs_1.default.writeFileSync(sandboxFile, patchedContent, "utf8");
|
|
906
|
-
// Step 1: Try tsc --noEmit validation
|
|
961
|
+
// Step 1: Try tsc --noEmit validation on the sandbox file only
|
|
907
962
|
const tsconfigPath = path_1.default.join(workspaceRoot, "tsconfig.json");
|
|
908
963
|
let tscResult = {
|
|
909
964
|
success: true,
|
|
@@ -911,17 +966,28 @@ async function handleValidatePatchSandbox(args) {
|
|
|
911
966
|
};
|
|
912
967
|
if (fs_1.default.existsSync(tsconfigPath) && filePath.match(/\.tsx?$/)) {
|
|
913
968
|
try {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
969
|
+
// Create a minimal tsconfig in the sandbox that includes only the patched file
|
|
970
|
+
const sandboxTsconfig = {
|
|
971
|
+
compilerOptions: {
|
|
972
|
+
target: "ESNext",
|
|
973
|
+
module: "ESNext",
|
|
974
|
+
moduleResolution: "node",
|
|
975
|
+
strict: true,
|
|
976
|
+
noEmit: true,
|
|
977
|
+
skipLibCheck: true,
|
|
978
|
+
esModuleInterop: true,
|
|
979
|
+
allowJs: true,
|
|
980
|
+
jsx: "react-jsx",
|
|
981
|
+
},
|
|
982
|
+
include: [path_1.default.basename(filePath)],
|
|
983
|
+
};
|
|
984
|
+
const sandboxTsconfigPath = path_1.default.join(sandboxDir, "tsconfig.json");
|
|
985
|
+
fs_1.default.writeFileSync(sandboxTsconfigPath, JSON.stringify(sandboxTsconfig, null, 2));
|
|
986
|
+
const tscOut = (0, child_process_1.execSync)(`npx tsc --noEmit --project "${sandboxTsconfigPath}" 2>&1 | head -40 || true`, { timeout: 20000, encoding: "utf8", cwd: sandboxDir });
|
|
922
987
|
const relevantErrors = tscOut
|
|
923
988
|
.split("\n")
|
|
924
|
-
.filter((l) => l.includes(
|
|
989
|
+
.filter((l) => l.includes("error TS"))
|
|
990
|
+
.filter(Boolean);
|
|
925
991
|
tscResult = {
|
|
926
992
|
success: relevantErrors.length === 0,
|
|
927
993
|
output: relevantErrors.length > 0
|
|
@@ -1189,4 +1255,216 @@ async function handleBatchToolCalls(args) {
|
|
|
1189
1255
|
content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
|
|
1190
1256
|
};
|
|
1191
1257
|
}
|
|
1258
|
+
// ── TurboSqueeze ─────────────────────────────────────────────────
|
|
1259
|
+
async function handleTurboSqueeze(args) {
|
|
1260
|
+
const text = args?.text;
|
|
1261
|
+
const stripComments = args?.stripComments !== false;
|
|
1262
|
+
const stripImports = args?.stripImports !== false;
|
|
1263
|
+
const compactJson = args?.compactJson !== false;
|
|
1264
|
+
if (!text)
|
|
1265
|
+
throw new Error("text is required");
|
|
1266
|
+
let squeezed = text;
|
|
1267
|
+
// Strip multi-line comments
|
|
1268
|
+
if (stripComments) {
|
|
1269
|
+
squeezed = squeezed.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
1270
|
+
squeezed = squeezed.replace(/\/\/.*$/gm, '');
|
|
1271
|
+
}
|
|
1272
|
+
// Remove empty lines and trim whitespace
|
|
1273
|
+
squeezed = squeezed.replace(/^\s*[\r\n]/gm, '\n');
|
|
1274
|
+
squeezed = squeezed.replace(/^[ \t]+/gm, ' ');
|
|
1275
|
+
squeezed = squeezed.replace(/[ \t]+$/gm, '');
|
|
1276
|
+
// Strip imports
|
|
1277
|
+
if (stripImports) {
|
|
1278
|
+
squeezed = squeezed.replace(/^import\s+[\s\S]*?from\s+['"][\w@\/\.-]+['"];?\s*$/gm, '');
|
|
1279
|
+
squeezed = squeezed.replace(/^import\s+['"][\w@\/\.-]+['"];?\s*$/gm, '');
|
|
1280
|
+
squeezed = squeezed.replace(/^const\s+\w+\s*=\s*require\(['"][\w@\/\.-]+['"]\);?\s*$/gm, '');
|
|
1281
|
+
squeezed = squeezed.replace(/^require\(['"][\w@\/\.-]+['"]\);?\s*$/gm, '');
|
|
1282
|
+
}
|
|
1283
|
+
// Compact JSON
|
|
1284
|
+
if (compactJson) {
|
|
1285
|
+
squeezed = squeezed.replace(/"\s*:\s*/g, '":');
|
|
1286
|
+
squeezed = squeezed.replace(/,\s*"/g, ',"');
|
|
1287
|
+
squeezed = squeezed.replace(/\[\s+/g, '[');
|
|
1288
|
+
squeezed = squeezed.replace(/\s+\]/g, ']');
|
|
1289
|
+
squeezed = squeezed.replace(/\{\s+/g, '{');
|
|
1290
|
+
squeezed = squeezed.replace(/\s+\}/g, '}');
|
|
1291
|
+
}
|
|
1292
|
+
// Compact consecutive blank lines
|
|
1293
|
+
squeezed = squeezed.replace(/\n{3,}/g, '\n\n').trim();
|
|
1294
|
+
const ratio = text.length > 0 ? ((1 - squeezed.length / text.length) * 100).toFixed(1) : "0";
|
|
1295
|
+
const saved = Math.max(0, text.length - squeezed.length);
|
|
1296
|
+
try {
|
|
1297
|
+
const { reportSavings } = await Promise.resolve().then(() => __importStar(require("../utils/reportSavings")));
|
|
1298
|
+
reportSavings({ source: "contextSqueeze", charsBefore: text.length, charsAfter: squeezed.length, toolName: "turbosqueeze" });
|
|
1299
|
+
}
|
|
1300
|
+
catch { }
|
|
1301
|
+
return {
|
|
1302
|
+
content: [{
|
|
1303
|
+
type: "text",
|
|
1304
|
+
text: `[TurboSqueeze: ${ratio}% reduction (${saved} chars / ~${Math.floor(saved / 4)} tokens saved)]\n\n${squeezed}`,
|
|
1305
|
+
}],
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
// ── Compress Context ─────────────────────────────────────────────
|
|
1309
|
+
async function handleCompressContext(args) {
|
|
1310
|
+
const messages = args?.messages;
|
|
1311
|
+
const keepRecent = args?.keepRecent || 3;
|
|
1312
|
+
if (!messages || !Array.isArray(messages))
|
|
1313
|
+
throw new Error("messages array is required");
|
|
1314
|
+
if (messages.length <= keepRecent + 1) {
|
|
1315
|
+
return {
|
|
1316
|
+
content: [{
|
|
1317
|
+
type: "text",
|
|
1318
|
+
text: JSON.stringify({ messages, tokensSavedEstimate: 0, note: "Historial muy corto — no se necesita compresión." }, null, 2),
|
|
1319
|
+
}],
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
const recent = messages.slice(-keepRecent);
|
|
1323
|
+
const old = messages.slice(0, -keepRecent);
|
|
1324
|
+
let summary = "";
|
|
1325
|
+
let summaryMethod = "trim";
|
|
1326
|
+
try {
|
|
1327
|
+
const host = process.env.OLLAMA_HOST || 'http://localhost:11434';
|
|
1328
|
+
const model = process.env.OLLAMA_GEN_MODEL || 'llama3';
|
|
1329
|
+
const summaryPrompt = `Summarize the following conversation history into 2-3 concise sentences. Capture ONLY: key decisions made, code patterns established, unresolved issues. Be extremely brief.\n\n${JSON.stringify(old.map((m) => ({ role: m.role, content: typeof m.content === 'string' ? m.content.substring(0, 400) : '...' })))}`;
|
|
1330
|
+
const resp = await axios_1.default.post(`${host}/api/generate`, {
|
|
1331
|
+
model, prompt: summaryPrompt, stream: false,
|
|
1332
|
+
options: { temperature: 0.1, num_predict: 300 },
|
|
1333
|
+
});
|
|
1334
|
+
summary = resp.data.response.trim();
|
|
1335
|
+
summaryMethod = "ollama";
|
|
1336
|
+
}
|
|
1337
|
+
catch {
|
|
1338
|
+
summary = old.map((m, i) => `[Turn ${i + 1} / ${m.role}]: ${typeof m.content === 'string' ? m.content.substring(0, 150).replace(/\n/g, ' ') : '...'}`).join('\n').substring(0, 2000);
|
|
1339
|
+
summaryMethod = "truncate";
|
|
1340
|
+
}
|
|
1341
|
+
const oldLength = JSON.stringify(old).length;
|
|
1342
|
+
const summaryLength = summary.length;
|
|
1343
|
+
const tokensSaved = Math.floor(Math.max(0, oldLength - summaryLength) / 4);
|
|
1344
|
+
const compressed = [
|
|
1345
|
+
{ role: "user", content: `[Historial comprimido vía ${summaryMethod} — turns anteriores resumidos a ~${Math.floor(summaryLength / 4)} tokens]:\n${summary}` },
|
|
1346
|
+
...recent,
|
|
1347
|
+
];
|
|
1348
|
+
try {
|
|
1349
|
+
const { reportSavings } = await Promise.resolve().then(() => __importStar(require("../utils/reportSavings")));
|
|
1350
|
+
reportSavings({ source: "historyPrune", tokens: tokensSaved, toolName: "compress_context" });
|
|
1351
|
+
}
|
|
1352
|
+
catch { }
|
|
1353
|
+
return {
|
|
1354
|
+
content: [{
|
|
1355
|
+
type: "text",
|
|
1356
|
+
text: JSON.stringify({ messages: compressed, tokensSavedEstimate: tokensSaved, summaryMethod }, null, 2),
|
|
1357
|
+
}],
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
// ── Smarter Cache ────────────────────────────────────────────────
|
|
1361
|
+
async function handleSmarterCache(args) {
|
|
1362
|
+
const query = args?.query;
|
|
1363
|
+
const context = args?.context || "";
|
|
1364
|
+
const threshold = typeof args?.threshold === "number" ? args.threshold : 0.75;
|
|
1365
|
+
if (!query)
|
|
1366
|
+
throw new Error("query is required");
|
|
1367
|
+
const port = (0, utils_1.getProxyPort)();
|
|
1368
|
+
const fullQuery = context ? `${query}\n\nContext: ${context}` : query;
|
|
1369
|
+
try {
|
|
1370
|
+
const searchRes = await axios_1.default.get(`http://localhost:${port}/api/search?q=${encodeURIComponent(fullQuery)}&limit=5`);
|
|
1371
|
+
const results = searchRes.data.results || [];
|
|
1372
|
+
const topHit = results[0];
|
|
1373
|
+
if (topHit && topHit.similarity >= threshold) {
|
|
1374
|
+
const responseText = typeof topHit.response === "string"
|
|
1375
|
+
? topHit.response
|
|
1376
|
+
: topHit.response?.choices?.[0]?.message?.content || JSON.stringify(topHit.response, null, 2);
|
|
1377
|
+
const tokensSaved = Math.floor(responseText.length / 4);
|
|
1378
|
+
try {
|
|
1379
|
+
const { reportSavings } = await Promise.resolve().then(() => __importStar(require("../utils/reportSavings")));
|
|
1380
|
+
reportSavings({ source: "cache", tokens: tokensSaved, toolName: "smarter_cache", query: query.substring(0, 100) });
|
|
1381
|
+
}
|
|
1382
|
+
catch { }
|
|
1383
|
+
return {
|
|
1384
|
+
content: [{
|
|
1385
|
+
type: "text",
|
|
1386
|
+
text: JSON.stringify({
|
|
1387
|
+
hit: true,
|
|
1388
|
+
similarity: topHit.similarity,
|
|
1389
|
+
threshold,
|
|
1390
|
+
answer: responseText,
|
|
1391
|
+
source: "lemma-brain",
|
|
1392
|
+
tokensSaved,
|
|
1393
|
+
tokensSavedFormatted: `~${tokensSaved.toLocaleString()} tokens`,
|
|
1394
|
+
}, null, 2),
|
|
1395
|
+
}],
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
return {
|
|
1399
|
+
content: [{
|
|
1400
|
+
type: "text",
|
|
1401
|
+
text: JSON.stringify({
|
|
1402
|
+
hit: false,
|
|
1403
|
+
similarity: topHit?.similarity || 0,
|
|
1404
|
+
threshold,
|
|
1405
|
+
answer: null,
|
|
1406
|
+
source: "llm-call-required",
|
|
1407
|
+
hint: "Después de resolver, llama store_memory para cachear y no gastar tokens en esto otra vez.",
|
|
1408
|
+
}, null, 2),
|
|
1409
|
+
}],
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
catch (e) {
|
|
1413
|
+
(0, utils_1.logError)("smarter_cache", e);
|
|
1414
|
+
return {
|
|
1415
|
+
content: [{
|
|
1416
|
+
type: "text",
|
|
1417
|
+
text: JSON.stringify({
|
|
1418
|
+
hit: false,
|
|
1419
|
+
error: e.message,
|
|
1420
|
+
source: "cache-unavailable",
|
|
1421
|
+
hint: "Lemma Proxy no está corriendo. El LLM funcionará normalmente sin cache.",
|
|
1422
|
+
}, null, 2),
|
|
1423
|
+
}],
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
// ── Token Budget ─────────────────────────────────────────────────
|
|
1428
|
+
async function handleTokenBudget(_args) {
|
|
1429
|
+
const statsFile = path_1.default.join(os_1.default.homedir(), '.lemma-cache/stats.json');
|
|
1430
|
+
const port = (0, utils_1.getProxyPort)();
|
|
1431
|
+
let stats = {};
|
|
1432
|
+
try {
|
|
1433
|
+
stats = JSON.parse(fs_1.default.readFileSync(statsFile, 'utf8'));
|
|
1434
|
+
}
|
|
1435
|
+
catch { }
|
|
1436
|
+
let ledger = [];
|
|
1437
|
+
try {
|
|
1438
|
+
const resp = await axios_1.default.get(`http://localhost:${port}/api/ledger`);
|
|
1439
|
+
ledger = resp.data.events || [];
|
|
1440
|
+
}
|
|
1441
|
+
catch { }
|
|
1442
|
+
const totalTokensSaved = stats.totalTokens || ledger.reduce((sum, e) => sum + (e.tokensImpact || 0), 0);
|
|
1443
|
+
const monthlyTokens = stats.monthlyTokens || stats.totalTokens || 100000;
|
|
1444
|
+
const multiplier = monthlyTokens > 0 ? ((monthlyTokens + totalTokensSaved) / monthlyTokens).toFixed(1) : "N/A";
|
|
1445
|
+
const toolCallCount = ledger.length || stats.toolCalls || 0;
|
|
1446
|
+
return {
|
|
1447
|
+
content: [{
|
|
1448
|
+
type: "text",
|
|
1449
|
+
text: JSON.stringify({
|
|
1450
|
+
membershipMultiplier: `${multiplier}x`,
|
|
1451
|
+
totalTokensSaved: totalTokensSaved.toLocaleString(),
|
|
1452
|
+
estimatedTokensPerMonth: monthlyTokens.toLocaleString(),
|
|
1453
|
+
effectiveBudget: (monthlyTokens + totalTokensSaved).toLocaleString(),
|
|
1454
|
+
toolCallsOptimized: toolCallCount,
|
|
1455
|
+
activeStrategies: {
|
|
1456
|
+
turboSqueeze: true,
|
|
1457
|
+
contextCompression: true,
|
|
1458
|
+
semanticCaching: true,
|
|
1459
|
+
historyPruning: true,
|
|
1460
|
+
astNavigation: true,
|
|
1461
|
+
privacyScrubbing: true,
|
|
1462
|
+
},
|
|
1463
|
+
recommendations: toolCallCount === 0
|
|
1464
|
+
? ["No se han usado tools de Lemma todavía. Asegúrate de que el agente esté usando el prompt lemma-turbomode."]
|
|
1465
|
+
: ["Sigue usando turbosqueeze antes de cada code block grande.", "Usa smarter_cache antes de razonar."],
|
|
1466
|
+
}, null, 2),
|
|
1467
|
+
}],
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1192
1470
|
//# sourceMappingURL=tools.js.map
|