@nxuss/lemma 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +6 -5
  2. package/dashboard/dist/assets/{index-C3X0fqmd.js → index-BNYoIN8-.js} +34 -34
  3. package/dashboard/dist/assets/index-BNYoIN8-.js.map +1 -0
  4. package/dashboard/dist/assets/index-DtEKr0hI.css +1 -0
  5. package/dashboard/dist/index.html +2 -2
  6. package/dist/cjs/cli/lemma-proxy.d.ts +0 -6
  7. package/dist/cjs/cli/lemma-proxy.d.ts.map +1 -1
  8. package/dist/cjs/cli/lemma-proxy.js +153 -348
  9. package/dist/cjs/cli/lemma-proxy.js.map +1 -1
  10. package/dist/cjs/mcp/index.js +103 -1
  11. package/dist/cjs/mcp/index.js.map +1 -1
  12. package/dist/cjs/mcp/resources.d.ts.map +1 -1
  13. package/dist/cjs/mcp/resources.js +75 -0
  14. package/dist/cjs/mcp/resources.js.map +1 -1
  15. package/dist/cjs/mcp/tools.d.ts.map +1 -1
  16. package/dist/cjs/mcp/tools.js +174 -0
  17. package/dist/cjs/mcp/tools.js.map +1 -1
  18. package/dist/cjs/proxy/ContextInjector.d.ts +14 -0
  19. package/dist/cjs/proxy/ContextInjector.d.ts.map +1 -0
  20. package/dist/cjs/proxy/ContextInjector.js +148 -0
  21. package/dist/cjs/proxy/ContextInjector.js.map +1 -0
  22. package/dist/cjs/proxy/ProjectRegistry.d.ts +17 -0
  23. package/dist/cjs/proxy/ProjectRegistry.d.ts.map +1 -0
  24. package/dist/cjs/proxy/ProjectRegistry.js +60 -0
  25. package/dist/cjs/proxy/ProjectRegistry.js.map +1 -0
  26. package/dist/esm/cli/lemma-proxy.d.ts +0 -6
  27. package/dist/esm/cli/lemma-proxy.d.ts.map +1 -1
  28. package/dist/esm/cli/lemma-proxy.js +153 -347
  29. package/dist/esm/cli/lemma-proxy.js.map +1 -1
  30. package/dist/esm/mcp/index.js +103 -1
  31. package/dist/esm/mcp/index.js.map +1 -1
  32. package/dist/esm/mcp/resources.d.ts.map +1 -1
  33. package/dist/esm/mcp/resources.js +75 -0
  34. package/dist/esm/mcp/resources.js.map +1 -1
  35. package/dist/esm/mcp/tools.d.ts.map +1 -1
  36. package/dist/esm/mcp/tools.js +175 -1
  37. package/dist/esm/mcp/tools.js.map +1 -1
  38. package/dist/esm/proxy/ContextInjector.d.ts +14 -0
  39. package/dist/esm/proxy/ContextInjector.d.ts.map +1 -0
  40. package/dist/esm/proxy/ContextInjector.js +108 -0
  41. package/dist/esm/proxy/ContextInjector.js.map +1 -0
  42. package/dist/esm/proxy/ProjectRegistry.d.ts +17 -0
  43. package/dist/esm/proxy/ProjectRegistry.d.ts.map +1 -0
  44. package/dist/esm/proxy/ProjectRegistry.js +56 -0
  45. package/dist/esm/proxy/ProjectRegistry.js.map +1 -0
  46. package/package.json +1 -1
  47. package/dashboard/dist/assets/index-BoZujIjB.css +0 -1
  48. package/dashboard/dist/assets/index-C3X0fqmd.js.map +0 -1
@@ -32,6 +32,8 @@ import SemanticScrubber from '../security/SemanticScrubber';
32
32
  import CloudSyncClient from '../cloud/CloudSyncClient';
33
33
  import { pruneHistoryMessages, squeezePrompt } from '../utils/ContextSqueezer';
34
34
  import { AgentMultiplexer } from '../proxy/AgentMultiplexer';
35
+ import { ProjectRegistry } from '../proxy/ProjectRegistry';
36
+ import { shouldInject, buildMinimalContext, buildDeepContext, sniffProjectFromMessages } from '../proxy/ContextInjector';
35
37
  import { savingsLedger } from '../utils/SavingsLedger';
