-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1376 lines (1215 loc) · 42.2 KB
/
Copy pathserver.js
File metadata and controls
1376 lines (1215 loc) · 42.2 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
import 'dotenv/config';
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
import path from 'path';
import dotenv from 'dotenv';
import fs from 'fs';
import { processTerminalMessage, initializeTerminalAI, fetchAvailableModels } from './src/coreai/mgmt/terminalAI.js';
import { fileURLToPath } from 'url';
import { runResearch } from './src/runResearch.js'; // Using existing file path
import { getChatHistory, saveChatMessage } from './src/coreai/mgmt/historyManager.js';
import { getCoreMemoryAI } from './src/memory/core-memory-ai.js';
import { getVeniceMemoryClient } from './src/memory/venice-memory-client.js';
import * as memoryController from './src/memory/memory-controller.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Make io available globally for scheduler status updates
global.io = io;
// Setup express static middleware
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Express routes
app.get('/', (req, res) => {
res.render('terminal');
});
app.get('/research', (req, res) => {
res.render('research');
});
app.get('/admin', (req, res) => {
res.render('admin');
});
app.get('/github', (req, res) => {
res.render('github');
});
app.get('/memory', (req, res) => {
res.render('memory');
});
app.get('/self', (req, res) => {
res.render('self');
});
// Socket.io connection handler
io.on('connection', (socket) => {
console.log('User connected');
// Check if research directory exists
(async () => {
try {
await fs.promises.access(path.join(__dirname, 'research'));
console.log('Research directory exists');
} catch (err) {
try {
await fs.promises.mkdir(path.join(__dirname, 'research'), { recursive: true });
console.log('Created research directory');
} catch (err) {
console.error('Error creating research directory:', err);
}
}
})();
socket.on('save-config', async data => {
if (data.github) {
socket.emit('plugin-status', { plugin: 'github', status: 'ACTIVE' });
}
try {
// Add your code here if needed
} catch (err) {
console.error('Error saving configuration:', err);
socket.emit('config-error', { message: 'Failed to save configuration' });
}
});
socket.on('save-research-settings', async data => {
try {
if (!global.researchSettings) global.researchSettings = {};
if (data.defaultDepth)
global.researchSettings.defaultDepth = parseInt(data.defaultDepth, 10);
if (data.defaultBreadth)
global.researchSettings.defaultBreadth = parseInt(
data.defaultBreadth,
10,
);
if (data.publicResearch !== undefined)
global.researchSettings.publicResearch = data.publicResearch;
const configPath = path.join(__dirname, 'config.json');
let config = {};
try {
const configContent = await fs.promises.readFile(configPath, 'utf8');
config = JSON.parse(configContent);
} catch (err) {
config = {};
}
config.researchSettings = global.researchSettings;
await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
socket.emit('research-settings-saved', {
message: 'Research settings saved successfully',
});
} catch (err) {
console.error('Error saving research settings:', err);
socket.emit('config-error', {
message: 'Failed to save research settings',
});
}
});
socket.on('save-github-settings', async data => {
try {
if (!global.githubSettings) global.githubSettings = {};
if (data.owner) global.githubSettings.owner = data.owner;
if (data.researchRepo)
global.githubSettings.researchRepo = data.researchRepo;
if (data.branch) global.githubSettings.branch = data.branch;
if (data.path) global.githubSettings.path = data.path;
const configPath = path.join(__dirname, 'config.json');
let config = {};
try {
const configContent = await fs.promises.readFile(configPath, 'utf8');
config = JSON.parse(configContent);
} catch (err) {
config = {};
}
config.githubSettings = global.githubSettings;
await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
let envContent = '';
try {
envContent = await fs.promises.readFile('.env', 'utf8');
} catch (err) {
envContent = '';
}
if (data.owner) {
process.env.GITHUB_OWNER = data.owner;
envContent = envContent.includes('GITHUB_OWNER=')
? envContent.replace(
/GITHUB_OWNER=.*\n?/,
`GITHUB_OWNER=${data.owner}\n`,
)
: envContent + `\nGITHUB_OWNER=${data.owner}`;
}
if (data.researchRepo) {
process.env.GITHUB_REPO = data.researchRepo;
envContent = envContent.includes('GITHUB_REPO=')
? envContent.replace(
/GITHUB_REPO=.*\n?/,
`GITHUB_REPO=${data.researchRepo}\n`,
)
: envContent + `\nGITHUB_REPO=${data.researchRepo}`;
}
if (data.branch) {
process.env.GITHUB_BRANCH = data.branch;
envContent = envContent.includes('GITHUB_BRANCH=')
? envContent.replace(
/GITHUB_BRANCH=.*\n?/,
`GITHUB_BRANCH=${data.branch}\n`,
)
: envContent + `\nGITHUB_BRANCH=${data.branch}`;
}
if (data.path) {
process.env.GITHUB_PATH = data.path;
envContent = envContent.includes('GITHUB_PATH=')
? envContent.replace(
/GITHUB_PATH=.*\n?/,
`GITHUB_PATH=${data.path}\n`,
)
: envContent + `\nGITHUB_PATH=${data.path}`;
}
await fs.promises.writeFile('.env', envContent.trim());
socket.emit('github-settings-saved', {
message: 'GitHub research repository settings saved successfully',
});
const githubConfigured =
!!process.env.GITHUB_TOKEN &&
!!process.env.GITHUB_OWNER &&
!!process.env.GITHUB_REPO;
if (githubConfigured)
socket.emit('plugin-status', { plugin: 'github', status: 'ACTIVE' });
} catch (err) {
console.error('Error saving GitHub settings:', err);
socket.emit('config-error', {
message: 'Failed to save GitHub settings',
});
}
});
socket.on('save-github-memory-settings', async data => {
try {
if (!global.githubSettings) global.githubSettings = {};
if (data.owner) global.githubSettings.owner = data.owner;
if (data.memoryRepo) global.githubSettings.memoryRepo = data.memoryRepo;
if (data.branch) global.githubSettings.memoryBranch = data.branch;
if (data.path) global.githubSettings.memoryPath = data.path;
const configPath = path.join(__dirname, 'config.json');
let config = {};
try {
const configContent = await fs.promises.readFile(configPath, 'utf8');
config = JSON.parse(configContent);
} catch (err) {
config = {};
}
config.githubSettings = global.githubSettings;
await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
let envContent = '';
try {
envContent = await fs.promises.readFile('.env', 'utf8');
} catch (err) {
envContent = '';
}
if (data.memoryRepo) {
process.env.GITHUB_MEMORY_REPO = data.memoryRepo;
envContent = envContent.includes('GITHUB_MEMORY_REPO=')
? envContent.replace(
/GITHUB_MEMORY_REPO=.*\n?/,
`GITHUB_MEMORY_REPO=${data.memoryRepo}\n`,
)
: envContent + `\nGITHUB_MEMORY_REPO=${data.memoryRepo}`;
}
if (data.branch) {
process.env.GITHUB_MEMORY_BRANCH = data.branch;
envContent = envContent.includes('GITHUB_MEMORY_BRANCH=')
? envContent.replace(
/GITHUB_MEMORY_BRANCH=.*\n?/,
`GITHUB_MEMORY_BRANCH=${data.branch}\n`,
)
: envContent + `\nGITHUB_MEMORY_BRANCH=${data.branch}`;
}
if (data.path) {
process.env.GITHUB_MEMORY_PATH = data.path;
envContent = envContent.includes('GITHUB_MEMORY_PATH=')
? envContent.replace(
/GITHUB_MEMORY_PATH=.*\n?/,
`GITHUB_MEMORY_PATH=${data.path}\n`,
)
: envContent + `\nGITHUB_MEMORY_PATH=${data.path}`;
}
await fs.promises.writeFile('.env', envContent.trim());
socket.emit('github-memory-settings-saved', {
message: 'GitHub memory repository settings saved successfully',
});
} catch (err) {
console.error('Error saving GitHub memory settings:', err);
socket.emit('config-error', {
message: 'Failed to save GitHub memory settings',
});
}
});
// ----------------------------
// System & Terminal AI Events
// ----------------------------
socket.on('get-system-stats', () => {
socket.emit('system-stats', getSystemStats());
});
socket.on('terminal:ai-message', async (data, callback) => {
try {
const terminalAI = await import('./src/coreai/mgmt/terminalAI.js');
const response = await terminalAI.processTerminalMessage(
data.message,
data.history || [],
);
callback(response);
} catch (error) {
console.error('Error processing terminal AI message:', error);
callback({
success: false,
response: `Error: ${error.message || 'Unknown error'}`,
});
}
});
socket.on('fetch-venice-models', async () => {
try {
const { fetchAvailableModels } = await import(
'./src/coreai/mgmt/terminalAI.js'
);
const modelsResponse = await fetchAvailableModels();
socket.emit('venice-models', modelsResponse);
} catch (error) {
console.error('Error handling fetch-venice-models:', error);
socket.emit('venice-models', {
success: false,
error: error.message || 'Failed to fetch models',
});
}
});
socket.on('chat-message', async (message, options = {}) => {
try {
const { processTerminalMessage } = await import(
'./src/coreai/mgmt/terminalAI.js'
);
const response = await processTerminalMessage(message, [], options);
socket.emit('chat-response', response);
if (response.reasoning) {
socket.emit('chat-reasoning', {
success: true,
reasoning: response.reasoning,
});
}
} catch (error) {
console.error('Error processing chat message:', error);
socket.emit('chat-response', {
success: false,
response: error.message || 'Error processing your message',
});
}
});
// ----------------------------
// Middleware for Research Thought Process
// ----------------------------
socket.use((packet, next) => {
if (packet[0] === 'research-thought' && packet[1]) {
const timestamp = new Date().toLocaleTimeString();
const thought = `[${timestamp}] ${packet[1].thought}`;
socket.emit('research-status', {
progress: packet[1].progress || 0,
message: packet[1].message || 'Processing...',
thoughtProcess: thought,
stage: packet[1].stage || 'researching',
});
socket.emit('research-thought', {
thought,
stage: packet[1].stage || 'researching',
});
console.log(`Research thought: ${packet[1].thought}`);
}
next();
});
// ----------------------------
// Disconnect Handler
// ----------------------------
socket.on('disconnect', () => {
console.log('User disconnected');
});
// ----------------------------
// Task Scheduler Socket Handlers
// ----------------------------
socket.on('self:get-tasks', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
const tasks = global.taskScheduler.getPrioritizedTasks();
callback({ success: true, tasks });
} catch (error) {
console.error('Error getting tasks:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:create-task', async (data, callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
const result = await global.taskScheduler.createTask(data);
callback(result);
} catch (error) {
console.error('Error creating task:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:execute-task', async (data, callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
const result = await global.taskScheduler.executeTask(data.taskPath);
callback(result);
} catch (error) {
console.error('Error executing task:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:cancel-task', async (data, callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
const result = await global.taskScheduler.cancelTask(data.taskPath);
callback(result);
} catch (error) {
console.error('Error cancelling task:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:delete-task', async (data, callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// Path check and validation
if (!data.taskPath) {
throw new Error('Task path is required');
}
// Use fs to delete the file directly if the scheduler doesn't have the method
if (typeof global.taskScheduler.deleteTask !== 'function') {
try {
await fs.promises.unlink(data.taskPath);
console.log(`Task file deleted: ${data.taskPath}`);
callback({ success: true, message: `Task deleted: ${data.taskPath}` });
return;
} catch (fsError) {
console.error('Error deleting task file:', fsError);
throw new Error(`Failed to delete task file: ${fsError.message}`);
}
} else {
const result = await global.taskScheduler.deleteTask(data.taskPath);
callback(result);
}
} catch (error) {
console.error('Error deleting task:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:view-task', async (data, callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// Path check and validation
if (!data.taskPath) {
throw new Error('Task path is required');
}
// If the scheduler doesn't have the viewTask method, implement a basic one
if (typeof global.taskScheduler.viewTask !== 'function') {
try {
const content = await fs.promises.readFile(data.taskPath, 'utf8');
callback({
success: true,
content,
path: data.taskPath
});
return;
} catch (fsError) {
throw new Error(`Failed to read task file: ${fsError.message}`);
}
} else {
const result = await global.taskScheduler.viewTask(data.taskPath);
callback(result);
}
} catch (error) {
console.error('Error viewing task:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:pull-tasks-from-github', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// Check for properly configured GitHub integration
if (!process.env.GITHUB_TOKEN || !process.env.GITHUB_OWNER || !process.env.GITHUB_REPO) {
throw new Error('GitHub is not properly configured. Please set up GitHub integration first.');
}
// If scheduler doesn't have the method, use the selfIntegration module directly
if (typeof global.taskScheduler.pullTasksFromGitHub !== 'function') {
const { pullFilesFromGitHub } = await import('./src/coreai/mgmt/selfIntegration.js');
const tasksDir = 'missions/tasks';
const result = await pullFilesFromGitHub(tasksDir);
callback({
success: true,
count: result.count || 0,
message: `Pulled ${result.count || 0} tasks from GitHub`
});
return;
}
const result = await global.taskScheduler.pullTasksFromGitHub();
callback(result);
} catch (error) {
console.error('Error pulling tasks from GitHub:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:push-tasks-to-github', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// Check for properly configured GitHub integration
if (!process.env.GITHUB_TOKEN || !process.env.GITHUB_OWNER || !process.env.GITHUB_REPO) {
throw new Error('GitHub is not properly configured. Please set up GitHub integration first.');
}
// If scheduler doesn't have the method, use the selfIntegration module directly
if (typeof global.taskScheduler.pushTasksToGitHub !== 'function') {
const { syncDirectoryToGitHub } = await import('./src/coreai/mgmt/selfIntegration.js');
const tasksDir = 'missions/tasks';
const result = await syncDirectoryToGitHub(tasksDir, 'Sync tasks to GitHub');
callback({
success: true,
count: result.count || 0,
message: `Pushed ${result.count || 0} tasks to GitHub`
});
return;
}
const result = await global.taskScheduler.pushTasksToGitHub();
callback(result);
} catch (error) {
console.error('Error pushing tasks to GitHub:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:sync-tasks-with-github', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// First pull tasks from GitHub
const pullResult = await global.taskScheduler.pullTasksFromGitHub();
// Then push local tasks to GitHub
const pushResult = await global.taskScheduler.pushTasksToGitHub();
callback({
success: true,
pull: pullResult,
push: pushResult,
message: `Synchronized tasks with GitHub. Downloaded ${pullResult.count}, uploaded ${pushResult.count} tasks.`
});
} catch (error) {
console.error('Error synchronizing tasks with GitHub:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:check-scheduler-status', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
callback({
success: true,
active: false
});
return;
}
const status = global.taskScheduler.getStatus();
callback({
success: true,
active: status.isActive,
lastRun: status.lastRun
});
} catch (error) {
console.error('Error checking scheduler status:', error);
callback({
success: false,
error: error.message,
active: false
});
}
});
socket.on('self:start-scheduler', async (callback) => {
try {
if (!global.taskScheduler) {
await initScheduler();
}
if (!global.taskScheduler) {
throw new Error('Failed to initialize task scheduler');
}
const result = global.taskScheduler.start();
// Check if callback is a function before calling it
if (typeof callback === 'function') {
callback({ success: true, message: 'Scheduler started successfully' });
} else {
console.log('Scheduler started successfully');
}
} catch (error) {
console.error('Error starting scheduler:', error);
// Check if callback is a function before calling it
if (typeof callback === 'function') {
callback({ success: false, error: error.message });
}
}
});
socket.on('self:stop-scheduler', async (callback) => {
try {
if (!global.taskScheduler) {
throw new Error('Task scheduler not initialized');
}
// Check if the scheduler has a stop method
if (typeof global.taskScheduler.stop === 'function') {
global.taskScheduler.stop();
} else {
// If no stop method exists, we'll implement a basic one by setting isActive to false
global.taskScheduler.isActive = false;
}
// Check if callback is a function before calling it
if (typeof callback === 'function') {
callback({ success: true, message: 'Scheduler stopped successfully' });
} else {
console.log('Scheduler stopped successfully');
}
} catch (error) {
console.error('Error stopping scheduler:', error);
// Check if callback is a function before calling it
if (typeof callback === 'function') {
callback({ success: false, error: error.message });
}
}
});
socket.on('self:save-module', async (data, callback) => {
try {
if (!data.path || !data.content) {
return callback({ success: false, error: 'Path and content are required' });
}
const { saveSelfModuleToGitHub } = await import('./src/coreai/mgmt/selfIntegration.js');
const result = await saveSelfModuleToGitHub({
path: data.path,
content: data.content,
message: data.message || `Update ${data.path}`
});
callback(result);
} catch (error) {
console.error('Error saving module:', error);
callback({ success: false, error: error.message });
}
});
// Prompt management socket handlers
socket.on('self:get-prompts', async (callback) => {
try {
const promptManager = await import('./src/coreai/mgmt/promptManager.js');
callback({
success: true,
prompts: {
research: {
active: promptManager.getActivePrompt('research'),
selectedPath: promptManager.getSelectedPromptPath('research'),
usingDefault: !promptManager.getSelectedPromptPath('research')
},
terminal: {
active: promptManager.getActivePrompt('terminal'),
selectedPath: promptManager.getSelectedPromptPath('terminal'),
usingDefault: !promptManager.getSelectedPromptPath('terminal')
}
}
});
} catch (error) {
console.error('Error getting prompts:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:load-default-prompt', async (data, callback) => {
try {
const { type } = data;
if (type !== 'research' && type !== 'terminal') {
return callback({ success: false, error: 'Invalid prompt type' });
}
const promptManager = await import('./src/coreai/mgmt/promptManager.js');
const prompt = await promptManager.loadDefaultPrompt(type);
callback({
success: true,
prompt,
message: `Loaded default ${type} prompt`
});
} catch (error) {
console.error('Error loading default prompt:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:set-prompt', async (data, callback) => {
try {
const { type, path, useDefault } = data;
if (type !== 'research' && type !== 'terminal') {
return callback({ success: false, error: 'Invalid prompt type' });
}
const promptManager = await import('./src/coreai/mgmt/promptManager.js');
if (useDefault) {
await promptManager.resetToDefaultPrompt(type);
return callback({ success: true, message: `Reset to default ${type} prompt` });
}
if (!path) {
return callback({ success: false, error: 'No prompt path provided' });
}
await promptManager.loadPrompt(type, path);
callback({ success: true, message: `Set ${type} prompt to ${path}` });
} catch (error) {
console.error('Error setting prompt:', error);
callback({ success: false, error: error.message });
}
});
socket.on('self:save-prompt', async (data, callback) => {
try {
const { type, content, name } = data;
if (!type || (type !== 'research' && type !== 'terminal')) {
return callback({ success: false, error: 'Invalid prompt type' });
}
if (!content) {
return callback({ success: false, error: 'No prompt content provided' });
}
if (!name) {
return callback({ success: false, error: 'No prompt name provided' });
}
const promptManager = await import('./src/coreai/mgmt/promptManager.js');
const result = await promptManager.savePromptToGitHub(type, content, name);
if (result.success) {
// Automatically set to use this prompt
await promptManager.loadPrompt(type, result.path);
callback({
success: true,
path: result.path,
message: `${type.charAt(0).toUpperCase() + type.slice(1)} prompt saved and activated`
});
} else {
callback({
success: false,
error: result.error || 'Failed to save prompt'
});
}
} catch (error) {
console.error('Error saving prompt:', error);
callback({ success: false, error: error.message });
}
});
// ----------------------------
// Self-Integration Socket Handlers
// ----------------------------
socket.on('self:verify-connection', async (data, callback) => {
try {
// Check if GitHub token and settings are configured
const githubConfigured = !!process.env.GITHUB_TOKEN &&
!!process.env.GITHUB_OWNER &&
!!process.env.GITHUB_REPO;
if (!githubConfigured) {
callback({
connected: false,
error: 'GitHub configuration is incomplete. Please set GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO.'
});
return;
}
// Try to verify connection by actually calling the GitHub API
try {
const { verifyGitHubConfig } = await import('./src/coreai/mgmt/selfIntegration.js');
const isValid = await verifyGitHubConfig();
if (isValid) {
callback({
connected: true,
user: process.env.GITHUB_OWNER,
repo: process.env.GITHUB_REPO,
branch: process.env.GITHUB_BRANCH || 'main'
});
} else {
callback({
connected: false,
error: 'GitHub API connection failed. Please check your token and permissions.'
});
}
} catch (apiError) {
callback({
connected: false,
error: `GitHub API error: ${apiError.message}`
});
}
} catch (error) {
console.error('Error verifying GitHub connection:', error);
callback({
connected: false,
error: error.message || 'Unknown error verifying GitHub connection'
});
}
});
// Memory system connection verification
socket.on('memory:verify-connection', async (data, callback) => {
try {
const coreMemoryAI = await getCoreMemoryAI();
const initialized = coreMemoryAI.initialized;
if (initialized) {
callback({ connected: true });
} else {
callback({ connected: false, error: 'Memory system not initialized' });
}
} catch (error) {
console.error('Error verifying memory system connection:', error);
callback({ connected: false, error: error.message });
}
});
// Get memory
socket.on('memory:get-memory', async (data, callback) => {
try {
const { type } = data;
if (!type) {
return callback({
success: false,
error: 'Memory type is required'
});
}
const coreMemoryAI = await getCoreMemoryAI();
if (!coreMemoryAI.initialized) {
return callback({
success: false,
error: 'Memory system not initialized'
});
}
// Get memory from cache
const content = coreMemoryAI.memoryCache[type];
callback({
success: true,
content
});
} catch (error) {
console.error('Error getting memory:', error);
callback({
success: false,
error: error.message
});
}
});
// Process memory query
socket.on('memory:process-query', async (data, callback) => {
try {
const { query, memoryContext, options } = data;
if (!query) {
return callback({
success: false,
error: 'Query is required'
});
}
// Get Venice memory client
const veniceClient = await getVeniceMemoryClient();
// Process the query
const result = await veniceClient.processMemoryQuery(
query,
memoryContext || '',
options || {}
);
callback(result);
} catch (error) {
console.error('Error processing memory query:', error);
callback({
success: false,
error: error.message
});
}
});
// Run memory maintenance
socket.on('memory:run-maintenance', async (data, callback) => {
try {
// Get core memory AI
const coreMemoryAI = await getCoreMemoryAI();
// Run maintenance
const result = await coreMemoryAI.runMaintenance();
callback({
success: result,
message: result ? 'Memory maintenance completedsuccessfully' : 'Memory maintenance failed'
});
} catch (error) {
console.error('Error running memory maintenance:', error);
callback({
success: false,
error: error.message
});
}
});
// Get memory metadata (size, consolidation status)
socket.on('memory:get-metadata', async (data, callback) => {
try {
const { type } = data;
const coreMemoryAI = await getCoreMemoryAI();
if (!coreMemoryAI) {
return callback({
success: false,
error: 'Memory system not initialized'
});
}
// Get memory content to calculate size
const memoryType = type.replace('-', '_');
const content = coreMemoryAI.memoryCache[memoryType];
// Calculate size - safely handle undefined content