Repository navigation
Expand file tree
/
Copy pathsettings.js
More file actions
3449 lines (3148 loc) · 128 KB
/
Copy pathsettings.js
File metadata and controls
3449 lines (3148 loc) · 128 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
/**
* Smart Memory - SillyTavern Extension
* Copyright (C) 2026 Senjin the Dragon
* https://github.com/senjinthedragon/Smart-Memory
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Settings management: default values, settings migration, and UI binding.
*
* defaultSettings - canonical default values for all extension_settings keys
* loadSettings - merges defaults + runs field migrations on startup
* bindSettingsUI - wires all settings panel controls; takes a ctrl object
* with getter/setter properties for index.js state variables
* so this module never imports from index.js
*/
import {
extension_prompt_types,
extension_prompt_roles,
setExtensionPrompt,
saveSettingsDebounced,
getMaxContextSize,
stopGeneration,
} from '../../../../script.js';
import { callGenericPopup, POPUP_TYPE } from '../../../../scripts/popup.js';
import { getContext, extension_settings } from '../../../extensions.js';
import {
estimateTokens,
MODULE_NAME,
META_KEY,
PROMPT_KEY_LONG,
PROMPT_KEY_SESSION,
PROMPT_KEY_SCENES,
PROMPT_KEY_ARCS,
PROMPT_KEY_PROFILES,
PROMPT_KEY_CANON,
PROMPT_KEY_RELATIONSHIPS,
PROMPT_KEY_EPISTEMIC,
PROMPT_KEY_STATE_LEDGER,
generateMemoryId,
} from './constants.js';
import { memory_sources, fetchOllamaModels } from './generate.js';
import { runCompaction, injectSummary, loadAndInjectSummary } from './compaction.js';
import {
extractAndStoreMemories,
consolidateMemories,
injectMemories,
loadCharacterMemories,
clearCharacterMemories,
clearRelationshipHistory,
loadRelationshipHistory,
saveRelationshipHistory,
injectRelationshipHistory,
isFreshStart,
setFreshStart,
getReadOnlyStartIndex,
setReadOnlyStartIndex,
getReadOnlyStartTime,
} from './longterm.js';
import {
clearEpistemicKnowledge,
extractEpistemicKnowledge,
injectEpistemicKnowledge,
isEpistemicEnabled,
loadEpistemicKnowledge,
saveEpistemicKnowledge,
resetEpistemicWarnFlag,
} from './epistemic.js';
import { hideChatMessageRange } from '../../../../scripts/chats.js';
import { generateRecap, displayRecap } from './recap.js';
import {
extractSessionMemories,
consolidateSessionMemories,
injectSessionMemories,
clearSessionMemories,
purgeSessionMemoriesSince,
} from './session.js';
import {
summarizeScene,
sceneSimilarity,
injectSceneHistory,
loadSceneHistory,
saveSceneHistory,
clearSceneHistory,
detectSceneBreakAI,
detectSceneBreakHeuristic,
} from './scenes.js';
import { extractArcs, injectArcs, clearArcs, clearArcSummaries, loadArcSummaries } from './arcs.js';
import { runModelTest } from './model-test.js';
/** Set to true while a model test is running to allow cancellation. */
let modelTestRunning = false;
import { checkContinuity, generateRepair, injectRepair, clearRepair } from './continuity.js';
import {
getHardwareProfile,
getEmbeddingBatch,
clearEmbeddingFailed,
saveEmbeddingApiKey,
hasEmbeddingApiKey,
} from './embeddings.js';
import { clearCanon, generateCanon, injectCanon, saveCanon } from './canon.js';
import { clearSessionEntityRegistry } from './graph-migration.js';
import {
clearStateLedger,
injectStateLedger,
isStateLedgerEnabled,
runStateCardExtraction,
} from './state-ledger.js';
import { generateProfiles, injectProfiles, clearProfiles, loadProfiles } from './profiles.js';
import { clearUnifiedSlot, injectUnified, maybeInjectUnified } from './unified-inject.js';
import { getTierHWStats, clearTierStats } from './trim-stats.js';
import { showMemoryGraph } from './graph.js';
import {
setStatusMessage,
updateLongTermUI,
updateRelationshipHistoryUI,
updateEpistemicUI,
updateSessionUI,
updateScenesUI,
updateArcsUI,
updateShortTermUI,
updateCanonUI,
updateProfilesUI,
updateFreshStartUI,
updateEntityPanel,
updateTokenDisplay,
updateEmbeddingNotice,
} from './ui.js';
// ---- Default settings ---------------------------------------------------
export const defaultSettings = {
enabled: true,
settings_mode: 'simple',
extraction_frequency: 'medium',
// LLM source for all memory operations (extraction, summarization, recap)
source: memory_sources.main,
// Ollama direct source settings
ollama_url: 'http://localhost:11434',
ollama_model: '',
// OpenAI Compatible source settings
openai_compat_url: '',
openai_compat_key: '',
openai_compat_model: '',
// ST connection profile source: ID of the saved profile to use for extraction
connection_profile_id: null,
// Maximum tokens the Memory LLM may generate per extraction call.
// 8192 covers any thinking model comfortably. -1 means unlimited (Ollama only).
generation_budget: 8192,
// Minimum number of AI messages between long-term and session injection refreshes.
// 1 = refresh on every extraction pass (default / current behaviour).
// Higher values keep the injected block stable for longer, preserving prompt cache
// hits on cloud APIs. Chat history covers the gap for recent events.
injection_refresh_period: 1,
// OpenAI Compatible embedding API key
embedding_api_key: '',
// Short-term (compaction)
compaction_enabled: true,
compaction_threshold: 80,
compaction_keep_recent: 10,
compaction_response_length: 2000,
compaction_position: extension_prompt_types.IN_PROMPT,
compaction_depth: 0,
compaction_role: extension_prompt_roles.SYSTEM,
compaction_template: 'Story so far:\n{{summary}}',
// Consolidation (shared across tiers)
consolidation_enabled: true,
longterm_consolidation_threshold_fact: 4,
longterm_consolidation_threshold_relationship: 3,
longterm_consolidation_threshold_preference: 3,
longterm_consolidation_threshold_event: 4,
session_consolidation_threshold_scene: 3,
session_consolidation_threshold_revelation: 3,
session_consolidation_threshold_development: 3,
session_consolidation_threshold_detail: 3,
// Long-term
longterm_enabled: true,
longterm_extract_every: 3,
longterm_max_memories: 25,
longterm_response_length: 600,
longterm_inject_budget: 500,
longterm_position: extension_prompt_types.IN_PROMPT,
longterm_depth: 2,
longterm_role: extension_prompt_roles.SYSTEM,
longterm_triggered_depth: 4,
longterm_triggers_enabled: false,
longterm_template: 'Memories from previous conversations:\n{{memories}}',
// Relationship history
relationships_enabled: true,
relationships_inject_budget: 250,
relationships_position: extension_prompt_types.IN_CHAT,
relationships_depth: 5,
relationships_role: extension_prompt_roles.SYSTEM,
relationships_template: 'Relationship history:\n{{relationships}}',
// Session memory
session_enabled: true,
session_extract_every: 3,
session_max_memories: 30,
session_response_length: 500,
session_inject_budget: 400,
session_position: extension_prompt_types.IN_CHAT,
session_depth: 3,
session_role: extension_prompt_roles.SYSTEM,
session_template: 'Details from this session:\n{{session}}',
// Scene detection
scene_enabled: true,
scene_ai_detect: false,
scene_max_history: 5,
scene_min_messages: 3,
scene_summary_length: 200,
scene_inject_budget: 300,
scene_position: extension_prompt_types.IN_CHAT,
scene_depth: 6,
scene_role: extension_prompt_roles.SYSTEM,
// Story arcs
arcs_enabled: true,
arcs_max: 10,
arcs_response_length: 400,
arcs_inject_budget: 700,
arcs_position: extension_prompt_types.IN_CHAT,
arcs_depth: 2,
arcs_role: extension_prompt_roles.SYSTEM,
arc_summary_response_length: 300,
canon_response_length: 600,
canon_enabled: true,
canon_inject_budget: 800,
canon_position: extension_prompt_types.IN_PROMPT,
canon_depth: 0,
canon_role: extension_prompt_roles.SYSTEM,
canon_template: 'Character history:\n{{canon}}',
// Away recap
recap_enabled: true,
recap_threshold_hours: 4,
recap_response_length: 300,
// Continuity
continuity_response_length: 300,
continuity_auto_check: true,
continuity_auto_repair: false,
// Semantic embedding deduplication
embedding_enabled: true,
embedding_source: 'ollama',
embedding_url: '',
embedding_model: 'nomic-embed-text',
embedding_keep: false,
// Character/world profiles
profiles_enabled: true,
profiles_stale_threshold_minutes: 30,
// 0 = regenerate only on extraction passes; positive = also regenerate every N
// messages even if extraction did not run (Profile B only - too expensive on local).
profiles_regen_every: 0,
profiles_response_length: 600,
profiles_inject_budget: 400,
profiles_position: extension_prompt_types.IN_PROMPT,
profiles_depth: 1,
profiles_role: extension_prompt_roles.SYSTEM,
profiles_template: '{{profiles}}',
// Perspectives & Secrets (epistemic tracking)
epistemic_enabled: true,
epistemic_inject_unaware: true,
epistemic_secondhand_framing: true,
epistemic_response_length: 400,
epistemic_inject_budget: 200,
epistemic_depth: 1,
epistemic_position: extension_prompt_types.IN_CHAT,
epistemic_role: extension_prompt_roles.SYSTEM,
// State Ledger (structured entity state cards)
state_ledger_enabled: false,
state_ledger_inject_budget: 200,
state_ledger_depth: 1,
state_ledger_position: extension_prompt_types.IN_CHAT,
state_ledger_role: extension_prompt_roles.SYSTEM,
// Hardware profile - 'auto' | 'a' | 'b'
// 'auto': detect from memory source (ollama/webllm -> A, main/openai_compat -> B)
// 'a': force Profile A (local/low-VRAM behaviour)
// 'b': force Profile B (hosted/high-performance behaviour)
hardware_profile: 'auto',
// Automatically reallocate the per-tier token budget after each extraction pass,
// based on actual observed demand. Tiers with unused headroom give it to tiers
// that are trimming content. The configured total budget is treated as a hard cap.
// Off by default so manually tuned advanced budgets are not overwritten.
auto_tune_budgets: false,
// Show a non-blocking activity indicator while background extraction is running.
// Gives users a visible signal that Smart Memory is working so they know not
// to send a new message until it finishes.
show_activity_indicator: true,
// Verbose logging - when false, operational extraction/migration logs are
// suppressed. Errors (console.error) are always shown regardless of this flag.
verbose_logging: false,
// Experimental: merge all tier content into a single IN_PROMPT block instead
// of injecting each tier into its own named slot at different depths/positions.
unified_injection: false,
unified_position: 2, // extension_prompt_types.IN_PROMPT (Before Main Prompt)
unified_depth: 0,
unified_role: 0, // extension_prompt_roles.SYSTEM
// Force macro injection mode for all tiers regardless of character card content.
// Use this when macros are placed in instruct templates (which cannot be auto-detected
// from character card fields). Auto-detection handles the common case of macros placed
// in the system prompt or other card fields without needing this toggle.
macros_enabled: false,
// Per-character memory storage (populated at runtime by longterm.js)
characters: {},
};
// ---- Settings mode helpers -----------------------------------------------
// Extraction frequency presets for the simple-mode dropdown.
const EXTRACTION_FREQUENCY_MAP = { low: 5, medium: 3, high: 1 };
// Fixed proportions for the simplified total-budget slider. Each value is a
// fraction of the total that gets allocated to that tier. Must sum to 1.0.
const BUDGET_RATIOS = {
longterm: 0.16,
session: 0.13,
scenes: 0.1,
arcs: 0.13,
canon: 0.18,
profiles: 0.13,
relationships: 0.08,
epistemic: 0.06,
state_ledger: 0.06,
};
/**
* Returns the sum of all per-tier inject budgets from current settings.
* Used to initialise the simplified slider from existing advanced values.
* @param {Object} s - Settings object.
* @returns {number}
*/
function totalBudgetFromSettings(s) {
return (
(s.longterm_inject_budget ?? 500) +
(s.session_inject_budget ?? 400) +
(s.scene_inject_budget ?? 300) +
(s.arcs_inject_budget ?? 700) +
(s.canon_inject_budget ?? 800) +
(s.profiles_inject_budget ?? 400) +
(s.relationships_inject_budget ?? 250) +
(s.epistemic_inject_budget ?? 200) +
(s.state_ledger_inject_budget ?? 200)
);
}
/**
* Distributes a total token budget across tiers using BUDGET_RATIOS and
* writes the results directly into the settings object. Rounds to nearest 50
* to match the step granularity of the individual sliders.
* @param {number} total
* @param {Object} s - Settings object (mutated in place).
*/
function applyTotalBudget(total, s) {
const snap = (v) => Math.max(50, Math.round(v / 50) * 50);
s.longterm_inject_budget = snap(total * BUDGET_RATIOS.longterm);
s.session_inject_budget = snap(total * BUDGET_RATIOS.session);
s.scene_inject_budget = snap(total * BUDGET_RATIOS.scenes);
s.arcs_inject_budget = snap(total * BUDGET_RATIOS.arcs);
s.canon_inject_budget = snap(total * BUDGET_RATIOS.canon);
s.profiles_inject_budget = snap(total * BUDGET_RATIOS.profiles);
s.relationships_inject_budget = snap(total * BUDGET_RATIOS.relationships);
s.epistemic_inject_budget = snap(total * BUDGET_RATIOS.epistemic);
s.state_ledger_inject_budget = snap(total * BUDGET_RATIOS.state_ledger);
}
/**
* Re-injects all memory tiers using the current budget settings and refreshes
* the token bar. Called after any budget slider change so the trim indicators
* clear immediately without waiting for the next message.
*
* Awaits the two async inject calls (injectMemories, injectSessionMemories) so
* that updateTokenDisplay sees fully populated trim stats rather than the stale
* values from the previous injection cycle.
*
* @param {string|null} characterName - Active character (or group selection).
*/
async function reinjectAfterBudgetChange(characterName) {
loadAndInjectSummary();
await injectMemories(characterName);
injectRelationshipHistory(characterName);
await injectSessionMemories();
injectSceneHistory();
injectArcs();
injectCanon(characterName);
injectProfiles(characterName);
injectEpistemicKnowledge(characterName, characterName);
injectStateLedger();
maybeInjectUnified();
updateTokenDisplay();
}
// Minimum budget any tier will be reduced to during auto-tune, and the headroom
// multiplier applied above actual demand so the next message doesn't immediately
// hit the limit again.
const AUTO_TUNE_FLOOR = 50;
const AUTO_TUNE_HEADROOM = 1.15;
// Maps each tunable tier to its settings key and DOM element IDs.
// Short-term is excluded - it self-corrects via regeneration rather than budget tuning.
const TUNABLE_TIERS = [
{
promptKey: PROMPT_KEY_LONG,
setting: 'longterm_inject_budget',
defaultBudget: 500,
slider: 'sm_longterm_inject_budget',
display: 'sm_longterm_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_SESSION,
setting: 'session_inject_budget',
defaultBudget: 400,
slider: 'sm_session_inject_budget',
display: 'sm_session_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_CANON,
setting: 'canon_inject_budget',
defaultBudget: 800,
slider: 'sm_canon_inject_budget',
display: 'sm_canon_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_SCENES,
setting: 'scene_inject_budget',
defaultBudget: 300,
slider: 'sm_scene_inject_budget',
display: 'sm_scene_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_ARCS,
setting: 'arcs_inject_budget',
defaultBudget: 700,
slider: 'sm_arcs_inject_budget',
display: 'sm_arcs_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_PROFILES,
setting: 'profiles_inject_budget',
defaultBudget: 400,
slider: 'sm_profiles_inject_budget',
display: 'sm_profiles_inject_budget_value',
fmt: (v) => `${v} tokens`,
},
{
promptKey: PROMPT_KEY_RELATIONSHIPS,
setting: 'relationships_inject_budget',
defaultBudget: 250,
slider: 'sm_relationships_inject_budget',
display: 'sm_relationships_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_EPISTEMIC,
setting: 'epistemic_inject_budget',
defaultBudget: 200,
slider: 'sm_epistemic_inject_budget',
display: 'sm_epistemic_inject_budget_value',
fmt: (v) => String(v),
},
{
promptKey: PROMPT_KEY_STATE_LEDGER,
setting: 'state_ledger_inject_budget',
defaultBudget: 200,
slider: 'sm_state_ledger_inject_budget',
display: 'sm_state_ledger_inject_budget_value',
fmt: (v) => String(v),
},
];
/**
* Redistributes the per-tier token budget based on observed demand.
* Tiers reporting unused headroom give it to tiers that are trimming.
* The sum of all tier budgets never exceeds the current configured total.
*
* Only runs when `auto_tune_budgets` is enabled. Safe to call after every
* extraction pass - does nothing if no trim stats have been recorded yet
* or if no tier's demand has changed enough to warrant an update.
*
* @param {string|null} characterName - Active character (or group selection).
*/
export function autoTuneBudgets(characterName) {
const s = extension_settings[MODULE_NAME];
if (!s.auto_tune_budgets) return;
const snap = (v, floor) => Math.max(floor ?? AUTO_TUNE_FLOOR, Math.round(v / 50) * 50);
// Compute target budget for each tier from its actual demand.
// Uses the high water mark so group chat budgets are sized for the greediest
// character seen this session, not just whichever character injected last.
// Tiers with no recorded stats (disabled or never injected) keep their
// current budget so they are not silently shrunk.
// The per-tier defaultBudget acts as a hard floor: auto-tune can grow a tier
// above its default when demand is high, but never shrinks it below, so
// characters with light content do not end up with sub-default budgets.
const targets = TUNABLE_TIERS.map((tier) => {
const stats = getTierHWStats(tier.promptKey);
if (!stats || stats.full === 0) {
return { tier, budget: s[tier.setting] };
}
return { tier, budget: snap(stats.full * AUTO_TUNE_HEADROOM, tier.defaultBudget) };
});
// In simple mode the user has set an explicit total budget cap; honour it by
// scaling targets down if they exceed it. In advanced mode each tier slider
// is independent and there is no user-set total, so auto-tune sets each tier
// to exactly what it needs without a cap constraint.
if ((s.settings_mode ?? 'simple') === 'simple') {
const totalCap = totalBudgetFromSettings(s);
const totalTarget = targets.reduce((sum, t) => sum + t.budget, 0);
if (totalTarget > totalCap) {
const scale = totalCap / totalTarget;
for (const t of targets) {
t.budget = Math.max(snap(t.tier.defaultBudget ?? AUTO_TUNE_FLOOR), snap(t.budget * scale));
}
}
}
// Apply any changes and update DOM sliders.
let changed = false;
for (const { tier, budget } of targets) {
if (s[tier.setting] !== budget) {
s[tier.setting] = budget;
$(`#${tier.slider}`).val(budget);
$(`#${tier.display}`).text(tier.fmt(budget));
// Invalidate stale trim stats for this tier. reinjectAfterBudgetChange fires
// async inject calls (injectMemories, injectSessionMemories) without awaiting
// them, so updateTokenDisplay may run before those Promises resolve and see
// the load-pass trim data rather than the fresh post-tune data. Clearing here
// ensures the token bar shows no trim until the next real injection reports.
clearTierStats(tier.promptKey);
changed = true;
}
}
if (changed) {
saveSettingsDebounced();
reinjectAfterBudgetChange(characterName);
}
}
/**
* Shows or hides advanced-only controls based on the current settings mode.
* Also syncs the simplified budget slider value from the current per-tier totals.
* @param {'simple'|'advanced'} mode
*/
function applySettingsMode(mode) {
const isSimple = mode === 'simple';
$('.sm-advanced-only').toggle(!isSimple);
$('.sm-simple-only').toggle(isSimple);
if (isSimple) {
const total = totalBudgetFromSettings(extension_settings[MODULE_NAME]);
$('#sm_total_budget').val(total);
$('#sm_total_budget_value').text(total);
}
}
// ---- Settings loading and migration -------------------------------------
/**
* Merges defaultSettings into extension_settings for any missing keys.
* Preserves existing values so user configuration is not overwritten on update.
*/
export function loadSettings() {
if (!extension_settings[MODULE_NAME]) {
extension_settings[MODULE_NAME] = {};
}
for (const [key, value] of Object.entries(defaultSettings)) {
if (extension_settings[MODULE_NAME][key] === undefined) {
extension_settings[MODULE_NAME][key] = value;
}
}
// Migration: replace old bracket-wrapped template defaults with plain-text equivalents.
// Only affects users who never customized these fields (exact match on the old default).
// Bracket notation in injections bleeds into RP output - the model mimics it.
const TEMPLATE_MIGRATIONS = {
compaction_template: {
from: '[Story so far:\n{{summary}}]',
to: 'Story so far:\n{{summary}}',
},
longterm_template: {
from: '[Memories from previous conversations:\n{{memories}}]',
to: 'Memories from previous conversations:\n{{memories}}',
},
session_template: {
from: '[Details from this session:\n{{session}}]',
to: 'Details from this session:\n{{session}}',
},
};
for (const [key, migration] of Object.entries(TEMPLATE_MIGRATIONS)) {
if (extension_settings[MODULE_NAME][key] === migration.from) {
extension_settings[MODULE_NAME][key] = migration.to;
}
}
// Migration: raise compaction response length from 1500 to 2000.
// 1500 tokens was too tight for a 9-section summary, causing truncated output.
if (extension_settings[MODULE_NAME].compaction_response_length === 1500) {
extension_settings[MODULE_NAME].compaction_response_length = 2000;
}
// Migration: raise arc injection budget to 700.
// 400 was too tight once the adaptive budget applies a 0.8x multiplier during intimate
// scenes, dropping the oldest arc from injection. 200 is the pre-1.3.0 default.
if (
extension_settings[MODULE_NAME].arcs_inject_budget === 200 ||
extension_settings[MODULE_NAME].arcs_inject_budget === 400
) {
extension_settings[MODULE_NAME].arcs_inject_budget = 700;
}
// Migration: longterm_consolidate -> consolidation_enabled (now controls both tiers).
// If a user had explicitly disabled long-term consolidation, carry that intent forward.
if (
Object.prototype.hasOwnProperty.call(extension_settings[MODULE_NAME], 'longterm_consolidate') &&
!Object.prototype.hasOwnProperty.call(extension_settings[MODULE_NAME], 'consolidation_enabled')
) {
extension_settings[MODULE_NAME].consolidation_enabled =
extension_settings[MODULE_NAME].longterm_consolidate;
}
}
// ---- Settings UI binding ------------------------------------------------
/**
* Shows a toastr error notification for a failed Smart Memory operation.
* Used by all manual button handlers so failures are visible to the user.
* @param {string} operation - Short label for what failed (e.g. "Summary generation").
* @param {Error} err - The caught error.
*/
function showError(operation, err) {
console.error(`[SmartMemory] ${operation} failed:`, err);
toastr.error(`${operation} failed. Check the browser console for details.`, 'Smart Memory', {
timeOut: 6000,
positionClass: 'toast-bottom-right',
});
}
/**
* Binds all settings panel controls to their corresponding settings values.
* Each control reads from extension_settings[MODULE_NAME] on mount and writes
* back on change, calling saveSettingsDebounced() to persist.
*
* @param {Object} ctrl - Getter/setter proxy for index.js module-level state:
* extractionRunning, compactionRunning, consolidationRunning, catchUpCancelled,
* sceneMessageBuffer, sceneBufferLastIndex, selectedGroupCharacter.
* Also carries callbacks: clearAllInjections, onChatChanged,
* getSelectedCharacterName, getStableExtractionWindowWithFallback.
*/
export function bindSettingsUI(ctrl) {
const s = extension_settings[MODULE_NAME];
/**
* Returns true and shows a warning toast if a catch-up or compaction is
* currently running. Use this to block manual extract/clear buttons that
* would conflict with an in-progress background job.
* @returns {boolean}
*/
function isCatchUpRunning() {
if (ctrl.extractionRunning || ctrl.compactionRunning) {
toastr.warning(
'Cannot do this while Memorize Chat is running. Cancel it first.',
'Smart Memory',
{
timeOut: 4000,
positionClass: 'toast-bottom-right',
},
);
return true;
}
return false;
}
/**
* Runs extraction on messages generated during the read-only window, then
* lifts the gate without purging or ghosting anything. Called when the user
* chooses to commit a read-only session rather than discard it.
*
* Session memories are already present (extraction was gated, not deleted).
* This function fills in the missing tiers: long-term, arcs, and profiles.
*
* @param {number} startIndex - Chat index where the read-only window began.
* @returns {Promise<void>}
*/
async function commitReadOnlyWindow(startIndex) {
const context = getContext();
const settings = extension_settings[MODULE_NAME];
const windowMessages = (context.chat ?? [])
.slice(startIndex)
.filter((m) => m.mes && !m.is_system);
if (windowMessages.length === 0) return;
const characterName = ctrl.getSelectedCharacterName();
const characterNames = (() => {
if (!context.groupId) return characterName ? [characterName] : [];
const group = context.groups?.find((g) => g.id === context.groupId);
if (!group) return characterName ? [characterName] : [];
return group.members
.filter((avatar) => !(group.disabled_members ?? []).includes(avatar))
.map((avatar) => context.characters.find((c) => c.avatar === avatar)?.name)
.filter(Boolean);
})();
setStatusMessage('Committing read-only session...');
for (const name of characterNames) {
if (settings.longterm_enabled) {
const nameWindow = context.groupId
? windowMessages.filter((m) => m.is_user || m.name === name)
: windowMessages;
if (nameWindow.length > 0) {
await extractAndStoreMemories(name, nameWindow).catch((err) =>
console.error('[SmartMemory] Commit long-term extraction error:', err),
);
if (settings.consolidation_enabled) {
await consolidateMemories(name).catch((err) =>
console.error('[SmartMemory] Commit consolidation error:', err),
);
}
}
}
if (settings.profiles_enabled && name) {
await generateProfiles(name)
.then((profiles) => {
if (profiles) {
injectProfiles(name);
updateProfilesUI(profiles);
}
})
.catch((err) => console.error('[SmartMemory] Commit profile generation error:', err));
}
}
if (settings.arcs_enabled) {
await extractArcs(windowMessages).catch((err) =>
console.error('[SmartMemory] Commit arc extraction error:', err),
);
}
saveSettingsDebounced();
setStatusMessage('Session committed.');
}
// Prevent section-header enable checkboxes from toggling the <details> open/closed
// when clicked. Without this, clicking the checkbox both changes the setting and
// collapses the section, which is never what the user intends.
$(document).on('click', '.sm-section-toggle', (e) => e.stopPropagation());
// ---- Master toggle --------------------------------------------------
$('#sm_enabled')
.prop('checked', s.enabled)
.on('change', function () {
extension_settings[MODULE_NAME].enabled = $(this).prop('checked');
saveSettingsDebounced();
if (!extension_settings[MODULE_NAME].enabled) {
// Remove all injections immediately so nothing lingers in the prompt.
ctrl.clearAllInjections();
} else {
// Restore injections from stored data so the user picks up where they left off.
ctrl.onChatChanged();
}
});
// ---- Settings mode toggle -------------------------------------------
$('#sm_settings_mode_advanced')
.prop('checked', s.settings_mode === 'advanced')
.on('change', function () {
const mode = $(this).prop('checked') ? 'advanced' : 'simple';
extension_settings[MODULE_NAME].settings_mode = mode;
saveSettingsDebounced();
applySettingsMode(mode);
applyInjectionOverrideUI();
});
// ---- Simplified total budget slider ---------------------------------
$('#sm_total_budget')
.val(totalBudgetFromSettings(s))
.on('input', function () {
const total = parseInt($(this).val(), 10);
$('#sm_total_budget_value').text(total);
applyTotalBudget(total, extension_settings[MODULE_NAME]);
saveSettingsDebounced();
reinjectAfterBudgetChange(ctrl.getSelectedCharacterName());
});
$('#sm_reset_budgets').on('click', function () {
const cur = extension_settings[MODULE_NAME];
const budgetKeys = [
'longterm_inject_budget',
'session_inject_budget',
'scene_inject_budget',
'arcs_inject_budget',
'canon_inject_budget',
'profiles_inject_budget',
'relationships_inject_budget',
'epistemic_inject_budget',
'state_ledger_inject_budget',
];
for (const key of budgetKeys) {
cur[key] = defaultSettings[key];
}
// Sync all slider DOM elements to the restored values.
for (const { setting, slider, display, fmt } of TUNABLE_TIERS) {
$(`#${slider}`).val(cur[setting]);
$(`#${display}`).text(fmt(cur[setting]));
}
// Sync the simple-mode total slider.
const total = totalBudgetFromSettings(cur);
$('#sm_total_budget').val(total);
$('#sm_total_budget_value').text(total);
saveSettingsDebounced();
reinjectAfterBudgetChange(ctrl.getSelectedCharacterName());
});
// Apply initial mode on load.
applySettingsMode(s.settings_mode ?? 'simple');
// ---- Group chat character selector ----------------------------------
$('#sm_group_char_select').on('change', async function () {
const selection = $(this).val() || null;
ctrl.selectedGroupCharacter = selection;
updateLongTermUI(ctrl.selectedGroupCharacter);
updateRelationshipHistoryUI(ctrl.selectedGroupCharacter);
updateEpistemicUI(ctrl.selectedGroupCharacter);
updateSessionUI();
updateFreshStartUI(isFreshStart());
updateCanonUI(ctrl.selectedGroupCharacter);
updateProfilesUI(loadProfiles(ctrl.selectedGroupCharacter));
// Re-inject the character-specific slots so updateTokenDisplay reads
// the selected character's content rather than whoever responded last.
// onGroupMemberDrafted will overwrite these again before the next Generate().
await injectMemories(selection);
if (ctrl.selectedGroupCharacter !== selection) return;
await injectSessionMemories();
injectCanon(selection);
injectProfiles(selection);
maybeInjectUnified();
updateTokenDisplay();
autoTuneBudgets(selection);
});
// ---- LLM source -----------------------------------------------------
/**
* Shows or hides the per-source settings sections based on the current source.
* @param {string} source
*/
function updateSourceSections(source) {
$('#sm_ollama_settings').toggle(source === memory_sources.ollama);
$('#sm_openai_compat_settings').toggle(source === memory_sources.openai_compatible);
$('#sm_connection_profile_settings').toggle(source === memory_sources.connection_profile);
}
/**
* Populates the connection profile picker with all profiles saved in the connection manager.
* Shows a placeholder if the connection manager has no profiles or is unavailable.
*/
function populateConnectionProfilePicker() {
const $select = $('#sm_connection_profile_id');
$select.empty();
const profiles = extension_settings?.connectionManager?.profiles ?? [];
// Filter by mode (cc = Chat Completion, tc = Text Completion). This covers all
// sub-types including ollama, koboldcpp, etc. - profile.api holds the sub-type
// string, not the top-level mode, so filtering by api would exclude most profiles.
const compatible = profiles.filter((p) => p.mode === 'cc' || p.mode === 'tc');
if (compatible.length === 0) {
$select.append('<option value="">- no compatible profiles found -</option>');
return;
}
compatible
.slice()
.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''))
.forEach((p) => {
$select.append($('<option>', { value: p.id, text: p.name ?? p.id }));
});
// Restore previously saved selection, or auto-save the first option so the
// setting is never null when profiles are available (the browser auto-selects
// the first option but does not fire a change event, so we save it explicitly).
const saved = extension_settings[MODULE_NAME].connection_profile_id;
if (saved && compatible.some((p) => p.id === saved)) {
$select.val(saved);
} else {
const firstId = compatible[0].id;
$select.val(firstId);
extension_settings[MODULE_NAME].connection_profile_id = firstId;
saveSettingsDebounced();
}
}
/**
* Fetches installed Ollama models and populates the model dropdown.
* On success: shows the select and hides the manual text input.
* On failure: hides the select and reveals the manual text input so users
* who cannot reach Ollama from their browser (e.g. accessing ST remotely
* via a different address) can still type a model name directly.
*/
async function refreshOllamaModels() {
const $select = $('#sm_ollama_model');
const $manual = $('#sm_ollama_model_manual');
const $btn = $('#sm_ollama_refresh');
const prevModel = extension_settings[MODULE_NAME].ollama_model;
$btn.prop('disabled', true);
try {
const models = await fetchOllamaModels();
$select.empty();
if (models.length === 0) {
$select.append('<option value="">No models found</option>');
} else {
models.forEach((name) => {
$select.append($('<option>', { value: name, text: name }));
});
const best = models.includes(prevModel) ? prevModel : models[0];
$select.val(best);
extension_settings[MODULE_NAME].ollama_model = best;
saveSettingsDebounced();
}
// Fetch succeeded - use the dropdown and hide the manual fallback.
$select.show();
$manual.hide();
$btn.show();
} catch (err) {
toastr.error(
`Could not reach Ollama at ${extension_settings[MODULE_NAME].ollama_url || 'http://localhost:11434'}. Is it running?`,
'Smart Memory',
);
console.error('[SmartMemory] Ollama model fetch failed:', err);
// Fetch failed - reveal the manual text input and hide the refresh
// button (it would just fail again until Ollama is reachable).
$select.hide();
$manual.val(prevModel ?? '').show();
$btn.hide();
} finally {
$btn.prop('disabled', false);
}
}
/**
* Fetches installed Ollama models and populates the embedding model dropdown.
* Uses the embedding-specific URL so users can point embeddings at a separate
* Ollama instance. Falls back to the manual text input on failure.
*/
async function refreshEmbeddingModels() {
const $select = $('#sm_embedding_model');
const $manual = $('#sm_embedding_model_manual');
const $btn = $('#sm_embedding_refresh');
const prevModel = extension_settings[MODULE_NAME].embedding_model;
const embeddingUrl = extension_settings[MODULE_NAME].embedding_url || 'http://localhost:11434';
$btn.prop('disabled', true);
try {
const models = await fetchOllamaModels(embeddingUrl);
$select.empty();
if (models.length === 0) {
$select.append('<option value="">No models found</option>');
} else {
models.forEach((name) => {
$select.append($('<option>', { value: name, text: name }));
});