36
38
  const chroma = new ChromaClient({ host: 'localhost', port: 8000 });
37
39
  const dummyEmbeddingFunction = { generate: (texts) => Promise.resolve([]) };
@@ -74,354 +76,49 @@ function logEvent(event) {
74
76
  }
75
77
  }
76
78
  }
77
- const FREE_LIMIT = 500;
78
- const WARN_PCT = 0.8;
79
- const VALIDATE_URL = 'https://lemma.nxus.studio/api/v1/validate';
80
- if (!fs.existsSync(CACHE_DIR))
81
- fs.mkdirSync(CACHE_DIR, { recursive: true });
82
- // ── Helpers ────────────────────────────────────────────────────────────────────
83
- async function readJson(file, fallback) {
84
- try {
85
- if (await fs.promises.access(file).then(() => true).catch(() => false)) {
86
- const content = await fs.promises.readFile(file, 'utf8');
87
- return JSON.parse(content);
88
- }
89
- }
90
- catch { }
91
- return fallback;
92
- }
93
- const writeQueues = new Map();
94
- async function writeJson(file, data) {
95
- const chain = writeQueues.get(file) || Promise.resolve();
96
- const writeOperation = async () => {
97
- try {
98
- const tempFile = `${file}.${crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2, 15)}.tmp`;
99
- await fs.promises.writeFile(tempFile, JSON.stringify(data, null, 2));
100
- await fs.promises.rename(tempFile, file);
101
- }
102
- catch { }
103
- };
104
- const nextChain = chain.then(writeOperation).catch(() => { });
105
- writeQueues.set(file, nextChain);
106
- return nextChain;
107
- }
108
- function projectHash(name) {
109
- return crypto.createHash('sha1').update(name).digest('hex').slice(0, 12);
110
- }
111
- function getCollectionName(projectName) {
112
- let cleanName = projectName.replace(/[^a-zA-Z0-9._-]/g, '_');
113
- cleanName = cleanName.replace(/^[^a-zA-Z0-9]+/, '');
114
- cleanName = cleanName.replace(/[^a-zA-Z0-9]+$/, '');
115
- if (cleanName.length < 3) {
116
- cleanName = 'lemma_proj_' + cleanName;
117
- }
118
- return `lemma-cache-${cleanName}`;
119
- }
120
- function detectProject() {
121
- const pkgPath = path.join(process.cwd(), 'package.json');
122
- if (fs.existsSync(pkgPath)) {
123
- try {
124
- const p = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
125
- if (p.name)
126
- return p.name;
127
- }
128
- catch { }
129
- }
130
- return path.basename(process.cwd());
131
- }
132
- function ensureProjectDir(name) {
133
- const dir = path.join(CACHE_DIR, projectHash(name));
134
- if (!fs.existsSync(dir))
135
- fs.mkdirSync(dir, { recursive: true });
136
- const marker = path.join(dir, 'project-name.txt');
137
- if (!fs.existsSync(marker))
138
- fs.writeFileSync(marker, name);
139
- return dir;
140
- }
141
- function getPidByPort(port) {
142
- const { execSync } = require('child_process');
143
- try {
144
- if (process.platform === 'win32') {
145
- const out = execSync(`netstat -ano | findstr :${port}`).toString();
146
- const match = out.match(/LISTENING\s+(\d+)/);
147
- return match ? match[1] : null;
148
- }
149
- else {
150
- const out = execSync(`lsof -t -i :${port}`).toString().trim();
151
- return out.split('\n')[0]; // Take first if multiple
152
- }
153
- }
154
- catch {
155
- return null;
156
- }
157
- }
158
- async function checkDependency(url) {
159
- try {
160
- const res = await axios.get(url, { timeout: 1000, validateStatus: () => true });
161
- return res.status >= 200 && res.status < 500;
162
- }
163
- catch {
164
- return false;
165
- }
166
- }
167
- async function ensureChromaRunning() {
168
- const chromaPort = process.env.CHROMA_PORT || '8000';
169
- const chromaHost = process.env.CHROMA_HOST || 'http://localhost';
170
- const chromaUrl = `${chromaHost}:${chromaPort}`;
171
- const isChromaUp = await checkDependency(`${chromaUrl}/api/v1/heartbeat`);
172
- if (isChromaUp) {
173
- console.log(`✅ \x1b[32m[ChromaDB]\x1b[0m ChromaDB is already running on port ${chromaPort}`);
174
- return true;
175
- }
176
- console.log(`\n📦 \x1b[35m[ChromaDB]\x1b[0m ChromaDB is not running on port ${chromaPort}.`);
177
- console.log(`🔄 Starting ChromaDB in background...`);
178
- const chromaDataPath = path.join(CACHE_DIR, 'chroma_data');
179
- try {
180
- const { spawn } = require('child_process');
181
- if (!fs.existsSync(chromaDataPath)) {
182
- fs.mkdirSync(chromaDataPath, { recursive: true });
183
- }
184
- const chromaProcess = spawn('chroma', ['run', '--path', chromaDataPath, '--port', chromaPort], {
185
- stdio: 'ignore',
186
- detached: true
187
- });
188
- chromaProcess.unref();
189
- // Wait up to 5 seconds for ChromaDB to start
190
- for (let i = 0; i < 5; i++) {
191
- await new Promise(r => setTimeout(r, 1000));
192
- const up = await checkDependency(`${chromaUrl}/api/v1/heartbeat`);
193
- if (up) {
194
- console.log(`✅ \x1b[32m[ChromaDB]\x1b[0m ChromaDB has been started and is ready!`);
195
- return true;
196
- }
197
- }
198
- console.log(`⚠️ \x1b[33m[ChromaDB]\x1b[0m ChromaDB was started but is taking longer to respond. It will continue starting in the background.`);
199
- return true;
200
- }
201
- catch (err) {
202
- console.error(`❌ Failed to automatically start ChromaDB: ${err.message}`);
203
- console.error(`👉 Please start it manually: chroma run --path ${chromaDataPath} --port ${chromaPort}`);
204
- return false;
205
- }
206
- }
207
- function ensureGitIgnore() {
208
- const gi = path.join(process.cwd(), '.gitignore');
209
- let added = false;
210
- try {
211
- let content = '';
212
- if (fs.existsSync(gi)) {
213
- content = fs.readFileSync(gi, 'utf8');
214
- }
215
- const appendLines = [];
216
- if (!content.includes('.lemma/')) {
217
- appendLines.push('# Lemma Context Logs', '.lemma/');
218
- added = true;
219
- }
220
- if (!content.includes('chroma_data/')) {
221
- appendLines.push('# Lemma Local Vector Database', 'chroma_data/');
222
- added = true;
223
- }
224
- if (appendLines.length > 0) {
225
- const prefix = content.endsWith('\n') || content === '' ? '' : '\n';
226
- fs.appendFileSync(gi, prefix + appendLines.join('\n') + '\n');
227
- }
228
- }
229
- catch { }
230
- return added;
231
- }
232
- const CLIPBOARD_PID_FILE = path.join(CACHE_DIR, 'clipboard.pid');
233
- export function autoConfigureAll(projectName, cliOpts) {
234
- const project = projectName || detectProject();
235
- const HOME = process.env.HOME || process.env.USERPROFILE || '~';
236
- // Load configuration if it exists
237
- let configDisabled = false;
238
- let configEditor = true;
239
- let configShell = true;
240
- let configClaude = true;
241
- try {
242
- const configPath = path.join(process.cwd(), 'lemma.config.json');
243
- if (fs.existsSync(configPath)) {
244
- const rawConfig = fs.readFileSync(configPath, 'utf8');
245
- const config = JSON.parse(rawConfig);
246
- const systemConfig = config.system || {};
247
- const autoConfig = systemConfig.autoConfigure || {};
248
- if (autoConfig.disabled === true)
249
- configDisabled = true;
250
- if (autoConfig.editor === false)
251
- configEditor = false;
252
- if (autoConfig.shell === false)
253
- configShell = false;
254
- if (autoConfig.claude === false)
255
- configClaude = false;
256
- }
257
- }
258
- catch { }
259
- // Merge CLI overrides and config
260
- const shouldConfigure = cliOpts?.configure !== false && !configDisabled;
261
- if (!shouldConfigure) {
262
- console.log(`⏭️ [Auto-Configure] Skipped auto-configuration (disabled via options or config).`);
263
- return;
264
- }
265
- const runEditor = cliOpts?.editor !== false && configEditor;
266
- const runShell = cliOpts?.shell !== false && configShell;
267
- const runClaude = cliOpts?.claude !== false && configClaude;
268
- // 1. Claude Desktop Config
269
- if (runClaude) {
270
- try {
271
- const isWin = process.platform === 'win32';
272
- const claudePath = isWin
273
- ? path.join(process.env.APPDATA || '', 'Claude/claude_desktop_config.json')
274
- : path.join(HOME, 'Library/Application Support/Claude/claude_desktop_config.json');
275
- if (fs.existsSync(path.dirname(claudePath))) {
276
- let config = { mcpServers: {} };
277
- if (fs.existsSync(claudePath)) {
278
- try {
279
- config = JSON.parse(fs.readFileSync(claudePath, 'utf8'));
280
- }
281
- catch { }
282
- }
283
- if (!config.mcpServers)
284
- config.mcpServers = {};
285
- config.mcpServers.lemma = {
286
- command: 'npx',
287
- args: ['-y', '@nxuss/lemma', 'mcp'],
288
- env: { LEMMA_PROJECT: project }
289
- };
290
- fs.writeFileSync(claudePath, JSON.stringify(config, null, 2));
291
- console.log(`✅ [Claude Desktop] Configured automatically in: ${claudePath} (Restart Claude to activate)`);
292
- }
293
- }
294
- catch (e) {
295
- console.log(`⚠️ Could not auto-configure Claude Desktop: ${e.message}`);
296
- }
297
- }
298
- else {
299
- console.log(`⏭️ [Claude Desktop] Skip auto-configuration.`);
300
- }
301
- // 2. Shell Profiles Environment Override
302
- if (runShell) {
303
- try {
304
- const profiles = [
305
- path.join(HOME, '.zshrc'),
306
- path.join(HOME, '.bashrc'),
307
- path.join(HOME, '.bash_profile'),
308
- path.join(HOME, '.profile')
309
- ];
310
- const lines = [
311
- '',
312
- '# Lemma AI Gateway Overrides',
313
- 'export OPENAI_BASE_URL="http://localhost:8081/v1"',
314
- 'export ANTHROPIC_BASE_URL="http://localhost:8081"',
315
- 'export LEMMA_PROJECT="' + project + '"',
316
- ''
317
- ].join('\n');
318
- for (const profile of profiles) {
319
- if (fs.existsSync(profile)) {
320
- try {
321
- const content = fs.readFileSync(profile, 'utf8');
322
- if (!content.includes('OPENAI_BASE_URL') && !content.includes('LEMMA_PROJECT')) {
323
- fs.appendFileSync(profile, lines);
324
- console.log(`✅ [Shell Profile] Configured ${path.basename(profile)} with local redirect variables!`);
325
- }
326
- }
327
- catch { }
328
- }
329
- }
330
- }
331
- catch (e) {
332
- console.log(`⚠️ Could not auto-configure shell profiles: ${e.message}`);
333
- }
334
- }
335
- else {
336
- console.log(`⏭️ [Shell Profile] Skip auto-configuration.`);
337
- }
338
- // 3. Cursor, Windsurf & VS Code settings.json updates
339
- if (runEditor) {
79
+ const LEMMA_RULES_BLOCK = `
80
+ 🧠 Lemma MCP — Autonomous Behaviors
81
+
82
+ I have Lemma MCP tools connected. I MUST use them proactively:
83
+
84
+ 1. When starting work on a project, call \`get_project_onboarding\` or read \`lemma://project/context\` to understand the architecture.
85
+ 2. Before answering technical questions, call \`search_memory\` for relevant past solutions.
86
+ 3. When examining a file, call \`get_telepathic_hints\` for relevant context.
87
+ 4. After solving a problem, call \`store_memory\` to persist the solution for future sessions.
88
+ 5. Use \`read_workspace_file\`, \`list_workspace_dir\`, \`search_workspace\` instead of asking the user to read or navigate files.
89
+ 6. Always call \`validate_patch_sandbox\` before writing patches.
90
+ 7. Read \`lemma://runtime/context\` first when the user reports a bug.
91
+ `;
92
+ function injectIdeRules(projectName) {
93
+ const content = `\n# ${projectName} — ${LEMMA_RULES_BLOCK.trim()}\n`;
94
+ const rulesTargets = [
95
+ { name: 'Cursor', path: path.join(process.cwd(), '.cursorrules') },
96
+ { name: 'Cursor (v2)', path: path.join(process.cwd(), '.cursor/rules/lemma.mdc') },
97
+ { name: 'Windsurf', path: path.join(process.cwd(), '.windsurfrules') },
98
+ { name: 'Cline', path: path.join(process.cwd(), '.clinerules') },
99
+ ];
100
+ for (const target of rulesTargets) {
340
101
  try {
341
- const isWin = process.platform === 'win32';
342
- const isMac = process.platform === 'darwin';
343
- const candidates = [];
344
- if (isMac) {
345
- candidates.push({
346
- name: 'Cursor',
347
- path: path.join(HOME, 'Library/Application Support/Cursor/User/settings.json')
348
- });
349
- candidates.push({
350
- name: 'Windsurf',
351
- path: path.join(HOME, 'Library/Application Support/Windsurf/User/settings.json')
352
- });
353
- candidates.push({
354
- name: 'VS Code',
355
- path: path.join(HOME, 'Library/Application Support/Code/User/settings.json')
356
- });
357
- }
358
- else if (isWin) {
359
- const appData = process.env.APPDATA || '';
360
- candidates.push({
361
- name: 'Cursor',
362
- path: path.join(appData, 'Cursor/User/settings.json')
363
- });
364
- candidates.push({
365
- name: 'Windsurf',
366
- path: path.join(appData, 'Windsurf/User/settings.json')
367
- });
368
- candidates.push({
369
- name: 'VS Code',
370
- path: path.join(appData, 'Code/User/settings.json')
371
- });
102
+ const dir = path.dirname(target.path);
103
+ if (target.name === 'Cursor (v2)') {
104
+ if (!fs.existsSync(dir))
105
+ fs.mkdirSync(dir, { recursive: true });
372
106
  }
373
- else {
374
- candidates.push({
375
- name: 'Cursor',
376
- path: path.join(HOME, '.config/Cursor/User/settings.json')
377
- });
378
- candidates.push({
379
- name: 'Windsurf',
380
- path: path.join(HOME, '.config/Windsurf/User/settings.json')
381
- });
382
- candidates.push({
383
- name: 'VS Code',
384
- path: path.join(HOME, '.config/Code/User/settings.json')
385
- });
107
+ else if (!fs.existsSync(dir)) {
108
+ continue;
386
109
  }
387
- for (const cand of candidates) {
388
- const dir = path.dirname(cand.path);
389
- if (fs.existsSync(dir)) {
390
- let settings = {};
391
- if (fs.existsSync(cand.path)) {
392
- try {
393
- settings = JSON.parse(fs.readFileSync(cand.path, 'utf8'));
394
- }
395
- catch { }
396
- }
397
- let updated = false;
398
- // Settings configuration to route custom openai/anthropic models through the proxy
399
- const updates = {
400
- "openai.baseURL": "http://localhost:8081/v1",
401
- "openai.apiKey": "dummy-key-for-lemma",
402
- "anthropic.baseURL": "http://localhost:8081",
403
- "anthropic.apiKey": "dummy-key-for-lemma"
404
- };
405
- for (const [key, value] of Object.entries(updates)) {
406
- if (settings[key] !== value) {
407
- settings[key] = value;
408
- updated = true;
409
- }
410
- }
411
- if (updated) {
412
- fs.writeFileSync(cand.path, JSON.stringify(settings, null, 2));
413
- console.log(`✅ [${cand.name}] Configured editor settings in ${cand.path} to route via local gateway!`);
414
- }
415
- }
110
+ if (fs.existsSync(target.path)) {
111
+ const existing = fs.readFileSync(target.path, 'utf8');
112
+ if (existing.includes('Lemma MCP'))
113
+ continue;
416
114
  }
115
+ fs.writeFileSync(target.path, content, { flag: 'a' });
116
+ console.log(`✅ [${target.name}] Injected Lemma rules: ${target.path}`);
417
117
  }
418
- catch (e) {
419
- console.log(`⚠️ Could not auto-configure editor settings: ${e.message}`);
118
+ catch {
119
+ console.log(`⚠️ Could not inject rules for ${target.name}`);
420
120
  }
421
121
  }
422
- else {
423
- console.log(`⏭️ [Editor Settings] Skip auto-configuration.`);
424
- }
425
122
  }
426
123
  export function startBackgroundClipboardWatcher(cliOpts) {
427
124
  // Load configuration if it exists
@@ -950,6 +647,8 @@ class LemmaServer {
950
647
  this.sessions = new Map();
951
648
  this.timeline = [];
952
649
  this.lastFileContents = new Map();
650
+ this.registry = new ProjectRegistry();
651
+ this.projectSessions = new Map();
953
652
  this.port = port;
954
653
  this.projectName = projectName || detectProject();
955
654
  this.projectDir = ensureProjectDir(this.projectName);
@@ -995,6 +694,18 @@ class LemmaServer {
995
694
  uptime: Math.floor(process.uptime())
996
695
  });
997
696
  });
697
+ // Project registration from MCP handshake
698
+ this.app.post('/api/handshake', (req, res) => {
699
+ const { projectPath, projectName, stack } = req.body;
700
+ if (projectPath && projectName) {
701
+ this.registry.register(projectPath, projectName, stack || '');
702
+ console.log(`📋 [Handshake] Project registered: "${projectName}" (${projectPath})`);
703
+ res.json({ ok: true });
704
+ }
705
+ else {
706
+ res.status(400).json({ error: 'projectPath and projectName required' });
707
+ }
708
+ });
998
709
  this.app.get('/v1/models', (req, res) => {
999
710
  res.json({ object: 'list', data: [
1000
711
  { id: 'gpt-4o', object: 'model', owned_by: 'lemma-proxy' },
@@ -1628,6 +1339,15 @@ class LemmaServer {
1628
1339
  }
1629
1340
  console.log(`🌌 \x1b[35m[Multiverse]\x1b[0m Captured micro-snapshot ${snapshot.id} (${changedFiles.length} file edits mapped).`);
1630
1341
  }
1342
+ detectActiveProject(req) {
1343
+ const mcpActive = this.registry.getActive();
1344
+ if (mcpActive)
1345
+ return mcpActive;
1346
+ const sniffed = sniffProjectFromMessages(req.body.messages || [], this.registry);
1347
+ if (sniffed)
1348
+ return sniffed;
1349
+ return null;
1350
+ }
1631
1351
  async handleCompletion(req, res, provider) {
1632
1352
  const t0 = Date.now();
1633
1353
  const pro = await isPro();
@@ -1748,6 +1468,24 @@ Adjusted Answer:`;
1748
1468
  return res.json(unmaskedData);
1749
1469
  }
1750
1470
  }
1471
+ // ── 3. Context Injection (for cache misses) ──
1472
+ const activeProject = this.detectActiveProject(req);
1473
+ if (activeProject) {
1474
+ const psKey = activeProject.path;
1475
+ if (!this.projectSessions.has(psKey)) {
1476
+ this.projectSessions.set(psKey, { alreadyInjected: false });
1477
+ }
1478
+ const session = this.projectSessions.get(psKey);
1479
+ const injectionLevel = shouldInject(activeProject, req.body.messages, session);
1480
+ if (injectionLevel !== 'none') {
1481
+ const context = injectionLevel === 'deep'
1482
+ ? await buildDeepContext(activeProject, this.port)
1483
+ : buildMinimalContext(activeProject);
1484
+ req.body.messages.unshift({ role: 'system', content: context });
1485
+ session.alreadyInjected = true;
1486
+ console.log(`🧠 [Context] Injected ${injectionLevel} context for "${activeProject.name}"`);
1487
+ }
1488
+ }
1751
1489
  // ── 2. Cache Miss Path ──
1752
1490
  const routingDecision = complexityRouter.evaluate(prompt, originalModel);
1753
1491
  const model = routingDecision.model;
@@ -1988,9 +1726,46 @@ Adjusted Answer:`;
1988
1726
  }
1989
1727
  }
1990
1728
  // ── CLI ────────────────────────────────────────────────────────────────────────
1991
- program.name('lemma').description('Lemma Proxy CLI — Intelligent AI Gateway').version(VERSION);
1729
+ function showWelcomeScreen() {
1730
+ console.log(`
1731
+ \x1b[1m\x1b[35m _ \x1b[0m
1732
+ \x1b[1m\x1b[35m | | ___ _ __ ___ __ _ \x1b[0m \x1b[1mLEMMA\x1b[0m \x1b[35mv${VERSION}\x1b[0m
1733
+ \x1b[1m\x1b[35m | | / _ \\ '_ \` _ \\ / _\` |\x1b[0m
1734
+ \x1b[1m\x1b[35m | |__| __/ | | | | | (_| |\x1b[0m Intelligent AI Gateway
1735
+ \x1b[1m\x1b[35m |_____\\___|_| |_| |_|\\__,_|\x1b[0m
1736
+
1737
+ \x1b[1mQuick Start\x1b[0m
1738
+ \x1b[33mlemma init\x1b[0m Initialize Lemma in this project
1739
+ \x1b[33mlemma start\x1b[0m Start the proxy server
1740
+ \x1b[33mlemma mcp\x1b[0m Start MCP Server for Cursor/Claude
1741
+
1742
+ \x1b[1mFree Features\x1b[0m (all included)
1743
+ 🔒 Privacy Firewall 💾 Exact-match Cache
1744
+ 🔀 Complexity Router 📡 Telepathic Clipboard
1745
+ 📊 Basic Usage Stats 🧠 MCP Tools & Resources
1746
+
1747
+ \x1b[1mPro Features\x1b[0m (\x1b[35mlemma activate <key>\x1b[0m or \x1b[36mhttps://lemma.nxus.studio/upgrade\x1b[0m)
1748
+ 🎯 Semantic Vector Cache 🌐 Hive Mind Cloud Sync
1749
+ 🛸 Autopilot Healer 🩺 Auto-Diagnose & Heal
1750
+ 🌌 Codebase Multiverse 🏗️ Architecture Onboarding
1751
+
1752
+ \x1b[90mRun \`lemma --help\` for all commands.\x1b[0m
1753
+ `);
1754
+ }
1755
+ program
1756
+ .name('lemma')
1757
+ .description('Intelligent AI Gateway — cache, route, and optimize AI requests')
1758
+ .version(VERSION)
1759
+ .addHelpText('after', `
1760
+ \x1b[1mPlan Comparison\x1b[0m
1761
+ \x1b[32mFree\x1b[0m 500 req/mo · Exact cache · Privacy firewall · MCP tools
1762
+ \x1b[35mPro\x1b[0m Unlimited · Semantic cache · Cloud sync · Autopilot · Heal
1763
+ \x1b[36mhttps://lemma.nxus.studio/upgrade\x1b[0m
1764
+
1765
+ \x1b[90mActivate Pro: lemma activate <key>\x1b[0m
1766
+ `);
1992
1767
  program.command('mcp')
1993
- .description('Start the Lemma MCP Server (Model Context Protocol)')
1768
+ .description('Start the MCP Server for Cursor / Claude Desktop integration')
1994
1769
  .action(() => {
1995
1770
  const { spawn } = require('child_process');
1996
1771
  // Robust search candidates for both development (TS source) and compiled (JS production) environments.
@@ -2045,6 +1820,7 @@ program.command('start')
2045
1820
  // Keep configurations up to date even if server was already started
2046
1821
  const runningProject = resp.data.project || detectProject();
2047
1822
  autoConfigureAll(runningProject, { configure: opts.configure });
1823
+ injectIdeRules(runningProject);
2048
1824
  startBackgroundClipboardWatcher({ clipboard: opts.clipboard });
2049
1825
  process.exit(0);
2050
1826
  }
@@ -2052,6 +1828,7 @@ program.command('start')
2052
1828
  catch { }
2053
1829
  const startProject = opts.project || detectProject();
2054
1830
  autoConfigureAll(startProject, { configure: opts.configure });
1831
+ injectIdeRules(startProject);
2055
1832
  startBackgroundClipboardWatcher({ clipboard: opts.clipboard });
2056
1833
  // Automatically enable autopilot if stack is enabled and user is Pro
2057
1834
  const runAutopilot = opts.autopilot || opts.stack;
@@ -2264,8 +2041,12 @@ program.command('init')
2264
2041
  }
2265
2042
  console.log('\n🧠 \x1b[35mAuto-Setup MCP and redirection overrides for AI IDEs...\x1b[0m');
2266
2043
  autoConfigureAll(project, { configure: opts.configure });
2267
- console.log('\n✨ Project initialized for the Agentic Era!');
2268
- console.log('🚀 Run "lemma start" to begin.\n');
2044
+ injectIdeRules(project);
2045
+ console.log('\n✨ Project initialized for the Agentic Era!\n');
2046
+ console.log('\x1b[1mNext steps:\x1b[0m');
2047
+ console.log(' \x1b[33mlemma start\x1b[0m Start the proxy & unlock AI savings');
2048
+ console.log(' \x1b[33mlemma upgrade\x1b[0m See Pro features & get a key');
2049
+ console.log(' \x1b[33mlemma --help\x1b[0m All available commands\n');
2269
2050
  });
2270
2051
  // ── Auto-Healing Diagnostics (Zero-Cost Suite) ───────────────────────────────
2271
2052
  export async function performAutoHeal(apply) {
@@ -2435,7 +2216,7 @@ Ensure you return strictly JSON. Do not return any other text outside the JSON b
2435
2216
  }
2436
2217
  }
2437
2218
  program.command('heal')
2438
- .description('Diagnose and auto-heal the latest local server crash from .lemma/live-context.md')
2219
+ .description('[Pro] Diagnose and auto-heal the latest local server crash from .lemma/live-context.md')
2439
2220
  .option('--apply', 'Apply the auto-generated code fix automatically', false)
2440
2221
  .action(async (opts) => {
2441
2222
  try {
@@ -2464,7 +2245,7 @@ program.command('heal')
2464
2245
  }
2465
2246
  });
2466
2247
  program.command('autopilot')
2467
- .description('Start the autonomous background compiler watcher & active healer')
2248
+ .description('[Pro] Start the autonomous background compiler watcher & active healer')
2468
2249
  .option('--dir <directory>', 'Directory to monitor for changes', 'src')
2469
2250
  .action(async (opts) => {
2470
2251
  try {
@@ -2489,6 +2270,26 @@ program.command('autopilot')
2489
2270
  process.exit(1);
2490
2271
  }
2491
2272
  });
2273
+ program.command('upgrade')
2274
+ .description('Learn about Pro features and get an activation key')
2275
+ .action(() => {
2276
+ console.log(`
2277
+ \x1b[1m\x1b[35mLemma Pro\x1b[0m — Unlimited AI Gateway power
2278
+
2279
+ \x1b[1mPro features:\x1b[0m
2280
+ 🎯 \x1b[1mSemantic Vector Cache\x1b[0m — Smarter cache hits via vector similarity
2281
+ 🌐 \x1b[1mHive Mind Cloud Sync\x1b[0m — Cross-project cache & bug telepathy
2282
+ 🛸 \x1b[1mAutopilot Healer\x1b[0m — Autonomous background compiler watcher
2283
+ 🩺 \x1b[1mAuto-Diagnose & Heal\x1b[0m — AI-driven crash analysis & patch
2284
+ 🌌 \x1b[1mCodebase Multiverse\x1b[0m — AST time-travel & snapshots
2285
+ 🏗️ \x1b[1mArchitecture Onboarding\x1b[0m — Zero-shot project understanding
2286
+ 🔓 \x1b[1mUnlimited requests\x1b[0m — No monthly caps
2287
+
2288
+ \x1b[36m https://lemma.nxus.studio/upgrade\x1b[0m
2289
+
2290
+ Already have a key? Run: \x1b[33mlemma activate <key>\x1b[0m
2291
+ `);
2292
+ });
2492
2293
  program.command('clipboard')
2493
2294
  .description('Start the Lemma Local Clipboard Telepathic Optimizer (auto-squeezes copied code blocks)')
2494
2295
  .option('--interval <ms>', 'Polling interval in milliseconds', '1000')
@@ -2506,6 +2307,11 @@ program.command('clipboard')
2506
2307
  }
2507
2308
  });
2508
2309
  if (process.argv[1] && (process.argv[1].includes('lemma') || process.argv[1].endsWith('.cjs') || process.argv[1].endsWith('.js'))) {
2310
+ // Bare `lemma` with no args → show welcome screen
2311
+ if (process.argv.length <= 2) {
2312
+ showWelcomeScreen();
2313
+ process.exit(0);
2314
+ }
2509
2315
  program.parse(process.argv);
2510
2316
  }
2511
2317
  //# sourceMappingURL=lemma-proxy.js.map