-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
6556 lines (5423 loc) · 247 KB
/
Copy pathindex.js
File metadata and controls
6556 lines (5423 loc) · 247 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
// Context Truncator with Summarization
// Based on Qvink Memory by Qvink, simplified and adapted for context truncation
import {
getStringHash,
debounce,
trimToEndSentence,
} from '../../../utils.js';
import {
animation_duration,
scrollChatToBottom,
saveSettingsDebounced,
getMaxContextSize,
streamingProcessor,
amount_gen,
extension_prompt_roles,
extension_prompt_types,
chat_metadata,
generateRaw,
} from '../../../../script.js';
import {
getContext,
extension_settings,
saveMetadataDebounced
} from '../../../extensions.js';
import { itemizedPrompts } from '../../../../scripts/itemized-prompts.js';
export { MODULE_NAME };
// Module constants
const MODULE_NAME = 'context_truncator';
const MODULE_NAME_FANCY = 'CacheGuard';
// Default settings
const default_settings = {
// ==================== TRUNCATION SETTINGS ====================
enabled: true,
target_context_size: 8000, // Target size in tokens
batch_size: 20, // Messages per batch
min_messages_to_keep: 10, // Safety limit
// Auto-calibration settings
auto_calibrate_target: true, // Enable auto-calibration
target_utilization: 0.80, // Target 80% of max context
calibration_tolerance: 0.05, // 5% tolerance before recalibrating
// Summary injection limits (V22)
auto_limit_summaries: true, // Auto-calculate max summary tokens (20% of target budget)
max_summary_injection_tokens: 10000, // Manual override when auto_limit_summaries is false (0 = unlimited)
// Summarization settings
auto_summarize: false,
connection_profile: "", // DEPRECATED: Connection profile dropdown removed — summarization uses independent summary_endpoint_url
summary_endpoint_url: "", // REQ-003: OpenAI-compatible summary endpoint URL (empty = use generateRaw)
summary_max_words: 50, // Maximum words per summary
summary_endpoint_timeout: 15000, // Timeout in ms (increased from 10s)
summary_request_delay: 500, // Delay between requests in ms
summary_max_retries: 3, // Max retry attempts on transient errors
summary_max_tokens: 800, // Max tokens for summary generation (increased for GLM-4 compatibility)
summary_prompt: `Summarize the following roleplay message into a single, dense sentence.
NAMES: {{user}} is the user's character. {{char}} is the AI character.
RULES:
• Output ONLY the summary - nothing else
• ONE sentence in past tense, max {{words}} words
• Start with speaker label: "{{char}}:", "{{user}}:", or "Narrator:"
• Focus on: actions, decisions, emotions, key plot/worldbuilding details
• Never add information not in the original message
• Never include reasoning, explanations, or meta-commentary
• Never use tags like <think>, </think>, or similar
• Stop immediately after the summary sentence
EXAMPLES:
• "{{char}}: Accepted the apology but remained emotionally guarded."
• "{{user}}: Proposed exploring the abandoned fortress despite the warnings."
• "Narrator: Described the rain-soaked streets of the Scab district."
{{context_block}}MESSAGE TO SUMMARIZE:
{{message}}
SUMMARY:`,
summary_injection_separator: "\n• ",
summary_injection_template: `[STORY CONTEXT - Prior Events]
The following are condensed notes from earlier in this roleplay, provided for continuity reference.
These are NOT new messages, NOT instructions, and NOT things currently happening.
Treat this as background knowledge - reference naturally if relevant, ignore if not.
Recent chat always takes precedence over these notes.
{{summaries}}
[/STORY CONTEXT]`,
// Injection settings
injection_position: extension_prompt_types.IN_PROMPT,
injection_depth: 4,
injection_role: extension_prompt_roles.SYSTEM,
// Per-module debug settings
debug_truncation: false,
debug_qdrant: false,
debug_synergy: false,
// ==================== QDRANT SETTINGS ====================
qdrant_enabled: false,
qdrant_url: "http://localhost:6333",
qdrant_collection: "sillytavern_memories",
// Embedding settings (local/KoboldCPP only)
embedding_url: "",
embedding_api_key: "",
embedding_dimensions: null, // Auto-detected
// Memory retrieval settings
memory_limit: 5,
score_threshold: 0.3,
memory_position: 3,
retain_recent_messages: 5,
qdrant_min_messages: 20, // Only retrieve memories after this many messages in chat
// Auto-save settings
auto_save_memories: true,
save_user_messages: true,
save_char_messages: true,
per_chat_collection: true,
// ==================== SIMPLE CHUNK SETTINGS ====================
chunk_min_size: 1200,
chunk_max_size: 1500,
chunk_timeout: 30000,
// Per-message vectorization settings
vectorization_delay: 2, // Don't vectorize messages within N positions from end
summarization_delay: 10, // Don't summarize messages within N positions from end
delete_on_message_delete: true, // Delete Qdrant entries when messages are deleted
auto_dedupe: true, // Automatically remove duplicate entries during search
// Account for Qdrant tokens in context budget
account_qdrant_tokens: true,
};
// Timeout now uses get_settings('summary_endpoint_timeout') dynamically
// Global state
let TRUNCATION_INDEX = null; // Current truncation position
// Estimation mode flag - true when char-based fallback is used instead of tokenizer
let USING_ESTIMATION_MODE = false;
// Popout state
let POPOUT_VISIBLE = false;
let POPOUT_LOCKED = false;
let $POPOUT = null;
let $DRAWER_CONTENT = null;
// Indexing state (for Qdrant)
let INDEXING_ACTIVE = false;
let INDEXING_STOPPED = false;
let INDEXING_ABORT_CONTROLLER = null;
// Calibration state machine
// States: WAITING -> INITIAL_TRAINING -> CALIBRATING -> RETRAINING -> STABLE
let CALIBRATION_STATE = 'WAITING';
let GENERATION_COUNT = 0; // Generations in current phase
let STABLE_COUNT = 0; // Consecutive stable generations
let LAST_CORRECTION_FACTOR = 1.0; // Previous factor for convergence detection
let RETRAIN_COUNT = 0; // Generations in retraining phase
let LAST_STABLE_CHAT_LENGTH = 0; // Chat length when entering STABLE state
// V33: Cache last valid raw prompt for fallback during intercept
let CACHED_RAW_PROMPT = null;
let CACHED_RAW_PROMPT_CHAT_LENGTH = 0;
const TRAINING_GENERATIONS = 2; // Generations needed to train correction factor (reduced from 3)
const STABLE_THRESHOLD = 5; // Consecutive stable gens to reach STABLE state
// Qdrant token averaging for variance handling
let QDRANT_TOKEN_HISTORY = []; // Rolling history of Qdrant injection tokens
const QDRANT_HISTORY_SIZE = 5; // Number of samples to average
// Summary injection tracking (V22)
let DROPPED_SUMMARY_COUNT = 0; // Summaries dropped due to token cap
// Debug summary tracking (V33)
let DEBUG_SEGMENT_COUNT = 0;
let DEBUG_MAP_HITS = 0;
let DEBUG_MAP_MISSES = 0;
// Vector Statistics State (V11)
let VECTOR_STATS = {
// Connection health
connected: false,
lastConnectionError: null,
// Collection stats (cached, refresh on demand)
collectionName: null,
totalPoints: 0,
chunkPoints: 0,
singlePoints: 0,
// Last retrieval stats
retrievedCount: 0,
scores: [], // Array of scores for distribution chart
avgScore: 0,
minScore: 0,
maxScore: 0,
duplicatesRemoved: 0,
// Buffer stats
bufferMessageCount: 0,
// Last update timestamps
lastCollectionCheck: 0,
lastRetrieval: 0
};
// Message change resilience (deletion/edit tracking)
let LAST_CHAT_LENGTH = 0; // Track chat length to detect deletions
let LAST_CHAT_HASHES = new Map(); // Map of message index -> content hash for edit detection
// V29: Pre-snapshot state for deletion detection (fixes race condition)
let PRE_SNAPSHOT_CHAT_LENGTH = 0;
let PRE_SNAPSHOT_CHAT_HASHES = new Map();
// Utility functions
function log(...args) {
console.log(`[${MODULE_NAME_FANCY}]`, ...args);
}
// V13: Timestamp normalization for consistent temporal filtering
function normalizeTimestamp(date) {
// Already a valid millisecond timestamp
if (typeof date === 'number' && date > 1000000000000) {
return date;
}
// Timestamp in seconds - convert to milliseconds
if (typeof date === 'number' && date > 1000000000 && date < 1000000000000) {
return date * 1000;
}
// Date object
if (date instanceof Date) {
const timestamp = date.getTime();
if (!isNaN(timestamp)) {
return timestamp;
}
}
// String date - try to parse it
if (typeof date === 'string' && date.trim()) {
const parsed = new Date(date);
const timestamp = parsed.getTime();
if (!isNaN(timestamp)) {
return timestamp;
}
}
// Fallback to current time
debug_qdrant('Could not normalize timestamp, using current time. Input:', date);
return Date.now();
}
// Module-specific debug functions
function debug_trunc(...args) {
if (get_settings('debug_truncation')) {
console.log(`[${MODULE_NAME_FANCY}][Truncation]`, ...args);
}
}
function debug_qdrant(...args) {
if (get_settings('debug_qdrant')) {
console.log(`[${MODULE_NAME_FANCY}][Qdrant]`, ...args);
}
}
// Consolidated generation summary for simplified debug output
function log_generation_summary(data) {
if (!get_settings('debug_truncation')) return;
const {
chatLength = 0,
oldIndex = 0,
newIndex = 0,
actualTokens = 0,
targetTokens = 0,
factor = 1.0,
state = 'UNKNOWN',
stableCount = 0,
stableThreshold = 5,
segmentCount = 0,
mapHits = 0,
mapMisses = 0,
summaryCount = 0,
summaryTokens = 0,
droppedCount = 0,
estimationMode = false
} = data;
const mode = estimationMode ? 'Estimation (large chat)' : 'Tokenizer';
const indexChange = oldIndex === newIndex ? `${newIndex} (unchanged)` : `${oldIndex}→${newIndex}`;
const tokenDiff = actualTokens - targetTokens;
const tokenStatus = tokenDiff > 0 ? `${tokenDiff} over` : `${Math.abs(tokenDiff)} under`;
const stateStr = state === 'STABLE' ? `${state} ✓` : `${state} (${stableCount}/${stableThreshold})`;
console.log(`[${MODULE_NAME_FANCY}][Truncation] === Generation Summary ===`);
console.log(` Mode: ${mode} | Chat: ${chatLength} msgs | Index: ${indexChange}`);
console.log(` Tokens: ${actualTokens} actual → ${targetTokens} target (${tokenStatus})`);
console.log(` Factor: ${factor.toFixed(3)} | State: ${stateStr}`);
console.log(` Segments: ${segmentCount} matched | Map: ${mapHits} hits, ${mapMisses} misses`);
console.log(` Summaries: ${summaryCount} injected (${summaryTokens} tokens) | Dropped: ${droppedCount}`);
}
// Legacy debug function - routes to truncation debug for backward compatibility
function debug(...args) {
if (get_settings('debug_truncation') || get_settings('debug_qdrant') || get_settings('debug_synergy')) {
console.log(`[${MODULE_NAME_FANCY}][DEBUG]`, ...args);
}
}
function error(...args) {
console.error(`[${MODULE_NAME_FANCY}]`, ...args);
toastr.error(Array.from(arguments).join(' '), MODULE_NAME_FANCY);
}
// Settings management
function initialize_settings() {
if (!extension_settings[MODULE_NAME]) {
log('Initializing settings...');
extension_settings[MODULE_NAME] = structuredClone(default_settings);
}
}
function get_settings(key) {
return extension_settings[MODULE_NAME]?.[key] ?? default_settings[key];
}
function set_settings(key, value) {
extension_settings[MODULE_NAME][key] = value;
saveSettingsDebounced();
}
// Token counting with fallback for large inputs
// SillyTavern's tokenizer returns 0 for inputs > ~200K chars
const TOKENIZER_CHAR_LIMIT = 150000; // Conservative limit
function count_tokens(text, padding = 0) {
if (!text) return padding;
const ctx = getContext();
const textLen = text.length;
// For small inputs, use tokenizer directly
if (textLen <= TOKENIZER_CHAR_LIMIT) {
const result = ctx.getTokenCount(text, padding);
// Clear estimation flag when tokenizer works
USING_ESTIMATION_MODE = false;
return result;
}
// For large inputs, use character-based estimate
// Average ratio is ~4 chars per token for English text
USING_ESTIMATION_MODE = true; // SET FLAG
const estimate = Math.floor(textLen / 4) + padding;
debug_trunc(`[TOKENIZER] Estimation mode: ${textLen} chars → ${estimate} tokens (4 chars/token)`);
return estimate;
}
// Connection profile helpers removed — summarization now uses an independent OpenAI-compatible endpoint (ct_summary_endpoint_url)
// Message data management (stores summaries and flags on messages)
function set_data(message, key, value) {
if (message?.extra?.[MODULE_NAME]?.[key] === value) return;
if (!message.extra) {
message.extra = {};
}
if (!message.extra[MODULE_NAME]) {
message.extra[MODULE_NAME] = {};
}
message.extra[MODULE_NAME][key] = value;
// Also save on current swipe
let swipe_index = message.swipe_id;
if (swipe_index && message.swipe_info?.[swipe_index]) {
if (!message.swipe_info[swipe_index].extra) {
message.swipe_info[swipe_index].extra = {};
}
message.swipe_info[swipe_index].extra[MODULE_NAME] = structuredClone(message.extra[MODULE_NAME]);
}
}
function get_data(message, key) {
return message?.extra?.[MODULE_NAME]?.[key];
}
function get_memory(message) {
return get_data(message, 'memory') ?? "";
}
// Previous prompt detection
function normalize_raw_prompt(raw_prompt) {
if (Array.isArray(raw_prompt)) {
return raw_prompt.map(x => x.content).join('\n');
}
return raw_prompt;
}
function get_last_prompt_raw() {
const ctx = getContext();
const last_index = ctx.chat.length - 1;
let raw_prompt = undefined;
for (let i = itemizedPrompts.length - 1; i >= 0; i--) {
let itemized_prompt = itemizedPrompts[i];
if (itemized_prompt.mesId === last_index) {
raw_prompt = itemized_prompt.rawPrompt;
break;
}
}
if (raw_prompt === undefined) {
return undefined;
}
return normalize_raw_prompt(raw_prompt);
}
function get_previous_prompt_size() {
let raw_prompt = get_last_prompt_raw();
if (!raw_prompt) {
debug('No previous prompt found');
return 0;
}
const size = count_tokens(raw_prompt);
debug(`Previous prompt size: ${size} tokens`);
return size;
}
// Parse raw prompt into chat segments with token counts
function get_prompt_chat_segments_from_raw(raw_prompt) {
if (!raw_prompt) {
debug(' get_prompt_chat_segments_from_raw: No raw prompt');
return null;
}
// Try ChatML format first: <|im_start|>role
const chatml_regex = /<\|im_start\|>(user|assistant|system)\n/g;
let matches = [];
let match;
// Check for ChatML format
while ((match = chatml_regex.exec(raw_prompt)) !== null) {
matches.push({
index: match.index,
role: match[1],
format: 'chatml'
});
}
// If no ChatML, try Llama 3 format
if (matches.length === 0) {
const llama3_regex = /<\|eot_id\|><\|start_header_id\|>(user|assistant|system)<\|end_header_id\|>/g;
while ((match = llama3_regex.exec(raw_prompt)) !== null) {
matches.push({
index: match.index,
role: match[1],
format: 'llama3'
});
}
}
debug(` get_prompt_chat_segments_from_raw: Found ${matches.length} header matches (format: ${matches[0]?.format || 'none'})`);
if (matches.length === 0) {
debug(' get_prompt_chat_segments_from_raw: No headers found, not Llama 3 or ChatML format');
return null;
}
let segments = [];
for (let i = 0; i < matches.length; i++) {
let current = matches[i];
let next = matches[i + 1];
// Only count user and assistant messages (skip system)
if (current.role !== 'user' && current.role !== 'assistant') {
continue;
}
let end_index;
if (current.format === 'chatml') {
// ChatML ends with <|im_end|>
const endMarker = raw_prompt.indexOf('<|im_end|>', current.index);
end_index = endMarker !== -1 ? endMarker + 10 : (next ? next.index : raw_prompt.length);
} else {
// Llama 3 ends at next header or end of prompt
end_index = next ? next.index : raw_prompt.length;
}
let segment = raw_prompt.slice(current.index, end_index);
segments.push({
role: current.role,
tokenCount: count_tokens(segment),
});
}
return segments;
}
// Build a map of message index to actual token count in prompt
function get_prompt_message_tokens_from_raw(raw_prompt, chat) {
let segments = get_prompt_chat_segments_from_raw(raw_prompt);
if (!segments) {
debug(' get_prompt_message_tokens_from_raw: No segments found');
return null;
}
debug(` get_prompt_message_tokens_from_raw: Found ${segments.length} segments`);
let map = new Map();
let segment_index = 0;
// V32 FIX: Start from truncation index (first kept message) instead of 0
// After truncation, only the LAST N messages are in the prompt, not all messages
const startIndex = TRUNCATION_INDEX || 0;
// Check if all segments are the same role (completion/roleplay mode)
const allSameRole = segments.length > 0 && segments.every(s => s.role === segments[0].role);
if (allSameRole && segments.length > 1) {
// Sequential mapping: map segments to non-system chat messages in order
let segmentIdx = 0;
for (let chatIdx = startIndex; chatIdx < chat.length && segmentIdx < segments.length; chatIdx++) {
const msg = chat[chatIdx];
if (msg.is_system) continue; // Skip system messages
map.set(chatIdx, segments[segmentIdx].tokenCount);
segmentIdx++;
}
return map;
}
// Match segments to chat messages
for (let i = startIndex; i < chat.length && segment_index < segments.length; i++) {
let message = chat[i];
// Skip system messages
if (message.is_system) {
continue;
}
let expected_role = message.is_user ? 'user' : 'assistant';
// Find next matching segment
while (segment_index < segments.length && segments[segment_index].role !== expected_role) {
segment_index += 1;
}
if (segment_index >= segments.length) {
break;
}
map.set(i, segments[segment_index].tokenCount);
segment_index += 1;
}
debug(` get_prompt_message_tokens_from_raw: Built map with ${map.size} entries (starting from index ${startIndex})`);
return map;
}
// Truncation index management
function load_truncation_index() {
debug(`Loading truncation index from metadata`);
if (chat_metadata?.[MODULE_NAME]?.truncation_index !== undefined) {
TRUNCATION_INDEX = chat_metadata[MODULE_NAME].truncation_index;
debug(`Loaded truncation index: ${TRUNCATION_INDEX}`);
} else {
// V34 BUG-002 FIX: Debug logging to verify no saved index exists
debug(`No truncation index found in metadata`);
debug(` chat_metadata exists: ${!!chat_metadata}`);
debug(` MODULE_NAME exists in metadata: ${!!chat_metadata?.[MODULE_NAME]}`);
}
// Also load correction factor if saved (Fix 4.2: Preserve correction factor across chat switches)
if (chat_metadata?.[MODULE_NAME]?.correction_factor !== undefined) {
CHAT_TOKEN_CORRECTION_FACTOR = chat_metadata[MODULE_NAME].correction_factor;
debug(`Loaded correction factor: ${CHAT_TOKEN_CORRECTION_FACTOR.toFixed(3)}`);
}
// Load calibration state for persistence across chat switches
if (chat_metadata?.[MODULE_NAME]?.calibration_state !== undefined) {
CALIBRATION_STATE = chat_metadata[MODULE_NAME].calibration_state;
GENERATION_COUNT = chat_metadata[MODULE_NAME].generation_count || 0;
STABLE_COUNT = chat_metadata[MODULE_NAME].stable_count || 0;
RETRAIN_COUNT = chat_metadata[MODULE_NAME].retrain_count || 0;
QDRANT_TOKEN_HISTORY = chat_metadata[MODULE_NAME].qdrant_token_history || [];
LAST_STABLE_CHAT_LENGTH = chat_metadata[MODULE_NAME].last_stable_chat_length || 0;
// V33 FIX: If loaded state is STABLE but LAST_STABLE_CHAT_LENGTH is 0 (legacy chat),
// initialize it to current chat length to prevent constant recalculation
if (CALIBRATION_STATE === 'STABLE' && LAST_STABLE_CHAT_LENGTH === 0) {
const currentChatLength = getContext().chat?.length || 0;
LAST_STABLE_CHAT_LENGTH = currentChatLength;
debug(`Fixed legacy STABLE state: initialized LAST_STABLE_CHAT_LENGTH to ${currentChatLength}`);
}
debug(`Loaded calibration state: ${CALIBRATION_STATE}, stable: ${STABLE_COUNT}/${STABLE_THRESHOLD}`);
} else {
// V32 FIX: If correction_factor was loaded but calibration_state wasn't,
// this is an older chat that learned a factor before state was persisted.
// Set to CALIBRATING instead of WAITING to preserve the learned factor.
const hasLearnedFactor = CHAT_TOKEN_CORRECTION_FACTOR !== 1.0;
if (hasLearnedFactor) {
CALIBRATION_STATE = 'CALIBRATING';
GENERATION_COUNT = 0;
STABLE_COUNT = 3; // Assume some stability since factor was learned
debug(`No calibration state but has learned factor (${CHAT_TOKEN_CORRECTION_FACTOR.toFixed(3)}), starting in CALIBRATING`);
} else {
CALIBRATION_STATE = 'WAITING';
GENERATION_COUNT = 0;
STABLE_COUNT = 0;
debug(`No calibration state found, reset to WAITING`);
}
RETRAIN_COUNT = 0;
QDRANT_TOKEN_HISTORY = [];
}
}
function save_truncation_index() {
if (!chat_metadata[MODULE_NAME]) {
chat_metadata[MODULE_NAME] = {};
}
chat_metadata[MODULE_NAME].truncation_index = TRUNCATION_INDEX;
chat_metadata[MODULE_NAME].target_size = get_settings('target_context_size');
chat_metadata[MODULE_NAME].correction_factor = CHAT_TOKEN_CORRECTION_FACTOR;
// Save calibration state for persistence across chat switches
chat_metadata[MODULE_NAME].calibration_state = CALIBRATION_STATE;
chat_metadata[MODULE_NAME].generation_count = GENERATION_COUNT;
chat_metadata[MODULE_NAME].stable_count = STABLE_COUNT;
chat_metadata[MODULE_NAME].retrain_count = RETRAIN_COUNT;
chat_metadata[MODULE_NAME].qdrant_token_history = QDRANT_TOKEN_HISTORY;
chat_metadata[MODULE_NAME].last_stable_chat_length = LAST_STABLE_CHAT_LENGTH;
debug(`Saved truncation index: ${TRUNCATION_INDEX}, correction factor: ${CHAT_TOKEN_CORRECTION_FACTOR.toFixed(3)}, state: ${CALIBRATION_STATE}`);
saveMetadataDebounced();
}
function reset_truncation_index() {
debug('Resetting truncation index');
TRUNCATION_INDEX = null;
// NOTE: We intentionally do NOT reset CHAT_TOKEN_CORRECTION_FACTOR here
// The correction factor is learned over time and should persist across
// target size changes to maintain calibration stability
save_truncation_index();
}
// ==================== MESSAGE CHANGE RESILIENCE ====================
// Compute a hash for message content (for edit detection)
function compute_message_hash(message) {
if (!message || !message.mes) return null;
return getStringHash(message.mes);
}
// Take a snapshot of current chat state for change detection
function snapshot_chat_state() {
const ctx = getContext();
const chat = ctx.chat;
// V29 FIX: Preserve pre-snapshot state for deletion detection (fixes race condition)
PRE_SNAPSHOT_CHAT_LENGTH = LAST_CHAT_LENGTH;
PRE_SNAPSHOT_CHAT_HASHES = new Map(LAST_CHAT_HASHES);
if (!chat) {
LAST_CHAT_LENGTH = 0;
LAST_CHAT_HASHES.clear();
return;
}
LAST_CHAT_LENGTH = chat.length;
LAST_CHAT_HASHES.clear();
for (let i = 0; i < chat.length; i++) {
const hash = compute_message_hash(chat[i]);
if (hash) {
LAST_CHAT_HASHES.set(i, hash);
}
}
debug_trunc(`Snapshot taken: ${chat.length} messages, ${LAST_CHAT_HASHES.size} hashes`);
}
// Handle message deletion with smart truncation adjustment
function handle_message_deleted() {
const ctx = getContext();
const chat = ctx.chat;
const currentLength = chat ? chat.length : 0;
// BUG-002 FIX: Use LAST_CHAT_LENGTH (stable snapshot before this event)
const deletedCount = LAST_CHAT_LENGTH - currentLength;
if (deletedCount <= 0) {
// No deletion detected or chat grew
LAST_CHAT_LENGTH = currentLength;
return;
}
debug_trunc(`═══ MESSAGE DELETION DETECTED ═══`);
debug_trunc(` Deleted: ${deletedCount} message(s)`);
debug_trunc(` Previous length: ${LAST_CHAT_LENGTH}, Current: ${currentLength}`);
// Determine deletion location relative to truncation index
let deletionsBeforeTruncation = 0;
let deletionsAfterTruncation = 0;
if (TRUNCATION_INDEX !== null && TRUNCATION_INDEX > 0) {
// V29 FIX: Detect where deletions occurred using PRE_SNAPSHOT hash (before CHAT_CHANGED)
const oldHash = PRE_SNAPSHOT_CHAT_HASHES.get(TRUNCATION_INDEX);
const newMessage = chat[TRUNCATION_INDEX];
const newHash = newMessage ? compute_message_hash(newMessage) : null;
if (TRUNCATION_INDEX >= currentLength) {
// Truncation index is beyond current chat = deletions were before/at it
deletionsBeforeTruncation = deletedCount;
TRUNCATION_INDEX = Math.max(0, currentLength - 1);
debug_trunc(` Truncation index adjusted to ${TRUNCATION_INDEX} (beyond chat)`);
} else if (oldHash && newHash && oldHash !== newHash) {
// Message at truncation point changed = deletion was before it
deletionsBeforeTruncation = deletedCount;
TRUNCATION_INDEX = Math.max(0, TRUNCATION_INDEX - deletedCount);
debug_trunc(` Truncation index adjusted to ${TRUNCATION_INDEX} (hash mismatch)`);
} else {
// Hash at truncation point is same = deletions were after it
deletionsAfterTruncation = deletedCount;
debug_trunc(` Deletions were after truncation point - no index adjustment`);
}
} else {
// No truncation yet, all deletions are "after" (in recent context)
deletionsAfterTruncation = deletedCount;
}
debug_trunc(` Deletions before truncation: ${deletionsBeforeTruncation}`);
debug_trunc(` Deletions after truncation: ${deletionsAfterTruncation}`);
// Save updated truncation index
save_truncation_index();
// Update snapshot
snapshot_chat_state();
// Refresh memory
refresh_memory();
// Update chat length tracking (FIX: ensure this always runs)
LAST_CHAT_LENGTH = currentLength;
debug_trunc(`═══════════════════════════════`);
}
// Detect message edits by comparing hashes
function detect_message_edits() {
const ctx = getContext();
const chat = ctx.chat;
if (!chat) return;
let editCount = 0;
for (let i = 0; i < Math.min(chat.length, LAST_CHAT_LENGTH); i++) {
const oldHash = LAST_CHAT_HASHES.get(i);
const newHash = compute_message_hash(chat[i]);
if (oldHash && newHash && oldHash !== newHash) {
editCount++;
debug_trunc(`Edit detected at message ${i}`);
// Mark summary as stale if message was lagging (excluded from context)
const message = chat[i];
if (get_data(message, 'lagging') && get_memory(message)) {
set_data(message, 'needs_summary', true);
debug_trunc(`Marked message ${i} for re-summarization`);
}
}
}
if (editCount > 0) {
debug_trunc(`Total edits detected: ${editCount}`);
}
// Update snapshot after detection
snapshot_chat_state();
}
function should_recalculate_truncation() {
// Recalculate if target size changed
const savedTargetSize = chat_metadata?.[MODULE_NAME]?.target_size;
const currentTargetSize = get_settings('target_context_size');
if (savedTargetSize !== undefined && savedTargetSize !== currentTargetSize) {
debug(`Target size changed from ${savedTargetSize} to ${currentTargetSize}, forcing recalculation`);
return true;
}
// V35 FIX: Remove correction factor change detection here
// The factor is loaded in load_truncation_index() which is called before this,
// so comparing against the module-level variable is correct now.
// But we should NOT trigger recalculation just because factor changed -
// factor changes are continuous and expected during calibration.
// Only target size changes should force full recalculation.
return false;
}
// Calculate truncation index based on target context size
// Based on MessageSummarize's get_injection_threshold() token-based calculation
function calculate_truncation_index() {
const ctx = getContext();
const chat = ctx.chat;
let targetSize = get_settings('target_context_size');
const batchSize = get_settings('batch_size');
const minKeep = get_settings('min_messages_to_keep');
const maxContext = getMaxContextSize();
// V33: Defensive cap - never exceed 90% of max context regardless of settings
const maxSafeContext = Math.floor(maxContext * 0.90);
if (targetSize > maxSafeContext) {
debug_trunc(`Target ${targetSize} exceeds safe limit, capping to ${maxSafeContext}`);
targetSize = maxSafeContext;
}
// SYNERGY: Account for Qdrant tokens in target size
if (get_settings('qdrant_enabled') && get_settings('account_qdrant_tokens')) {
const qdrantTokens = get_qdrant_injection_tokens();
if (qdrantTokens > 0) {
targetSize = targetSize - qdrantTokens;
}
}
// Use current context size from intercept
const currentPromptSize = CURRENT_CONTEXT_SIZE;
if (currentPromptSize === 0) {
debug_trunc('No context size available, cannot calculate truncation');
debug_trunc(`═══ TRUNCATION CALCULATION END (no data) ═══`);
return 0;
}
// Check if we're under target
if (currentPromptSize <= targetSize) {
// If no truncation is currently active, return 0
if (!TRUNCATION_INDEX || TRUNCATION_INDEX === 0) {
debug_trunc('Under target with no active truncation, returning 0');
return 0;
}
// We're under target but have truncation - we should try to REDUCE it
// to include more messages and better utilize the context budget
debug_trunc(`Under target (${currentPromptSize} <= ${targetSize}) but truncation active (${TRUNCATION_INDEX})`);
debug_trunc('Will attempt to reduce truncation to include more messages...');
// Fall through to the rest of the function which will try to optimize
}
// Get the current truncation index (or start at 0)
let currentIndex = TRUNCATION_INDEX || 0;
let maxIndex = Math.max(chat.length - minKeep, 0);
// V32 FIX: Also limit to keeping at least 10% of messages (never truncate more than 90%)
// This prevents pathological cases where correction factor collapse causes massive over-truncation
const percentageMinKeep = Math.floor(chat.length * 0.10);
maxIndex = Math.min(maxIndex, chat.length - percentageMinKeep);
debug_trunc(` Max index (with 10% floor): ${maxIndex} (keeps at least ${percentageMinKeep} messages)`);
let nextIndex = Math.min(currentIndex, maxIndex);
// Calculate separator size for summaries
const sepSize = calculate_injection_separator_size();
// Prompt header tokens (for estimating message sizes in prompt)
const PROMPT_HEADER_USER = '<|eot_id|><|start_header_id|>user<|end_header_id|>';
const PROMPT_HEADER_ASSISTANT = '<|eot_id|><|start_header_id|>assistant<|end_header_id|>';
const promptHeaderTokens = {
user: count_tokens(PROMPT_HEADER_USER),
assistant: count_tokens(PROMPT_HEADER_ASSISTANT),
};
// Build message token map from last prompt for accurate estimation
let last_raw_prompt = get_last_prompt_raw();
// V33: Fallback to cached raw prompt if unavailable but chat length matches
if (!last_raw_prompt) {
const currentChatLength = getContext().chat?.length || 0;
if (CACHED_RAW_PROMPT && CACHED_RAW_PROMPT_CHAT_LENGTH === currentChatLength) {
last_raw_prompt = CACHED_RAW_PROMPT;
debug_trunc(`Using cached raw prompt for fallback (${last_raw_prompt.length} chars, chat length: ${currentChatLength})`);
} else {
debug_trunc(`No cached prompt or chat length mismatch (${CACHED_RAW_PROMPT_CHAT_LENGTH} vs ${currentChatLength})`);
}
}
let message_token_map = get_prompt_message_tokens_from_raw(last_raw_prompt, chat);
// Calculate non-chat budget from the current raw prompt
// Both total and chat tokens must come from the SAME prompt for accuracy
let totalPromptTokens;
let promptChatTokens = 0;
let nonChatBudget;
if (!last_raw_prompt) {
// V33: Use learned ratio from previous generations (more accurate than fixed 40%)
nonChatBudget = Math.floor(currentPromptSize * LAST_KNOWN_NON_CHAT_RATIO);
debug_trunc(` No raw prompt available - using ${LAST_KNOWN_NON_CHAT_RATIO * 100}% learned ratio`);
debug_trunc(` Non-chat budget (estimated): ${nonChatBudget} tokens`);
} else {
// Have raw prompt - calculate accurately
totalPromptTokens = count_tokens(last_raw_prompt);
let segments = get_prompt_chat_segments_from_raw(last_raw_prompt);
if (segments && segments.length > 0) {
promptChatTokens = segments.reduce((sum, seg) => sum + seg.tokenCount, 0);
DEBUG_SEGMENT_COUNT = segments.length;
}
// V35 FIX: Do NOT apply correction factor to non-chat budget
// Non-chat (system prompt, etc.) is measured directly from raw prompt and is accurate
// Only CHAT token estimates need correction (they're calculated, not measured)
const rawNonChatBudget = Math.max(totalPromptTokens - promptChatTokens, 0);
nonChatBudget = rawNonChatBudget; // Use raw value directly
}
// Track token map usage
let map_hits = 0;
let map_misses = 0;
// Function to estimate message tokens in prompt
function estimateMessagePromptTokens(message, index) {
// Try to use actual token count from map first
if (message_token_map) {
let mapped = message_token_map.get(index);
if (mapped !== undefined) {
map_hits++;
DEBUG_MAP_HITS++;
return mapped;
}
}
// Fall back to estimation
map_misses++;
DEBUG_MAP_MISSES++;
const roleHeaderTokens = message.is_user ? promptHeaderTokens.user : promptHeaderTokens.assistant;
return count_tokens(message.mes) + roleHeaderTokens;
}
// Function to estimate total chat size with given truncation index
function estimateChatSize(startIndex) {
let total = 0;
for (let i = 0; i < chat.length; i++) {
const message = chat[i];
// Skip system messages
if (message.is_system) continue;
// Messages before startIndex are excluded (lagging)
// Messages at or after startIndex are kept in full
const lagging = i < startIndex;
if (!lagging) {
// Kept message - use full token count
// V32 FIX: Token map values are already accurate from prompt parsing
// Only apply correction factor to fallback estimates (map misses)
const mapValue = message_token_map ? message_token_map.get(i) : undefined;
if (mapValue !== undefined) {
total += mapValue; // Token map values are already accurate
} else {
// Fall back to estimation with correction factor
const rawEstimate = estimateMessagePromptTokens(message, i);
total += Math.floor(rawEstimate * CHAT_TOKEN_CORRECTION_FACTOR);
}
continue;
}
// V33 FIX: Do NOT add summary tokens for lagging messages!
// Summaries are injected via setExtensionPrompt() and counted in nonChatBudget.
// Adding them here caused double-counting and ~35% over-estimation.