-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsheet-generator.js
More file actions
1507 lines (1299 loc) · 64.6 KB
/
sheet-generator.js
File metadata and controls
1507 lines (1299 loc) · 64.6 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
// =============================================================================
// CARROT SHEET GENERATOR & TEMPLATE SYSTEM 🥕
// Character sheet generation and template management for BunnyMo format
// =============================================================================
import { CarrotDebug } from './debugger.js';
import { saveSettingsDebounced } from '../../../../script.js';
import { extension_settings, writeExtensionField } from '../../../extensions.js';
import { loadWorldInfo } from '../../../world-info.js';
import {
scannedCharacters,
selectedLorebooks,
characterRepoBooks,
getLastInjectedCharacters,
EXTENSION_NAME
} from './carrot-state.js';
// Use EXTENSION_NAME consistently
const extensionName = EXTENSION_NAME;
// Forward declaration - will be provided by index.js
// This is a temporary solution to avoid circular dependency
// TODO: Consider moving findCharacterByName to carrot-state.js or a utilities module
let findCharacterByName = null;
/**
* Initialize the sheet generator with required dependencies
* Called by index.js after it defines findCharacterByName
* @param {Function} findCharFn - The findCharacterByName function from index.js
*/
export function initializeSheetGenerator(findCharFn) {
findCharacterByName = findCharFn;
CarrotDebug.init('Sheet generator initialized with dependencies');
}
// =============================================================================
// SHEET GENERATION FUNCTIONS
// =============================================================================
async function generateFullSheet(characterName, charData) {
const currentTemplate = CarrotTemplateManager.getPrimaryTemplateForCategory('BunnyMo Fullsheet Format');
if (currentTemplate) {
// Use template system
const templateData = {
name: characterName,
tags: charData.tags
};
return await CarrotTemplateManager.processTemplate(currentTemplate.content, templateData);
}
// Fallback to default format
let content = `# 📋 FULL CHARACTER SHEET: ${characterName}\n\n`;
for (const [category, values] of charData.tags) {
if (values.size > 0) {
content += `## ${category.toUpperCase()}\n`;
Array.from(values).forEach(tag => {
content += `- ${tag}\n`;
});
content += '\n';
}
}
return content;
}
// Generate tag-focused sheet
async function generateTagSheet(characterName, charData) {
const currentTemplate = CarrotTemplateManager.getPrimaryTemplateForCategory('BunnyMo Tagsheet Format');
if (currentTemplate) {
// Use template system
const templateData = {
name: characterName,
tags: charData.tags
};
return await CarrotTemplateManager.processTemplate(currentTemplate.content, templateData);
}
// Fallback to BunnymoTags format
let content = `<BunnymoTags><Name:${characterName}>`;
// Build structured BunnymoTags format
const tagMap = new Map();
for (const [category, values] of charData.tags) {
if (values.size > 0) {
tagMap.set(category.toUpperCase(), Array.from(values));
}
}
// Add genre if available
if (tagMap.has('GENRE')) {
content += `, <GENRE:${tagMap.get('GENRE').join(',')}>`;
}
// Physical section
const physicalTags = ['SPECIES', 'GENDER', 'BUILD', 'SKIN', 'HAIR', 'STYLE'];
const physicalData = physicalTags.filter(tag => tagMap.has(tag));
if (physicalData.length > 0) {
content += ' <PHYSICAL>';
physicalData.forEach(tag => {
const values = tagMap.get(tag);
values.forEach(value => content += `<${tag}:${value}>, `);
});
content = content.slice(0, -2) + '</PHYSICAL>';
}
// Personality section
const personalityTags = ['PERSONALITY', 'TRAIT', 'DERE', 'ATTACHMENT', 'CONFLICT', 'BOUNDARIES', 'FLIRTING'];
const personalityData = personalityTags.filter(tag => tagMap.has(tag));
if (personalityData.length > 0) {
content += ' <PERSONALITY>';
personalityData.forEach(tag => {
const values = tagMap.get(tag);
values.forEach(value => content += `<${tag}:${value}>, `);
});
content = content.slice(0, -2) + '</PERSONALITY>';
}
// NSFW section
const nsfwTags = ['ORIENTATION', 'POWER', 'KINK', 'CHEMISTRY', 'AROUSAL', 'TRAUMA', 'JEALOUSY'];
const nsfwData = nsfwTags.filter(tag => tagMap.has(tag));
if (nsfwData.length > 0) {
content += ' <NSFW>';
nsfwData.forEach(tag => {
const values = tagMap.get(tag);
values.forEach(value => content += `<${tag}:${value}>, `);
});
content = content.slice(0, -2) + '</NSFW>';
}
content += ' </BunnymoTags>';
// Add linguistics if available
if (tagMap.has('LING') || tagMap.has('LINGUISTICS')) {
const lingValues = tagMap.get('LING') || tagMap.get('LINGUISTICS') || [];
if (lingValues.length > 0) {
content += `\n\n<Linguistics> Character uses `;
lingValues.forEach((ling, index) => {
content += `<LING:${ling}>`;
if (index < lingValues.length - 1) content += ' and ';
});
content += ' in their speech patterns. </Linguistics>';
}
}
return content;
}
// Generate quick reference sheet
async function generateQuickSheet(characterName, charData) {
const currentTemplate = CarrotTemplateManager.getPrimaryTemplateForCategory('BunnyMo Quicksheet Format');
if (currentTemplate) {
// Use template system
const templateData = {
name: characterName,
tags: charData.tags
};
return await CarrotTemplateManager.processTemplate(currentTemplate.content, templateData);
}
// Fallback to default format
let content = `# ⚡ QUICK SHEET: ${characterName}\n\n`;
// Key categories only
const keyCategories = ['PHYSICAL', 'PERSONALITY', 'SPECIES', 'GENDER', 'NSFW'];
for (const category of keyCategories) {
const values = charData.tags.get(category);
if (values && values.size > 0) {
content += `**${category}:** ${Array.from(values).join(', ')}\n`;
}
}
return content;
}
// =============================================================================
// CARROT TEMPLATE MANAGER SYSTEM 🥕
// Simple, reliable template system inspired by qvink_memory's excellent approach
// Avoids BunnyMoTags' overcomplicated failures - uses clean string substitution
// =============================================================================
const CarrotTemplateManager = {
// Advanced template system with BunnyMoTags-inspired structure
defaultTemplates: {
'character_consistency': {
id: 'character_consistency',
name: 'Character Consistency',
description: 'Maintains character consistency across conversations',
category: 'Character Data Injection',
role: 'system',
content: `OOC MANDATORY: [CHARACTER CONTEXT - CarrotKernel Tags]
{{TRIGGERED_CHARACTER_TAGS}}
**CRITICAL INSTRUCTIONS:**
1. You MUST incorporate this character information into your response planning
2. Stay true to their personality traits, species characteristics, and behavioral patterns
3. When using your <think> blocks for reasoning, you MUST include exactly 10 carrot emotes (🥕) distributed throughout your thinking process
4. Carrot emotes (🥕) must ONLY appear inside <think></think> blocks - NEVER in your actual response
5. Use carrots when referencing or applying the character information: "🥕 Luna has the trait \`PROTECTIVE\`, so she'd react immediately in defense of her new found family..."
**CARROT REQUIREMENT:** Exactly 10 🥕 emotes within <think> blocks only.`,
macros: {
'CHARACTERS': {
type: 'system',
description: 'Active character data from scannedCharacters Map',
enabled: true,
format: 'detailed'
},
'PERSONALITY_TAGS': {
type: 'tag_category',
description: 'Personality and trait tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'PHYSICAL_TAGS': {
type: 'tag_category',
description: 'Physical appearance and body tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'MBTI_TAGS': {
type: 'tag_category',
description: 'MBTI personality type tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'COMMUNICATION_TAGS': {
type: 'tag_category',
description: 'Language and communication tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'IDENTITY_TAGS': {
type: 'tag_category',
description: 'Identity and context tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'KINK_TAGS': {
type: 'tag_category',
description: 'Adult/kink tags from all scanned characters',
enabled: true,
format: 'category_list'
},
'SELECTED_LOREBOOKS': {
type: 'system',
description: 'List of enabled lorebooks from selectedLorebooks Set',
enabled: true,
format: 'list'
},
'CHARACTER_REPO_BOOKS': {
type: 'system',
description: 'Lorebooks marked as character repositories from characterRepoBooks Set',
enabled: true,
format: 'list'
},
'BUNNYMO_PACK_TAGS': {
type: 'bunnymo',
description: 'Extracted tag options from BunnyMo pack lorebooks, grouped by prefix (DERE, MBTI, TRAIT, etc.)',
enabled: true,
format: 'structured'
},
'CHARACTER_COUNT': {
type: 'system',
description: 'Total number of characters in scannedCharacters Map',
enabled: true,
format: 'number'
},
'CHARACTER_LIST': {
type: 'system',
description: 'Names of all scanned characters from scannedCharacters keys',
enabled: true,
format: 'list'
},
'TRIGGERED_CHARACTER_TAGS': {
type: 'triggered',
description: 'Tags from characters currently detected in chat context',
enabled: true,
format: 'triggered_detailed'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_fullsheet_injection_default': {
id: 'bunnymo_fullsheet_injection_default',
name: 'Default Fullsheet Injection',
description: 'System prompt for !fullsheet commands',
category: 'BunnyMo Fullsheet Injection',
role: 'system',
content: `🚨 **MANDATORY OOC OVERRIDE** 🚨
**SYSTEM DIRECTIVE:** A !FULLSHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !FULLSHEET request for "{{CHARACTER_NAME}}" with complete comprehensive detail
• **PROVIDE** ALL character categories, tags, and information in organized sections
• **INCLUDE** physical traits, personality, background, abilities, and all available data
• **RESUME** normal roleplay only after completing this comprehensive character sheet
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the sheet request',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_tagsheet_injection_default': {
id: 'bunnymo_tagsheet_injection_default',
name: 'Default Tagsheet Injection',
description: 'System prompt for !tagsheet commands',
category: 'BunnyMo Tagsheet Injection',
role: 'system',
content: `🏷️ **MANDATORY OOC OVERRIDE** 🏷️
**SYSTEM DIRECTIVE:** A !TAGSHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !TAGSHEET request for ALL characters referenced in the message
• **PROVIDE** complete BunnymoTags format for each character:
<BunnymoTags><Name:CHARACTER_NAME>, <GENRE:GENRE> <PHYSICAL><SPECIES:TYPE>, <GENDER:GENDER>, <BUILD:BUILD>, <SKIN:SKIN>, <HAIR:HAIR>, <STYLE:STYLE></PHYSICAL> <PERSONALITY><Dere:TYPE>, <TRAIT:TRAITS>, <ATTACHMENT:TYPE>, etc.</PERSONALITY> <NSFW><ORIENTATION:TYPE>, <POWER:TYPE>, <KINK:KINKS>, etc.</NSFW> </BunnymoTags>
• **INCLUDE** <Linguistics> sections with <LING:STYLE> speech patterns
• **RESUME** normal roleplay only after completing all character tagsheets
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the sheet request',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_quicksheet_injection_default': {
id: 'bunnymo_quicksheet_injection_default',
name: 'Default Quicksheet Injection',
description: 'System prompt for !quicksheet commands',
category: 'BunnyMo Quicksheet Injection',
role: 'system',
content: `⚡ **MANDATORY OOC OVERRIDE** ⚡
**SYSTEM DIRECTIVE:** A !QUICKSHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !QUICKSHEET request for "{{CHARACTER_NAME}}" with essential information only
• **PROVIDE** key character details: Physical, Personality, Species, Gender, and NSFW basics
• **FOCUS** on the most important identifying traits and characteristics
• **RESUME** normal roleplay only after completing this quick reference
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the sheet request',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_memsheet_injection_default': {
id: 'bunnymo_memsheet_injection_default',
name: 'Default Memsheet Injection',
description: 'System prompt for !memsheet commands',
category: 'BunnyMo Memsheet Injection',
role: 'system',
content: `📖 **MANDATORY OOC OVERRIDE** 📖
**SYSTEM DIRECTIVE:** A !MEMSHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !MEMSHEET request - catalogue the specific memory event being referenced
• **PROVIDE** comprehensive memory cataloguing with temporal data, spatial details, participants, concrete events, relationship dynamics, significance analysis, memory tags, and future reference triggers
• **DO NOT CONTINUE** the story after completing this memory catalogue
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative. Story does NOT resume after memory cataloguing.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the memory entry',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_updatesheet_injection_default': {
id: 'bunnymo_updatesheet_injection_default',
name: 'Default Updatesheet Injection',
description: 'System prompt for !updatesheet commands',
category: 'BunnyMo Updatesheet Injection',
role: 'system',
content: `🔄 **MANDATORY OOC OVERRIDE** 🔄
**SYSTEM DIRECTIVE:** A !UPDATESHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !UPDATESHEET request for "{{CHARACTER_NAME}}" - perform comprehensive psychological tag evolution assessment
• **PROVIDE** complete evolution analysis including: assessment scope, change magnitude, psychological analysis by category (Dere, Attachment, MBTI, Traits, NSFW, Boundaries, Genre), overall change assessment with statistics, updated tag block (copy-paste ready), and detailed change log
• **ANALYZE** all scenes since last update to identify tag strengthening/weakening/converting/emerging/fading
• **RESUME** normal roleplay only after completing this comprehensive psychological profile update
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the update assessment',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
},
'bunnymo_physsheet_injection_default': {
id: 'bunnymo_physsheet_injection_default',
name: 'Default Physsheet Injection',
description: 'System prompt for !physheet commands',
category: 'BunnyMo Physsheet Injection',
role: 'system',
content: `💪 **MANDATORY OOC OVERRIDE** 💪
**SYSTEM DIRECTIVE:** A !PHYSSHEET command has been detected and must be executed immediately.
**INSTRUCTIONS:**
• **CEASE** all current roleplay and narrative progression
• **EXECUTE** the !PHYSSHEET request for "{{CHARACTER_NAME}}" with complete comprehensive physical detail
• **PROVIDE** comprehensive physical bio using the format provided in the Physical Sheet template
• **INCLUDE** appearance overview, core features, distinguishing marks, grooming, physical presence, sensory profile, erogenous zones, intimate details, sexual responses, physical capability, and outfit catalog
• **RESUME** normal roleplay only after completing this comprehensive physical profile
**PRIORITY:** CRITICAL - This system command takes precedence over all ongoing narrative.`,
variables: {
'CHARACTER_NAME': {
type: 'system',
description: 'Character name for the physical profile',
enabled: true,
format: 'text'
}
},
settings: {
inject_depth: 4,
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: Date.now(),
modified: Date.now(),
usage_count: 0,
is_default: true,
is_primary: true
}
}
},
// Current template and state management
currentEditingTemplate: null,
// Template storage and retrieval
getTemplates() {
const settings = extension_settings[extensionName] || {};
const userTemplates = settings.templates || {};
const allTemplates = { ...this.defaultTemplates, ...userTemplates };
// Convert all templates to BunnyMoTags-compatible format
const compatibleTemplates = {};
for (const [id, template] of Object.entries(allTemplates)) {
compatibleTemplates[id] = {
...template,
label: template.name,
isDefault: template.metadata?.is_default || false,
variables: template.variables || []
};
}
return compatibleTemplates;
},
getTemplate(id) {
const templates = this.getTemplates();
const template = templates[id];
if (!template) return null;
// Convert CarrotKernel format to BunnyMoTags-compatible format
return {
...template,
label: template.name,
isDefault: template.metadata?.is_default || false,
variables: template.variables || [],
// Ensure depth is available from multiple possible sources
depth: template.depth !== undefined ? template.depth :
(template.settings?.inject_depth !== undefined ? template.settings.inject_depth : 4)
};
},
getPrimaryTemplate() {
const settings = extension_settings[extensionName] || {};
const primaryId = settings.primaryTemplate || 'character_consistency';
return this.getTemplate(primaryId);
},
// Method to reset a template to its default version
resetTemplateToDefault(templateId) {
const settings = extension_settings[extensionName] || {};
if (settings.templates && settings.templates[templateId]) {
delete settings.templates[templateId];
saveSettingsDebounced();
}
},
// Get templates by category
getTemplatesByCategory(category) {
const allTemplates = this.getTemplates();
return Object.entries(allTemplates)
.filter(([id, template]) => template.category === category)
.reduce((acc, [id, template]) => {
acc[id] = template;
return acc;
}, {});
},
// Get primary template for a category
getPrimaryTemplateForCategory(category) {
const categoryTemplates = this.getTemplatesByCategory(category);
// Find the template marked as primary
const primaryTemplate = Object.entries(categoryTemplates)
.find(([id, template]) => template.isPrimary || template.metadata?.is_primary);
if (primaryTemplate) {
return primaryTemplate[1];
}
// If no primary template, return the first available template
const firstTemplate = Object.values(categoryTemplates)[0];
if (firstTemplate) {
return firstTemplate;
}
// Fallback to the character_consistency template
return this.getTemplate('character_consistency');
},
setPrimaryTemplate(id) {
// CRITICAL: Never overwrite extension_settings completely - use optional chaining
if (!extension_settings[extensionName]) {
CarrotDebug.error('⚠️ TEMPLATES: extension_settings not initialized - this should not happen');
extension_settings[extensionName] = {};
}
extension_settings[extensionName].primaryTemplate = id;
this.saveSettings();
CarrotDebug.ui(`Primary template set to: ${id}`);
},
// Template operations
saveTemplate(template) {
// CRITICAL: Never overwrite extension_settings completely
if (!extension_settings[extensionName]) {
CarrotDebug.error('⚠️ TEMPLATES: extension_settings not initialized - this should not happen');
extension_settings[extensionName] = {};
}
if (!extension_settings[extensionName].templates) {
extension_settings[extensionName].templates = {};
}
template.metadata = template.metadata || {};
template.metadata.modified = Date.now();
template.metadata.usage_count = template.metadata.usage_count || 0;
extension_settings[extensionName].templates[template.id] = template;
this.saveSettings(true); // Force immediate save for template creation
CarrotDebug.ui(`Template '${template.name}' saved successfully`);
return true;
},
duplicateTemplate(id) {
const template = this.getTemplate(id);
if (!template) return null;
const newTemplate = JSON.parse(JSON.stringify(template));
newTemplate.id = `${id}_copy_${Date.now()}`;
newTemplate.name = `${template.name} (Copy)`;
newTemplate.metadata.created = Date.now();
newTemplate.metadata.modified = Date.now();
newTemplate.metadata.usage_count = 0;
newTemplate.metadata.is_default = false;
this.saveTemplate(newTemplate);
return newTemplate.id;
},
deleteTemplate(id) {
const template = this.getTemplate(id);
if (!template) return false;
if (template.metadata && template.metadata.is_default) {
CarrotDebug.ui(`Cannot delete default template: ${template.name}`);
return false;
}
delete extension_settings[extensionName].templates[id];
this.saveSettings(true); // Force immediate save for template deletion
CarrotDebug.ui(`Template '${template.name}' deleted successfully`);
return true;
},
resetTemplate(id) {
const defaultTemplate = this.defaultTemplates[id];
if (!defaultTemplate) return false;
if (extension_settings[extensionName]?.templates?.[id]) {
delete extension_settings[extensionName].templates[id];
this.saveSettings(true); // Force immediate save for template reset
CarrotDebug.ui(`Template '${defaultTemplate.name}' reset to default`);
}
return true;
},
updateTemplate(id, updatedTemplate) {
// CRITICAL: Never overwrite extension_settings completely
if (!extension_settings[extensionName]) {
CarrotDebug.error('⚠️ TEMPLATES: extension_settings not initialized - this should not happen');
extension_settings[extensionName] = {};
}
if (!extension_settings[extensionName].templates) {
extension_settings[extensionName].templates = {};
}
updatedTemplate.id = id;
updatedTemplate.metadata = updatedTemplate.metadata || {};
updatedTemplate.metadata.modified = Date.now();
updatedTemplate.metadata.usage_count = updatedTemplate.metadata.usage_count || 0;
updatedTemplate.metadata.is_default = false;
extension_settings[extensionName].templates[id] = updatedTemplate;
this.saveSettings(true); // Force immediate save for template updates
CarrotDebug.ui(`Template '${updatedTemplate.name}' updated successfully`);
return true;
},
// Compatibility method for BunnyMoTags interface
setTemplate(id, template) {
// Convert BunnyMoTags template format to CarrotKernel format
const convertedTemplate = {
id: id,
name: template.label || template.name || id,
description: template.description || '',
category: template.category || 'general',
role: template.role || 'system',
content: template.content || '',
macros: template.macros || {},
variables: template.variables || [],
depth: template.depth !== undefined ? template.depth : 4, // Handle 0 correctly - don't treat as falsy
scan: template.scan !== false,
settings: {
inject_depth: template.depth !== undefined ? template.depth : 4, // Handle 0 correctly - don't treat as falsy
inject_position: 'depth',
auto_activate: true,
ephemeral: true
},
metadata: {
created: template.metadata?.created || Date.now(),
modified: Date.now(),
usage_count: template.metadata?.usage_count || 0,
is_default: template.isDefault || false
}
};
return this.updateTemplate(id, convertedTemplate);
},
// Compatibility method for BunnyMoTags interface
saveUserTemplates() {
this.saveSettings();
},
exportAllTemplates() {
const templates = this.getTemplates();
const userTemplates = {};
// Only export non-default templates
Object.entries(templates).forEach(([id, template]) => {
if (!template.metadata?.is_default) {
userTemplates[id] = template;
}
});
return JSON.stringify({
version: '2.0',
extension: 'CarrotKernel',
type: 'template_collection',
templates: userTemplates,
exported: Date.now()
}, null, 2);
},
// Advanced macro processing system
// FIXED: Now async to await macro processing
async processTemplate(template, characterData) {
let content = template.content;
// Use the new real macro processing system
// FIXED: Await async macro processing
content = await this.processMacros(content);
// Update usage statistics
if (template.metadata) {
template.metadata.usage_count = (template.metadata.usage_count || 0) + 1;
if (!template.metadata.is_default) {
this.saveTemplate(template);
}
}
return content;
},
// Import/Export functionality
exportTemplate(id) {
const template = this.getTemplate(id);
if (!template) return null;
return JSON.stringify({
version: '2.0',
extension: 'CarrotKernel',
type: 'template',
template: template,
exported: Date.now()
}, null, 2);
},
importTemplate(jsonData) {
try {
const data = JSON.parse(jsonData);
if (data.extension !== 'CarrotKernel') {
throw new Error('Invalid template format');
}
const template = data.template;
template.id = `imported_${Date.now()}`;
template.metadata = template.metadata || {};
template.metadata.created = Date.now();
template.metadata.modified = Date.now();
template.metadata.is_default = false;
this.saveTemplate(template);
return template.id;
} catch (error) {
CarrotDebug.ui(`Template import failed: ${error.message}`);
return null;
}
},
saveSettings(immediate = false) {
if (immediate) {
// Force immediate save for critical operations like template saving
// First ensure the entire extension settings object is saved
if (typeof saveSettingsDebounced === 'function') {
saveSettingsDebounced();
}
// Also try to force immediate write
if (typeof writeExtensionField === 'function') {
writeExtensionField(extensionName, 'templates', extension_settings[extensionName]?.templates || {});
}
} else {
saveSettingsDebounced();
}
},
// Helper function to get currently triggered/active characters
getTriggeredCharacters() {
const lastInjectedCharacters = getLastInjectedCharacters();
if (!lastInjectedCharacters || lastInjectedCharacters.length === 0) {
return [];
}
if (!findCharacterByName) {
CarrotDebug.error('⚠️ findCharacterByName not initialized - call initializeSheetGenerator first');
return [];
}
return lastInjectedCharacters.map(name => findCharacterByName(name))
.filter(result => result && result.data)
.map(result => ({ name: result.name, data: result.data }));
},
// Helper function to extract tags by category from triggered characters only
getTagsByCategory(categoryKeywords) {
const triggeredChars = this.getTriggeredCharacters();
if (triggeredChars.length === 0) return 'No characters triggered in conversation';
const categoryTags = new Set();
for (const { name, data } of triggeredChars) {
if (data.tags && data.tags.size > 0) {
for (const [category, tags] of data.tags) {
// Check if this category matches our keywords
if (categoryKeywords.some(keyword => category.toLowerCase().includes(keyword.toLowerCase()))) {
const tagArray = Array.isArray(tags) ? tags : Array.from(tags);
tagArray.forEach(tag => categoryTags.add(`${name}: ${tag}`));
}
}
}
}
return categoryTags.size > 0 ? Array.from(categoryTags).join(', ') : `No ${categoryKeywords[0]} tags found in triggered characters`;
},
// Macro processors - exposed as property so macro display system can access them
macroProcessors: {
'CHARACTERS': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
if (triggeredChars.length === 0) return 'No characters triggered in conversation';
let output = '';
for (const { name, data } of triggeredChars) {
output += `**${name}** (from ${data.source})\n`;
if (data.tags && data.tags.size > 0) {
const tagList = Array.from(data.tags.entries())
.map(([category, tags]) => `${category}: ${Array.isArray(tags) ? tags.join(', ') : tags}`)
.join(' | ');
output += `${tagList}\n\n`;
}
}
return output;
},
// Individual character name macros
'CHARACTER1': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
return triggeredChars.length >= 1 ? triggeredChars[0].name : 'No character 1';
},
'CHARACTER2': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
return triggeredChars.length >= 2 ? triggeredChars[1].name : 'No character 2';
},
'CHARACTER3': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
return triggeredChars.length >= 3 ? triggeredChars[2].name : 'No character 3';
},
'CHARACTER4': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
return triggeredChars.length >= 4 ? triggeredChars[3].name : 'No character 4';
},
'CHARACTER5': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
return triggeredChars.length >= 5 ? triggeredChars[4].name : 'No character 5';
},
'PERSONALITY_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['personality', 'traits', 'behavior', 'mental', 'attitude', 'mind', 'dere', 'trait']);
},
'PHYSICAL_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['physical', 'appearance', 'body', 'species', 'gender', 'age', 'looks', 'build', 'skin', 'hair', 'style']);
},
'MBTI_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['entj', 'intj', 'enfp', 'infp', 'estp', 'istp', 'esfj', 'isfj', 'entp', 'intp', 'enfj', 'infj', 'estj', 'istj', 'esfp', 'isfp', 'mbti']);
},
'COMMUNICATION_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['ling', 'linguistics', 'speech', 'language', 'communication']);
},
'IDENTITY_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['name', 'genre', 'context', 'identity']);
},
'KINK_TAGS': () => {
return CarrotTemplateManager.getTagsByCategory(['kinks', 'fetish', 'sexual', 'nsfw', 'adult', 'erotic', 'kink']);
},
'TRIGGERED_CHARACTER_TAGS': () => {
const triggeredChars = CarrotTemplateManager.getTriggeredCharacters();
if (triggeredChars.length === 0) return 'No characters triggered in conversation';
let output = '';
for (const { name, data } of triggeredChars) {
output += `${name}: `;
if (data.tags && data.tags.size > 0) {
const allTags = [];
for (const [category, tags] of data.tags) {
const tagArray = Array.isArray(tags) ? tags : Array.from(tags);
allTags.push(...tagArray);
}
output += allTags.join(', ');
}
output += '\n';
}
return output;
},
'SELECTED_LOREBOOKS': () => {
return selectedLorebooks.size > 0 ? Array.from(selectedLorebooks).join(', ') : 'None selected';
},
'CHARACTER_REPO_BOOKS': () => {
return characterRepoBooks.size > 0 ? Array.from(characterRepoBooks).join(', ') : 'None configured';
},