forked from RossAscends/STMP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1423 lines (1272 loc) · 56.2 KB
/
server.js
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
const http = require('http');
const fs = require('fs');
const util = require('util');
const { v4: uuidv4 } = require('uuid');
const writeFileAsync = util.promisify(fs.writeFile);
const existsAsync = util.promisify(fs.exists);
const fsp = require('fs').promises;
const path = require('path');
const WebSocket = require('ws');
const $ = require('jquery');
const characterCardParser = require('./character-card-parser.js');
const express = require('express');
const { url } = require('inspector');
const localApp = express();
const remoteApp = express();
const crypto = require('crypto');
localApp.use(express.static('public'));
remoteApp.use(express.static('public'));
//Import db handler from STMP/db.js
const db = require('./db.js');
//for console coloring
const color = {
byNum: (mess, fgNum) => {
mess = mess || '';
fgNum = fgNum === undefined ? 31 : fgNum;
return '\u001b[' + fgNum + 'm' + mess + '\u001b[39m';
},
black: (mess) => color.byNum(mess, 30),
red: (mess) => color.byNum(mess, 31),
green: (mess) => color.byNum(mess, 32),
yellow: (mess) => color.byNum(mess, 33),
blue: (mess) => color.byNum(mess, 34),
magenta: (mess) => color.byNum(mess, 35),
cyan: (mess) => color.byNum(mess, 36),
white: (mess) => color.byNum(mess, 37),
};
const usernameColors = [
'#FF5C5C', // Red
'#FFB54C', // Orange
'#FFED4C', // Yellow
'#4CFF69', // Green
'#4CCAFF', // Blue
'#AD4CFF', // Purple
'#FF4CC3', // Magenta
'#FF4C86', // Pink
];
// Create both HTTP servers
const wsPort = 8181; //WS for host
const wssPort = 8182; //WSS for guests
let modKey = ''
let hostKey = ''
var TabbyAPIDefaults, HordeAPIDefaults
//set the engine mode to either 'tabby' or 'horde'
let engineMode = 'tabby'
async function getAPIDefaults() {
try {
const fileContents = await readFile('default-API-Parameters.json');
const jsonData = JSON.parse(fileContents);
const { TabbyAPICallParams, HordeAPICallParams } = jsonData[0];
TabbyAPIDefaults = TabbyAPICallParams;
HordeAPIDefaults = HordeAPICallParams;
} catch (error) {
console.error('Error reading or parsing the default API Param JSON file:', error);
}
}
releaseLock()
getAPIDefaults()
// Configuration
const apiKey = "_YOUR_API_KEY_HERE_";
const authString = "_STUsername_:_STPassword_";
const secretsPath = path.join(__dirname, 'secrets.json');
console.log("");
console.log("")
console.log("")
console.log('===========================')
console.log("SillyTavern MultiPlayer");
// Create directory if it does not exist
function createDirectoryIfNotExist(path) {
if (!fs.existsSync(path)) {
try {
fs.mkdirSync(path, { recursive: true });
console.log(`-- Created '${path}' folder.`);
} catch (err) {
console.error(`Failed to create '${path}' folder. Check permissions or path.`);
process.exit(1);
}
}
}
localApp.get('/', (req, res) => {
const filePath = path.join(__dirname, '/public/client.html');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error loading the client HTML file');
} else {
res.status(200).send(data);
}
});
});
remoteApp.get('/', (req, res) => {
const filePath = path.join(__dirname, '/public/client.html');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error loading the client HTML file');
} else {
res.status(200).send(data);
}
});
});
// Handle 404 Not Found
localApp.use((req, res) => {
res.status(404).send('Not found');
});
remoteApp.use((req, res) => {
res.status(404).send('Not found');
});
const localServer = http.createServer(localApp);
const guestServer = http.createServer(remoteApp);
const TabbyURL = 'http://127.0.0.1:5000';
const TabbyGenEndpoint = '/v1/completions';
const secretsObj = JSON.parse(fs.readFileSync('secrets.json', { encoding: 'utf8' }));
const tabbyAPIkey = secretsObj.api_key_tabby
const STBasicAuthCredentials = secretsObj?.sillytavern_basic_auth_string
// Create a WebSocket server
const wsServer = new WebSocket.Server({ server: localServer });
const wssServer = new WebSocket.Server({ server: guestServer });
wsServer.setMaxListeners(0);
wssServer.setMaxListeners(0);
// Arrays to store connected clients of each server
var clientsObject = [];
var connectedUsers = [];
var hostUUID
//default values
var selectedCharacter
var isAutoResponse = true
var responseLength = 200
var contextSize = 4096
var liveConfig
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function generateAndPrintKeys() {
// Generate a 16-byte hex string for the host key
hostKey = crypto.randomBytes(16).toString('hex');
// Generate a 16-byte hex string for the mod key
modKey = crypto.randomBytes(16).toString('hex');
// Print the keys
console.log(`${color.yellow(`Host Key: ${hostKey}`)}`);
console.log(`${color.yellow(`Mod Key: ${modKey}`)}`);
}
async function initFiles() {
const configPath = 'config.json';
const secretsPath = 'secrets.json';
// Default values for config.json
const defaultConfig = {
engineMode: 'tabby',
selectedCharacter: 'public/characters/CodingSensei.png',
responseLength: 200,
contextSize: 2048,
isAutoResponse: true,
selectedPreset: "public/api-presets/Tabby-Temp-2_MinP-0.2.json",
instructFormat: "public/instructFormats/ChatML.json",
D1JB: ''
};
const instructSequences = await readFile(defaultConfig.instructFormat)
defaultConfig.instructSequences = instructSequences
const samplerData = await readFile(defaultConfig.selectedPreset)
defaultConfig.samplers = samplerData
defaultConfig.selectedCharDisplayName = "Coding Sensei"
// Default values for secrets.json
const defaultSecrets = {
api_key: 'YourAPIKey',
authString: 'YourAuthString'
};
// Check and create config.json if it doesn't exist
if (!await existsAsync(configPath)) {
console.log('Creating config.json with default values...');
await writeFileAsync(configPath, JSON.stringify(defaultConfig, null, 2));
console.log('config.json created.');
liveConfig = await readConfig()
} else {
console.log('Loading config.json...');
liveConfig = await readConfig()
//console.log(liveConfig)
}
// Check and create secrets.json if it doesn't exist
if (!await existsAsync(secretsPath)) {
console.log('Creating secrets.json with default values...');
await writeFileAsync(secretsPath, JSON.stringify(defaultSecrets, null, 2));
console.log('secrets.json created, please update it with real credentials now and restart the server.');
}
}
// Create directories
createDirectoryIfNotExist("./public/api-presets");
generateAndPrintKeys();
// Call the function to initialize the files
initFiles();
// Handle incoming WebSocket connections for wsServer
wsServer.on('connection', (ws, request) => {
handleConnections(ws, 'host', request);
});
// Handle incoming WebSocket connections for wssServer
wssServer.on('connection', (ws, request) => {
handleConnections(ws, 'guest', request);
});
async function charaRead(img_url, input_format) {
return characterCardParser.parse(img_url, input_format);
}
async function getCardList() {
const path = 'public/characters'
const files = await fs.promises.readdir(path);
var cards = []
var i = 0
//console.log('Files in character directory:');
for (const file of files) {
try {
let fullPath = `${path}/${file}`
const cardData = await charaRead(fullPath);
var jsonData = JSON.parse(cardData);
jsonData.filename = `${path}/${file}`
cards[i] = {
name: jsonData.name,
filename: jsonData.filename
}
} catch (error) {
console.error(`Error reading file ${file}:`, error);
}
i++
}
//console.log(cards)
return cards;
}
async function getInstructList() {
const path = 'public/instructFormats'
const files = await fs.promises.readdir(path);
var instructs = []
var i = 0
//console.log('Files in Instruct directory:');
for (const file of files) {
try {
let fullPath = `${path}/${file}`
//console.log(fullPath)
const cardData = await readFile(fullPath);
//console.log('got data')
var jsonData = JSON.parse(cardData);
jsonData.filename = `${path}/${file}`
instructs[i] = {
name: jsonData.name,
filename: jsonData.filename
}
} catch (error) {
console.error(`Error reading file ${file}:`, error);
}
i++
}
//console.log(instructs)
return instructs;
}
async function getSamplerPresetList() {
const path = 'public/api-presets'
const files = await fs.promises.readdir(path);
var presets = []
var i = 0
for (const file of files) {
try {
let fullPath = `${path}/${file}`
presets[i] = {
name: file.replace('.json', ''),
filename: fullPath,
}
} catch (error) {
console.error(`Error reading file ${file}:`, error);
}
i++
}
return presets;
}
async function broadcast(message) {
//alter the type check for bug checking purposes, otherwise this is turned off
if (message.type === "BuggyTypeHere") {
console.log('broadcasting this:')
//console.log(message)
}
Object.keys(clientsObject).forEach(clientUUID => {
const client = clientsObject[clientUUID];
const socket = client.socket;
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
}
});
}
async function broadcastToHosts(message) {
//alter the type check for bug checking purposes, otherwise this is turned off
console.log('HOST BROADCAST:')
console.log(message)
//console.log(clientsObject)
let hostsObjects = Object.values(clientsObject).filter(obj => obj.role === 'host');
//console.log(hostsObjects)
Object.keys(hostsObjects).forEach(clientUUID => {
const client = hostsObjects[clientUUID];
const socket = client.socket;
if (socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
}
});
}
// Broadcast the updated array of connected usernames to all clients
async function broadcastUserList() {
const userListMessage = {
type: 'userList',
userList: connectedUsers
};
//console.log('-----broadcastUserList() is about to send this as a userlist:')
//console.log(connectedUsers)
broadcast(userListMessage);
//console.log(`[UserList BroadCast]:`)
//console.log(connectedUsers)
}
async function removeLastAIChatMessage() {
await db.removeLastAIChatMessage()
let AIChatJSON = await db.readAIChat();
let jsonArray = JSON.parse(AIChatJSON)
let chatUpdateMessage = {
type: 'chatUpdate',
chatHistory: jsonArray
}
console.log('sending AI Chat Update instruction to clients')
broadcast(chatUpdateMessage);
}
async function saveAndClearChat(type) {
await db.newSession();
}
async function handleConnections(ws, type, request) {
// Parse the URL to get the query parameters
const urlParams = new URLSearchParams(request.url.split('?')[1]);
//get the username from the encodedURI parameters
const encodedUsername = urlParams.get('username');
let thisUserColor, thisUserUsername, thisUserRole, user
// Retrieve the UUID from the query parameters
let uuid = urlParams.get('uuid');
if (uuid === null || uuid === undefined || uuid === '') {
//console.log('Client connected without UUID...assigning a new one..');
//assign them a UUID
uuid = uuidv4()
//console.log(`uuid assigned as ${uuid}`)
} else {
//console.log('Client connected with UUID:', uuid);
}
//check if we have them in the DB
user = await db.getUser(uuid);
//console.log('initial user check:')
//console.log(user)
if (user !== undefined && user !== null) {
//if we know them, use DB values
thisUserColor = user.username_color;
thisUserUsername = user.username
thisUserRole = user.role
} else {
//if we don't know them code a random color
thisUserColor = usernameColors[Math.floor(Math.random() * usernameColors.length)];
thisUserRole = type;
await db.upsertUserRole(uuid, thisUserRole);
//attempt to decode the username
thisUserUsername = decodeURIComponent(encodedUsername);
if (thisUserUsername === null || thisUserUsername === undefined) {
console.log('COULD NOT FIND USERNAME FOR CLIENT')
console.log('CONNECTION REJECTED')
ws.close()
return
}
}
clientsObject[uuid] = {
socket: ws,
color: thisUserColor,
role: thisUserRole,
username: thisUserUsername
};
user = clientsObject[uuid]
await db.upsertUser(uuid, thisUserUsername, thisUserColor);
console.log(`Adding ${thisUserUsername} to connected user list..`)
updateConnectedUsers()
//console.log('CONNECTED USERS')
//console.log(connectedUsers)
//console.log('CLIENTS OBJECT')
//console.log(clientsObject)
//console.log("USER =======")
//console.log(user)
const cardList = await getCardList()
const instructList = await getInstructList()
const samplerPresetList = await getSamplerPresetList()
var AIChatJSON = await db.readAIChat();
var userChatJSON = await db.readUserChat()
if (!liveConfig.selectedCharacter || liveConfig.selectedCharacter === '') {
console.log('No selected character found, setting to default character...')
liveConfig.selectedCharacter = cardList[0].filename;
liveConfig.selectedCharDisplayName = cardList[0].name;
await writeConfig(liveConfig, 'selectedCharacter', liveConfig.selectedCharacter)
await writeConfig(liveConfig, 'selectedCharDisplayName', liveConfig.selectedCharDisplayName)
}
//send connection confirmation along with both chat history, card list, selected char, and assigned user color.
let connectionConfirmedMessage = {
clientUUID: uuid,
type: 'connectionConfirmed',
chatHistory: userChatJSON,
AIChatHistory: AIChatJSON,
color: thisUserColor,
role: thisUserRole,
selectedCharacterDisplayName: liveConfig.selectedCharDisplayName,
newUserChatDelay: liveConfig?.userChatDelay,
newAIChatDelay: liveConfig?.AIChatDelay,
userList: connectedUsers
}
//send control-related metadata to the Host user
if (thisUserRole === 'host') {
console.log("including metadata for host")
hostUUID = uuid
connectionConfirmedMessage["cardList"] = cardList
connectionConfirmedMessage["instructList"] = instructList
connectionConfirmedMessage["samplerPresetList"] = samplerPresetList
connectionConfirmedMessage["selectedCharacter"] = liveConfig.selectedCharacter
connectionConfirmedMessage["selectedSamplerPreset"] = liveConfig.selectedPreset
connectionConfirmedMessage["engineMode"] = liveConfig.engineMode
connectionConfirmedMessage["isAutoResponse"] = liveConfig.isAutoResponse
connectionConfirmedMessage["contextSize"] = liveConfig.contextSize
connectionConfirmedMessage["responseLength"] = liveConfig.responseLength
connectionConfirmedMessage["D1JB"] = liveConfig.D1JB
connectionConfirmedMessage["instructFormat"] = liveConfig.instructFormat
}
await broadcastUserList()
ws.send(JSON.stringify(connectionConfirmedMessage))
function updateConnectedUsers() {
const userList = Object.values(clientsObject).map(client => ({
username: client.username,
color: client.color,
role: client.role
}));
connectedUsers = userList;
}
// Handle incoming messages from clients
ws.on('message', async function (message) {
console.log(`--- MESSAGE IN`)
// Parse the incoming message as JSON
let parsedMessage;
try {
parsedMessage = JSON.parse(message);
const senderUUID = parsedMessage.UUID
let userColor = await db.getUserColor(senderUUID)
let thisClientObj = clientsObject[parsedMessage.UUID];
//If there is no UUID, then this is a new client and we need to add it to the clientsObject
if (!thisClientObj) {
thisClientObj = {
username: '',
color: '',
role: '',
};
clientsObject[parsedMessage.UUID] = thisClientObj;
}
console.log('Received message from client:', parsedMessage);
//first check if the sender is host, and if so, process possible host commands
if (user.role === 'host') {
//console.log(`saw message from host, type (${parsedMessage.type})`)
if (parsedMessage.type === 'clearChat') {
//clear the UserChat.json file
await saveAndClearChat('UserChat')
const clearUserChatInstruction = {
type: 'clearChat'
}
// Broadcast the clear chat message to all connected clients
await broadcast(clearUserChatInstruction);
return
}
else if (parsedMessage.type === 'toggleAutoResponse') {
isAutoResponse = parsedMessage.value
liveConfig.isAutoResponse = isAutoResponse
await writeConfig(liveConfig, 'isAutoResponse', isAutoResponse)
let settingChangeMessage = {
type: 'autoAItoggleUpdate',
value: liveConfig.isAutoResponse
}
await broadcastToHosts(settingChangeMessage)
return
}
else if (parsedMessage.type === 'adjustContextSize') {
contextSize = parsedMessage.value
liveConfig.contextSize = contextSize
await writeConfig(liveConfig, 'contextSize', contextSize)
let settingChangeMessage = {
type: 'contextSizeChange',
value: liveConfig.contextSize
}
await broadcastToHosts(settingChangeMessage)
return
}
else if (parsedMessage.type === 'adjustResponseLength') {
responseLength = parsedMessage.value
liveConfig.responseLength = responseLength
await writeConfig(liveConfig, 'responseLength', responseLength)
let settingChangeMessage = {
type: 'responseLengthChange',
value: liveConfig.responseLength
}
await broadcastToHosts(settingChangeMessage)
return
}
else if (parsedMessage.type === 'AIChatDelayChange') {
AIChatDelay = parsedMessage.value
liveConfig.AIChatDelay = AIChatDelay
await writeConfig(liveConfig, 'AIChatDelay', AIChatDelay)
let settingChangeMessage = {
type: 'AIChatDelayChange',
value: liveConfig.AIChatDelay
}
await broadcast(settingChangeMessage)
return
}
else if (parsedMessage.type === 'userChatDelayChange') {
userChatDelay = parsedMessage.value
liveConfig.userChatDelay = userChatDelay
await writeConfig(liveConfig, 'userChatDelay', userChatDelay)
let settingChangeMessage = {
type: 'userChatDelayChange',
value: liveConfig.userChatDelay
}
await broadcast(settingChangeMessage)
return
}
else if (parsedMessage.type === 'clearAIChat') {
await saveAndClearChat('AIChat')
const clearAIChatInstruction = {
type: 'clearAIChat'
}
await broadcast(clearAIChatInstruction);
let charFile = liveConfig.selectedCharacter
console.log(`selected character: ${charFile}`)
let cardData = await charaRead(charFile, 'png')
let cardJSON = JSON.parse(cardData)
let firstMes = cardJSON.first_mes
let charName = cardJSON.name
let charColor = await db.getCharacterColor(charName)
firstMes = replaceMacros(firstMes)
const newAIChatFirstMessage = {
type: 'chatMessage',
chatID: 'AIChat',
content: firstMes,
username: charName,
AIChatUserList: [{ username: charName, color: charColor }]
}
//console.log('adding the first mesage to the chat file')
await db.writeAIChatMessage(charName, charName, firstMes, 'AI');
console.log(`Sending ${charName}'s first message to AI Chat..`)
await broadcast(newAIChatFirstMessage)
return
}
else if (parsedMessage.type === 'deleteLast') {
await removeLastAIChatMessage()
return
}
else if (parsedMessage.type === 'changeCharacterRequest') {
const changeCharMessage = {
type: 'changeCharacter',
char: parsedMessage.newChar,
charDisplayName: parsedMessage.newCharDisplayName
}
liveConfig.selectedCharacter = parsedMessage.newChar
liveConfig.selectedCharDisplayName = parsedMessage.newCharDisplayName
await writeConfig(liveConfig)
await broadcast(changeCharMessage);
return
}
else if (parsedMessage.type === 'changeSamplerPreset') {
const changePresetMessage = {
type: 'changeSamplerPreset',
newPreset: parsedMessage.newPreset
}
selectedPreset = parsedMessage.newPreset
liveConfig.selectedPreset = selectedPreset
const samplerData = await readFile(selectedPreset)
liveConfig.samplers = samplerData
await writeConfig(liveConfig, 'samplers', liveConfig.samplers)
await writeConfig(liveConfig, 'selectedPreset', selectedPreset)
await broadcast(changePresetMessage);
return
}
else if (parsedMessage.type === 'changeInstructFormat') {
const changeInstructMessage = {
type: 'changeInstructFormat',
newInstructFormat: parsedMessage.newInstructFormat
}
liveConfig.instructFormat = parsedMessage.newInstructFormat
const instructSequences = await readFile(liveConfig.instructFormat)
liveConfig.instructSequences = instructSequences
await writeConfig(liveConfig, 'instructSequences', liveConfig.instructSequences)
await writeConfig(liveConfig, 'instructFormat', parsedMessage.newInstructFormat)
await broadcast(changeInstructMessage);
return
}
else if (parsedMessage.type === 'changeD1JB') {
const changeD1JBMessage = {
type: 'changeD1JB',
newD1JB: parsedMessage.newD1JB
}
liveConfig.D1JB = parsedMessage.newD1JB
await writeConfig(liveConfig)
await broadcast(changeD1JBMessage);
return
}
else if (parsedMessage.type === 'AIRetry') {
// Read the AIChat file
try {
await removeLastAIChatMessage()
userPrompt = {
'chatID': parsedMessage.chatID,
'username': parsedMessage.username,
'content': '',
}
let [AIResponse, AIChatUserList] = await getAIResponse()
const AIResponseMessage = {
chatID: parsedMessage.chatID,
content: AIResponse,
username: `${liveConfig.selectedCharDisplayName}`,
type: 'AIResponse',
userColor: userColor,
AIChatUserList: AIChatUserList
}
broadcast(AIResponseMessage)
return
} catch (parseError) {
console.error('An error occurred while parsing the JSON:', parseError);
return;
}
}
else if (parsedMessage.type === 'modeChange') {
engineMode = parsedMessage.newMode
const modeChangeMessage = {
type: 'modeChange',
engineMode: engineMode
}
liveConfig.engineMode = engineMode
await writeConfig(liveConfig, 'engineMode', engineMode)
await broadcast(modeChangeMessage);
return
}
else if (parsedMessage.type === 'pastChatsRequest') {
const pastChats = await db.getPastChats()
const pastChatsListMessage = {
type: 'pastChatsList',
pastChats: pastChats
}
await broadcast(pastChatsListMessage)
return
}
else if (parsedMessage.type === 'loadPastChat') {
const [pastChat, sessionID] = await db.readAIChat(parsedMessage.session)
let jsonArray = JSON.parse(pastChat)
const pastChatsLoadMessage = {
type: 'pastChatToLoad',
pastChatHistory: jsonArray,
sessionID: sessionID
}
await broadcast(pastChatsLoadMessage)
return
}
else if (parsedMessage.type === 'pastChatDelete') {
const sessionID = parsedMessage.sessionID
let [result, wasActive] = await db.deletePastChat(sessionID)
console.log(result, wasActive)
if (result === 'ok') {
const pastChatsDeleteConfirmation = {
type: 'pastChatDeleted',
wasActive: wasActive
}
await broadcast(pastChatsDeleteConfirmation)
return
} else {
return
}
}
}
//process universal message types
//console.log(`processing universal message types...`)
if (parsedMessage.type === 'usernameChange') {
clientsObject[uuid].username = parsedMessage.newName;
updateConnectedUsers()
const nameChangeNotification = {
type: 'userChangedName',
content: `[System]: ${parsedMessage.oldName} >>> ${parsedMessage.newName}`
}
//console.log(nameChangeNotification)
console.log('sending notification of username change')
await broadcast(nameChangeNotification);
await broadcastUserList()
}
else if (parsedMessage.type === 'submitKey') {
console.log(hostKey)
console.log(parsedMessage.key)
console.log(modKey)
if (parsedMessage.key === hostKey) {
const keyAcceptedMessage = {
type: 'keyAccepted',
role: 'host'
}
db.upsertUserRole(uuid, 'host');
await ws.send(JSON.stringify(keyAcceptedMessage))
//await broadcast(keyAcceptedMessage);
}
else if (parsedMessage.key === modKey) {
const keyAcceptedMessage = {
type: 'keyAccepted',
role: 'mod'
}
db.upsertUserRole(uuid, 'mod');
await ws.send(JSON.stringify(keyAcceptedMessage))
//await broadcast(keyAcceptedMessage);
}
else {
const keyRejectedMessage = {
type: 'keyRejected'
}
console.error(`Key rejected: ${parsedMessage.key} from ${senderUUID}`)
await ws.send(JSON.stringify(keyRejectedMessage))
//await broadcast(keyRejectedMessage);
}
}
else if (parsedMessage.type === 'chatMessage') { //handle normal chat messages
//having this enable sends the user's colors along with the response message if it uses parsedMessage as the base..
parsedMessage.userColor = thisUserColor
const chatID = parsedMessage.chatID;
const username = parsedMessage.username
const userColor = thisUserColor
const userInput = parsedMessage?.userInput
const hordePrompt = parsedMessage?.userInput
var userPrompt
//setup the userPrompt arrayin order to send the input into the AIChat box
if (chatID === 'AIChat') {
userPrompt = {
'chatID': chatID,
'username': username,
//send the HTML-ized message into the AI chat
'content': parsedMessage.userInput,
'userColor': userColor
}
let isEmptyTrigger = userPrompt.content.length == 0 ? true : false
//if the message isn't empty (i.e. not a forced AI trigger), then add it to AIChat
if (!isEmptyTrigger) {
await db.writeAIChatMessage(username, senderUUID, userInput, 'user');
await broadcast(userPrompt)
}
if (liveConfig.isAutoResponse || isEmptyTrigger) {
let [AIResponse, AIChatUserList] = await getAIResponse()
const AIResponseMessage = {
chatID: parsedMessage.chatID,
content: AIResponse,
username: `${liveConfig.selectedCharDisplayName}`,
type: 'AIResponse',
userColor: parsedMessage.userColor,
AIChatUserList: AIChatUserList
}
broadcast(AIResponseMessage)
}
}
//read the current userChat file
if (chatID === 'UserChat') {
let data = await db.readUserChat()
let jsonArray = JSON.parse(data);
// Add the new object to the array
jsonArray.push(parsedMessage);
const updatedData = JSON.stringify(jsonArray, null, 2);
// Write the updated array back to the file
await db.writeUserChatMessage(uuid, parsedMessage.content)
const newUserChatMessage = {
chatID: chatID,
username: username,
userColor: userColor,
content: parsedMessage.content
}
await broadcast(newUserChatMessage)
}
} else {
console.log(`unknown message type received (${parsedMessage.type})...ignoring...`)
}
async function getAIResponse() {
try {
console.log(engineMode)
let APICallParams
if (engineMode === 'tabby') {
APICallParams = TabbyAPIDefaults
} else {
APICallParams = HordeAPIDefaults
}
let isEmptyTrigger = userPrompt.content.length == 0 ? true : false
//console.log(`Is this an empty trigger? ${isEmptyTrigger}`)
//if it's not an empty trigger from host
//if userInput is empty we can just request the AI directly
let charFile = liveConfig.selectedCharacter
//console.log(`selected character: ${charFile}`)
let cardData = await charaRead(charFile, 'png')
let cardJSON = JSON.parse(cardData)
let charName = cardJSON.name
var finalCharName = JSON.stringify(`\n${charName}:`);
//strips out HTML tags from last message
var fixedFinalCharName = JSON.parse(finalCharName.replace(/<[^>]+>/g, ''));
//a careful observer might notice that we don't set the userInput string into the 'prompt' section of the API Params at this point.
//this is because the userInput has already been saved into the chat session, and the next function will read
//that file and parse the contents from there. All we need to do is pass the cardDefs, charName. and userName.
const [fullPromptforAI, includedChatObjects] = await addCharDefsToPrompt(charFile, fixedFinalCharName, parsedMessage.username)
const samplers = JSON.parse(liveConfig.samplers);
//apply the selected preset values to the API call
for (const [key, value] of Object.entries(samplers)) {
APICallParams[key] = value;
}
//add full prompt to API call
APICallParams.prompt = fullPromptforAI;
//ctx and response length for Tabby
APICallParams.truncation_length = Number(liveConfig.contextSize)
APICallParams.max_tokens = Number(liveConfig.responseLength)
//ctx and response length for Horde
APICallParams.max_context_length = Number(liveConfig.contextSize)
APICallParams.max_length = Number(liveConfig.responseLength)
//add stop strings
const [finalAPICallParams, entitiesList] = await setStopStrings(APICallParams, includedChatObjects)
var AIResponse = '';
if (liveConfig.engineMode === 'horde') {
const [hordeResponse, workerName, hordeModel, kudosCost] = await requestToHorde(finalAPICallParams);
AIResponse = hordeResponse;
}
else {
AIResponse = trimIncompleteSentences(await requestToTabby(finalAPICallParams))
}
await db.upsertChar(charName, charName, parsedMessage.userColor);
await db.writeAIChatMessage(charName, charName, AIResponse, 'AI');
let AIChatUserList = await makeAIChatUserList(entitiesList, includedChatObjects)
return [AIResponse, AIChatUserList]
} catch (error) {
console.log(error);
}
}
} catch (error) {
console.error('Error parsing message:', error);
return;
}
});
ws.on('close', async () => {
// Remove the disconnected client from the clientsObject
console.debug(`Client ${uuid} disconnected..removing from clientsObject`);
delete clientsObject[uuid];
updateConnectedUsers()
await broadcastUserList();
});
};
//entityList is a set of entities drawn from setStopStrings, which gathers names for all entities in the chat history.
//chatHistoryFromPrompt is a JSON array of chat messages which made it into the prompt for the AI, as set by addCharDefsToPrompt
//this function compares the entity username from the set against the username in the chat object arrray
//if a match is found, the username and associated color are added into the AIChatUserList array
//this array is returned and sent along with the AI response, in order to populate the AI Chat UserList.
async function makeAIChatUserList(entitiesList, chatHistoryFromPrompt) {
//console.log('-----------MAKING ENTITIES LIST NOW');
const chatHistoryEntities = entitiesList;
//console.log(chatHistoryEntities)
const fullChatDataJSON = chatHistoryFromPrompt;
const AIChatUserList = [];
for (const entity of chatHistoryEntities) {
//console.log(entity);
for (const chat of fullChatDataJSON) {
//console.log(chat);
//console.log(`${chat.username} vs ${entity.username}`);
if (chat.username === entity.username) {
//console.log('found match');
const userColor = chat.userColor;
const username = chat.username;
const entityType = chat.entity;
AIChatUserList.push({ username: username, color: userColor, entity: entityType });
break; // Once a match is found, no need to continue the inner loop
}
}
}
//console.log('Latest AI Chat User List:');
//console.log(AIChatUserList);
return AIChatUserList;
}
function countTokens(str) {
let chars = str.length
let tokens = Math.ceil(chars / 3)
//console.log(`estimated tokens: ${tokens}`)
return tokens
}
async function readConfig() {
await acquireLock()
//await delay(100)
//console.log('--- READ CONFIG started')
return new Promise(async (resolve, reject) => {
fs.readFile('config.json', 'utf8', async (err, data) => {
if (err) {