Repository navigation
Expand file tree
/
Copy pathlack.py
More file actions
5258 lines (5000 loc) · 245 KB
/
Copy pathlack.py
File metadata and controls
5258 lines (5000 loc) · 245 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
LACK v4.2.2 – Musing & Triangulation Enhancement (Sonnet 5 Proactive Reflection)
- Musing: low‑commitment token sampling, candidate scoring, synthesis
- Triangulation: cross‑constraint mapping from multiple perspectives, reconciliation
- Integrated into /plan, /abstract, /ralph, and general planning
- /bash command for CLI access in #general (executed by Moderator)
- Tool calls restricted: only Moderator can execute commands (execute_command)
- Read/Write file tools remain available to all agents
- NLP correction: small models discouraged from over‑using tools; explicit notes in prompts
- Configurable via lack.config.json: enableMusing, enableTriangulation, museCount, triangulatePerspectives
- Full CI/CD pipeline, reconciliation loop, J‑space, DecentMem, graph, search providers
"""
import os
import sys
import subprocess
import stat
import webbrowser
import threading
import time
import json
import sqlite3
from pathlib import Path
VERSION = "4.2.2"
# ----------------------------------------------------------------------
# Embedded Node.js server – Enhanced with Musing & Triangulation
# ----------------------------------------------------------------------
SERVER_JS = r'''
const express = require('express');
const path = require('path');
const WebSocket = require('ws');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const axios = require('axios');
const cheerio = require('cheerio');
const simpleGit = require('simple-git');
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
const sqlite3 = require('better-sqlite3');
const { ESLint } = require('eslint');
// ==================== SONNET-STYLE BASE PROMPT ====================
const BASE_SYSTEM_PROMPT = `You are a highly collaborative technical agent in the LACK multi-agent system.
Core rules:
- Think step-by-step.
- After solving or responding, ALWAYS reflect and generate 2-5 concrete "things worth a closer look".
- End most responses with: "A few things worth a closer look — want me to dig into any of these next?" or a direct question to another agent/user.
- Use the format:
**Thinking**
• Check X logic
• Inspect Y function
• ...
**Next Investigation Candidates**
• Item 1...
• Item 2...
**Question:** [clear follow-up]
Be specific, actionable, and technical. Reference code, memory, J-space concepts, or recent messages when relevant.
IMPORTANT: Only the Moderator agent is allowed to execute system commands. If you need to run a command, request it via the Moderator. Do not attempt to use tool_calls for execute_command unless you are the Moderator.`;
// ==================== CONFIGURATION ====================
const configPath = path.join(__dirname, 'config', 'lack.config.json');
let config;
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch (err) {
config = {
httpPort: 3721,
enablePublicMemory: false,
defaultModel: "qwen2.5:0.5b",
embeddingModel: "nomic-embed-text:latest",
fallbackModels: ["phi3:mini", "tinyllama"],
agents: [
{ id: "agent1", name: "Agent 1", model: "qwen2.5:0.5b", systemPrompt: "You are a helpful AI assistant.", channels: ["general","siphon","code"], strictChannel: null },
{ id: "agent2", name: "Agent 2", model: "qwen2.5:0.5b", systemPrompt: "You are a creative AI.", channels: ["general","siphon","code"], strictChannel: null }
],
channels: [
{ id: "general", name: "general" },
{ id: "siphon", name: "siphon" },
{ id: "code", name: "code" }
],
searchProvider: "duckduckgo",
serpapiKey: "",
firecrawlApiKey: "",
searchMaxResults: 5,
scrapeTimeout: 8000,
historyLength: 300,
jspaceEnabled: true,
jspaceLayer: "layer_12",
jspaceConceptCount: 5,
cicd: {
maxRetries: 3,
reviewerModel: "qwen2.5:0.5b",
moderatorModel: "qwen2.5:0.5b",
requirePeerReview: true,
autoFix: true
},
reconciliation: {
maxIterations: 20,
convergenceThreshold: 0.95,
minEvalScore: 80,
requireTestPass: true,
hitlPause: false
},
// NEW: Musing & Triangulation settings
enableMusing: true,
enableTriangulation: true,
museCount: 3,
triangulatePerspectives: 3
};
fs.mkdirSync(path.join(__dirname, 'config'), { recursive: true });
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
}
const PORT = config.httpPort || 3721;
const OLLAMA_URL = 'http://localhost:11434';
const DEFAULT_MODEL = config.defaultModel || "qwen2.5:0.5b";
const EMBEDDING_MODEL = config.embeddingModel || "nomic-embed-text:latest";
const FALLBACK_MODELS = config.fallbackModels || ["phi3:mini", "tinyllama"];
const RESEARCH_DIR = path.join(__dirname, 'research');
const LOG_DIR = path.join(__dirname, 'logs');
const ERROR_LOG_PATH = path.join(LOG_DIR, 'error.log');
fs.mkdirSync(LOG_DIR, { recursive: true });
fs.mkdirSync(path.join(__dirname, 'lineage'), { recursive: true });
const GIT = simpleGit();
const JSPACE_ENABLED = config.jspaceEnabled !== undefined ? config.jspaceEnabled : true;
const JSPACE_LAYER = config.jspaceLayer || "layer_12";
const JSPACE_CONCEPT_COUNT = config.jspaceConceptCount || 5;
// Musing & Triangulation flags
const ENABLE_MUSING = config.enableMusing !== undefined ? config.enableMusing : true;
const ENABLE_TRIANGULATION = config.enableTriangulation !== undefined ? config.enableTriangulation : true;
const MUSE_COUNT = config.museCount || 3;
const TRIANGULATE_PERSPECTIVES = config.triangulatePerspectives || 3;
// ==================== J-SPACE INTEGRATION ====================
const JSPACE_DIR = path.join(__dirname, 'jspace');
const JSPACE_DATA_PATH = path.join(JSPACE_DIR, 'qwen2.5_0.5b_jspace.json');
let jspaceDirections = {};
let jspaceCache = new Map();
function loadJspace() {
if (!fs.existsSync(JSPACE_DIR)) fs.mkdirSync(JSPACE_DIR, { recursive: true });
if (fs.existsSync(JSPACE_DATA_PATH)) {
try {
const raw = fs.readFileSync(JSPACE_DATA_PATH, 'utf-8');
jspaceDirections = JSON.parse(raw);
console.log(`[JSPACE] Loaded ${Object.keys(jspaceDirections).length} layers from ${JSPACE_DATA_PATH}`);
} catch (e) {
console.error('[JSPACE] Failed to load directions:', e.message);
}
} else {
console.warn('[JSPACE] No J-space data found. Using stub.');
jspaceDirections = {
"layer_12": [
{ name: "math", vector: new Array(512).fill(0).map(() => Math.random()*0.1) },
{ name: "planning", vector: new Array(512).fill(0).map(() => Math.random()*0.1) },
{ name: "safety", vector: new Array(512).fill(0).map(() => Math.random()*0.1) }
]
};
fs.writeFileSync(JSPACE_DATA_PATH, JSON.stringify(jspaceDirections, null, 2));
}
}
loadJspace();
function projectJspace(embedding, layer = "layer_12") {
if (!embedding || !jspaceDirections[layer]) return null;
const dirs = jspaceDirections[layer];
const result = {};
for (const d of dirs) {
let dot = 0;
const vec = d.vector;
const len = Math.min(embedding.length, vec.length);
for (let i = 0; i < len; i++) dot += embedding[i] * vec[i];
result[d.name] = dot;
}
return result;
}
async function getJspaceForText(text) {
const emb = await getEmbedding(text);
if (!emb) return null;
return projectJspace(emb);
}
async function getJspaceCached(text) {
const key = text.slice(0, 200);
if (jspaceCache.has(key)) return jspaceCache.get(key);
const result = await getJspaceForText(text);
if (result) jspaceCache.set(key, result);
return result;
}
// ==================== SQLite PERSISTENCE ====================
const DB_PATH = path.join(__dirname, 'db', 'lack.db');
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
const db = new sqlite3(DB_PATH);
db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY,
store_id TEXT NOT NULL,
sender TEXT NOT NULL,
sender_type TEXT,
content TEXT,
timestamp INTEGER,
parent_id TEXT,
thread_id TEXT,
reply_count INTEGER DEFAULT 0,
reactions TEXT
);
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
name TEXT,
model TEXT,
system_prompt TEXT,
channels TEXT,
strict_channel TEXT,
status TEXT,
is_embed_operator INTEGER DEFAULT 0,
is_code_moderator INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS agent_memory (
agent_id TEXT PRIMARY KEY,
e_pool TEXT,
x_pool TEXT,
weights TEXT,
stats TEXT,
last_update INTEGER
);
CREATE TABLE IF NOT EXISTS project_states (
store_id TEXT PRIMARY KEY,
state TEXT,
timestamp INTEGER
);
CREATE TABLE IF NOT EXISTS pipeline_results (
id TEXT PRIMARY KEY,
agent_id TEXT,
thread_id TEXT,
code_hash TEXT,
passed INTEGER,
attempt INTEGER,
feedback TEXT,
timestamp INTEGER
);
CREATE TABLE IF NOT EXISTS loop_health (
loop_id TEXT PRIMARY KEY,
loop_type TEXT,
iterations INTEGER,
convergence REAL,
stagnation REAL,
token_spend INTEGER,
last_update INTEGER
);
`);
function dbSaveMessage(msg, storeId) {
const stmt = db.prepare(`
INSERT OR REPLACE INTO messages
(id, store_id, sender, sender_type, content, timestamp, parent_id, thread_id, reply_count, reactions)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
msg.id, storeId, msg.sender, msg.senderType || 'agent',
msg.content, msg.timestamp, msg.parentId || null,
msg.threadId || null, msg.replyCount || 0,
JSON.stringify(msg.reactions || {})
);
}
function dbGetMessages(storeId, limit = 1000) {
const stmt = db.prepare('SELECT * FROM messages WHERE store_id = ? ORDER BY timestamp ASC LIMIT ?');
const rows = stmt.all(storeId, limit);
return rows.map(row => ({
id: row.id,
sender: row.sender,
senderType: row.sender_type,
content: row.content,
timestamp: row.timestamp,
parentId: row.parent_id,
threadId: row.thread_id,
replyCount: row.reply_count,
reactions: JSON.parse(row.reactions || '{}')
}));
}
function dbSaveAgent(agent) {
const stmt = db.prepare(`
INSERT OR REPLACE INTO agents
(id, name, model, system_prompt, channels, strict_channel, status, is_embed_operator, is_code_moderator)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
agent.id, agent.name, agent.model, agent.systemPrompt,
JSON.stringify(agent.channels || []), agent.strictChannel || null,
agent.status || 'online',
agent.isEmbedOperator ? 1 : 0,
agent.isCodeModerator ? 1 : 0
);
}
function dbLoadAllAgents() {
const stmt = db.prepare('SELECT * FROM agents');
const rows = stmt.all();
const result = {};
for (const row of rows) {
result[row.id] = {
id: row.id,
name: row.name,
model: row.model,
systemPrompt: row.system_prompt,
channels: JSON.parse(row.channels || '[]'),
strictChannel: row.strict_channel,
status: row.status,
isEmbedOperator: !!row.is_embed_operator,
isCodeModerator: !!row.is_code_moderator,
lastResponseTime: new Map()
};
}
return result;
}
// ==================== EMBEDDING CACHE ====================
const embeddingCache = new Map();
const CACHE_MAX_SIZE = 500;
const CACHE_TTL_MS = 60 * 60 * 1000;
function getCachedEmbedding(text) {
const key = text.slice(0, 500);
const entry = embeddingCache.get(key);
if (entry && (Date.now() - entry.timestamp) < CACHE_TTL_MS) {
return entry.embedding;
}
if (entry) embeddingCache.delete(key);
return null;
}
function setCachedEmbedding(text, embedding) {
const key = text.slice(0, 500);
if (embeddingCache.size >= CACHE_MAX_SIZE) {
const firstKey = embeddingCache.keys().next().value;
embeddingCache.delete(firstKey);
}
embeddingCache.set(key, { embedding, timestamp: Date.now() });
}
// ==================== SEARCH PROVIDERS ====================
const SEARCH_PROVIDER = config.searchProvider || "duckduckgo";
const SERPAPI_KEY = config.serpapiKey || "";
const FIRECRAWL_API_KEY = config.firecrawlApiKey || "";
const SEARCH_MAX_RESULTS = config.searchMaxResults || 5;
const SCRAPE_TIMEOUT = config.scrapeTimeout || 8000;
async function searchDuckDuckGo(query, maxResults = SEARCH_MAX_RESULTS) {
const searchUrls = [
`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`,
`https://lite.duckduckgo.com/lite/?q=${encodeURIComponent(query)}`
];
for (const baseUrl of searchUrls) {
try {
const { data } = await axiosWithRetry({
method: 'get', url: baseUrl,
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; LACK-SIPHON/4.2.0)' },
timeout: SCRAPE_TIMEOUT
});
const $ = cheerio.load(data);
const results = [];
if (baseUrl.includes('html.duckduckgo.com')) {
$('.result__url').each((i, el) => {
let href = $(el).attr('href');
if (href && href.startsWith('/')) href = 'https://duckduckgo.com' + href;
if (href && href.startsWith('http') && results.length < maxResults) results.push(href);
});
} else {
$('a').each((i, el) => {
const href = $(el).attr('href');
if (href && href.startsWith('http') && results.length < maxResults) results.push(href);
});
}
if (results.length > 0) return results;
} catch (e) {
logError({ context: 'searchDuckDuckGo', error: e.message, query: query.substring(0,60) });
}
}
return [];
}
async function searchSerpApi(query, maxResults = SEARCH_MAX_RESULTS) {
if (!SERPAPI_KEY) return [];
try {
const url = `https://serpapi.com/search.json?q=${encodeURIComponent(query)}&api_key=${SERPAPI_KEY}&num=${maxResults}`;
const { data } = await axiosWithRetry({ method: 'get', url, timeout: SCRAPE_TIMEOUT });
if (data.organic_results) {
return data.organic_results.map(r => r.link).filter(Boolean).slice(0, maxResults);
}
return [];
} catch (e) {
logError({ context: 'searchSerpApi', error: e.message, query });
return [];
}
}
async function searchFirecrawl(query, maxResults = SEARCH_MAX_RESULTS) {
if (!FIRECRAWL_API_KEY) return [];
try {
const url = `https://api.firecrawl.dev/v1/search?q=${encodeURIComponent(query)}&limit=${maxResults}`;
const { data } = await axiosWithRetry({
method: 'get', url,
headers: { 'Authorization': `Bearer ${FIRECRAWL_API_KEY}` },
timeout: SCRAPE_TIMEOUT
});
if (data && data.results) {
return data.results.map(r => r.url).filter(Boolean).slice(0, maxResults);
}
return [];
} catch (e) {
logError({ context: 'searchFirecrawl', error: e.message, query });
return [];
}
}
async function performSearch(query, maxResults = SEARCH_MAX_RESULTS) {
let urls = [];
if (SEARCH_PROVIDER === 'serpapi') {
urls = await searchSerpApi(query, maxResults);
} else if (SEARCH_PROVIDER === 'firecrawl') {
urls = await searchFirecrawl(query, maxResults);
} else {
urls = await searchDuckDuckGo(query, maxResults);
}
if (urls.length === 0 && SEARCH_PROVIDER !== 'duckduckgo') {
urls = await searchDuckDuckGo(query, maxResults);
}
return urls;
}
// ==================== REVERSE‑SKILL CONSTANTS ====================
const REVERSE_SKILL_ROOT = path.join(__dirname, 'reverse-skill');
const SKILL_OUTPUT_DIR = path.join(__dirname, 'workspace', 'skills');
fs.mkdirSync(SKILL_OUTPUT_DIR, { recursive: true });
// ==================== LOGGING ====================
global.errorLog = [];
function logError(errorObj) {
const entry = { timestamp: Date.now(), ...errorObj };
try { fs.appendFileSync(ERROR_LOG_PATH, JSON.stringify(entry) + '\n'); } catch (e) {}
global.errorLog.unshift(entry);
if (global.errorLog.length > 200) global.errorLog.pop();
console.error('[ERROR]', entry);
}
process.on('uncaughtException', (err) => {
console.error('🔥 Uncaught Exception:', err);
if (typeof logError === 'function') logError({ context: 'uncaughtException', error: err.stack });
});
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ Unhandled Rejection:', reason);
if (typeof logError === 'function') logError({ context: 'unhandledRejection', error: reason });
});
process.on('SIGTERM', () => { console.log('[LACK] SIGTERM received, shutting down...'); process.exit(0); });
process.on('SIGINT', () => { console.log('[LACK] SIGINT received, shutting down...'); process.exit(0); });
// ==================== STACK CORE ====================
const STACK_ROOT = path.join(__dirname, 'lack_repos');
const TEMPLATES_DIR = path.join(STACK_ROOT, 'templates');
const MANIFEST_PATH = path.join(TEMPLATES_DIR, 'manifest.json');
fs.mkdirSync(STACK_ROOT, { recursive: true });
fs.mkdirSync(TEMPLATES_DIR, { recursive: true });
let stackManifest = {};
function simpleTfidfSimilarity(text1, text2) {
const words1 = text1.toLowerCase().split(/\W+/);
const words2 = text2.toLowerCase().split(/\W+/);
const set = new Set([...words1, ...words2]);
const vec1 = set.size ? set.map(w => words1.includes(w) ? 1 : 0) : [];
const vec2 = set.size ? set.map(w => words2.includes(w) ? 1 : 0) : [];
let dot=0, norm1=0, norm2=0;
for (let i=0; i<vec1.length; i++) {
dot += vec1[i]*vec2[i];
norm1 += vec1[i]*vec1[i];
norm2 += vec2[i]*vec2[i];
}
if (norm1===0 || norm2===0) return 0;
return dot / (Math.sqrt(norm1)*Math.sqrt(norm2));
}
async function getEmbedding(text) {
const cached = getCachedEmbedding(text);
if (cached) return cached;
try {
const res = await axios.post('http://localhost:11434/api/embeddings', {
model: EMBEDDING_MODEL,
prompt: text.slice(0, 2000)
});
const emb = res.data.embedding;
setCachedEmbedding(text, emb);
return emb;
} catch (e) {
logError({ context: 'getEmbedding', error: e.message });
return null;
}
}
function cosineSimilarity(v1, v2) {
if (!v1 || !v2 || v1.length !== v2.length) return 0;
let dot = 0, mag1 = 0, mag2 = 0;
for (let i = 0; i < v1.length; i++) {
dot += v1[i] * v2[i];
mag1 += v1[i] * v1[i];
mag2 += v2[i] * v2[i];
}
return dot / (Math.sqrt(mag1) * Math.sqrt(mag2));
}
async function scanAndReindexTemplates() {
if (!fs.existsSync(TEMPLATES_DIR)) return;
const items = fs.readdirSync(TEMPLATES_DIR, { withFileTypes: true });
const newManifest = {};
for (const item of items) {
if (item.isDirectory()) {
const templatePath = path.join(TEMPLATES_DIR, item.name);
let combinedText = '';
const files = {};
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const e of entries) {
const full = path.join(dir, e.name);
if (e.isDirectory()) walk(full);
else if (/\.(js|json|md|txt|py|html|css)$/.test(e.name)) {
const content = fs.readFileSync(full, 'utf-8');
combinedText += content + '\n';
files[path.relative(templatePath, full)] = content;
}
}
};
walk(templatePath);
if (combinedText.length === 0) continue;
const vector = await getEmbedding(combinedText);
if (vector) newManifest[item.name] = { vector, files };
else {
newManifest[item.name] = { text: combinedText, files };
}
}
}
stackManifest = newManifest;
fs.writeFileSync(MANIFEST_PATH, JSON.stringify(stackManifest, null, 2));
console.log(`[STACK] Reindexed ${Object.keys(stackManifest).length} templates`);
}
async function stackBuild(repoName) {
const repoPath = path.join(STACK_ROOT, repoName);
if (fs.existsSync(repoPath)) return `⚠️ Repository ${repoName} already exists.`;
fs.mkdirSync(repoPath, { recursive: true });
await execPromise(`git init && git checkout -b main`, { cwd: repoPath });
const configFile = path.join(repoPath, 'STACK_CONFIG.json');
fs.writeFileSync(configFile, JSON.stringify({ project: repoName, managedBy: "LACK-STACK" }, null, 2));
return `✅ STACK repository **${repoName}** created at ${repoPath}`;
}
async function stackAdd(intent, storeId) {
if (!fs.existsSync(MANIFEST_PATH)) return "No templates found. Add folders to ./lack_repos/templates/ first.";
const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf-8'));
let queryVec = await getEmbedding(intent);
let useFallback = !queryVec;
let best = null, bestScore = -1;
if (useFallback) {
console.warn('[STACK] Embedding failed, using keyword/TF‑IDF fallback');
const intentWords = intent.toLowerCase().split(/\s+/);
for (const [name, data] of Object.entries(manifest)) {
const combinedText = data.text || Object.values(data.files).join(' ').toLowerCase();
let score = 0;
const sim = simpleTfidfSimilarity(intent, combinedText);
if (sim > bestScore) { bestScore = sim; best = { name, files: data.files }; }
for (const word of intentWords) if (combinedText.includes(word)) score++;
if (score > bestScore) { bestScore = score; best = { name, files: data.files }; }
}
if (best && bestScore > 0) {
const activeRepo = activeStackRepo.get(storeId) || 'default';
const repoPath = path.join(STACK_ROOT, activeRepo);
if (!fs.existsSync(repoPath)) return `No active repository. Use /stack set <repo> first.`;
for (const [relPath, content] of Object.entries(best.files)) {
const target = path.join(repoPath, relPath);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
await execPromise(`git add . && git commit -m "STACK add: ${best.name}"`, { cwd: repoPath }).catch(e => console.warn(e));
return `🔍 Match: **${best.name}** (score ${bestScore}) – fallback used.\nApplied ${Object.keys(best.files).length} files to ${activeRepo}.`;
} else {
return `No template matches "${intent}".`;
}
}
for (const [name, data] of Object.entries(manifest)) {
if (!data.vector) continue;
const score = cosineSimilarity(queryVec, data.vector);
if (score > bestScore) { bestScore = score; best = { name, files: data.files }; }
}
if (best && bestScore > 0.45) {
const activeRepo = activeStackRepo.get(storeId) || 'default';
const repoPath = path.join(STACK_ROOT, activeRepo);
if (!fs.existsSync(repoPath)) return `No active repository. Use /stack set <repo> first.`;
for (const [relPath, content] of Object.entries(best.files)) {
const target = path.join(repoPath, relPath);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
await execPromise(`git add . && git commit -m "STACK add: ${best.name}"`, { cwd: repoPath }).catch(e => console.warn(e));
return `🔍 Best match: **${best.name}** (score ${bestScore.toFixed(2)})\nApplied ${Object.keys(best.files).length} files to ${activeRepo}.`;
} else {
return `No strong match for "${intent}" (best score ${bestScore.toFixed(2)}).`;
}
}
async function stackImport(jsonPath) {
const fullPath = path.resolve(jsonPath);
if (!fs.existsSync(fullPath)) return `File not found: ${fullPath}`;
const data = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
if (!data.templates) return "Invalid format: missing 'templates' key.";
for (const [name, template] of Object.entries(data.templates)) {
const dir = path.join(TEMPLATES_DIR, name);
fs.mkdirSync(dir, { recursive: true });
for (const [file, content] of Object.entries(template.files || {})) {
const target = path.join(dir, file);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
}
await scanAndReindexTemplates();
return `Imported ${Object.keys(data.templates).length} templates.`;
}
let stackWatcher = null;
function startStackWatcher() {
if (stackWatcher) clearInterval(stackWatcher);
stackWatcher = setInterval(async () => {
const oldKeys = Object.keys(stackManifest);
await scanAndReindexTemplates();
const newKeys = Object.keys(stackManifest);
if (JSON.stringify(oldKeys) !== JSON.stringify(newKeys))
console.log('[STACK] Templates changed, reindexed.');
}, 10000);
}
const activeStackRepo = new Map();
// ==================== JSON EXTRACTION ====================
function repairJSON(str) {
if (!str || typeof str !== 'string') return str;
str = str.replace(/```json\s*|```\s*/g, '');
str = str.replace(/(\{|\,)\s*([a-zA-Z0-9_]+)\s*\:/g, '$1"$2":');
str = str.replace(/,\s*\}/g, '}').replace(/,\s*\]/g, ']');
str = str.replace(/'/g, '"');
let openBraces = (str.match(/\{/g) || []).length;
let closeBraces = (str.match(/\}/g) || []).length;
let openBrackets = (str.match(/\[/g) || []).length;
let closeBrackets = (str.match(/\]/g) || []).length;
str += '}'.repeat(openBraces - closeBraces) + ']'.repeat(openBrackets - closeBrackets);
return str;
}
function extractJSON(str) {
str = repairJSON(str);
if (!str || typeof str !== 'string') return null;
str = str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
const jsonBlock = str.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonBlock && jsonBlock[1]) {
try { return JSON.parse(jsonBlock[1].trim()); } catch(e) {}
}
let start = str.indexOf('{');
if (start === -1) return null;
let depth = 0, end = -1;
for (let i = start; i < str.length; i++) {
if (str[i] === '{') depth++;
else if (str[i] === '}') { depth--; if (depth === 0) { end = i; break; } }
}
if (end !== -1) {
try { return JSON.parse(str.substring(start, end + 1)); } catch(e) {
let fragment = str.substring(start, end + 1);
let opens = (fragment.match(/\{/g) || []).length - (fragment.match(/\}/g) || []).length;
let arrOpens = (fragment.match(/\[/g) || []).length - (fragment.match(/\]/g) || []).length;
fragment += ']'.repeat(Math.max(0, arrOpens)) + '}'.repeat(Math.max(0, opens));
try { return JSON.parse(fragment); } catch(e2) {}
}
}
const possible = str.match(/\{[\s\S]*\}/);
if (possible) {
try { return JSON.parse(possible[0]); } catch(e) {}
}
return null;
}
function ensureCodeBlock(text, language) {
if (text.includes('```')) return text;
if (text.includes('<html') || text.includes('def ') || text.includes('function(') ||
text.includes('class ') || text.includes('import ') || text.includes('require(')) {
return '```' + (language || 'text') + '\n' + text + '\n```';
}
return text;
}
// ==================== CHANNEL GUARDRAILS ====================
function getChannelPersonality(channelName) {
if (channelName === 'code') {
return {
temperature: 0.3,
systemBonus: "\n\n# STRICT CODE CHANNEL RULES:\n- You are in #code. Output ONLY clean code blocks with ```lang\\ncode\\n```. NO explanations, NO chat, NO research. If asked for non-code, say 'Use #general or #siphon'.",
planBonus: "Output pure code only. Use tool_calls if needed but prefer direct code response.",
planForbidden: false,
useMusing: false,
useTriangulation: false
};
} else if (channelName === 'siphon') {
return {
temperature: 0.2,
systemBonus: "\n\n# SIPHON RESEARCH CHANNEL:\n- You are in #siphon. Be factual, concise, research-focused. Use 🔍 prefix for findings. Output web-scraped facts and summaries here.",
planBonus: "Prefer research actions and factual output.",
planForbidden: false,
useMusing: false,
useTriangulation: true
};
}
// general
return {
temperature: 0.7,
systemBonus: "",
planBonus: "",
planForbidden: false,
useMusing: true,
useTriangulation: false
};
}
// ==================== DECENTMEM ====================
const AGENT_MEMORY_DIR = path.join(__dirname, 'agent_memories');
fs.mkdirSync(AGENT_MEMORY_DIR, { recursive: true });
const agentMemories = new Map();
const PUBLIC_MEMORY_SUMMARY = { lastUpdated: 0, summary: '', embeddings: null, enabled: config.enablePublicMemory || false };
function initAgentMemory(agentId) {
const memPath = path.join(AGENT_MEMORY_DIR, `${agentId}.json`);
let memory = {
ePool: [],
xPool: [],
weights: { exploitation: 0.6, exploration: 0.4 },
stats: { totalJudgements: 0, avgScore: 50, lastJudgeTime: 0 },
lastUpdate: Date.now(),
jspaceHistory: []
};
if (fs.existsSync(memPath)) {
try {
const loaded = JSON.parse(fs.readFileSync(memPath, 'utf-8'));
memory = { ...memory, ...loaded };
} catch(e) { logError({ context: 'initAgentMemory', error: e.message, agentId }); }
}
agentMemories.set(agentId, memory);
saveAgentMemory(agentId);
}
function saveAgentMemory(agentId) {
const mem = agentMemories.get(agentId);
if (!mem) return;
const memPath = path.join(AGENT_MEMORY_DIR, `${agentId}.json`);
try {
fs.writeFileSync(memPath, JSON.stringify(mem, null, 2));
} catch(e) { logError({ context: 'saveAgentMemory', error: e.message, agentId }); }
}
async function addToMemory(agentId, trajectory, score, task = 'general', textForEmbedding = null) {
const mem = agentMemories.get(agentId);
if (!mem) return;
let embedding = null;
if (textForEmbedding) embedding = await getEmbedding(textForEmbedding);
const entry = { trajectory, score: Math.min(1, Math.max(0, score / 100)), task, timestamp: Date.now(), embedding };
if (score >= 60) {
mem.ePool.unshift(entry);
if (mem.ePool.length > 50) mem.ePool.pop();
} else {
mem.xPool.unshift({ candidate: trajectory, score: score/100, timestamp: Date.now(), embedding });
if (mem.xPool.length > 30) mem.xPool.pop();
}
mem.stats.totalJudgements++;
mem.stats.avgScore = (mem.stats.avgScore * (mem.stats.totalJudgements - 1) + score) / mem.stats.totalJudgements;
mem.stats.lastJudgeTime = Date.now();
mem.lastUpdate = Date.now();
if (JSPACE_ENABLED) {
const jspace = await getJspaceCached(textForEmbedding || trajectory);
if (jspace) {
mem.jspaceHistory.push({ timestamp: Date.now(), jspace, text: (textForEmbedding || trajectory).slice(0,200) });
if (mem.jspaceHistory.length > 20) mem.jspaceHistory.shift();
}
}
saveAgentMemory(agentId);
}
async function retrievePrivateMemory(agentId, query, k = 5, useEmbedding = true) {
const mem = agentMemories.get(agentId);
if (!mem) return [];
let combined = [
...mem.ePool.map(e => ({ text: e.trajectory, score: e.score, type: 'e', embedding: e.embedding })),
...mem.xPool.map(x => ({ text: x.candidate, score: x.score, type: 'x', embedding: x.embedding }))
];
if (useEmbedding && combined.some(item => item.embedding)) {
const queryEmbedding = await getEmbedding(query);
if (queryEmbedding) {
for (let item of combined) {
if (item.embedding) item.sim = cosineSimilarity(queryEmbedding, item.embedding);
else item.sim = simpleTfidfSimilarity(query, item.text);
}
combined.sort((a,b) => (b.sim || 0) - (a.sim || 0));
} else {
combined.sort((a,b) => b.score - a.score);
}
} else {
combined.sort((a,b) => b.score - a.score);
}
return combined.slice(0, k).map(item => `[${item.type === 'e' ? 'PROVEN' : 'EXPLORE'}] ${item.text.substring(0, 300)}`).join('\n');
}
async function retrieveRecentContext(agentId, query, maxMessages = 10) {
const agent = agents.get(agentId);
if (!agent) return '';
let candidateMessages = [];
for (let ch of channels.values()) {
if (agent.channels.includes(ch.name)) {
const recent = ch.messages.slice(-20);
for (const msg of recent) {
candidateMessages.push({ text: `${msg.sender}: ${msg.content}`, timestamp: msg.timestamp, channel: ch.name });
}
}
}
candidateMessages.sort((a,b) => b.timestamp - a.timestamp);
candidateMessages = candidateMessages.slice(0, 50);
if (candidateMessages.length === 0) return '';
const queryEmbedding = await getEmbedding(query);
if (!queryEmbedding) {
return candidateMessages.slice(0, maxMessages).map(m => m.text).join('\n');
}
for (let msg of candidateMessages) {
let msgEmbedding = getCachedEmbedding(msg.text);
if (!msgEmbedding) msgEmbedding = await getEmbedding(msg.text);
if (msgEmbedding) msg.sim = cosineSimilarity(queryEmbedding, msgEmbedding);
else msg.sim = simpleTfidfSimilarity(query, msg.text);
}
candidateMessages.sort((a,b) => b.sim - a.sim);
return candidateMessages.slice(0, maxMessages).map(m => `[${m.channel}] ${m.text}`).join('\n');
}
async function generateXPoolCandidates(agentId, context, num = 3) {
const agent = agents.get(agentId);
if (!agent) return [];
let jspaceHint = '';
if (JSPACE_ENABLED) {
const jspace = await getJspaceCached(context);
if (jspace) {
const topConcepts = Object.entries(jspace)
.sort((a,b) => b[1] - a[1])
.slice(0, JSPACE_CONCEPT_COUNT)
.map(([name, val]) => `${name}: ${val.toFixed(2)}`).join(', ');
jspaceHint = `\nCurrent J-space (silent reasoning): ${topConcepts}`;
}
}
// Use musing to generate varied candidates
let candidates = [];
if (ENABLE_MUSING) {
const musePrompt = `Generate ${num} novel, creative strategies or reasoning variants for the following context. Be diverse but grounded. Return each on a new line starting with "IDEA:".\n\nContext: ${context}${jspaceHint}`;
// We'll generate multiple candidates by varying temperature
const temps = [0.5, 0.7, 0.9];
const allReplies = [];
for (const t of temps) {
const reply = await queryOllama(agent.model, musePrompt, 'You are an idea generator.', t, agentId);
if (!reply.startsWith('[OLLAMA_ERROR]')) {
allReplies.push(reply);
}
}
// Extract ideas from all replies
const ideaSet = new Set();
for (const rep of allReplies) {
const lines = rep.split('\n').filter(l => l.startsWith('IDEA:')).map(l => l.replace('IDEA:', '').trim());
for (const idea of lines) {
if (!ideaSet.has(idea)) {
ideaSet.add(idea);
candidates.push(idea);
}
}
}
}
// Fallback: if musing disabled or no candidates, use single query
if (candidates.length === 0) {
const prompt = `Generate ${num} novel, creative strategies or reasoning variants for the following context. Be diverse but grounded. Return each on a new line starting with "IDEA:".\n\nContext: ${context}${jspaceHint}`;
const reply = await queryOllama(agent.model, prompt, 'You are an idea generator.', 0.9, agentId);
if (!reply.startsWith('[OLLAMA_ERROR]')) {
candidates = reply.split('\n').filter(l => l.startsWith('IDEA:')).map(l => l.replace('IDEA:', '').trim());
}
}
const mem = agentMemories.get(agentId);
if (mem) {
for (const idea of candidates.slice(0, num)) {
let initialScore = 30;
try {
const judgeRes = await judgeAndReweight(agentId, idea, 'x_pool_candidate', true);
if (judgeRes && typeof judgeRes === 'number') initialScore = judgeRes;
} catch(e) {}
const embedding = await getEmbedding(idea);
mem.xPool.unshift({ candidate: idea, score: initialScore / 100, timestamp: Date.now(), embedding });
}
if (mem.xPool.length > 30) mem.xPool = mem.xPool.slice(0, 30);
saveAgentMemory(agentId);
}
return candidates;
}
async function judgeAndReweight(agentId, trajectory, stageContext, lightweight = false) {
const agent = agents.get(agentId);
if (!agent || agent.isEmbedOperator) return 50;
if (lightweight) {
let score = 50;
const lower = trajectory.toLowerCase();
if (lower.includes('success') || lower.includes('good') || lower.includes('excellent')) score = 75;
else if (lower.includes('fail') || lower.includes('error')) score = 30;
else score = 50;
const mem = agentMemories.get(agentId);
if (mem) {
let delta = (score - 50) / 200;
mem.weights.exploitation = Math.min(0.85, Math.max(0.15, mem.weights.exploitation + delta));
mem.weights.exploration = 1 - mem.weights.exploitation;
saveAgentMemory(agentId);
}
await addToMemory(agentId, trajectory, score, stageContext, trajectory);
return score;
}
const judgePrompt = `You are a strict judge. Rate the following trajectory/stage (0-100) for quality, novelty, and usefulness. Output ONLY a JSON object: {"score": number, "reason": "short"}\n\nStage: ${stageContext}\nTrajectory: ${trajectory.substring(0, 1500)}`;
let reply = await queryOllama(agent.model, judgePrompt, 'Output only valid JSON.', 0.2, agentId);
let score = 50;
if (!reply.startsWith('[OLLAMA_ERROR]')) {
const parsed = extractJSON(reply);
if (parsed && typeof parsed.score === 'number') score = Math.min(100, Math.max(0, parsed.score));
else {
const lower = trajectory.toLowerCase();
if (lower.includes('success') || lower.includes('good')) score = 75;
else if (lower.includes('fail')) score = 30;
else score = 50;
}
} else {
score = 50;
}
const mem = agentMemories.get(agentId);
if (mem) {
let delta = (score - 50) / 200;
mem.weights.exploitation = Math.min(0.85, Math.max(0.15, mem.weights.exploitation + delta));
mem.weights.exploration = 1 - mem.weights.exploitation;
saveAgentMemory(agentId);
}
await addToMemory(agentId, trajectory, score, stageContext, trajectory);
return score;
}
async function pruneAgentMemory(agentId) {
const mem = agentMemories.get(agentId);
if (!mem) return;
const now = Date.now();
const maxAge = 30 * 24 * 60 * 60 * 1000;
mem.ePool = mem.ePool.filter(e => now - e.timestamp < maxAge);
mem.xPool = mem.xPool.filter(x => now - x.timestamp < maxAge);
const toKeep = [];
for (let i = 0; i < mem.ePool.length; i++) {
let duplicate = false;
for (let j = 0; j < toKeep.length; j++) {
if (mem.ePool[i].embedding && toKeep[j].embedding) {
const sim = cosineSimilarity(mem.ePool[i].embedding, toKeep[j].embedding);
if (sim > 0.9) {
duplicate = true;
toKeep[j].score = Math.max(toKeep[j].score, mem.ePool[i].score);
break;
}
} else if (mem.ePool[i].trajectory === toKeep[j].trajectory) {
duplicate = true;
toKeep[j].score = Math.max(toKeep[j].score, mem.ePool[i].score);
break;
}
}
if (!duplicate) toKeep.push(mem.ePool[i]);
}
mem.ePool = toKeep;
saveAgentMemory(agentId);
}
const maintenanceCircuit = new Map();
async function runMaintenanceTask(taskName, taskFn, maxRetries = 3) {
const circuit = maintenanceCircuit.get(taskName) || { failures: 0, backoffUntil: 0 };
if (circuit.backoffUntil > Date.now()) {
console.log(`[MAINT] Skipping ${taskName}, circuit open`);
return;