forked from aikohanasaki/SillyTavern-MemoryBooks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautosummary.js
More file actions
278 lines (246 loc) · 13.2 KB
/
Copy pathautosummary.js
File metadata and controls
278 lines (246 loc) · 13.2 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
// Copyright (C) 2024–2026 Aiko Hanasaki
// SPDX-License-Identifier: AGPL-3.0-only
import { extension_settings } from '../../../extensions.js';
import { chat, chat_metadata } from '../../../../script.js';
import { METADATA_KEY } from '../../../world-info.js';
import { getSceneMarkers, saveMetadataForCurrentContext, clearScene } from './sceneManager.js';
import {
clampInt,
getCurrentManualLorebookResolution,
showLorebookSelectionPopup,
} from './utils.js';
import { Popup, POPUP_TYPE, POPUP_RESULT } from '../../../popup.js';
import { isMemoryProcessing } from './index.js';
import { translate } from '../../../i18n.js';
import { validateLorebookRequirement } from './lorebookValidation.js';
let autoSummarySkippedForProcessing = false;
// STMBC-HOOK-PHASE2-P2.4 + PHA-1664: autosummary is NO LONGER blocked when
// Sentinel is on. Per PHA-1656/sync-decisions.md §2.a, upstream autosummary
// runs as usual and its cadence-detected scene markers are exposed to Sentinel
// as an additional upstream signal (read by Sentinel via getSceneMarkers()).
//
// The helper is preserved for mergeability (and any third-party callers that
// may import it), but it is now a permanent no-op returning false. Sentinel's
// own enable state is consulted by Sentinel itself via resolveSentinelEnabled
// from autoSettings.js — autosummary does not make that decision.
function isAutoSummaryBlockedBySentinel() {
return false;
}
let autoSummarySkippedMarkersRef = null;
/**
* i18n helper: translate with Mustache-style {{var}} interpolation
* Use like i18n('KEY', 'Fallback {{var}}', { var: 'value' })
* Internally calls SillyTavern's translate(fallback, key).
*/
function i18n(key, fallback, params) {
const localized = translate(fallback, key);
if (!params) return localized;
return localized.replace(/{{\s*(\w+)\s*}}/g, (m, p1) => {
const v = params[p1];
return v !== undefined && v !== null ? String(v) : '';
});
}
/**
* Validates lorebook for auto-summary with user-friendly prompts
*/
async function validateLorebookForAutoSummary() {
const settings = extension_settings.STMemoryBooks;
const manualMode = !!settings?.moduleSettings?.manualModeEnabled;
if (manualMode) {
// Manual mode - check if a lorebook is already selected
const stmbData = getSceneMarkers() || {};
let lorebookName = getCurrentManualLorebookResolution({ settings, markers: stmbData }).lorebookName;
// If no lorebook is selected, ask user what to do
if (!lorebookName) {
const popupContent = `
<h4 data-i18n="STMemoryBooks_AutoSummaryReadyTitle">Auto-Summary Ready</h4>
<div class="world_entry_form_control">
<p data-i18n="STMemoryBooks_AutoSummaryNoAssignedLorebook">Auto-summary is enabled but there is no assigned lorebook for this chat.</p>
<p data-i18n="STMemoryBooks_AutoSummarySelectOrPostponeQuestion">Would you like to select a lorebook for memory storage, or postpone this auto-summary?</p>
<label for="stmb-postpone-messages" data-i18n="STMemoryBooks_PostponeLabel">Postpone for how many messages?</label>
<select id="stmb-postpone-messages" class="text_pole">
<option value="10" data-i18n="STMemoryBooks_Postpone10">10 messages</option>
<option value="20" data-i18n="STMemoryBooks_Postpone20">20 messages</option>
<option value="30" data-i18n="STMemoryBooks_Postpone30">30 messages</option>
<option value="40" data-i18n="STMemoryBooks_Postpone40">40 messages</option>
<option value="50" data-i18n="STMemoryBooks_Postpone50">50 messages</option>
</select>
</div>
`;
const popup = new Popup(popupContent, POPUP_TYPE.TEXT, '', {
okButton: i18n('STMemoryBooks_Button_SelectLorebook', 'Select Lorebook'),
cancelButton: i18n('STMemoryBooks_Button_Postpone', 'Postpone')
});
const result = await popup.show();
if (result === POPUP_RESULT.AFFIRMATIVE) {
// User wants to select a lorebook
const selectedLorebook = await showLorebookSelectionPopup();
if (selectedLorebook) {
stmbData.manualLorebook = selectedLorebook;
saveMetadataForCurrentContext();
lorebookName = selectedLorebook;
} else {
return { valid: false, error: i18n('STMemoryBooks_Error_NoLorebookSelectedForAutoSummary', 'No lorebook selected for auto-summary.') };
}
} else {
// User wants to postpone
const postponeSelect = popup.dlg.querySelector('#stmb-postpone-messages');
const parsed = parseInt(postponeSelect.value, 10);
const postponeMessages = Number.isFinite(parsed) ? parsed : 10;
const currentMessageCount = chat.length;
// Set postpone flag
stmbData.autoSummaryNextPromptAt = currentMessageCount + postponeMessages;
saveMetadataForCurrentContext();
console.log(i18n('autosummary.log.postponed', 'STMemoryBooks: Auto-summary postponed for {{count}} messages (until message {{until}})', { count: postponeMessages, until: stmbData.autoSummaryNextPromptAt }));
return { valid: false, error: i18n('STMemoryBooks_Info_AutoSummaryPostponed', 'Auto-summary postponed for {{count}} messages.', { count: postponeMessages }) };
}
}
return await validateLorebookRequirement({
createContext: 'auto-summary',
manualMode: true,
retryText: i18n('STMemoryBooks_AutoSummaryRetryAfterSelection', 'After selecting a lorebook, try again.'),
});
}
return await validateLorebookRequirement({
createContext: 'auto-summary',
manualMode: false,
lorebookName: chat_metadata?.[METADATA_KEY] || null,
retryText: i18n('STMemoryBooks_AutoSummaryRetryAfterSelection', 'After selecting a lorebook, try again.'),
});
}
/**
* Check if auto-summary should trigger based on current message count and settings
* @returns {Promise<void>}
*/
async function checkAutoSummaryTrigger() {
try {
const settings = extension_settings.STMemoryBooks;
if (!settings?.moduleSettings?.autoSummaryEnabled) {
return;
}
const stmbData = getSceneMarkers() || {};
const currentMessageCount = chat.length;
const currentLastMessage = currentMessageCount - 1;
const requiredInterval = settings.moduleSettings.autoSummaryInterval;
const rawBuf = settings?.moduleSettings?.autoSummaryBuffer;
const buffer = clampInt(parseInt(rawBuf) || 0, 0, 50);
const requiredTotal = requiredInterval + buffer;
const rawHighestProcessed = stmbData.highestMemoryProcessed;
const hasHighestProcessed =
typeof rawHighestProcessed === 'number' && Number.isFinite(rawHighestProcessed);
// Treat "no baseline" as -1 (none processed yet) so the next range starts at 0.
const highestProcessed = hasHighestProcessed ? rawHighestProcessed : -1;
// Check if memory creation is in progress
if (isMemoryProcessing()) {
autoSummarySkippedForProcessing = true;
autoSummarySkippedMarkersRef = stmbData;
console.log(i18n('autosummary.log.skippedInProgress', 'STMemoryBooks: Auto-summary skipped - memory creation in progress'));
return;
}
// Calculate messages since last memory
let messagesSinceLastMemory;
// Count messages since the last processed memory. With highestProcessed = -1, this becomes currentMessageCount.
messagesSinceLastMemory = currentLastMessage - highestProcessed;
if (!hasHighestProcessed) {
console.log(i18n('autosummary.log.noPrevious', 'STMemoryBooks: No previous memories found - counting from start'));
} else {
console.log(i18n('autosummary.log.sinceLast', 'STMemoryBooks: Messages since last memory ({{highestProcessed}}): {{count}}', { highestProcessed, count: messagesSinceLastMemory }));
}
console.log(i18n('autosummary.log.triggerCheck', 'STMemoryBooks: Auto-summary trigger check: {{count}} >= {{required}}?', { count: messagesSinceLastMemory, required: requiredTotal }));
if (messagesSinceLastMemory < requiredTotal) {
console.log(i18n('autosummary.log.notTriggered', 'STMemoryBooks: Auto-summary not triggered - need {{needed}} more messages', { needed: requiredTotal - messagesSinceLastMemory }));
return;
}
// Check if user has postponed auto-summary
if (stmbData.autoSummaryNextPromptAt && currentMessageCount < stmbData.autoSummaryNextPromptAt) {
console.log(i18n('autosummary.log.postponedUntil', 'STMemoryBooks: Auto-summary postponed until message {{until}}', { until: stmbData.autoSummaryNextPromptAt }));
return; // Still in postpone period
}
// Auto-summary will set new scene markers - no need to clear existing ones
const lorebookValidation = await validateLorebookForAutoSummary();
if (!lorebookValidation.valid) {
console.log(i18n('autosummary.log.blocked', 'STMemoryBooks: Auto-summary blocked - lorebook validation failed: {{error}}', { error: lorebookValidation.error }));
return; // No lorebook available or user cancelled
}
// Clear any postpone flag since we're proceeding with auto-summary
if (stmbData.autoSummaryNextPromptAt) {
delete stmbData.autoSummaryNextPromptAt;
saveMetadataForCurrentContext();
console.log(i18n('autosummary.log.clearedPostpone', 'STMemoryBooks: Cleared auto-summary postpone flag'));
}
// Calculate the scene range for auto-summary (apply buffer to end)
let sceneStart, sceneEnd;
const sceneEndCandidate = currentLastMessage - buffer;
const safeEnd = Math.max(0, sceneEndCandidate);
// Start from the message after the last processed memory (or 0 if none processed yet).
sceneStart = highestProcessed + 1;
sceneEnd = safeEnd;
// Defensive: ensure valid range
if (sceneStart > sceneEnd) {
return;
}
console.log(i18n('autosummary.log.triggered', 'STMemoryBooks: Auto-summary triggered - creating memory for range {{start}}-{{end}}', { start: sceneStart, end: sceneEnd }));
// Set scene markers for the range we want to process
stmbData.sceneStart = sceneStart;
stmbData.sceneEnd = sceneEnd;
saveMetadataForCurrentContext();
// Use the existing memory creation system via slash command
const { executeSlashCommands } = await import('../../../slash-commands.js');
await executeSlashCommands('/creatememory');
} catch (error) {
console.error(i18n('autosummary.log.triggerError', 'STMemoryBooks: Error in auto-summary trigger check:'), error);
}
}
/**
* Handle auto-summary on message received
* @returns {Promise<void>}
*/
export async function handleAutoSummaryMessageReceived() {
try {
// PHA-1664: the previous P2.4 BLOCK was inverted — autosummary runs
// when Sentinel is on so its cadence-detected scene markers become
// upstream signal input for Sentinel (see isAutoSummaryBlockedBySentinel
// and the new sentinelCore signal-merge in sentinelCore.js).
if (extension_settings.STMemoryBooks?.moduleSettings?.autoSummaryEnabled) {
const currentMessageCount = chat.length;
console.log(i18n('autosummary.log.messageReceivedSingle', 'STMemoryBooks: Message received - auto-summary enabled, current count: {{count}}', { count: currentMessageCount }));
await checkAutoSummaryTrigger();
}
} catch (error) {
console.error(i18n('autosummary.log.messageHandlerError', 'STMemoryBooks: Error in auto-summary message received handler:'), error);
}
}
/**
* Retry an auto-summary check that was skipped while memory/job processing was active.
* @returns {Promise<void>}
*/
export async function retryAutoSummaryAfterJobIdle() {
if (!autoSummarySkippedForProcessing) {
return;
}
if (isMemoryProcessing()) {
return;
}
if (autoSummarySkippedMarkersRef && autoSummarySkippedMarkersRef !== getSceneMarkers()) {
autoSummarySkippedForProcessing = false;
autoSummarySkippedMarkersRef = null;
return;
}
autoSummarySkippedForProcessing = false;
autoSummarySkippedMarkersRef = null;
await checkAutoSummaryTrigger();
}
/**
* Clear auto-summary state after successful memory creation
* @returns {void}
*/
export function clearAutoSummaryState() {
// PHA-1664: the previous P2.4 BLOCK was inverted (no longer consults
// isAutoSummaryBlockedBySentinel). clearScene() still runs as before —
// Sentinel reads scene markers separately and is not affected by this
// autosummary-internal cleanup.
if (extension_settings.STMemoryBooks?.moduleSettings?.autoSummaryEnabled) {
// Clear scene markers; baseline is updated upon successful memory creation
clearScene();
}
}