This repository has been archived by the owner on Apr 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontent.js
2221 lines (1935 loc) · 85.6 KB
/
content.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
// content.js for character.ai
var caughtOne = false;
var dctempdata = "";
function initMemoryManager() {
if (localStorage.getItem("memoryManagerEnabled") === "true") {
// create a fixed sidebar on the right
var sidebar = document.createElement("div");
var screenWidth = window.innerWidth;
var userName;
sidebar.id = "memory-manager";
sidebar.style.position = "fixed";
sidebar.style.overflow = "auto";
sidebar.style.right = "0"; // Initially hide the sidebar
sidebar.style.top = "0";
console.log(screenWidth);
sidebar.style.width = screenWidth <= 960 ? "100%" : "25%";
sidebar.style.height = "100%";
sidebar.style.zIndex = screenWidth <= 960 ? "15000" : "999";
sidebar.style.backgroundColor = "#f0f0f0";
sidebar.style.borderLeft = "1px solid #ccc";
sidebar.style.transition = "right 0.5s ease-in-out";
sidebar.style.padding = "10px";
sidebar.style.boxShadow = "-5px 0 10px rgba(0,0,0,0.1)";
document.body.appendChild(sidebar);
// create a button to toggle sidebar visibility
var toggleButton = document.createElement("button");
toggleButton.id = "toggle-sidebar-button";
toggleButton.textContent = ">";
toggleButton.style.position = "fixed";
toggleButton.style.right = "0";
toggleButton.style.top = screenWidth <= 960 ? "50px" : "10px";
toggleButton.style.zIndex = "16999";
toggleButton.style.backgroundColor = "#e0e0e0";
toggleButton.style.color = "#333";
toggleButton.style.boxShadow = "0 0 5px rgba(0,0,0,0.2)";
toggleButton.style.transition = "all 0.3s ease-in-out";
toggleButton.addEventListener("mouseenter", function () {
toggleButton.style.backgroundColor = "#ccc";
toggleButton.style.color = "#000";
toggleButton.style.transform = "scale(1.1)";
});
toggleButton.addEventListener("mouseleave", function () {
toggleButton.style.backgroundColor = "#e0e0e0";
toggleButton.style.color = "#333";
toggleButton.style.transform = "none";
});
toggleButton.style.border = "none";
toggleButton.style.padding = "5px";
toggleButton.style.fontWeight = "bold";
toggleButton.style.fontSize = "20px";
toggleButton.style.cursor = "pointer";
toggleButton.addEventListener("click", function () {
if (sidebar.style.right === "-100%") {
sidebar.style.right = "0";
toggleButton.textContent = ">"; // change the direction of the arrow
} else {
sidebar.style.right = "-100%";
toggleButton.textContent = "<"; // change the direction of the arrow
}
});
document.body.appendChild(toggleButton);
// after 1 second, withdraw the sidebar
setTimeout(function () {
sidebar.style.right = "-100%";
toggleButton.textContent = "<";
}, 1000);
// create a title for the sidebar
var title = document.createElement("h3");
title.textContent = "Memory Manager";
title.style.textAlign = "center";
sidebar.appendChild(title);
// create a form element for the memory manager
var form = document.createElement("form");
form.id = "memory-manager-form";
// create a textarea to display the memory string
var textarea = document.createElement("textarea");
textarea.id = "memory-display";
textarea.style.padding = "10px";
textarea.style.width = "85%";
textarea.name = "memory-display"; // add a name attribute for form submission
textarea.placeholder = "Your memory string will appear here"; // add a placeholder attribute for user guidance
textarea.rows = 10; // adjust the number of rows for better appearance
textarea.cols = 40; // adjust the number of columns for better appearance
textarea.readOnly = true; // prevent user from editing the textarea directly
form.appendChild(textarea);
// create two fields for character memory and user memory
var fields = ["character", "user"];
for (var i = 0; i < fields.length; i++) {
var fieldset = document.createElement("fieldset"); // use a fieldset element to group related elements
fieldset.id = fields[i] + "-memory-fieldset"; // change the id to match the fieldset element
// create a legend element for the fieldset
var legend = document.createElement("legend"); // use a legend element to provide a caption for the fieldset
legend.textContent =
fields[i].charAt(0).toUpperCase() + fields[i].slice(1) + " memory:";
fieldset.appendChild(legend);
// create a select element for the field
var select = document.createElement("select");
select.id = fields[i] + "-memory-select";
select.style.padding = "10px";
select.style.borderRadius = "5px";
select.style.border = "1px solid #ccc";
select.name = fields[i] + "-memory-select"; // add a name attribute for form submission
// create an option element for the select element
var option = document.createElement("option");
option.value = "";
option.textContent = "--Select a memory--";
option.selected = true;
option.disabled = true;
select.appendChild(option);
// append the select element to the fieldset
fieldset.appendChild(select);
// create two buttons for adding and removing memory
var buttons = ["add", "remove"];
for (var j = 0; j < buttons.length; j++) {
var button = document.createElement("button");
button.style.marginTop = "12px";
button.style.border = "none";
button.style.fontWeight = "bold";
button.style.borderRadius = "5px";
button.style.backgroundColor = "#2377d2";
button.style.padding = "5px";
button.style.paddingLeft = "10px";
button.style.paddingRight = "10px";
button.style.color = "white";
button.id = buttons[j] + "-" + fields[i] + "-memory-button";
button.textContent =
buttons[j].charAt(0).toUpperCase() + buttons[j].slice(1) + " memory";
button.style.display = buttons[j] === "add" ? "inline-block" : "none"; // hide the remove button initially
button.style.marginLeft = buttons[j] === "add" ? "10px" : "5px"; // adjust the margin
button.type = "button"; // specify the button type to prevent form submission
button.addEventListener("click", function (e) {
e.preventDefault();
handleMemoryButton(e.target.id); // call a function to handle the button click
});
fieldset.appendChild(button);
}
// append the fieldset to the form
form.appendChild(fieldset);
}
// append the form to the sidebar
sidebar.appendChild(form);
// create a variable to store the memory string
var memoryString;
// create a function to handle the add and remove memory buttons
function handleMemoryButton(buttonId) {
// get the button type and the memory type from the button id
var buttonType =
buttonId.split("-")[0].charAt(0).toUpperCase() +
buttonId.split("-")[0].slice(1);
var memoryType =
buttonId.split("-")[1].charAt(0).toUpperCase() +
buttonId.split("-")[1].slice(1);
// get the select element and the options for the memory type
var selectElement = document.getElementById(
memoryType.toLowerCase() + "-memory-select"
);
var options = selectElement.options;
if (buttonType === "Add") {
// prompt the user to enter a new memory
var newMemory =
prompt(`Enter a new ${memoryType.toLowerCase()} memory:`) || "";
if (newMemory.trim() !== "") {
// create a new option element with the new memory
var newOption = document.createElement("option");
newOption.value = newMemory;
newOption.textContent = newMemory;
// append the new option to the select element
selectElement.appendChild(newOption);
// select the new option
selectElement.selectedIndex = options.length - 1;
// show the remove button
document.getElementById(
"remove-" + memoryType.toLowerCase() + "-memory-button"
).style.display = "inline-block";
}
} else if (buttonType === "Remove") {
// get the selected option index
var selectedIndex = selectElement.selectedIndex;
if (selectedIndex > 0) {
// remove the selected option from the select element
selectElement.removeChild(options[selectedIndex]);
// select the first option
selectElement.selectedIndex = 0;
// hide the remove button if there are no more options
if (options.length === 1) {
document.getElementById(
"remove-" + memoryType.toLowerCase() + "-memory-button"
).style.display = "none";
}
}
}
// update the memory string and display it in the textarea
updateMemoryString();
}
function updateMemoryString() {
var characterMemorySelect = document.getElementById(
"character-memory-select"
);
var userMemorySelect = document.getElementById("user-memory-select");
var characterMemories = Array.from(characterMemorySelect.options)
.map((option) => option.value)
.filter((memory) => memory.trim() !== "");
var userMemories = Array.from(userMemorySelect.options)
.map((option) => option.value)
.filter((memory) => memory.trim() !== "");
var characterMemoryString = characterMemories
.map((memory) => '"' + memory + '"')
.join("; ");
var userMemoryString = userMemories
.map((memory) => '"' + memory + '"')
.join("; ");
memoryString = "[ AI memories: " + characterMemoryString + " ]";
if (userMemoryString.trim() !== "") {
memoryString += "\n[ User Facts: " + userMemoryString + " ]";
}
document.getElementById("memory-display").value = memoryString;
if (localStorage.getItem("autoSaveEnabled") === "true") {
localStorage.setItem("memoryString", memoryString);
}
}
function importMemoryString(memoryString) {
var characterMemorySelect = document.getElementById(
"character-memory-select"
);
var userMemorySelect = document.getElementById("user-memory-select");
// Clear existing memory options
characterMemorySelect.innerHTML =
'<option value="" disabled selected>--Select a memory--</option>';
userMemorySelect.innerHTML =
'<option value="" disabled selected>--Select a memory--</option>';
// Split memoryString by newlines
var memoryLines = memoryString.split("\n");
memoryLines.forEach(function (memoryLine) {
// Trim whitespace and check for AI memories or User Facts keywords
var cleanedLine = memoryLine.trim();
if (cleanedLine.startsWith("[ AI memories:")) {
var memories = cleanedLine.match(/"([^"]*)"/g);
if (memories) {
memories.forEach(function (memory) {
var cleanedMemory = memory.slice(1, -1); // Remove the surrounding double quotes
var newOption = document.createElement("option");
newOption.value = cleanedMemory;
newOption.textContent = cleanedMemory;
characterMemorySelect.appendChild(newOption);
characterMemorySelect.selectedIndex = 1;
});
}
} else if (cleanedLine.startsWith("[ User Facts:")) {
var memories = cleanedLine.match(/"([^"]*)"/g);
if (memories) {
memories.forEach(function (memory) {
var cleanedMemory = memory.slice(1, -1); // Remove the surrounding double quotes
var newOption = document.createElement("option");
newOption.value = cleanedMemory;
newOption.textContent = cleanedMemory;
userMemorySelect.appendChild(newOption);
userMemorySelect.selectedIndex = 1;
});
}
}
});
// Show remove button if there are more than one options
if(characterMemorySelect.options.length > 1){
document.getElementById(
"remove-character-memory-button"
).style.display = "inline-block";
}
if(userMemorySelect.options.length > 1){
document.getElementById(
"remove-user-memory-button"
).style.display = "inline-block";
}
updateMemoryString(); // Update the displayed memory string
}
if (localStorage.getItem("memoryString") !== null && localStorage.getItem("autoSaveEnabled") === "true") {
importMemoryString(localStorage.getItem("memoryString"));
}
// create a function to insert the memory string to the user input textarea
function insertMemoryString() {
// get the user input textarea element
var userInputTextarea = document.getElementById("user-input");
// insert the memory string to the user input textarea with a newline
userInputTextarea.value = memoryString + "\n\n" + userInputTextarea.value;
// Trigger the input event to avoid glitches
var inputEvent = new Event("input", {"bubbles": true});
userInputTextarea.dispatchEvent(inputEvent);
}
function handleSubmit(event) {
event.preventDefault();
updateMemoryString();
insertMemoryString();
}
// add an event listener to the form element for submission
form.addEventListener("submit", handleSubmit);
// create a style element for the sidebar
var style = document.createElement("style");
style.textContent = `
#memory-manager-form {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 50px;
}
#memory-manager-form fieldset {
width: 80%;
margin: 10px;
}
#memory-manager-form legend {
font-weight: bold;
}
#memory-manager-form select {
width: 100%;
}
#memory-manager-form input[type="submit"] {
width: 80%;
margin-top: 20px;
padding: 10px;
border: none;
border-radius: 5px;
background-image: linear-gradient(to right, #00c6ff, #0072ff);
color: white;
`;
document.head.appendChild(style);
var DIVFORTHEINSERTBUTTON = document.createElement("div");
DIVFORTHEINSERTBUTTON.style.display = "flex";
DIVFORTHEINSERTBUTTON.style.flexDirection = "column"; // To vertically center
DIVFORTHEINSERTBUTTON.style.alignItems = "center"; // To horizontally center
sidebar.appendChild(DIVFORTHEINSERTBUTTON);
// create a button element for inserting memory string
var insertButton = document.createElement("button");
insertButton.innerText = "Insert Memory String";
insertButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
insertButton.style.padding = "10px";
insertButton.style.borderRadius = "5px";
insertButton.style.border = "none";
insertButton.style.marginTop = "30px !important";
insertButton.style.width = "80%";
insertButton.style.color = "white";
insertButton.addEventListener("click", function () {
insertMemoryString();
});
DIVFORTHEINSERTBUTTON.appendChild(insertButton);
// create a button element for importing memory string
var importButton = document.createElement("button");
importButton.innerText = "Import Memory String";
importButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
importButton.style.padding = "10px";
importButton.style.justifyContent = "center";
importButton.style.alignItems = "center";
importButton.style.borderRadius = "5px";
importButton.style.border = "none";
importButton.style.marginTop = "10px";
importButton.style.width = "80%";
importButton.style.color = "white";
importButton.addEventListener("click", function () {
openImportDialog();
});
DIVFORTHEINSERTBUTTON.appendChild(importButton);
var clearButton = document.createElement("button");
clearButton.innerText = "Clear Memory String";
clearButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
clearButton.style.padding = "10px";
clearButton.style.justifyContent = "center";
clearButton.style.alignItems = "center";
clearButton.style.borderRadius = "5px";
clearButton.style.border = "none";
clearButton.style.marginTop = "10px";
clearButton.style.width = "80%";
clearButton.style.color = "white";
clearButton.addEventListener("click", function () {
clearMemoryString();
});
DIVFORTHEINSERTBUTTON.appendChild(clearButton);
function clearMemoryString() {
var characterMemorySelect = document.getElementById(
"character-memory-select"
);
var userMemorySelect = document.getElementById("user-memory-select");
// Clear existing memory options
characterMemorySelect.innerHTML =
'<option value="" disabled selected>--Select a memory--</option>';
userMemorySelect.innerHTML =
'<option value="" disabled selected>--Select a memory--</option>';
// Hide remove buttons
document.getElementById(
"remove-character-memory-button"
).style.display = "none";
document.getElementById(
"remove-user-memory-button"
).style.display = "none";
document.getElementById("memory-display").value = "";
if (localStorage.getItem("autoSaveEnabled") === "true") {
localStorage.removeItem("memoryString");
}
}
// Add a "Scan" button to trigger the message scanning process
var scanButton = document.createElement("button");
scanButton.id = "scan-button";
scanButton.textContent = "Generate Automatically";
scanButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
scanButton.style.padding = "10px";
scanButton.style.borderRadius = "5px";
scanButton.style.border = "none";
scanButton.style.marginTop = "10px";
scanButton.style.width = "80%";
scanButton.style.color = "white";
scanButton.style.cursor = "pointer";
scanButton.style.color = "white";
scanButton.addEventListener("click", scanMessages);
DIVFORTHEINSERTBUTTON.appendChild(scanButton);
var continueChatButton = document.createElement("button");
continueChatButton.id = "continue-chat-button";
continueChatButton.textContent = "Continue Chat";
continueChatButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
continueChatButton.style.padding = "10px";
continueChatButton.style.borderRadius = "5px";
continueChatButton.style.border = "none";
continueChatButton.style.marginTop = "10px";
continueChatButton.style.width = "80%";
continueChatButton.style.color = "white";
continueChatButton.style.cursor = "pointer";
continueChatButton.style.color = "white";
continueChatButton.addEventListener("click", continueChat);
DIVFORTHEINSERTBUTTON.appendChild(continueChatButton);
// Add a new select element for choosing which model to use for auto-scanning
var modelSelect = document.createElement("select");
modelSelect.id = "model-select";
modelSelect.style.borderRadius = "5px";
modelSelect.style.marginTop = "10px";
modelSelect.style.padding = "10px";
modelSelect.style.width = "80%";
var currentlySelectedModel = "command";
// Add options to the select element
modelSelect.innerHTML = `<option value="command">Normal (Higher Quality, Slower)</option><option value="command-light">Fast (Lower Quality, Faster)</option><option value="command-light-nightly">Small Nightly (Experimental, Fast)</option>`;
modelSelect.addEventListener("change", function () {
currentlySelectedModel = modelSelect.value;
})
DIVFORTHEINSERTBUTTON.appendChild(modelSelect);
// Add a text input for the user to enter the API key
var apiKeyInput = document.createElement("input");
apiKeyInput.style.borderRadius = "5px";
apiKeyInput.style.marginTop = "10px";
apiKeyInput.style.padding = "10px";
apiKeyInput.style.width = "80%";
apiKeyInput.id = "api-key-input";
apiKeyInput.placeholder = "Enter your API key here";
apiKeyInput.addEventListener("change", function () {
localStorage.setItem("cohereApiKey", apiKeyInput.value);
});
if (localStorage.getItem("cohereApiKey")) {
apiKeyInput.value = localStorage.getItem("cohereApiKey");
}
DIVFORTHEINSERTBUTTON.appendChild(apiKeyInput);
function convertToMemoryString(obj) {
// Extract the summary from the object
var summary = obj.summary;
// Split the summary into individual lines
var lines = summary.split("\n");
// Initialize an array to store the formatted lines
var formattedLines = [];
// Iterate through each line
lines.forEach(function (line) {
// Remove the leading dash and any whitespace characters
line = line.replace(/^-/, "").trim();
// Also try to remove any leading bullet points
line = line.replace(/^•/, "").trim();
// ...or any leading asterisks
line = line.replace(/^\*/, "").trim();
// Add the line to the formattedLines array, enclosed in double quotes
formattedLines.push(`"${line}"`);
});
// Join the formatted lines with a semicolon separator
var memoryString = `[ AI memories: ${formattedLines.join("; ")} ]`;
// Return the resulting memory string
return memoryString;
}
async function continueChat() {
var ctempdata = "";
ctempdata = getChatHistory();
if (apiKeyInput.value.trim() === "") {
alert("Please enter your Cohere API key. You can get one for free at https://cohere.com/");
return;
}
continueChatButton.textContent = "Continuing... (Might take a while, if it misunderstands the chat, please refresh the page and try again.)";
var ourdata = convertHistory(ctempdata, returnUsername = true);
// It returned a promise and we need to resolve it
ourdata.then(async function (result) {
// Now we get the list of messages AND the username, but they're in an object. The key for the list is "chats" and the key for the username is "username"
var username = result.username;
var result = result.chats;
for (var i = 0; i < result.length; i++) {
dctempdata += result[i] + "\n";
}
// Set the global dctempdata variable to the result
console.log(dctempdata);
var nicetext = dctempdata;
// Check if the summaryText is less than 500 characters long
if (nicetext.length < 500) {
alert("The chat is too short to scan.");
continueChatButton.textContent = "Continue Chat";
return;
}
evenbettertext = "You are a model for suggesting chat completions, your goal is to provide a new message the user can send to the other user, also supporting roleplays. The current conversation is:\n\n```\n";
evenbettertext += nicetext;
evenbettertext += "\n```";
evenbettertext += "\n\nProvide the next message the user \""
evenbettertext += username;
evenbettertext += "\" can send. Do not send any other content than the message. Do not include the enclosing tag. Do not surround the message with \"."
// Send a request to the API using fetch method
const response = await fetch('https://api.cohere.ai/v1/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKeyInput.value}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: evenbettertext,
model: currentlySelectedModel,
temperature: 0.3,
max_tokens: 150,
k: 0,
stop_sequences: [],
return_likelihoods: "NONE"
})
});
if (!response.ok) {
alert("Something went wrong. Please try again.\n\n" + response.statusText);
continueChatButton.textContent = "Continue Chat";
return
}
const data = await response.json();
var summary = "";
summary = data.generations[0].text;
navigator.clipboard.writeText(summary).then(function() {
alert("The suggested message is (will be copied to your clipboard):\n\n" + summary);
continueChatButton.textContent = "Continue Chat";
});
});
}
// Function to scan and summarize messages
async function scanMessages() {
if (apiKeyInput.value.trim() === "") {
alert("Please enter your Cohere API key. You can get one for free at https://cohere.com/");
return;
}
scanButton.textContent = "Scanning... (Might take a while, if it misunderstands the chat, please refresh the page and try again.)";
scanButton.disabled = true;
var ctempdata = "";
ctempdata = getChatHistory();
var ourdata = convertHistory(ctempdata);
// It returned a promise and we need to resolve it
ourdata.then(async function (result) {
for (var i = 0; i < result.length; i++) {
dctempdata += result[i] + "\n";
}
// Set the global dctempdata variable to the result
console.log(dctempdata);
var nicetext = dctempdata;
// Check if the summaryText is less than 500 characters long
if (nicetext.length < 500) {
alert("The chat is too short to scan.");
scanButton.textContent = "Generate Automatically";
scanButton.disabled = false;
return;
}
// Send a request to the API using fetch method
const response = await fetch('https://api.cohere.ai/v1/summarize', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKeyInput.value}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: nicetext,
length: 'auto',
format: 'bullets',
model: currentlySelectedModel,
additional_command: 'Extract facts and events from the conversation. Do not make up any information.',
temperature: 0.6
})
});
scanButton.textContent = "Generate Automatically";
scanButton.disabled = false;
if (!response.ok) {
alert("Something went wrong. Please try again.\n\n" + response.statusText);
return
}
const data = await response.json();
var summary = "";
summary = convertToMemoryString(data);
importMemoryString(summary);
console.log(data);
});
}
function openImportDialog() {
var importDialog = document.createElement("div");
importDialog.id = "import-dialog";
importDialog.style.position = "fixed";
importDialog.style.left = "50%";
importDialog.style.top = "50%";
importDialog.style.transform = "translate(-50%, -50%)";
importDialog.style.backgroundColor = "white";
importDialog.style.padding = "20px";
importDialog.style.borderRadius = "5px";
importDialog.style.boxShadow = "0 0 10px rgba(0, 0, 0, 0.2)";
var textarea = document.createElement("textarea");
textarea.style.width = "100%";
textarea.style.height = "100px";
textarea.placeholder = "Paste your memory string here...";
importDialog.appendChild(textarea);
var confirmButton = document.createElement("button");
confirmButton.innerText = "Confirm";
confirmButton.style.marginTop = "10px";
confirmButton.style.backgroundImage =
"linear-gradient(to right, #00c6ff, #0072ff)";
confirmButton.style.padding = "5px 10px";
confirmButton.style.borderRadius = "5px";
confirmButton.style.border = "none";
confirmButton.style.color = "white";
confirmButton.style.cursor = "pointer";
confirmButton.addEventListener("click", function () {
var importedMemoryString = textarea.value;
if (isValidMemoryString(importedMemoryString)) {
importMemoryString(importedMemoryString);
sidebar.removeChild(importDialog);
} else {
alert(
"Invalid memory string format. Please provide a valid memory string."
);
}
});
importDialog.appendChild(confirmButton);
var cancelButton = document.createElement("button");
cancelButton.innerText = "Cancel";
cancelButton.style.marginTop = "10px";
cancelButton.style.backgroundImage =
"linear-gradient(to right, #ff0000, #ff6666)";
cancelButton.style.padding = "5px 10px";
cancelButton.style.borderRadius = "5px";
cancelButton.style.border = "none";
cancelButton.style.color = "white";
cancelButton.style.cursor = "pointer";
cancelButton.addEventListener("click", function () {
sidebar.removeChild(importDialog);
});
importDialog.appendChild(cancelButton);
sidebar.appendChild(importDialog);
}
// Function to validate the imported memory string format
function isValidMemoryString(memoryString) {
// Modify this regex pattern according to the expected format
var regexPattern =
/^\[ AI memories: "[^"]*(?:";\s*"[^"]*)*" ](?:\n\[ User Facts: "[^"]*(?:";\s*"[^"]*)*" ])?$/;
return regexPattern.test(memoryString);
}
}
}
function toggleFixedField() {
var fixedField = document.getElementById("fixed-field");
var toggleButton = document.getElementById("toggle-fixedfield-button");
if (fixedField.style.display === "block") {
fixedField.style.display = "none";
toggleButton.innerHTML = "⋮";
}
else {
fixedField.style.display = "block";
toggleButton.innerHTML = "⋮";
}
}
function updateSidebarWidth() {
var screenWidth = window.innerWidth;
var sidebar = document.getElementById("memory-manager");
var toggleButton = document.getElementById("toggle-sidebar-button");
var fixedField = document.getElementById("fixed-field");
if (screenWidth <= 960) {
if (sidebar) {
sidebar.style.width = "100%";
toggleButton.style.top = "50px";
sidebar.style.zIndex = 15000;
}
if (fixedField.style.display === "none") {
fixedField.style.display = "none";
} else {
fixedField.style.display = "block";
}
fixedField.style.position = "fixed";
fixedField.style.width = "100%";
fixedField.style.left = "0";
fixedField.style.bottom = "0";
fixedField.style.height = "90px";
// Create a button to toggle the fixed field
if (!document.getElementById("toggle-fixedfield-button")) {
var toggleButton2 = document.createElement("button");
toggleButton2.id = "toggle-fixedfield-button";
toggleButton2.innerHTML = `⋮`;
toggleButton2.style.right = "0";
toggleButton2.style.top = "100px";
toggleButton2.style.padding = "5px 10px";
toggleButton2.style.border = "none";
toggleButton2.style.position = "fixed";
toggleButton2.style.zIndex = 9999;
toggleButton2.addEventListener("click", function () {
toggleFixedField();
})
document.body.appendChild(toggleButton2);
}
// Move fixedField to below the #root div
document.body.insertAdjacentElement("afterend", fixedField);
} else {
if (sidebar) {
sidebar.style.width = "25%";
toggleButton.style.top = "10px";
sidebar.style.zIndex = 999;
}
fixedField.style.position = "fixed";
fixedField.style.display = "block";
fixedField.style.marginBottom = "0";
fixedField.style.width = "115px";
fixedField.style.left = "20px";
fixedField.style.height = "60px";
fixedField.style.bottom = "20px";
if (document.getElementById("toggle-fixedfield-button"))
{
document.getElementById("toggle-fixedfield-button").remove();
}
// Move fixedField to above the #root div
document.body.insertAdjacentElement("afterbegin", fixedField);
}
}
// Add an event listener to the window's resize event
window.addEventListener("resize", updateSidebarWidth);
function toggleRoundedAvatars() {
const roundedAvatarsEnabled =
localStorage.getItem("roundedAvatars") === "true";
const images = document.querySelectorAll("img");
function applyRoundedStyle(image) {
image.style.borderRadius = roundedAvatarsEnabled ? "0" : "45px";
}
images.forEach((image) => {
if (image.src.includes("https://characterai.io/i/80/static/avatars/")) {
if (image.complete) {
applyRoundedStyle(image);
} else {
image.onload = function () {
applyRoundedStyle(image);
};
}
}
});
}
// Observe mutations in the document to handle dynamically loaded content
const observer = new MutationObserver(function (mutationsList) {
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
toggleRoundedAvatars(); // Call your function whenever the DOM changes
}
}
});
// Start observing the document for changes
observer.observe(document.body, { childList: true, subtree: true });
// Initial call to apply rounded avatars to existing images
toggleRoundedAvatars();
// create a fixed field in the bottom-left corner
var screenWidth = window.innerWidth;
var fixedField = document.createElement("div");
fixedField.id = "fixed-field";
fixedField.style.position = screenWidth <= 960 ? "fixed" : "fixed";
fixedField.style.left = screenWidth <= 960 ? "0" : "20px";
fixedField.style.bottom <= 960 ? "0" : "20px";
fixedField.style.width = screenWidth <= 960 ? "100%" : "115px";
fixedField.style.height = "60px";
fixedField.style.marginBottom = screenWidth <= 960 ? "0" : "0";
fixedField.style.backgroundColor = "#f0f0f0";
fixedField.style.zIndex = "9999";
fixedField.style.padding = "10px";
fixedField.style.boxShadow = "5px 5px 10px rgba(0, 0, 0, 0.1)";
document.body.insertAdjacentElement("afterend", fixedField);
updateSidebarWidth();
// create a cog button for opening addon settings
var cogButton = document.createElement("button");
cogButton.id = "addon-settings-button";
cogButton.textContent = "\u2699"; // Unicode for cog symbol
cogButton.style.backgroundColor = "#e0e0e0";
cogButton.style.color = "#333";
cogButton.style.border = "none";
cogButton.style.borderRadius = "50%";
cogButton.style.width = "40px";
cogButton.style.height = "40px";
cogButton.style.fontSize = "20px";
cogButton.style.cursor = "pointer";
cogButton.style.margin = "0";
cogButton.style.boxShadow = "0 0 5px rgba(0, 0, 0, 0.2)";
cogButton.style.transition = "all 0.3s ease-in-out";
cogButton.addEventListener("mouseenter", function () {
cogButton.style.backgroundColor = "#ccc";
cogButton.style.color = "#000";
});
cogButton.addEventListener("mouseleave", function () {
cogButton.style.backgroundColor = "#e0e0e0";
cogButton.style.color = "#333";
});
fixedField.appendChild(cogButton);
// create settings panel for C.ai addons
var settingsPanel = document.createElement("div");
settingsPanel.id = "addon-settings-panel";
settingsPanel.style.display = "none";
settingsPanel.style.position = "absolute";
settingsPanel.style.bottom = screenWidth <= 960 ? "75px" : "50px";
settingsPanel.style.left = "10px";
settingsPanel.style.width = "300px";
settingsPanel.style.backgroundColor = "#fff";
settingsPanel.style.border = "1px solid #ccc";
settingsPanel.style.borderRadius = "5px";
settingsPanel.style.padding = "10px";
settingsPanel.style.boxShadow = "5px 5px 10px rgba(0, 0, 0, 0.1)";
fixedField.appendChild(settingsPanel);
// create a toggle button for enabling/disabling Memory Manager
var memoryToggle = document.createElement("input");
memoryToggle.type = "checkbox";
memoryToggle.id = "memory-toggle";
memoryToggle.style.marginRight = "5px";
memoryToggle.checked = true; // Enabled by default
settingsPanel.appendChild(memoryToggle);
var memoryToggleLabel = document.createElement("label");
memoryToggleLabel.htmlFor = "memory-toggle";
memoryToggleLabel.textContent = "Enable Memory Manager";
settingsPanel.appendChild(memoryToggleLabel);
var br = document.createElement("br");
settingsPanel.appendChild(br);
// create a toggle button for enabling/disabling automatic memory string saving
var autoSaveToggle = document.createElement("input");
autoSaveToggle.type = "checkbox";
autoSaveToggle.id = "auto-save-toggle";
autoSaveToggle.style.marginRight = "5px";
autoSaveToggle.checked = true; // Enabled by default
settingsPanel.appendChild(autoSaveToggle);
var autoSaveToggleLabel = document.createElement("label");
autoSaveToggleLabel.htmlFor = "auto-save-toggle";
autoSaveToggleLabel.textContent = "Enable Autosave";
settingsPanel.appendChild(autoSaveToggleLabel);
autoSaveToggle.addEventListener("change", function () {
localStorage.setItem("autoSaveEnabled", this.checked);
});
// if the memory manager is disabled, disable the autosave toggle
if (localStorage.getItem("memoryManagerEnabled") === "false") {
autoSaveToggle.disabled = true;
}
if (localStorage.getItem("autoSaveEnabled") === "true") {
autoSaveToggle.checked = true;
} else {
autoSaveToggle.checked = false;
}