-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathutils.js
More file actions
1621 lines (1385 loc) · 67.1 KB
/
Copy pathutils.js
File metadata and controls
1621 lines (1385 loc) · 67.1 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
// Copyright (C) 2024–2026 Aiko Hanasaki
// SPDX-License-Identifier: AGPL-3.0-only
import { chat_metadata, characters, eventSource, name2, this_chid } from '../../../../script.js';
import { getContext, extension_settings } from '../../../extensions.js';
import { selected_group, groups } from '../../../group-chats.js';
import { METADATA_KEY, world_names } from '../../../world-info.js';
import { Popup, POPUP_TYPE, POPUP_RESULT } from '../../../popup.js';
import { getSceneMarkers, saveMetadataForCurrentContext } from './sceneManager.js';
import { getPrompt as getCustomPresetPrompt } from './summaryPromptManager.js';
import { DISPLAY_NAME_DEFAULTS, DISPLAY_NAME_I18N_KEYS, MEMORY_TIER_CACHE_REFRESH_EVENT } from './constants.js';
import { translate } from '../../../i18n.js';
import { escapeHtml } from '../../../utils.js';
import { tr } from './i18nHelpers.js';
import { isNarratorModeActive } from './narratorMode.js';
import {
getCharacterMemoryBookLock,
resolveManualLorebookForCharacter,
} from './characterMemoryBookLocks.js';
const MODULE_NAME = 'STMemoryBooks-Utils';
const $ = window.jQuery;
// Prefer the first selector that exists in the DOM
function pick$(...selectors) {
for (const s of selectors) {
const $el = $(s);
if ($el.length) return $el;
}
return $(); // empty jQuery
}
// Returns '#group_' if group UI controls are present, otherwise '#'
function groupPrefix() {
return document.querySelector('#group_chat_completion_source') ? '#group_' : '#';
}
export function readIntInput(inputEl, fallback) {
if (!inputEl) return fallback;
const parsed = parseInt(inputEl.value, 10);
return Number.isFinite(parsed) ? parsed : fallback;
}
export function clampInt(n, min, max) {
return Math.min(Math.max(n, min), max);
}
export function markStmbPopup(popup) {
popup?.dlg?.classList?.add('stmb-popup');
return popup;
}
export function withGoBackButton(options = {}) {
return {
...options,
customButtons: [
...(Array.isArray(options.customButtons) ? options.customButtons : []),
{
text: translate('Go back', 'STMemoryBooks_GoBack'),
result: POPUP_RESULT.CANCELLED,
classes: ['menu_button'],
},
],
};
}
// Centralized DOM selectors - single source of truth
export const SELECTORS = {
extensionsMenu: '#extensionsMenu .list-group',
menuItem: '#stmb-menu-item',
chatContainer: '#chat',
// API and model selectors for profile settings
mainApi: '#main_api',
completionSource: '#chat_completion_source',
modelOpenai: '#model_openai_select',
modelClaude: '#model_claude_select',
modelOpenrouter: '#model_openrouter_select',
modelAi21: '#model_ai21_select',
modelGoogle: '#model_google_select',
modelMistralai: '#model_mistralai_select',
modelCohere: '#model_cohere_select',
modelPerplexity: '#model_perplexity_select',
modelGroq: '#model_groq_select',
modelNanogpt: '#model_nanogpt_select',
modelDeepseek: '#model_deepseek_select',
modelElectronhub: '#model_electronhub_select',
modelVertexai: '#model_vertexai_select',
modelAimlapi: '#model_aimlapi_select',
modelXai: '#model_xai_select',
modelPollinations: '#model_pollinations_select',
modelMoonshot: '#model_moonshot_select',
modelFireworks: '#model_fireworks_select',
modelCometapi: '#model_cometapi_select',
modelAzureOpenai: '#model_azure_openai_select',
modelZai: '#model_zai_select',
modelChutes: '#model_chutes_select',
tempOpenai: '#temp_openai',
tempCounterOpenai: '#temp_counter_openai'
};
// Supported Chat Completion sources - BULLETPROOF
const SUPPORTED_COMPLETION_SOURCES = [
'openai', 'claude', 'openrouter', 'ai21', 'makersuite', 'vertexai',
'mistralai', 'custom', 'cohere', 'perplexity', 'groq', 'nanogpt',
'deepseek', 'electronhub', 'aimlapi', 'xai', 'pollinations',
'moonshot', 'fireworks', 'cometapi', 'azure_openai', 'zai', 'chutes'
];
/**
* Normalize completion source names.
* Note: In ST base code, the provider is represented as 'makersuite'.
* Keep 'makersuite' as the canonical key and avoid other aliases.
*/
export function normalizeCompletionSource(source) {
const s = String(source || '').trim().toLowerCase();
// Canonical provider key is 'makersuite' in ST base code.
// Accept legacy alias and normalize to 'makersuite' to match ST without changing ST code.
if (s === 'google') return 'makersuite';
return s === '' ? 'openai' : s;
}
/**
* BULLETPROOF: Get current API and completion source information with comprehensive error handling
*/
export function getCurrentApiInfo() {
try {
let api = 'unknown';
let model = 'unknown';
let completionSource = 'unknown';
// Try SillyTavern's built-in functions first
if (typeof window.getGeneratingApi === 'function') {
api = window.getGeneratingApi();
} else {
api = $(SELECTORS.mainApi).val() || 'unknown';
}
if (typeof window.getGeneratingModel === 'function') {
model = window.getGeneratingModel();
}
completionSource = $(SELECTORS.completionSource).val() || api;
// Validate completion source
if (!SUPPORTED_COMPLETION_SOURCES.includes(completionSource)) {
console.warn(`${MODULE_NAME}: Unsupported completion source: ${completionSource}, falling back to openai`);
completionSource = 'openai';
}
return { api, model, completionSource };
} catch (e) {
console.warn(`${MODULE_NAME}: Error getting API info:`, e);
return {
api: $(SELECTORS.mainApi).val() || 'unknown',
model: 'unknown',
completionSource: $(SELECTORS.completionSource).val() || 'openai'
};
}
}
/**
* BULLETPROOF: Get the appropriate model and temperature selectors for current completion source
*/
export function getApiSelectors() {
const prefix = groupPrefix();
// current completion source from active UI (group or normal)
const $source = pick$(`${prefix}chat_completion_source`, '#chat_completion_source');
const completionSource = ($source.val?.() || 'openai');
// Model selectors per provider/source (group-aware via prefix)
const modelSelectorMap = {
openai: `${prefix}model_openai_select`,
claude: `${prefix}model_claude_select`,
openrouter: `${prefix}model_openrouter_select`,
ai21: `${prefix}model_ai21_select`,
makersuite: `${prefix}model_google_select`,
mistralai: `${prefix}model_mistralai_select`,
custom: `${prefix}model_custom_select`,
cohere: `${prefix}model_cohere_select`,
perplexity: `${prefix}model_perplexity_select`,
groq: `${prefix}model_groq_select`,
nanogpt: `${prefix}model_nanogpt_select`,
deepseek: `${prefix}model_deepseek_select`,
electronhub: `${prefix}model_electronhub_select`,
vertexai: `${prefix}model_vertexai_select`,
aimlapi: `${prefix}model_aimlapi_select`,
xai: `${prefix}model_xai_select`,
pollinations: `${prefix}model_pollinations_select`,
moonshot: `${prefix}model_moonshot_select`,
fireworks: `${prefix}model_fireworks_select`,
cometapi: `${prefix}model_cometapi_select`,
azure_openai: `${prefix}model_azure_openai_select`,
zai: `${prefix}model_zai_select`,
chutes: `${prefix}model_chutes_select`,
};
const model = modelSelectorMap[completionSource] || modelSelectorMap.openai;
// Temps share same ids per UI set
const temp = `${prefix}temp_openai`.replace('##', '#');
const tempCounter = `${prefix}temp_counter_openai`.replace('##', '#');
return { model, temp, tempCounter };
}
/**
* GROUP CHAT SUPPORT: Get current context - detects group vs single character chats
* @returns {Object} Context information including group/character detection
*/
export function getCurrentMemoryBooksContext() {
try {
let characterName = null;
let chatId = null;
let chatName = null;
// Check if we're in a group chat (following group-chats.js pattern)
const isGroupChat = !!selected_group;
const isManualMode = extension_settings?.STMemoryBooks?.moduleSettings?.manualModeEnabled === true;
const isNarratorMode = isNarratorModeActive({
isGroupChat,
manualModeEnabled: isManualMode,
enabled: chat_metadata?.STMemoryBooks?.narratorMode?.enabled === true,
});
const groupId = selected_group || null;
let groupName = null;
if (isGroupChat) {
// Group chat context (following group-chats.js pattern)
const group = groups?.find(x => x.id === groupId);
if (group) {
groupName = group.name;
chatId = group.chat_id;
chatName = chatId;
// For group chats, use the group name as the "character" identifier for compatibility
characterName = groupName;
}
} else {
// Single character chat context (following group-chats.js and script.js patterns)
// Method 1: Use name2 variable (primary character name from script.js)
if (name2 && name2.trim()) {
characterName = String(name2).trim();
}
// Method 2: Try to get current character from characters array and this_chid
else if (this_chid !== undefined && characters && characters[this_chid]) {
characterName = characters[this_chid].name;
}
// Method 3: Try chat_metadata.character_name as fallback
else if (chat_metadata?.character_name) {
characterName = String(chat_metadata.character_name).trim();
}
// Normalize unicode characters for consistency
if (characterName && characterName.normalize) {
characterName = characterName.normalize('NFC');
}
// Get chat information using SillyTavern's context system
try {
const context = getContext();
if (context?.chatId) {
chatId = context.chatId;
chatName = chatId;
} else if (typeof window.getCurrentChatId === 'function') {
chatId = window.getCurrentChatId();
chatName = chatId;
}
} catch (error) {
console.warn(`${MODULE_NAME}: Could not get context, trying fallback methods`);
if (typeof window.getCurrentChatId === 'function') {
chatId = window.getCurrentChatId();
chatName = chatId;
}
}
}
// Get bound lorebook information
let lorebookName = null;
if (chat_metadata && METADATA_KEY in chat_metadata) {
lorebookName = chat_metadata[METADATA_KEY];
}
// Get current model/temperature settings (following ModelTempLocks approach)
let modelSettings = null;
try {
// Get API info using the same method as ModelTempLocks
const currentApiInfo = getCurrentApiInfo();
// Get temperature using the same method as ModelTempLocks
const apiSelectors = getApiSelectors();
const rawTemp =
$(apiSelectors.temp).val() ??
$(apiSelectors.tempCounter).val();
const currentTemp = Number.isFinite(parseFloat(rawTemp))
? parseFloat(rawTemp)
: 0.7;
// Get model using the same method as ModelTempLocks
let currentModel = $(apiSelectors.model).val() || '';
modelSettings = {
api: currentApiInfo.api,
model: currentModel,
temperature: currentTemp,
completionSource: currentApiInfo.completionSource,
source: 'current_ui'
};
} catch (error) {
console.warn(`${MODULE_NAME}: Could not get current model/temperature settings:`, error);
modelSettings = null;
}
const result = {
characterName,
chatId,
chatName,
groupId,
isGroupChat,
isNarratorMode,
isMultiCharacter: isGroupChat || isNarratorMode,
chatMode: isGroupChat ? 'group' : isNarratorMode ? 'narrator' : 'solo',
supportsNativeCharacterFilters: isGroupChat,
lorebookName,
modelSettings
};
// Add group-specific properties when in group chat
if (isGroupChat) {
result.groupName = groupName;
}
return result;
} catch (error) {
console.warn(`${MODULE_NAME}: Error getting context:`, error);
return {
characterName: null,
chatId: null,
chatName: null,
groupId: null,
groupName: null,
isGroupChat: false,
isNarratorMode: false,
isMultiCharacter: false,
chatMode: 'solo',
supportsNativeCharacterFilters: false,
};
}
}
export function getCurrentManualLorebookResolution(options = {}) {
const settings = options.settings || extension_settings.STMemoryBooks || {};
const markers = options.markers || getSceneMarkers() || {};
const context = options.context || getCurrentMemoryBooksContext();
const character = options.character || characters?.[this_chid] || null;
return resolveManualLorebookForCharacter({
manualModeEnabled: !!settings?.moduleSettings?.manualModeEnabled,
isGroupChat: !!context?.isGroupChat,
characterKey: character?.avatar,
manualLorebook: markers.manualLorebook,
locks: settings.characterMemoryBookLocks,
});
}
/**
* Determines which lorebook to use based on settings and chat metadata.
* If in manual mode and no lorebook is set, it will trigger a selection popup.
*
* Note: This function only shows the selection popup when NO manual lorebook is currently set.
* If a manual lorebook already exists, it returns that lorebook without prompting.
* For "change" operations that should always show a selection popup, use showLorebookSelectionPopup() instead.
*
* @returns {Promise<string|null>} The name of the effective lorebook, or null if none is available/selected.
*/
export async function getEffectiveLorebookName() {
const settings = extension_settings.STMemoryBooks;
// This helper keeps its legacy behavior on purpose. Passive read paths still
// use it to resolve a best-effort lorebook without invoking the shared
// interactive recovery flow, which is reserved for write/generation paths.
// If manual mode is OFF, use the default chat-bound lorebook
if (!settings.moduleSettings.manualModeEnabled) {
return chat_metadata?.[METADATA_KEY] || null;
}
// Manual mode is ON. A solo character lock overrides this chat's manual selection.
const stmbData = getSceneMarkers() || {}; // This function already gets the right metadata object
const resolution = getCurrentManualLorebookResolution({ settings, markers: stmbData });
if (resolution.lorebookName) {
// Ensure the designated lorebook still exists
if (world_names.includes(resolution.lorebookName)) {
return resolution.lorebookName;
} else if (resolution.source === 'character-lock') {
toastr.error(tr(
'STMemoryBooks_CharacterMemoryBookLockMissing',
'The locked Memory Book "{{lorebookName}}" no longer exists. Unlock this character and choose a valid Memory Book.',
{ lorebookName: resolution.lorebookName },
));
return null;
} else {
toastr.error(`The designated manual lorebook "${resolution.lorebookName}" no longer exists. Please select a new one.`);
delete stmbData.manualLorebook; // Clear the invalid entry
}
}
// No manual lorebook is set. We need to ask the user.
const lorebookOptions = world_names.map(name => `<option value="${name}">${name}</option>`).join('');
if (lorebookOptions.length === 0) {
toastr.error('No lorebooks found to select from.', 'STMemoryBooks');
return null;
}
const popupContent = `
<h4>Select a Memory Book</h4>
<div class="world_entry_form_control">
<p>Manual mode is enabled, but no lorebook has been designated for this chat's memories. Please select one.</p>
<select id="stmb-manual-lorebook-select" class="text_pole">
${lorebookOptions}
</select>
</div>
`;
const popup = new Popup(popupContent, POPUP_TYPE.TEXT, '', { okButton: 'Select', cancelButton: 'Cancel' });
const result = await popup.show();
if (result === POPUP_RESULT.AFFIRMATIVE) {
const selectedLorebook = popup.dlg.querySelector('#stmb-manual-lorebook-select').value;
// Save the selection to the chat's metadata
stmbData.manualLorebook = selectedLorebook;
saveMetadataForCurrentContext(); // Use the existing function from sceneManager to save correctly for groups/single chats
void eventSource.emit(MEMORY_TIER_CACHE_REFRESH_EVENT);
toastr.success(`"${selectedLorebook}" is now the Memory Book for this chat.`, 'STMemoryBooks');
return selectedLorebook;
}
// User cancelled the selection
return null;
}
/**
* Always shows a lorebook selection popup, regardless of current manual lorebook state.
* This function is intended for "change" operations where the user explicitly wants to select a different lorebook.
*
* @param {string} currentLorebook - The currently selected lorebook (optional, for display purposes)
* @param {{excludedLorebookNames?: string[]}} options - Lorebooks unavailable for selection.
* @returns {Promise<string|null>} The name of the selected lorebook, or null if cancelled/no selection made.
*/
export async function showLorebookSelectionPopup(currentLorebook = null, options = {}) {
const markers = getSceneMarkers() || {};
const currentCharacterLorebooks = markers.manualCharacterLorebooks
&& typeof markers.manualCharacterLorebooks === 'object'
&& !Array.isArray(markers.manualCharacterLorebooks)
? Object.values(markers.manualCharacterLorebooks)
: [];
const lockedGroupLorebooks = getCurrentGroupLorebookMembers()
.map(member => getCharacterMemoryBookLock(
extension_settings.STMemoryBooks?.characterMemoryBookLocks,
member?.avatar || member?.key,
)?.lorebookName)
.filter(Boolean);
const excludedLorebooks = new Set([
...currentCharacterLorebooks,
...lockedGroupLorebooks,
...(Array.isArray(options.excludedLorebookNames) ? options.excludedLorebookNames : []),
].map(name => String(name || '').trim()).filter(Boolean));
const availableLorebooks = world_names.filter(name => !excludedLorebooks.has(name));
// Check if lorebooks are available
if (availableLorebooks.length === 0) {
toastr.error('No lorebooks found to select from.', 'STMemoryBooks');
return null;
}
const lorebookOptions = [
currentLorebook && excludedLorebooks.has(currentLorebook)
? `<option value="${escapeHtml(currentLorebook)}" selected disabled>${translate('Unavailable character Memory Book: {{name}}', 'STMemoryBooks_ManualLorebookUnavailableCharacterBook').replace('{{name}}', escapeHtml(currentLorebook))}</option>`
: !currentLorebook
? `<option value="" selected disabled>${translate('None selected', 'STMemoryBooks_NoneSelected')}</option>`
: '',
...availableLorebooks.map(name => {
const selected = name === currentLorebook ? ' selected' : '';
return `<option value="${escapeHtml(name)}"${selected}>${escapeHtml(name)}</option>`;
}),
].join('');
const popupContent = `
<h4>Select a Memory Book</h4>
<div class="world_entry_form_control">
<p>Choose which lorebook should be used for this chat's memories.</p>
${currentLorebook ? `<p><strong>Current:</strong> ${escapeHtml(currentLorebook)}</p>` : ''}
<select id="stmb-manual-lorebook-select" class="text_pole">
${lorebookOptions}
</select>
</div>
`;
const popup = new Popup(popupContent, POPUP_TYPE.TEXT, '', { okButton: 'Select', cancelButton: 'Cancel' });
const result = await popup.show();
if (result === POPUP_RESULT.AFFIRMATIVE) {
const selectedLorebook = popup.dlg.querySelector('#stmb-manual-lorebook-select').value;
if (!selectedLorebook) {
toastr.error(translate('Please select a lorebook for manual mode', 'STMemoryBooks_PleaseSelectLorebookForManualMode'), 'STMemoryBooks');
return null;
}
if (excludedLorebooks.has(selectedLorebook)) {
toastr.error(
translate('A character Memory Book cannot also be the main group Memory Book.', 'STMemoryBooks_ManualLorebookCharacterConflict'),
'STMemoryBooks',
);
return null;
}
// Only save and show success if a different lorebook was actually selected
if (selectedLorebook !== currentLorebook) {
const stmbData = getSceneMarkers();
stmbData.manualLorebook = selectedLorebook;
saveMetadataForCurrentContext();
void eventSource.emit(MEMORY_TIER_CACHE_REFRESH_EVENT);
toastr.success(`Manual lorebook changed to: ${selectedLorebook}`, 'STMemoryBooks');
return selectedLorebook;
} else {
// Same lorebook selected, no need to save or show success
return selectedLorebook;
}
}
// User cancelled the selection
return null;
}
/**
* Get current model and temperature settings with comprehensive validation
*/
export function getCurrentModelSettings(profile) {
try {
if (!profile) {
throw new Error('getCurrentModelSettings requires a profile');
}
const conn = profile.effectiveConnection || profile.connection;
if (!conn) {
throw new Error('Profile is missing connection');
}
const model = (conn.model || '').trim();
if (!model) {
throw new Error('Profile is missing required connection.model');
}
let temp = parseTemperature(conn.temperature);
if (temp === null) temp = 0.7;
return {
model,
temperature: temp,
};
} catch (error) {
console.warn(`${MODULE_NAME}: Error getting current model settings:`, error);
throw error;
}
}
/**
* UI-based model/temperature reader (for dynamic ST settings or overrides)
*/
export function getUIModelSettings() {
try {
const selectors = getApiSelectors();
const currentModel = ($(selectors.model).val() || '').trim();
let currentTemp = 0.7;
const tempValue = $(selectors.temp).val() || $(selectors.tempCounter).val();
if (tempValue !== null && tempValue !== undefined && tempValue !== '') {
const parsedTemp = parseFloat(tempValue);
if (!isNaN(parsedTemp) && parsedTemp >= 0 && parsedTemp <= 2) {
currentTemp = parsedTemp;
}
}
return {
model: currentModel,
temperature: currentTemp,
};
} catch (error) {
console.warn(`${MODULE_NAME}: Error getting UI model settings:`, error);
return {
model: '',
temperature: 0.7
};
}
}
/**
* Estimate tokens for a text string using the project tokenizer with a safe fallback.
* Returns input (prompt) tokens, an estimated output token count, and the total.
*
* Callers should pass the exact string they intend to send to the model
* (e.g., system + prompt + scene), to ensure accurate budgeting and warnings.
*
* @param {string} text
* @param {{ estimatedOutput?: number }} [options]
* @returns {Promise<{ input: number, output: number, total: number }>}
*/
export async function estimateTokens(text, options = {}) {
const { estimatedOutput = 300 } = options;
const content = String(text || '');
const inputTokens = Math.ceil(content.length / 4);
return {
input: inputTokens,
output: estimatedOutput,
total: inputTokens + estimatedOutput,
};
}
/**
* Resolve a profile's effective connection into a normalized shape
* { api, model, temperature, endpoint, apiKey, connectionProfileId, reverseProxy }.
* - Applies normalizeCompletionSource to api
* - Clamps temperature to [0, 2] with default 0.7
* - Passes through endpoint/apiKey/connectionProfileId/reverseProxy if provided on the profile connection
*
* @param {Object} profile
* @returns {{ api: string, model: string, temperature: number, endpoint?: string, apiKey?: string, connectionProfileId?: string, reverseProxy?: boolean }}
*/
export function resolveEffectiveConnectionFromProfile(profile) {
const conn = (profile?.effectiveConnection || profile?.connection || {});
const api = normalizeCompletionSource(conn.api || 'openai');
const model = (conn.model || '').trim();
let temperature = 0.7;
if (typeof conn.temperature === 'number' && !Number.isNaN(conn.temperature)) {
temperature = Math.max(0, Math.min(2, conn.temperature));
}
const endpoint = conn.endpoint ? String(conn.endpoint) : undefined;
const apiKey = conn.apiKey ? String(conn.apiKey) : undefined;
const connectionProfileId = conn.connectionProfileId ? String(conn.connectionProfileId) : undefined;
const reverseProxy = !!conn.reverseProxy;
return { api, model, temperature, endpoint, apiKey, connectionProfileId, reverseProxy };
}
export function createGroupParticipantResolver() {
if (!selected_group || !Array.isArray(groups) || !Array.isArray(characters)) {
return null;
}
const group = groups.find(item => String(item?.id) === String(selected_group));
if (!group || !Array.isArray(group.members) || group.members.length === 0) {
return null;
}
const members = [];
const memberAvatars = new Set();
const avatarsBySpeaker = new Map();
const seen = new Set();
for (const member of group.members) {
const memberId = String(member || '').trim();
if (!memberId) {
continue;
}
const character = characters.find(item => item?.avatar === memberId || item?.name === memberId);
const avatar = String(character?.avatar || memberId).trim();
if (!avatar) {
continue;
}
memberAvatars.add(avatar);
const speakerName = String(character?.name || '').trim();
if (speakerName) {
if (!avatarsBySpeaker.has(speakerName)) {
avatarsBySpeaker.set(speakerName, new Set());
}
avatarsBySpeaker.get(speakerName).add(avatar);
}
const key = avatar || memberId;
if (seen.has(memberId) || seen.has(key)) {
continue;
}
seen.add(memberId);
seen.add(key);
const name = String(character?.name || memberId).trim() || memberId;
members.push({
key,
avatar,
memberId,
name,
characterFilterName: getCharacterFilterNameFromAvatar(avatar),
});
}
return { memberAvatars, avatarsBySpeaker, members };
}
export function getCurrentGroupLorebookMembers() {
return createGroupParticipantResolver()?.members || [];
}
export function resolveGroupParticipantFilterName(message, resolver, messageId = null, logPrefix = MODULE_NAME) {
const originalAvatar = String(message?.original_avatar || '').trim();
if (originalAvatar && resolver.memberAvatars.has(originalAvatar)) {
return getCharacterFilterNameFromAvatar(originalAvatar);
}
const speakerName = String(message?.name || '').trim();
if (!speakerName) {
return null;
}
const avatarMatches = resolver.avatarsBySpeaker.get(speakerName);
if (!avatarMatches || avatarMatches.size !== 1) {
if (avatarMatches?.size > 1) {
console.warn(
`${logPrefix}: Ambiguous group participant name "${speakerName}" at message ${messageId ?? 'unknown'}; skipping character filter participant because original_avatar is unavailable or does not match a group member.`,
{ speakerName, avatarMatches: Array.from(avatarMatches) },
);
}
return null;
}
return getCharacterFilterNameFromAvatar(Array.from(avatarMatches)[0]);
}
export function getCharacterFilterNameFromAvatar(avatar) {
const trimmed = String(avatar || '').trim();
if (!trimmed) {
return '';
}
return trimmed.replace(/\.[^/.]+$/, '');
}
/**
* Localized built-in preset prompts via i18n.
* Keys are stable; values are localized strings from SillyTavern i18n.
* JSON keys in responses must remain: "title", "content", "keywords".
*/
export function getBuiltInPresetPrompts() {
return {
summary: translate(
`You are a talented summarist skilled at capturing scenes from stories comprehensively. Analyze the following roleplay scene and return a detailed memory as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short scene title (1-3 words)",
"content": "Detailed beat-by-beat summary in narrative prose...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, create a detailed beat-by-beat summary in narrative prose. First, note the dates/time. Then capture this scene accurately without losing ANY important information EXCEPT FOR [OOC] conversation/interaction. All [OOC] conversation/interaction is not useful for summaries.
This summary will go in lorebook entry, so include:
- All important story beats/events that happened
- Key interaction highlights and character developments
- Notable details, memorable quotes, and revelations
- Outcome and anything else important for future interactions between {{user}} and {{char}}
Capture ALL nuance without repeating verbatim. Make it comprehensive yet digestible.
For the keywords field, provide 15-30 specific, descriptive, relevant keywords for keyword retrieval via word-matching in chat context. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_summary'
),
group: translate(
`Analyze the following roleplay scene and create a memory entry from an omniscient POV.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short, descriptive scene title (3-6 words)",
"content": "Structured memory summary...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
- Write the memory as continuity relevant to the target group as a shared unit.
- Include shared events, mutual decisions, group plans, promises, conflicts, secrets, relationship shifts, unresolved tensions, and facts that affect the group dynamic.
- Include individual actions or emotions only when they changed the shared group state.
- Do not create a merged personality for the group. Keep attribution clear: Alice did X, Bob thought Y, both agreed Z.
- If only one member knows something, say so. Do not imply shared knowledge unless the scene supports it.
For the content field, use this markdown structure:
# [Scene Title]
**Timeline**: (date/day/time, if known)
## Target-Relevant Events
- Summarize the events that matter to this group in chronological order.
- Use cause -> intention -> reaction -> consequence logic.
- Exclude flavor-only details unless they reveal a lasting character or relationship change.
## Attribution
- Clearly state who did what.
- Clearly state who knew what.
- Clearly state who felt, believed, suspected, misunderstood, or intended what.
- Do not assign private thoughts or emotions to a character unless the scene text supports them.
## Continuity Impact
- Record what should matter in future scenes: decisions, injuries, promises, secrets, changed relationships, new knowledge, unresolved threads, practical consequences, emotional shifts, or altered trust.
- Separate shared knowledge from member-specific knowledge.
## Exclusions
- Ignore and exclude all [OOC] or meta discussion.
- Do not include unsupported assumptions.
- Do not collapse multiple characters into vague phrases like "they felt" unless every target member clearly felt it.
For the keywords field:
- Generate 15-30 standalone topical keywords for retrieval.
- Keywords must be concrete and scene-specific: locations, objects, proper nouns, unique actions, repeated motifs, plans, injuries, named events, or distinctive phrases.
- Do not use abstract themes.
- Do not use these major character names as keywords: {{group}}. NPC names may be used if the NPC played a major role.
- Prefer keywords that would fire if the user later mentions the noun/action alone.
Return ONLY the JSON, no additional text.`,
'STMemoryBooks_Prompt_group'
),
char: translate(
`Analyze the following scene and create a memory entry written with {{char}} as the focus.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short, descriptive scene title (3-6 words)",
"content": "Structured memory summary...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
Important: This is NOT a general scene summary. This is a targeted memory entry.
- Write the memory as continuity relevant to {{char}}.
- Include what {{char}} did, said, thought, felt, noticed, learned, decided, promised, concealed, misunderstood, or was affected by.
- Include other characters depending on how their actions, words, emotions, or decisions matter to {{char}}'s future continuity.
- Do not include information {{char}} could not know unless it directly affects future continuity and is clearly marked as external scene knowledge.
- Attribute all actions, thoughts, emotions, and knowledge clearly. Do not blur characters together.
For the content field, use this markdown structure:
# [Scene Title]
**Timeline**: (date/day/time, if known)
## Target-Relevant Events
- Summarize the events that matter to {{char}} in chronological order.
- Use cause -> intention -> reaction -> consequence logic.
- Exclude flavor-only details unless they reveal a lasting character or relationship change.
## Attribution
- Clearly state who did what.
- Clearly state who knew what.
- Clearly state who felt, believed, suspected, misunderstood, or intended what.
- Do not assign private thoughts or emotions to a character unless the scene text supports them.
## Continuity Impact
- Record what should matter in future scenes: decisions, injuries, promises, secrets, changed relationships, new knowledge, unresolved threads, practical consequences, emotional shifts, or altered trust.
- Separate shared knowledge from member-specific knowledge.
## Exclusions
- Ignore and exclude all [OOC] or meta discussion.
- Do not summarize the whole scene if it is not relevant to {{char}}.
- Do not include unsupported assumptions.
For the keywords field, generate 15-30 specific, descriptive, highly relevant keywords for database retrieval - focus on the most important topical terms. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). No compound keywords unless they are proper nouns. Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no additional text.`,
'STMemoryBooks_Prompt_char'
),
summarize: translate(
`Analyze the following roleplay scene and return a structured summary as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short scene title (1-3 words)",
"content": "Detailed summary with markdown headers...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, create a detailed bullet-point summary using markdown with these headers (but skip and ignore all OOC conversation/interaction):
- **Timeline**: Day/time this scene covers.
- **Story Beats**: List all important plot events and story developments that occurred.
- **Key Interactions**: Describe the important character interactions, dialogue highlights, and relationship developments.
- **Notable Details**: Mention any important objects, settings, revelations, or details that might be relevant for future interactions.
- **Outcome**: Summarize the result, resolution, or state of affairs at the end of the scene.
For the keywords field, provide 15-30 specific, descriptive, relevant keywords that would help a keyworded database find this conversation again if something is mentioned. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Ensure you capture ALL important information - comprehensive detail is more important than brevity.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_summarize'
),
synopsis: translate(
`Analyze the following roleplay scene and return a comprehensive synopsis as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short scene title (1-3 words)",
"content": "Long detailed synopsis with markdown structure...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, create a long and detailed beat-by-beat summary using markdown structure. Capture the most recent scene accurately without losing ANY information. [OOC] conversation/interaction is not useful for summaries and should be ignored and excluded. Use this structure:
# [Scene Title]
**Timeline**: (day/time)
## Story Beats
- (List all important plot events and developments)
## Key Interactions
- (Detail all significant character interactions and dialogue)
## Notable Details
- (Include memorable quotes, revelations, objects, settings)
## Outcome
- (Describe results, resolutions, and final state)
Include EVERYTHING important for future interactions between {{user}} and {{char}}. Capture all nuance without regurgitating verbatim.
For the keywords field, provide 15-30 specific, descriptive, relevant keywords for keyworded database retrieval. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_synopsis'
),
sumup: translate(
`Analyze the following roleplay scene and return a beat summary as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short scene title (1-3 words)",
"content": "Comprehensive beat summary...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, write a comprehensive beat summary that captures this scene completely. Format it as:
# Scene Summary - Day X - [Title]
First note the dates/time covered by the scene. Then narrate ALL important story beats/events that happened, key interaction highlights, notable details, memorable quotes, character developments, and outcome. Ensure no important information is lost. [OOC] conversation/interaction is not useful for summaries and should be ignored and excluded.
For the keywords field, provide 15-30 specific, descriptive, relevant keywords that would help a keyworded database find this summary again if mentioned. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_sumup'
),
minimal: translate(
`Analyze the following roleplay scene and return a minimal memory entry as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short scene title (1-3 words)",
"content": "Brief 2-5 sentence summary...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, provide a very brief 2-5 sentence summary of what happened in this scene. [OOC] conversation/interaction is not useful for summaries and should be ignored and excluded.
For the keywords field, generate 15-30 specific, descriptive, highly relevant keywords for database retrieval - focus on the most important terms that would help find this scene later. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_minimal'
),
northgate: translate(
`You are a memory archivist for a long-form narrative. Your function is to analyze the provided scene and extract all pertinent information into a structured JSON object.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Concise Scene Title (3-5 words)",
"content": "A detailed, literary summary of the scene written in a third-person, past-tense narrative style. Capture all key actions, emotional shifts, character development, and significant dialogue. Focus on "showing" what happened through concrete details. Ensure the summary is comprehensive enough to serve as a standalone record of the scene's events and their impact on the characters.",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the "content" field, write with literary quality. Do not simply list events; synthesize them into a coherent narrative block.
For the "keywords" field, provide 15-30 specific and descriptive keywords that capture the scene's core elements. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON object, with no additional text or explanations.`,
'STMemoryBooks_Prompt_northgate'
),
aelemar: translate(
`You are a meticulous archivist, skilled at accurately capturing all key plot points and memories from a story. Analyze the following story scene and extract a detailed summary as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Concise scene title (3-5 words)",
"content": "Detailed summary of key plot points and character memories, beat-by-beat in narrative prose...",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
For the content field, create a beat-by-beat summary in narrative prose. Capture all key plot points that advance the story and character memories that leave a lasting impression, ensuring nothing essential is omitted. This summary will go in a keyworded database, so include:
- Story beats, events, actions and consequences, turning points, and outcomes
- Key character interactions, character developments, significant dialogue, revelations, emotional impact, and relationships
- Outcomes and anything else important for future interactions between the user and the world
Capture ALL nuance without repeating verbatim. Do not simply list events; synthesize them into a coherent narrative block. This summary must be comprehensive enough to serve as a standalone record of the story so far, even if the original text is lost. Use at least 300 words. Avoid redundancy.
For the keywords field, provide 15-30 specific and descriptive keywords that capture the scene's core elements. Keywords must be concrete and scene-specific (locations, objects, proper nouns, unique actions). Do not use abstract themes (e.g., "sadness", "love") or character names.
Return ONLY the JSON, no other text.`,
'STMemoryBooks_Prompt_aelemar'
),
comprehensive: translate(
`Analyze the following roleplay scene in the context of previous summaries provided (if available) and return a comprehensive synopsis as JSON.
You must respond with ONLY valid JSON in this exact format:
{
"title": "Short, descriptive scene title (3-6 words)",