-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
10214 lines (8790 loc) · 439 KB
/
index.js
File metadata and controls
10214 lines (8790 loc) · 439 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 { eventSource, event_types, chat, saveSettingsDebounced, chat_metadata, addOneMessage, this_chid, characters, generateQuietPrompt, animation_duration, setExtensionPrompt, extension_prompt_types, extension_prompt_roles } from '../../../../script.js';
import { getTokenCountAsync } from '../../../../scripts/tokenizers.js';
import { extension_settings, getContext, writeExtensionField, saveMetadataDebounced } from '../../../extensions.js';
import { loadWorldInfo, world_names, createNewWorldInfo, createWorldInfoEntry, saveWorldInfo, updateWorldInfoList, selected_world_info, world_info, METADATA_KEY, parseRegexFromString } from '../../../world-info.js';
import { executeSlashCommandsWithOptions, registerSlashCommand } from '../../../slash-commands.js';
import { getMessageTimeStamp, dragElement } from '../../../RossAscends-mods.js';
import { loadMovingUIState } from '../../../power-user.js';
import { highlightRegex } from '../../../utils.js';
import { CarrotWorldBookTracker } from './worldbook-tracker.js';
import { CarrotLorebookConnector } from './lorebook-connector.js';
import { CarrotDebug, initializeDebugger } from './debugger.js';
import { CarrotContextManager, CarrotStorageManager } from './context-manager.js';
import { CarrotGitHubBrowser } from './github-browser.js';
import { CarrotPackManager } from './pack-manager.js';
import { generateFullSheet, generateTagSheet, generateQuickSheet, CarrotTemplateManager, initializeSheetGenerator } from './sheet-generator.js';
import {
scannedCharacters,
selectedLorebooks,
characterRepoBooks,
tagLibraries,
setLastInjectedCharacters,
getLastInjectedCharacters,
currentRepoView,
setCurrentRepoView,
selectedCharacter,
setSelectedCharacter,
selectedRepository,
setSelectedRepository,
_packManagerOpening,
setPackManagerOpening,
pendingSheetCommand,
setPendingSheetCommand,
lastProcessedMessage,
setLastProcessedMessage,
pendingThinkingBlockData,
setPendingThinkingBlockData,
addToPendingThinkingBlockData,
clearPendingThinkingBlockData,
EXTENSION_NAME
} from './carrot-state.js';
import { renderAsCards, loadCarrotCardStyles, attachExternalCardsToMessage, ensureBunnyMoAnimations, createExternalCardContainer, createTabbedCharacterCard, createCharacterCard } from './card-renderer.js';
import { initializeUIUpdates, updateStatusPanels } from './ui-updates.js';
import { initializeTutorials, openSystemTutorial, openRepositoryTutorial, openInjectionTutorial, openTemplateEditorTutorial, startTutorial, closeTutorial } from './tutorials.js';
import { checkForCompletedSheets, initialize_baby_bunny_message_button, add_baby_bunny_button_to_message, add_baby_bunny_buttons_to_all_existing_messages, remove_all_baby_bunny_buttons, showTutorialBabyBunnyPopup, closeBabyBunnyTutorial, baby_bunny_button_class } from './baby-bunny-mode.js';
import { initializeChunkVisualizer, openChunkVisualizer as openChunkVisualizerModule, closeChunkVisualizer, saveChunkChanges } from './chunk-visualizer.js';
import { CarrotTemplatePromptEditInterface } from './template-editor.js';
import {
initializeRepositoryManager,
openRepositoryManager,
cleanupStaleRepositories,
manualRepositoryScan,
navigateRepoHome,
selectRepository,
updateRepositoryPreview,
navigateToRepository,
renderRepositoryManager,
returnToRepositoryManager,
updateRepositoryManagerContent,
showCharacterDetails,
navigateToCharacter
} from './repository-manager.js';
// Import fullsheet-rag.js dynamically
let fullsheetAPI = {};
let fullsheetRAGLoaded = false;
// Pack Manager state (module-level)
let githubBrowser = null;
let hasScannedExisting = false;
// Main settings popout state
let mainLorebookPopoutVisible = false;
let $mainLorebookContent = null;
let $mainLorebookOriginalParent = null;
let $mainLorebookPopout = null;
async function loadFullsheetRAG() {
if (fullsheetRAGLoaded) {
return fullsheetAPI;
}
try {
const module = await import('./fullsheet-rag.js');
fullsheetRAGLoaded = true;
fullsheetAPI = {
initializeRAG: module.initializeRAG || (() => {}),
saveRAGSettings: module.saveRAGSettings || (() => {}),
addRAGButtonsToAllMessages: module.addRAGButtonsToAllMessages || (() => {}),
removeAllRAGButtons: module.removeAllRAGButtons || (() => {}),
detectFullsheetInMessage: module.detectFullsheetInMessage || (() => {}),
vectorizeFullsheetFromMessage: module.vectorizeFullsheetFromMessage || (() => Promise.resolve(false)),
getCurrentContextLevel: module.getCurrentContextLevel || (() => 'global'),
getContextualLibrary: module.getContextualLibrary || (() => ({})),
getKeywordPriority: module.getKeywordPriority || ((keyword) => 20),
normalizeKeyword: module.normalizeKeyword || ((word) => (word || '').toLowerCase().trim()),
regenerateChunkKeywords: module.regenerateChunkKeywords || (() => Promise.resolve()),
applyAutomaticLinks: module.applyAutomaticLinks || (() => {}),
updateChunksInLibrary: module.updateChunksInLibrary || ((collectionId, chunks) => {
CarrotDebug.error('updateChunksInLibrary not implemented in fullsheet-rag.js');
return Promise.resolve();
}),
};
return fullsheetAPI;
} catch (error) {
CarrotDebug.error('CarrotKernel: Error loading fullsheet-rag.js', error);
return {};
}
}
// Start loading immediately
const fullsheetRAGPromise = loadFullsheetRAG();
// Create async wrapper functions that wait for the module to load
async function initializeRAG() {
await fullsheetRAGPromise;
return fullsheetAPI.initializeRAG?.() || Promise.resolve();
}
async function saveRAGSettings(settings) {
await fullsheetRAGPromise;
return fullsheetAPI.saveRAGSettings?.(settings);
}
async function addRAGButtonsToAllMessages() {
await fullsheetRAGPromise;
return fullsheetAPI.addRAGButtonsToAllMessages?.();
}
async function removeAllRAGButtons() {
await fullsheetRAGPromise;
return fullsheetAPI.removeAllRAGButtons?.();
}
async function detectFullsheetInMessage(message) {
await fullsheetRAGPromise;
return fullsheetAPI.detectFullsheetInMessage?.(message);
}
async function vectorizeFullsheetFromMessage(characterName, content) {
await fullsheetRAGPromise;
// Prompt user for custom collection name
const defaultName = characterName;
const customName = prompt('Enter a name for this collection:', defaultName);
// User cancelled the prompt
if (customName === null) {
toastr.info('Vectorization cancelled');
return false;
}
// Proceed with vectorization
const success = await fullsheetAPI.vectorizeFullsheetFromMessage?.(characterName, content) || Promise.resolve(false);
// If vectorization succeeded and user provided a custom name (different from default), save it
if (success && customName.trim() !== '' && customName.trim() !== defaultName) {
const ragState = extension_settings[extensionName]?.rag;
if (ragState) {
// We need to get the collection ID to save the custom name
// The collection ID is generated based on characterName and current context
if (globalThis.CarrotKernelFullsheetRag?.generateCollectionId) {
const collectionId = globalThis.CarrotKernelFullsheetRag.generateCollectionId(characterName);
await setCollectionName(collectionId, customName.trim());
CarrotDebug.ui(`Set custom name "${customName.trim()}" for collection ${collectionId}`);
}
}
}
return success;
}
async function getCurrentContextLevel() {
await fullsheetRAGPromise;
if (fullsheetAPI.getCurrentContextLevel) {
return fullsheetAPI.getCurrentContextLevel();
}
return 'global'; // Default fallback
}
async function getContextualLibrary() {
await fullsheetRAGPromise;
if (fullsheetAPI.getContextualLibrary) {
return fullsheetAPI.getContextualLibrary();
}
return {}; // Default fallback
}
// Extract clean character name from collection ID by removing prefixes and context suffixes
function getCharacterNameFromCollectionId(collectionId) {
// Check for custom name first
const ragState = extension_settings[extensionName]?.rag;
if (ragState?.collectionNames && ragState.collectionNames[collectionId]) {
return ragState.collectionNames[collectionId];
}
// Fall back to auto-generated name
return collectionId
.replace(/^carrotkernel_char_/, '') // Remove prefix
.replace(/_charid_\d+$/, '') // Remove character ID suffix
.replace(/_chat_[a-z0-9_]+$/, '') // Remove chat ID suffix
.replace(/_/g, ' ') // Convert remaining underscores to spaces
.trim();
}
// Set custom name for a collection
async function setCollectionName(collectionId, customName) {
const ragState = extension_settings[extensionName].rag;
if (!ragState.collectionNames) {
ragState.collectionNames = {};
}
ragState.collectionNames[collectionId] = customName;
await saveSettingsDebounced();
}
// Show context selection popup for moving collections between storage levels
async function showCopyContextPopup(collectionId, sourceContext) {
return new Promise((resolve) => {
const characterName = getCharacterNameFromCollectionId(collectionId);
const popup = $(`
<div class="carrot-popup-container rag-copy-context-popup" style="padding: 0; max-width: 600px; width: 90%;">
<div class="carrot-card" style="margin: 0; height: auto;">
<!-- Header -->
<div class="carrot-card-header" style="padding: 24px 32px 16px;">
<h3 style="margin: 0 0 8px; font-size: 22px;">📦 Move Collection</h3>
<p class="carrot-card-subtitle" style="margin: 0; color: var(--grey70, #94a3b8);">
Move <strong style="color: var(--SmartThemeQuoteColor, #10b981);">${characterName}</strong> from <strong>${sourceContext.toUpperCase()}</strong> storage to:
</p>
</div>
<div class="carrot-card-body" style="padding: 0 32px 24px; display: flex; flex-direction: column; gap: 20px;">
<!-- Context Level Options -->
<div class="carrot-setup-step">
<div style="display: flex; flex-direction: column; gap: 12px;">
<label style="
display: flex;
align-items: flex-start;
gap: 12px;
padding: 16px;
background: var(--black30a, rgba(0,0,0,0.2));
border: 2px solid ${sourceContext === 'global' ? 'rgba(255,255,255,0.05)' : 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))'};
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
${sourceContext === 'global' ? 'opacity: 0.5; cursor: not-allowed;' : ''}
" class="copy-context-option" data-level="global" ${sourceContext === 'global' ? 'style="pointer-events: none;"' : ''}>
<input type="radio" name="copy-context-level" value="global" ${sourceContext === 'global' ? 'disabled' : ''} style="
accent-color: var(--SmartThemeQuoteColor, #10b981);
margin-top: 2px;
width: 18px;
height: 18px;
">
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 16px; margin-bottom: 4px; color: var(--SmartThemeEmColor, white);">
🌍 Global Storage
</div>
<div style="color: var(--grey70, #94a3b8); font-size: 14px; line-height: 1.5;">
${sourceContext === 'global' ? 'Cannot move - already here' : 'Accessible across all characters and chats'}
</div>
</div>
</label>
<label style="
display: flex;
align-items: flex-start;
gap: 12px;
padding: 16px;
background: var(--black30a, rgba(0,0,0,0.2));
border: 2px solid ${sourceContext === 'character' ? 'rgba(255,255,255,0.05)' : 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))'};
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
${sourceContext === 'character' ? 'opacity: 0.5; cursor: not-allowed;' : ''}
" class="copy-context-option" data-level="character" ${sourceContext === 'character' ? 'style="pointer-events: none;"' : ''}>
<input type="radio" name="copy-context-level" value="character" ${sourceContext === 'character' ? 'disabled' : ''} ${sourceContext !== 'character' && sourceContext !== 'global' ? 'checked' : ''} style="
accent-color: var(--SmartThemeQuoteColor, #10b981);
margin-top: 2px;
width: 18px;
height: 18px;
">
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 16px; margin-bottom: 4px; color: var(--SmartThemeEmColor, white);">
👤 Character Storage
</div>
<div style="color: var(--grey70, #94a3b8); font-size: 14px; line-height: 1.5;">
${sourceContext === 'character' ? 'Cannot move - already here' : 'Available for this character only, across all chats'}
</div>
</div>
</label>
<label style="
display: flex;
align-items: flex-start;
gap: 12px;
padding: 16px;
background: var(--black30a, rgba(0,0,0,0.2));
border: 2px solid ${sourceContext === 'chat' ? 'rgba(255,255,255,0.05)' : 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))'};
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
${sourceContext === 'chat' ? 'opacity: 0.5; cursor: not-allowed;' : ''}
" class="copy-context-option" data-level="chat" ${sourceContext === 'chat' ? 'style="pointer-events: none;"' : ''}>
<input type="radio" name="copy-context-level" value="chat" ${sourceContext === 'chat' ? 'disabled' : ''} style="
accent-color: var(--SmartThemeQuoteColor, #10b981);
margin-top: 2px;
width: 18px;
height: 18px;
">
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 16px; margin-bottom: 4px; color: var(--SmartThemeEmColor, white);">
💬 Chat Storage
</div>
<div style="color: var(--grey70, #94a3b8); font-size: 14px; line-height: 1.5;">
${sourceContext === 'chat' ? 'Cannot move - already here' : 'Only available in this specific chat conversation'}
</div>
</div>
</label>
</div>
</div>
<!-- Action Buttons -->
<div style="display: flex; gap: 12px; justify-content: flex-end; padding-top: 8px; border-top: 1px solid var(--SmartThemeBorderColor, rgba(255,255,255,0.1));">
<button class="carrot-secondary-btn" id="copy-context-cancel" style="padding: 10px 24px;">
Cancel
</button>
<button class="carrot-primary-btn" id="copy-context-confirm" style="padding: 10px 24px;">
<i class="fa-solid fa-right-left"></i> Move Collection
</button>
</div>
</div>
</div>
</div>
`);
// Show popup overlay
const $overlay = $('#carrot-popup-overlay');
$overlay.html(popup).css('display', 'flex').addClass('active');
// Handle option hover effects (only for enabled options)
popup.find('.copy-context-option:not([style*="pointer-events: none"])').on('mouseenter', function() {
const isSelected = $(this).find('input[type="radio"]').is(':checked');
if (!isSelected) {
$(this).css('border-color', 'var(--SmartThemeQuoteColor, #10b981)');
$(this).css('opacity', '0.8');
}
}).on('mouseleave', function() {
const isSelected = $(this).find('input[type="radio"]').is(':checked');
if (!isSelected) {
$(this).css('border-color', 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))');
$(this).css('opacity', '1');
}
});
// Handle option click - highlight selected (only for enabled options)
popup.find('.copy-context-option:not([style*="pointer-events: none"])').on('click', function() {
popup.find('.copy-context-option').css('border-color', 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))');
$(this).css('border-color', 'var(--SmartThemeQuoteColor, #10b981)');
$(this).find('input[type="radio"]').prop('checked', true);
});
// Handle radio button change
popup.find('input[name="copy-context-level"]').on('change', async function() {
popup.find('.copy-context-option').css('border-color', 'var(--SmartThemeBorderColor, rgba(255,255,255,0.1))');
$(this).closest('.copy-context-option').css('border-color', 'var(--SmartThemeQuoteColor, #10b981)');
});
// Cancel button
popup.find('#copy-context-cancel').on('click', () => {
$overlay.removeClass('active');
setTimeout(() => {
$overlay.hide().empty();
}, 300);
resolve(null); // Return null to indicate cancellation
});
// Confirm button
popup.find('#copy-context-confirm').on('click', () => {
const selectedLevel = popup.find('input[name="copy-context-level"]:checked').val();
if (!selectedLevel) {
toastr.warning('Please select a destination storage level');
return;
}
$overlay.removeClass('active');
setTimeout(() => {
$overlay.hide().empty();
}, 300);
resolve(selectedLevel);
});
// ESC key to cancel
$(document).one('keydown', (e) => {
if (e.key === 'Escape') {
popup.find('#copy-context-cancel').click();
}
});
});
}
// Use EXTENSION_NAME from carrot-state.js
const extensionName = EXTENSION_NAME;
// =============================================================================
// CARROT SHEET COMMAND SYSTEM 🥕
// Handles !fullsheet, !tagsheet, !quicksheet commands for character sheet injection
// =============================================================================
// Sheet command detection and processing - now using imported pendingSheetCommand from carrot-state
// Check if user message contains sheet commands
function detectSheetCommand(messageText) {
if (!messageText || typeof messageText !== 'string') return null;
const sheetCommands = [
{ command: '!fullsheet', type: 'fullsheet' },
{ command: '!tagsheet', type: 'tagsheet' },
{ command: '!quicksheet', type: 'quicksheet' },
{ command: '!memsheet', type: 'memsheet' },
{ command: '!updatesheet', type: 'updatesheet' },
{ command: '!physheet', type: 'physheet' }
];
for (const { command, type } of sheetCommands) {
const regex = new RegExp(`${command}\\s+(.+)`, 'i');
const match = messageText.match(regex);
if (match) {
// Handle multiple character names separated by commas
const characterNames = match[1].split(',').map(name => name.trim()).filter(name => name.length > 0);
return {
type: type,
command: command,
characterNames: characterNames,
fullMatch: match[0]
};
}
}
return null;
}
// Process sheet command and generate appropriate injection
async function processSheetCommand(sheetData) {
CarrotDebug.inject('processSheetCommand called with:', sheetData);
const { type, entry } = sheetData;
CarrotDebug.inject('Processing sheet command type:', type);
CarrotDebug.inject('Processing sheet command', {
type: type,
entry: !!entry
});
// Create injection command
const settings = extension_settings[extensionName];
// Create simple, effective mandatory prompt without duplicating macro content
const sheetTypeMap = {
'fullsheet': 'FULLSHEET',
'tagsheet': 'TAGSHEET',
'quicksheet': 'QUICKSHEET',
'memsheet': 'MEMSHEET',
'updatesheet': 'UPDATESHEET',
'physheet': 'PHYSSHEET'
};
// Get the appropriate injection template
const templateCategoryMap = {
'fullsheet': 'BunnyMo Fullsheet Injection',
'tagsheet': 'BunnyMo Tagsheet Injection',
'quicksheet': 'BunnyMo Quicksheet Injection',
'memsheet': 'BunnyMo Memsheet Injection',
'updatesheet': 'BunnyMo Updatesheet Injection',
'physheet': 'BunnyMo Physsheet Injection'
};
const injectionTemplate = CarrotTemplateManager.getPrimaryTemplateForCategory(templateCategoryMap[type]);
let injectionText;
let depth = 4; // Default depth
let role = 'system'; // Default role
if (injectionTemplate) {
// Use custom template - no character name needed since ST handles the targeting
injectionText = injectionTemplate.content;
// Use template-specific depth and role settings
// CRITICAL: Template depth property takes priority over legacy settings.inject_depth
depth = injectionTemplate.depth !== undefined ? injectionTemplate.depth : (injectionTemplate.settings?.inject_depth || 4);
role = injectionTemplate.role || 'system';
CarrotDebug.inject('Using template settings:', {
templateName: injectionTemplate.name,
depth: depth,
role: role,
templateDepth: injectionTemplate.depth,
legacyDepth: injectionTemplate.settings?.inject_depth
});
} else {
// Fallback to default fancy format and global settings
depth = settings.injectionDepth || 4;
role = settings.injectionRole || 'system';
injectionText = `🚨 **MANDATORY OOC OVERRIDE** 🚨
**SYSTEM DIRECTIVE:** A !${sheetTypeMap[type]} command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !${sheetTypeMap[type]} request as specified
• **PROVIDE** comprehensive character sheet information
• **RESUME** normal roleplay only after completing this request
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`;
CarrotDebug.inject('Using fallback settings:', {
depth: depth,
role: role
});
}
const injectionCommand = `/inject id=carrot-sheet-${type} position=chat ephemeral=true scan=true depth=${depth} role=${role} ${injectionText}`;
CarrotDebug.inject('Executing sheet injection command', {
command: injectionCommand.substring(0, 100) + '...',
type: type,
promptLength: injectionText.length
});
try {
await executeSlashCommandsWithOptions(injectionCommand, { displayCommand: false, showOutput: false });
CarrotDebug.inject('✅ Sheet injection executed successfully', {
type: type,
injectionSize: injectionText.length
});
return true;
} catch (error) {
CarrotDebug.error('❌ Sheet injection failed', {
error: error,
type: type
});
return false;
}
}
// =============================================================================
// SHEET GENERATION & TEMPLATE SYSTEM 🥕
// Now loaded from ./sheet-generator.js
// Includes: generateFullSheet, generateTagSheet, generateQuickSheet, CarrotTemplateManager
// =============================================================================
// =============================================================================
// CARROT PACK MANAGER SYSTEM 🥕
// Auto-sync BunnyMo packs from GitHub repository
// Now loaded from ./pack-manager.js and ./github-browser.js
// =============================================================================
// =============================================================================
// CARROT CONTEXT & STORAGE MANAGEMENT SYSTEM 🥕
// Now loaded from ./context-manager.js
// =============================================================================
// Global instances
let CarrotContext = null;
let CarrotStorage = null;
// =============================================================================
// CARROT DEBUG MODULE 🥕
// Now loaded from ./debugger.js
// =============================================================================
// Initialize debugger (sets up window.CarrotDebug and window.cd)
initializeDebugger();
// =============================================================================
// END CARROT DEBUG MODULE 🥕
// =============================================================================
// ✅ FIXED: All core data structures now imported from carrot-state.js
// This eliminates circular dependencies and provides single source of truth
// See carrot-state.js for:
// - selectedLorebooks, characterRepoBooks, tagLibraries
// - scannedCharacters
// - lastInjectedCharacters
// - currentRepoView, selectedCharacter, selectedRepository
// - _packManagerOpening
// - pendingSheetCommand, lastProcessedMessage, pendingThinkingBlockData
// Initialize UI updates module with data collections
initializeUIUpdates(scannedCharacters, selectedLorebooks, characterRepoBooks);
// Initialize tutorials system
initializeTutorials();
// Update status panels after a short delay to ensure DOM is ready
setTimeout(() => {
updateStatusPanels();
}, 500);
// Debug functionality now handled by CarrotDebug module
// Default settings
const defaultSettings = {
enabled: true,
selectedLorebooks: [],
characterRepoBooks: [],
tagLibraries: [],
displayMode: 'thinking', // 'none', 'thinking', 'cards'
autoExpand: false,
sendToAI: true,
injectionRole: 'system',
injectionDepth: 4,
maxCharactersDisplay: 6, // Max characters shown in chat
maxCharactersInject: 6, // Max characters sent to AI
debugMode: false,
rag: {
enabled: false,
autoVectorize: true,
debugMode: false,
contextLevel: 'global',
topK: 3,
scoreThreshold: 0.15,
queryContext: 3,
chunkSize: 1000,
chunkOverlap: 300,
injectionDepth: 4,
injectionRole: 'system',
smartCrossReference: true,
crosslinkThreshold: 0.25,
keywordFallback: true,
keywordFallbackPriority: false,
keywordFallbackLimit: 2,
simpleChunking: false,
// Vectorization settings (matching ST's vectors extension)
vectorSource: 'transformers',
openaiModel: 'text-embedding-ada-002',
cohereModel: 'embed-english-v3.0',
googleModel: 'text-embedding-005',
togetheraiModel: 'togethercomputer/m2-bert-80M-32k-retrieval',
ollamaModel: 'mxbai-embed-large',
ollamaKeep: false,
vllmModel: '',
webllmModel: '',
useAltUrl: false,
altUrl: '',
// Custom collection names
collectionNames: {},
// Keyword matching
caseSensitiveKeywords: false,
// Disabled collections (don't query)
disabledCollections: [],
},
babyBunnyMode: false, // 🐰 Baby Bunny Mode - guided automation for sheet processing
worldBookTrackerEnabled: true, // WorldBook Tracker toggle
autoRescanOnChatLoad: true, // Auto-rescan character repos on chat switch
bunnymoTagWrapping: false, // Wrap worldbook entries with <BunnymoTags:Entry_Name> when triggered
excludeTagSynthesis: false // Exclude TAG SYNTHESIS / BunnymoTags block at end of fullsheet from chunking
};
// Debug logging function - now uses centralized CarrotDebug module
function logSeq(message) {
CarrotDebug.init(message);
}
// Initialize extension settings
function initializeSettings() {
// CRITICAL: Check if settings exist and are valid
// Use strict checks to handle edge cases (null, undefined, etc.)
const settingsExist = extension_settings.hasOwnProperty(extensionName) &&
extension_settings[extensionName] !== null &&
typeof extension_settings[extensionName] === 'object';
if (!settingsExist) {
// Initialization is silent - no logs needed
extension_settings[extensionName] = { ...defaultSettings };
} else {
// Loading existing settings - silent
}
// Note: We no longer auto-reset templates to preserve user modifications
// Ensure all default properties exist (safe merge - preserves user values)
Object.keys(defaultSettings).forEach(key => {
if (extension_settings[extensionName][key] === undefined) {
extension_settings[extensionName][key] = defaultSettings[key];
}
});
// Restore lorebook sets from settings, but only include lorebooks that actually exist
selectedLorebooks.clear();
const availableLorebooks = world_names || [];
const invalidSelectedBooks = [];
if (extension_settings[extensionName].selectedLorebooks) {
extension_settings[extensionName].selectedLorebooks.forEach(book => {
// Only add if the lorebook actually exists
if (availableLorebooks.includes(book)) {
selectedLorebooks.add(book);
} else {
invalidSelectedBooks.push(book);
}
});
}
characterRepoBooks.clear();
tagLibraries.clear();
const invalidCharRepos = [];
const invalidTagLibs = [];
if (extension_settings[extensionName].characterRepoBooks) {
extension_settings[extensionName].characterRepoBooks.forEach(book => {
// Only add if the lorebook actually exists (selection status doesn't matter)
if (availableLorebooks.includes(book)) {
characterRepoBooks.add(book);
} else {
invalidCharRepos.push(book);
}
});
}
if (extension_settings[extensionName].tagLibraries) {
extension_settings[extensionName].tagLibraries.forEach(book => {
// Only add if the lorebook actually exists (selection status doesn't matter)
if (availableLorebooks.includes(book)) {
tagLibraries.add(book);
} else {
invalidTagLibs.push(book);
}
});
}
// After loading tag libraries, wrap them if bunnymoTagWrapping is enabled
// (deferred to avoid blocking initialization)
if (extension_settings[extensionName].bunnymoTagWrapping && tagLibraries.size > 0) {
setTimeout(() => {
wrapExistingTagLibraries();
}, 1000);
}
// Log cleanup if any invalid entries were found
const totalCleaned = invalidSelectedBooks.length + invalidCharRepos.length + invalidTagLibs.length;
if (totalCleaned > 0) {
CarrotDebug.scan('Cleaned up lorebooks that no longer exist:', {
invalidSelectedBooks,
invalidCharRepos,
invalidTagLibs
});
// Also remove any characters from deleted repos
const charsToRemove = [];
scannedCharacters.forEach((char, name) => {
if (invalidCharRepos.includes(char.source)) {
charsToRemove.push(name);
}
});
charsToRemove.forEach(name => scannedCharacters.delete(name));
// Save cleaned settings
extension_settings[extensionName].selectedLorebooks = Array.from(selectedLorebooks);
extension_settings[extensionName].characterRepoBooks = Array.from(characterRepoBooks);
extension_settings[extensionName].tagLibraries = Array.from(tagLibraries);
saveSettingsDebounced();
}
CarrotDebug.repo('Settings loaded', {
selectedLorebooks: selectedLorebooks.size,
characterRepos: characterRepoBooks.size,
cleanedInvalidBooks: totalCleaned
});
}
// Save settings to extension storage
function saveSettings() {
extension_settings[extensionName].selectedLorebooks = Array.from(selectedLorebooks);
extension_settings[extensionName].characterRepoBooks = Array.from(characterRepoBooks);
extension_settings[extensionName].tagLibraries = Array.from(tagLibraries);
saveSettingsDebounced();
}
// Parse BunnymoTags blocks from lorebook entries
// Only called for Character Repos, not Tag Libraries
function extractBunnyMoCharacters(entry, lorebookName) {
const characters = [];
const content = entry.content || '';
const entryKey = entry.key || entry.keys || entry.comment || 'unknown';
// Look for <BunnymoTags> blocks (character sheets)
const bunnyMoMatches = content.match(/<BunnymoTags>(.*?)<\/BunnymoTags>/gs);
if (!bunnyMoMatches) {
// No BunnymoTags block - silently skip, this entry is for other purposes
return characters;
}
bunnyMoMatches.forEach((match, index) => {
const tagContent = match.replace(/<\/?BunnymoTags>/g, '');
const result = parseBunnyMoTagBlock(tagContent, lorebookName, entryKey);
if (result.success) {
characters.push(result.character);
} else {
// Log parsing failure with specific reason
CarrotDebug.repo(`⏭️ Skipped entry "${entryKey}" in ${lorebookName}: ${result.reason}`);
}
});
return characters;
}
// Parse individual BunnymoTags block (copied from BunnyMoTags and enhanced)
// Returns: { success: boolean, character?: object, reason?: string }
function parseBunnyMoTagBlock(tagContent, lorebookName, entryKey = 'unknown') {
// Extract ALL <TAG:VALUE> patterns using regex, regardless of nesting or prose
// This will extract GENRE and LING tags from within <Genre> and <Linguistics> blocks
const tagPattern = /<([^:>]+):([^>]+)>/g;
const matches = [...tagContent.matchAll(tagPattern)];
// Check if block has any tags at all
if (matches.length === 0) {
return {
success: false,
reason: 'BunnymoTags block contains no valid <TAG:VALUE> patterns'
};
}
let characterName = null;
const tagMap = new Map();
matches.forEach(match => {
const [, tagType, tagValue] = match;
const cleanType = tagType.trim().toUpperCase();
const cleanValue = tagValue.trim().toUpperCase().replace(/_/g, ' ');
if (cleanType === 'NAME') {
characterName = cleanValue.replace(/_/g, ' ');
} else {
// Normalize category names
let categoryKey = cleanType;
// Map variations to standard names
if (cleanType === 'DERE') categoryKey = 'DERE';
else if (cleanType === 'LINGUISTIC' || cleanType === 'LINGUISTICS') categoryKey = 'LING';
if (!tagMap.has(categoryKey)) {
tagMap.set(categoryKey, new Set());
}
tagMap.get(categoryKey).add(cleanValue);
}
});
// Validation: Must have Name tag
if (!characterName) {
return {
success: false,
reason: `BunnymoTags block missing required <Name:CHARACTER_NAME> tag (found ${matches.length} other tags)`
};
}
// Validation: Must have at least one tag besides Name
if (tagMap.size === 0) {
return {
success: false,
reason: `BunnymoTags block for "${characterName}" has no character tags (only Name tag found)`
};
}
return {
success: true,
character: {
name: characterName,
tags: tagMap,
source: lorebookName
}
};
}
// =============================================================================
// BUNNYMO TAG WRAPPING - File-level lorebook modification
// =============================================================================
/**
* Create a backup of a lorebook before modification
*/
async function backupLorebook(lorebookName) {
try {
const backupName = `${lorebookName}.carrot_backup`;
// Check if backup already exists
if (world_names.includes(backupName)) {
CarrotDebug.scan(`Backup already exists for ${lorebookName}, skipping`);
return true;
}
const lorebook = await loadWorldInfo(lorebookName);
if (!lorebook) {
CarrotDebug.error(`Cannot backup lorebook: ${lorebookName} not found`);
return false;
}
await saveWorldInfo(backupName, lorebook, true);
CarrotDebug.repo(`✅ Backed up lorebook: ${lorebookName} → ${backupName}`);
return true;
} catch (error) {
CarrotDebug.error(`Failed to backup lorebook ${lorebookName}:`, error);
return false;
}
}
/**
* Automatically wrap existing tag libraries on load (if not already wrapped)
*/
async function wrapExistingTagLibraries() {
if (!extension_settings[extensionName].bunnymoTagWrapping) {
return;
}
const tagLibsList = Array.from(tagLibraries);
if (tagLibsList.length === 0) {
return;
}
CarrotDebug.repo(`🔄 Checking ${tagLibsList.length} tag libraries for wrapping...`);
for (const lorebookName of tagLibsList) {
try {
// Load the lorebook to check if it needs wrapping
const lorebook = await loadWorldInfo(lorebookName);
if (!lorebook) {
continue;
}
// Get entries
let entries = [];
if (Array.isArray(lorebook.entries)) {
entries = lorebook.entries;
} else if (lorebook.entries && typeof lorebook.entries === 'object') {
entries = Object.values(lorebook.entries);
}
if (entries.length === 0) {
continue;
}
// Check if any entry needs wrapping
let needsWrapping = false;
for (const entry of entries) {
if (!entry.content || !entry.content.trim()) {
continue;
}
const entryName = (entry.comment || entry.key?.[0] || 'Entry').replace(/[<>]/g, '');
const expectedWrapper = `<BunnymoTags:${entryName}>`;
// If any entry is not wrapped, the lorebook needs wrapping
if (!entry.content.trim().startsWith(expectedWrapper)) {
needsWrapping = true;
break;
}
}
// Wrap if needed
if (needsWrapping) {
CarrotDebug.repo(`📦 Wrapping tag library: ${lorebookName}`);
await wrapLorebookEntries(lorebookName);
} else {
CarrotDebug.scan(`✓ Tag library already wrapped: ${lorebookName}`);
}
} catch (error) {
CarrotDebug.error(`Failed to check/wrap ${lorebookName}:`, error);
}
}
CarrotDebug.repo(`✅ Finished checking tag libraries for wrapping`);
}
/**
* Wrap all entries in a tag library with BunnymoTags
*/
export async function wrapLorebookEntries(lorebookName) {
try {
// Create backup first
const backed = await backupLorebook(lorebookName);
if (!backed) {
toastr.error(`Failed to backup ${lorebookName}. Wrapping cancelled.`);
return false;
}
// Load the lorebook
const lorebook = await loadWorldInfo(lorebookName);
if (!lorebook) {
CarrotDebug.error(`Cannot wrap entries: ${lorebookName} not found`);
return false;
}
// ST's worldbook structure: .entries can be array OR object with numeric keys
let entries = [];
if (Array.isArray(lorebook.entries)) {
entries = lorebook.entries;
} else if (lorebook.entries && typeof lorebook.entries === 'object') {