mirror of
https://github.com/Wx-2025/ST-Amily2-Chat-Optimisation.git
synced 2026-06-06 09:15:50 +00:00
进行解耦合功能拆分处理
This commit is contained in:
@@ -56,4 +56,9 @@ if (!window.Amily2Bus) {
|
||||
window.Amily2Bus = new Amily2Bus();
|
||||
}
|
||||
|
||||
export default Amily2Bus;
|
||||
export function initializeAmilyBus() {
|
||||
if (!window.Amily2Bus) {
|
||||
window.Amily2Bus = new Amily2Bus();
|
||||
console.log('[Amily2] Amily2Bus 已成功初始化并附加到 window 对象');
|
||||
}
|
||||
}
|
||||
10
core/bus.js
10
core/bus.js
@@ -1,11 +1,11 @@
|
||||
import { eventSource, event_types } from '/script.js';
|
||||
|
||||
export const LOG_LEVELS = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3,
|
||||
NONE: 99
|
||||
DEBUG: 0b0001,
|
||||
INFO: 0b0010,
|
||||
WARN: 0b0100,
|
||||
ERROR: 0b1000,
|
||||
NONE: 0
|
||||
};
|
||||
|
||||
class FilePipe {
|
||||
|
||||
41
imports.js
Normal file
41
imports.js
Normal file
@@ -0,0 +1,41 @@
|
||||
// Side-effect imports (独立模块/自初始化模块)
|
||||
import "./PresetSettings/index.js";
|
||||
import "./PreOptimizationViewer/index.js";
|
||||
import "./WorldEditor/WorldEditor.js";
|
||||
import './core/amily2-updater.js';
|
||||
import './SL/bus/Amily2Bus.js'
|
||||
|
||||
// Re-exports (重新导出供 index.js 使用)
|
||||
export { createDrawer } from "./ui/drawer.js";
|
||||
export { showPlotOptimizationProgress, updatePlotOptimizationProgress, hidePlotOptimizationProgress } from './ui/optimization-progress.js';
|
||||
export { registerSlashCommands } from "./core/commands.js";
|
||||
export { onMessageReceived, handleTableUpdate } from "./core/events.js";
|
||||
export { processPlotOptimization } from "./core/summarizer.js";
|
||||
|
||||
// External SillyTavern scripts (外部脚本)
|
||||
export { getContext, extension_settings } from "/scripts/extensions.js";
|
||||
export { characters, this_chid, eventSource, event_types, saveSettingsDebounced } from '/script.js';
|
||||
|
||||
// Core Systems
|
||||
export { injectTableData, generateTableContent } from "./core/table-system/injector.js";
|
||||
export { initialize as initializeRagProcessor } from "./core/rag-processor.js";
|
||||
export { loadTables, clearHighlights, rollbackAndRefill, rollbackState, commitPendingDeletions, saveStateToMessage, getMemoryState, clearUpdatedTables } from './core/table-system/manager.js';
|
||||
export { fillWithSecondaryApi } from './core/table-system/secondary-filler.js';
|
||||
export { renderTables } from './ui/table-bindings.js';
|
||||
export { log } from './core/table-system/logger.js';
|
||||
export { checkForUpdates, fetchMessageBoardContent } from './core/api.js';
|
||||
export { setUpdateInfo, applyUpdateIndicator } from './ui/state.js';
|
||||
export { pluginVersion, extensionName, defaultSettings } from './utils/settings.js';
|
||||
export { checkAuthorization, refreshUserInfo } from './utils/auth.js';
|
||||
export { tableSystemDefaultSettings } from './core/table-system/settings.js';
|
||||
export { manageLorebookEntriesForChat } from './core/lore.js';
|
||||
|
||||
// Feature Modules
|
||||
export { initializeCharacterWorldBook } from './CharacterWorldBook/cwb_index.js';
|
||||
export { cwbDefaultSettings } from './CharacterWorldBook/src/cwb_config.js';
|
||||
export { bindGlossaryEvents } from './glossary/GT_bindings.js';
|
||||
export { updateOrInsertTableInChat, startContinuousRendering, stopContinuousRendering } from './ui/message-table-renderer.js';
|
||||
export { initializeRenderer } from './core/tavern-helper/renderer.js';
|
||||
export { initializeApiListener, registerApiHandler, amilyHelper, initializeAmilyHelper } from './core/tavern-helper/main.js';
|
||||
export { registerContextOptimizerMacros, resetContextBuffer } from './core/context-optimizer.js';
|
||||
export { initializeSuperMemory } from './core/super-memory/manager.js';
|
||||
393
index.js
393
index.js
@@ -1,36 +1,33 @@
|
||||
import { createDrawer } from "./ui/drawer.js";
|
||||
import "./PresetSettings/index.js"; // 【预设设置】独立模块
|
||||
import "./PreOptimizationViewer/index.js"; // 【优化前文查看器】独立模块
|
||||
import "./WorldEditor/WorldEditor.js"; // 【世界编辑器】独立模块
|
||||
import { showPlotOptimizationProgress, updatePlotOptimizationProgress, hidePlotOptimizationProgress } from './ui/optimization-progress.js';
|
||||
import { registerSlashCommands } from "./core/commands.js";
|
||||
import { onMessageReceived, handleTableUpdate } from "./core/events.js";
|
||||
import { processPlotOptimization } from "./core/summarizer.js";
|
||||
import { getContext } from "/scripts/extensions.js";
|
||||
import { characters, this_chid } from '/script.js';
|
||||
import { injectTableData, generateTableContent } from "./core/table-system/injector.js";
|
||||
import { initialize as initializeRagProcessor } from "./core/rag-processor.js";
|
||||
import { loadTables, clearHighlights, rollbackAndRefill, rollbackState, commitPendingDeletions, saveStateToMessage, getMemoryState, clearUpdatedTables } from './core/table-system/manager.js';
|
||||
import { fillWithSecondaryApi } from './core/table-system/secondary-filler.js';
|
||||
import { renderTables } from './ui/table-bindings.js';
|
||||
import { log } from './core/table-system/logger.js';
|
||||
import { eventSource, event_types, saveSettingsDebounced } from '/script.js';
|
||||
import { checkForUpdates, fetchMessageBoardContent } from './core/api.js';
|
||||
import { setUpdateInfo, applyUpdateIndicator } from './ui/state.js';
|
||||
import { pluginVersion, extensionName, defaultSettings } from './utils/settings.js';
|
||||
import { checkAuthorization, refreshUserInfo } from './utils/auth.js';
|
||||
import { tableSystemDefaultSettings } from './core/table-system/settings.js';
|
||||
import { extension_settings } from '/scripts/extensions.js';
|
||||
import { manageLorebookEntriesForChat } from './core/lore.js';
|
||||
import { initializeCharacterWorldBook } from './CharacterWorldBook/cwb_index.js';
|
||||
import { cwbDefaultSettings } from './CharacterWorldBook/src/cwb_config.js';
|
||||
import { bindGlossaryEvents } from './glossary/GT_bindings.js';
|
||||
import './core/amily2-updater.js';
|
||||
import { updateOrInsertTableInChat, startContinuousRendering, stopContinuousRendering } from './ui/message-table-renderer.js';
|
||||
import { initializeRenderer } from './core/tavern-helper/renderer.js';
|
||||
import { initializeApiListener, registerApiHandler, amilyHelper, initializeAmilyHelper } from './core/tavern-helper/main.js';
|
||||
import { registerContextOptimizerMacros, resetContextBuffer } from './core/context-optimizer.js';
|
||||
import { initializeSuperMemory } from './core/super-memory/manager.js';
|
||||
import {
|
||||
createDrawer,
|
||||
showPlotOptimizationProgress, updatePlotOptimizationProgress, hidePlotOptimizationProgress,
|
||||
registerSlashCommands,
|
||||
onMessageReceived, handleTableUpdate,
|
||||
processPlotOptimization,
|
||||
getContext, extension_settings,
|
||||
characters, this_chid, eventSource, event_types, saveSettingsDebounced,
|
||||
injectTableData, generateTableContent,
|
||||
initializeRagProcessor,
|
||||
loadTables, clearHighlights, rollbackAndRefill, rollbackState, commitPendingDeletions, saveStateToMessage, getMemoryState, clearUpdatedTables,
|
||||
fillWithSecondaryApi,
|
||||
renderTables,
|
||||
log,
|
||||
checkForUpdates, fetchMessageBoardContent,
|
||||
setUpdateInfo, applyUpdateIndicator,
|
||||
pluginVersion, extensionName, defaultSettings,
|
||||
checkAuthorization, refreshUserInfo,
|
||||
tableSystemDefaultSettings,
|
||||
manageLorebookEntriesForChat,
|
||||
initializeCharacterWorldBook,
|
||||
cwbDefaultSettings,
|
||||
bindGlossaryEvents,
|
||||
updateOrInsertTableInChat, startContinuousRendering, stopContinuousRendering,
|
||||
initializeRenderer,
|
||||
initializeApiListener, registerApiHandler, amilyHelper, initializeAmilyHelper,
|
||||
registerContextOptimizerMacros, resetContextBuffer,
|
||||
initializeSuperMemory
|
||||
} from './imports.js';
|
||||
import { initializeAmilyBus } from './SL/bus/Amily2Bus.js';
|
||||
|
||||
const DOMPURIFY_CDN = "https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.7/purify.min.js";
|
||||
|
||||
@@ -409,99 +406,77 @@ window.addEventListener("error", (event) => {
|
||||
});
|
||||
|
||||
|
||||
jQuery(async () => {
|
||||
console.log("[Amily2号-帝国枢密院] 开始执行开国大典...");
|
||||
let isProcessingPlotOptimization = false;
|
||||
|
||||
// 启动外部库加载 (DOMPurify)
|
||||
/**
|
||||
* 加载必要的外部库(如 DOMPurify)。
|
||||
* 如果加载失败,会回退到内置的简单净化器。
|
||||
*/
|
||||
function loadExternalLibraries() {
|
||||
loadExternalScript(DOMPURIFY_CDN, 'DOMPurify').catch(e => console.warn("[Amily2] DOMPurify 加载失败,将使用内置净化器:", e));
|
||||
}
|
||||
|
||||
// 【V146.2 紧急优化】优先注册上下文优化器,确保它在密折司之前拦截并处理 Prompt
|
||||
/**
|
||||
* 初始化上下文优化器模块。
|
||||
* 优先注册宏,确保其在其他处理之前生效。
|
||||
*/
|
||||
function initializeContextOptimizer() {
|
||||
try {
|
||||
console.log("[Amily2号-开国大典] 步骤0:优先注册上下文优化器...");
|
||||
registerContextOptimizerMacros();
|
||||
} catch (e) {
|
||||
console.error("[Amily2号-开国大典] 上下文优化器注册失败:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 【密折司】延迟加载,确保它排在优化器之后
|
||||
/**
|
||||
* 异步初始化“密折司”模块。
|
||||
* 该模块通常用于处理机密或特殊的后台逻辑。
|
||||
*/
|
||||
async function initializeMiZheSi() {
|
||||
try {
|
||||
await import("./MiZheSi/index.js");
|
||||
console.log("[Amily2号-开国大典] 密折司模块已就位。");
|
||||
} catch (e) {
|
||||
console.error("[Amily2号-开国大典] 密折司加载失败:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册所有与 SillyTavern 交互的 API 处理器。
|
||||
* 包括消息获取、设置、删除,以及 Lorebook 管理等功能。
|
||||
*/
|
||||
function registerAllApiHandlers() {
|
||||
initializeApiListener();
|
||||
|
||||
registerApiHandler('getChatMessages', async (data) => {
|
||||
return amilyHelper.getChatMessages(data.range, data.options);
|
||||
});
|
||||
|
||||
registerApiHandler('setChatMessages', async (data) => {
|
||||
return await amilyHelper.setChatMessages(data.messages, data.options);
|
||||
});
|
||||
|
||||
registerApiHandler('getChatMessages', async (data) => amilyHelper.getChatMessages(data.range, data.options));
|
||||
registerApiHandler('setChatMessages', async (data) => amilyHelper.setChatMessages(data.messages, data.options));
|
||||
registerApiHandler('setChatMessage', async (data) => {
|
||||
const field_values = data.field_values || data.content;
|
||||
const message_id = data.message_id !== undefined ? data.message_id : data.index;
|
||||
const options = data.options || {};
|
||||
|
||||
console.log('[Amily2-API] setChatMessage 收到参数:', { field_values, message_id, options, raw_data: data });
|
||||
|
||||
return await amilyHelper.setChatMessage(field_values, message_id, options);
|
||||
});
|
||||
|
||||
registerApiHandler('createChatMessages', async (data) => {
|
||||
return await amilyHelper.createChatMessages(data.messages, data.options);
|
||||
});
|
||||
|
||||
registerApiHandler('deleteChatMessages', async (data) => {
|
||||
return await amilyHelper.deleteChatMessages(data.ids, data.options);
|
||||
});
|
||||
|
||||
registerApiHandler('getLorebooks', async (data) => {
|
||||
return await amilyHelper.getLorebooks();
|
||||
});
|
||||
|
||||
registerApiHandler('getCharLorebooks', async (data) => {
|
||||
return await amilyHelper.getCharLorebooks(data.options);
|
||||
});
|
||||
|
||||
registerApiHandler('getLorebookEntries', async (data) => {
|
||||
return await amilyHelper.getLorebookEntries(data.bookName);
|
||||
});
|
||||
|
||||
registerApiHandler('setLorebookEntries', async (data) => {
|
||||
return await amilyHelper.setLorebookEntries(data.bookName, data.entries);
|
||||
});
|
||||
|
||||
registerApiHandler('createLorebookEntries', async (data) => {
|
||||
return await amilyHelper.createLorebookEntries(data.bookName, data.entries);
|
||||
});
|
||||
|
||||
registerApiHandler('createLorebook', async (data) => {
|
||||
return await amilyHelper.createLorebook(data.bookName);
|
||||
});
|
||||
|
||||
registerApiHandler('triggerSlash', async (data) => {
|
||||
return await amilyHelper.triggerSlash(data.command);
|
||||
});
|
||||
|
||||
registerApiHandler('getLastMessageId', async (data) => {
|
||||
return amilyHelper.getLastMessageId();
|
||||
});
|
||||
|
||||
registerApiHandler('createChatMessages', async (data) => amilyHelper.createChatMessages(data.messages, data.options));
|
||||
registerApiHandler('deleteChatMessages', async (data) => amilyHelper.deleteChatMessages(data.ids, data.options));
|
||||
registerApiHandler('getLorebooks', async (data) => amilyHelper.getLorebooks());
|
||||
registerApiHandler('getCharLorebooks', async (data) => amilyHelper.getCharLorebooks(data.options));
|
||||
registerApiHandler('getLorebookEntries', async (data) => amilyHelper.getLorebookEntries(data.bookName));
|
||||
registerApiHandler('setLorebookEntries', async (data) => amilyHelper.setLorebookEntries(data.bookName, data.entries));
|
||||
registerApiHandler('createLorebookEntries', async (data) => amilyHelper.createLorebookEntries(data.bookName, data.entries));
|
||||
registerApiHandler('createLorebook', async (data) => amilyHelper.createLorebook(data.bookName));
|
||||
registerApiHandler('triggerSlash', async (data) => amilyHelper.triggerSlash(data.command));
|
||||
registerApiHandler('getLastMessageId', async (data) => amilyHelper.getLastMessageId());
|
||||
registerApiHandler('toastr', async (data) => {
|
||||
if (window.toastr && typeof window.toastr[data.type] === 'function') {
|
||||
window.toastr[data.type](data.message, data.title);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
registerApiHandler('switchSwipe', async (data) => {
|
||||
const { messageIndex, swipeIndex } = data;
|
||||
const messages = await amilyHelper.getChatMessages(messageIndex, { include_swipes: true });
|
||||
|
||||
if (messages && messages.length > 0 && messages[0].swipes) {
|
||||
const content = messages[0].swipes[swipeIndex];
|
||||
if (content !== undefined) {
|
||||
@@ -509,56 +484,39 @@ jQuery(async () => {
|
||||
message_id: messageIndex,
|
||||
message: content
|
||||
}], { refresh: 'affected' });
|
||||
|
||||
const context = getContext();
|
||||
if (context.chat[messageIndex]) {
|
||||
context.chat[messageIndex].swipe_id = swipeIndex;
|
||||
}
|
||||
|
||||
return { success: true, message: `已切换至开场白 ${swipeIndex}` };
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`无法切换到开场白 ${swipeIndex}`);
|
||||
});
|
||||
}
|
||||
|
||||
initializeAmilyHelper();
|
||||
|
||||
console.log("[Amily2号-帝国枢密院] 开始执行开国大典...");
|
||||
|
||||
/**
|
||||
* 合并插件的默认设置与用户设置。
|
||||
* 确保即使在升级后,新增加的设置项也有默认值。
|
||||
*/
|
||||
function mergePluginSettings() {
|
||||
if (!extension_settings[extensionName]) {
|
||||
extension_settings[extensionName] = {};
|
||||
}
|
||||
const combinedDefaultSettings = { ...defaultSettings, ...tableSystemDefaultSettings, ...cwbDefaultSettings, render_on_every_message: false, amily_render_enabled: false };
|
||||
|
||||
for (const key in combinedDefaultSettings) {
|
||||
if (extension_settings[extensionName][key] === undefined) {
|
||||
extension_settings[extensionName][key] = combinedDefaultSettings[key];
|
||||
}
|
||||
}
|
||||
console.log("[Amily2号-帝国枢密院] 帝国基本法已确认,档案室已与国库对接完毕。");
|
||||
}
|
||||
|
||||
let attempts = 0;
|
||||
const maxAttempts = 100;
|
||||
const checkInterval = 100;
|
||||
const targetSelector = "#sys-settings-button";
|
||||
|
||||
const deploymentInterval = setInterval(async () => {
|
||||
if ($(targetSelector).length > 0) {
|
||||
clearInterval(deploymentInterval);
|
||||
console.log("[Amily2号-帝国枢密院] SillyTavern宫殿主体已确认,开国大典正式开始!");
|
||||
|
||||
try {
|
||||
console.log("[Amily2号-开国大典] 步骤一:为宫殿披上华服...");
|
||||
loadPluginStyles();
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤二:皇家仪仗队就位...");
|
||||
await registerSlashCommands();
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤三:开始召唤府邸...");
|
||||
createDrawer();
|
||||
|
||||
function waitForGlossaryPanelAndBindEvents() {
|
||||
/**
|
||||
* 等待术语表面板加载完毕并绑定事件。
|
||||
* 包含重试机制,防止面板尚未渲染导致绑定失败。
|
||||
*/
|
||||
function waitForGlossaryPanelAndBindEvents() {
|
||||
let attempts = 0;
|
||||
const maxAttempts = 50;
|
||||
const interval = 100;
|
||||
@@ -583,10 +541,13 @@ jQuery(async () => {
|
||||
}
|
||||
}
|
||||
}, interval);
|
||||
}
|
||||
waitForGlossaryPanelAndBindEvents();
|
||||
}
|
||||
|
||||
function waitForCwbPanelAndInitialize() {
|
||||
/**
|
||||
* 等待角色世界书面板加载完毕并进行初始化。
|
||||
* 包含重试机制。
|
||||
*/
|
||||
function waitForCwbPanelAndInitialize() {
|
||||
let attempts = 0;
|
||||
const maxAttempts = 50;
|
||||
const interval = 100;
|
||||
@@ -611,23 +572,19 @@ jQuery(async () => {
|
||||
}
|
||||
}
|
||||
}, interval);
|
||||
}
|
||||
|
||||
waitForCwbPanelAndInitialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册用于表格内容的 SillyTavern 宏。
|
||||
* 允许在 Prompt 中使用 {{Amily2EditContent}} 来插入动态生成的表格数据。
|
||||
*/
|
||||
function registerTableMacros() {
|
||||
console.log("[Amily2号-开国大典] 步骤3.8:注册表格占位符宏...");
|
||||
try {
|
||||
// 【V144.0】注册上下文优化器宏 (已移至开国大典步骤0优先执行,此处仅保留重置逻辑)
|
||||
// registerContextOptimizerMacros();
|
||||
|
||||
// 注册生成开始事件以重置缓冲区
|
||||
eventSource.on(event_types.GENERATION_STARTED, () => {
|
||||
resetContextBuffer();
|
||||
|
||||
// 故障恢复:如果生成开始了,说明之前的优化肯定结束了(或者被绕过了),强制重置标志位
|
||||
if (isProcessingPlotOptimization) {
|
||||
console.warn("[Amily2-剧情优化] 检测到生成开始,但优化标志位仍为 true。这可能是并发生成或状态未及时重置。");
|
||||
// 我们不在这里强制重置,因为优化可能正在进行中,我们希望它完成并修改输入框。
|
||||
}
|
||||
});
|
||||
|
||||
@@ -647,32 +604,30 @@ jQuery(async () => {
|
||||
} catch (error) {
|
||||
console.error('[Amily2-核心引擎] 注册表格宏时发生错误:', error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤四:部署帝国哨兵网络...");
|
||||
|
||||
let isProcessingPlotOptimization = false;
|
||||
|
||||
async function onPlotGenerationAfterCommands(type, params, dryRun) {
|
||||
/**
|
||||
* 处理用户发送消息前的逻辑(剧情优化)。
|
||||
* 拦截消息发送,进行剧情梳理和总结,然后注入到 Prompt 中。
|
||||
*
|
||||
* @param {string} type - 触发类型 (例如 'send')
|
||||
* @param {object} params - 参数对象
|
||||
* @param {boolean} dryRun - 是否为试运行
|
||||
* @returns {Promise<boolean>} - 返回 false 以阻止默认行为(如果已异步处理),或不做阻拦。
|
||||
*/
|
||||
async function onPlotGenerationAfterCommands(type, params, dryRun) {
|
||||
clearUpdatedTables();
|
||||
|
||||
// 如果正在处理中,拦截所有其他触发(防止意外的双重触发)
|
||||
if (isProcessingPlotOptimization) {
|
||||
console.log("[Amily2-剧情优化] 优化正在进行中,拦截重复触发。");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[Amily2-剧情优化] Generation after commands triggered", { type, params, dryRun });
|
||||
|
||||
// Skip for regenerations or dry runs
|
||||
if (type === 'regenerate' || dryRun) {
|
||||
console.log("[Amily2-剧情优化] Skipping due to regenerate or dryRun.");
|
||||
return false;
|
||||
}
|
||||
|
||||
const globalSettings = extension_settings[extensionName];
|
||||
if (globalSettings?.plotOpt_enabled === false) {
|
||||
return false;
|
||||
}
|
||||
if (globalSettings?.plotOpt_enabled === false) return false;
|
||||
|
||||
const isJqyhEnabled = globalSettings?.jqyhEnabled === true;
|
||||
const isMainApiConfigured = !!globalSettings?.apiUrl || !!globalSettings?.tavernProfile;
|
||||
@@ -682,7 +637,6 @@ jQuery(async () => {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Determine the message to be processed
|
||||
let userMessage = $('#send_textarea').val();
|
||||
let isFromTextarea = true;
|
||||
const context = getContext();
|
||||
@@ -696,12 +650,8 @@ jQuery(async () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!userMessage) return false;
|
||||
|
||||
if (!userMessage) {
|
||||
return false; // Nothing to process
|
||||
}
|
||||
|
||||
// Set the flag to prevent loops and show progress
|
||||
isProcessingPlotOptimization = true;
|
||||
const cancellationState = { isCancelled: false };
|
||||
showPlotOptimizationProgress(cancellationState);
|
||||
@@ -727,13 +677,10 @@ jQuery(async () => {
|
||||
const optimizationPromise = processPlotOptimization({ mes: userMessage }, slicedContext, cancellationState, onProgress);
|
||||
const result = await Promise.race([optimizationPromise, cancellationPromise]);
|
||||
|
||||
if (cancellationState.isCancelled) {
|
||||
throw new Error("Optimization cancelled by user");
|
||||
}
|
||||
if (cancellationState.isCancelled) throw new Error("Optimization cancelled by user");
|
||||
|
||||
if (result && result.contentToAppend) {
|
||||
const finalMessage = userMessage + '\n' + result.contentToAppend;
|
||||
|
||||
if (params && typeof params === 'object') {
|
||||
try {
|
||||
if (params.prompt) params.prompt = finalMessage;
|
||||
@@ -747,19 +694,15 @@ jQuery(async () => {
|
||||
console.warn("[Amily2-剧情优化] 尝试修改 params 失败:", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (isFromTextarea) {
|
||||
$('#send_textarea').val(finalMessage).trigger('input');
|
||||
} else {
|
||||
const targetMessageId = context.chat.length - 1;
|
||||
await amilyHelper.setChatMessage(finalMessage, targetMessageId, { refresh: 'none' });
|
||||
}
|
||||
|
||||
toastr.success('剧情优化已完成并注入,继续生成...', '操作成功');
|
||||
|
||||
isProcessingPlotOptimization = false;
|
||||
hidePlotOptimizationProgress();
|
||||
|
||||
return false;
|
||||
} else {
|
||||
console.log("[Amily2-剧情优化] Plot optimization returned no result. Sending original message.");
|
||||
@@ -780,7 +723,14 @@ jQuery(async () => {
|
||||
hidePlotOptimizationProgress();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册核心事件监听器。
|
||||
* 包含对消息接收、编辑、删除、滑动等事件的处理,以及剧情优化的触发。
|
||||
*/
|
||||
function registerEventListeners() {
|
||||
console.log("[Amily2号-开国大典] 步骤四:部署帝国哨兵网络...");
|
||||
if (!window.amily2EventsRegistered) {
|
||||
eventSource.on(event_types.GENERATION_AFTER_COMMANDS, onPlotGenerationAfterCommands);
|
||||
eventSource.on(event_types.MESSAGE_RECEIVED, onMessageReceived);
|
||||
@@ -792,20 +742,16 @@ jQuery(async () => {
|
||||
log('【监察系统】检测到消息滑动,但聊天记录不足,已跳过状态回退。', 'info');
|
||||
return;
|
||||
}
|
||||
|
||||
log('【监察系统】检测到消息滑动 (SWIPED),开始执行状态回退...', 'warn');
|
||||
rollbackState();
|
||||
|
||||
const latestMessage = context.chat[chat_id] || context.chat[context.chat.length - 1];
|
||||
if (latestMessage.is_user) {
|
||||
log('【监察系统】滑动后最新消息是用户,跳过填表。', 'info');
|
||||
renderTables();
|
||||
return;
|
||||
}
|
||||
|
||||
const settings = extension_settings[extensionName];
|
||||
const fillingMode = settings.filling_mode || 'main-api';
|
||||
|
||||
if (fillingMode === 'main-api') {
|
||||
log(`【监察系统】主填表模式,回退后强制刷新消息ID: ${chat_id}。`, 'info');
|
||||
await handleTableUpdate(chat_id, true);
|
||||
@@ -815,7 +761,6 @@ jQuery(async () => {
|
||||
} else {
|
||||
log('【监察系统】未配置填表模式,跳过填表。', 'info');
|
||||
}
|
||||
|
||||
renderTables();
|
||||
log('【监察系统】滑动后填表完成,UI 已刷新。', 'success');
|
||||
});
|
||||
@@ -823,11 +768,9 @@ jQuery(async () => {
|
||||
handleTableUpdate(mes_id);
|
||||
updateOrInsertTableInChat();
|
||||
});
|
||||
|
||||
eventSource.on(event_types.CHAT_CHANGED, () => {
|
||||
window.lastPreOptimizationResult = null;
|
||||
document.dispatchEvent(new CustomEvent('preOptimizationTextUpdated'));
|
||||
|
||||
manageLorebookEntriesForChat();
|
||||
setTimeout(() => {
|
||||
log("【监察系统】检测到“朝代更迭”(CHAT_CHANGED),开始重修史书并刷新宫殿...", 'info');
|
||||
@@ -835,7 +778,6 @@ jQuery(async () => {
|
||||
clearUpdatedTables();
|
||||
loadTables();
|
||||
renderTables();
|
||||
|
||||
if (extension_settings[extensionName].render_on_every_message) {
|
||||
startContinuousRendering();
|
||||
} else {
|
||||
@@ -843,40 +785,31 @@ jQuery(async () => {
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
eventSource.on(event_types.MESSAGE_DELETED, (message, index) => {
|
||||
log(`【监察系统】检测到消息 ${index} 被删除,开始精确回滚UI状态。`, 'warn');
|
||||
clearHighlights();
|
||||
loadTables(index);
|
||||
renderTables();
|
||||
});
|
||||
|
||||
eventSource.on(event_types.MESSAGE_RECEIVED, updateOrInsertTableInChat);
|
||||
eventSource.on(event_types.chat_updated, updateOrInsertTableInChat);
|
||||
|
||||
window.amily2EventsRegistered = true;
|
||||
}
|
||||
}
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤五:初始化RAG处理器...");
|
||||
|
||||
try {
|
||||
initializeRagProcessor();
|
||||
console.log('[Amily2-翰林院] RAG处理器已成功初始化');
|
||||
} catch (error) {
|
||||
console.error('[Amily2-翰林院] RAG处理器初始化失败:', error);
|
||||
}
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤六:智能冲突检测与注入策略...");
|
||||
|
||||
async function executeAmily2Injection(...args) {
|
||||
/**
|
||||
* 执行 Amily2 的统一注入逻辑。
|
||||
* 同时兼容表格数据注入和 RAG 上下文重排。
|
||||
* @param {...any} args - 传递给 injectTableData 和 rearrangeChat 的参数
|
||||
*/
|
||||
async function executeAmily2Injection(...args) {
|
||||
console.log('[Amily2-核心引擎] 开始执行统一注入 (聊天长度:', args[0]?.length || 0, ')');
|
||||
|
||||
try {
|
||||
await injectTableData(...args);
|
||||
} catch (error) {
|
||||
console.error('[Amily2-内存储司] 表格注入失败:', error);
|
||||
}
|
||||
|
||||
if (window.hanlinyuanRagProcessor && typeof window.hanlinyuanRagProcessor.rearrangeChat === 'function') {
|
||||
try {
|
||||
console.log('[Amily2-核心引擎] 执行内置RAG注入。');
|
||||
@@ -885,31 +818,45 @@ jQuery(async () => {
|
||||
console.error('[Amily2-翰林院] RAG注入失败:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 RAG 处理器并设置注入策略。
|
||||
* 覆盖 `vectors_rearrangeChat` 以确保 Amily2 的注入逻辑优先执行。
|
||||
*/
|
||||
function initializeRagAndInjection() {
|
||||
console.log("[Amily2号-开国大典] 步骤五:初始化RAG处理器...");
|
||||
try {
|
||||
initializeRagProcessor();
|
||||
console.log('[Amily2-翰林院] RAG处理器已成功初始化');
|
||||
} catch (error) {
|
||||
console.error('[Amily2-翰林院] RAG处理器初始化失败:', error);
|
||||
}
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤六:智能冲突检测与注入策略...");
|
||||
console.log('[Amily2-策略] 采用“完全主导”策略,覆盖 `vectors_rearrangeChat`。');
|
||||
window['vectors_rearrangeChat'] = executeAmily2Injection;
|
||||
|
||||
if (window['amily2HanlinyuanInjector']) {
|
||||
window['amily2HanlinyuanInjector'] = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行部署完成后的后续任务。
|
||||
* 包括:版本检查、在线人数统计、本地联动、超级记忆初始化、渲染器启动和主题应用。
|
||||
*/
|
||||
function performPostDeploymentTasks() {
|
||||
console.log("【Amily2号】帝国秩序已完美建立。Amily2号的府邸已恭候陛下的莅临。");
|
||||
|
||||
if (checkAuthorization()) {
|
||||
const userType = localStorage.getItem("plugin_user_type") || "未知";
|
||||
const userNote = localStorage.getItem("plugin_user_note");
|
||||
|
||||
const displayNote = userNote || userType;
|
||||
toastr.success(`欢迎回来!授权状态有效 (用户: ${displayNote})`, "Amily2 插件已就绪");
|
||||
|
||||
refreshUserInfo().then(data => {
|
||||
if (data && data.note && data.note !== userNote) {
|
||||
console.log("[Amily2] 用户信息已更新:", data.note);
|
||||
}
|
||||
}).catch(e => {
|
||||
console.warn("[Amily2] 后台刷新用户信息失败:", e);
|
||||
});
|
||||
}).catch(e => console.warn("[Amily2] 后台刷新用户信息失败:", e));
|
||||
}
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤七:初始化版本显示系统...");
|
||||
@@ -924,13 +871,10 @@ jQuery(async () => {
|
||||
|
||||
handleUpdateCheck();
|
||||
handleMessageBoard();
|
||||
initializeOnlineTracker(); // 【Amily2号-在线统计】启动在线人数统计
|
||||
initializeLocalLinkage(); // 【Amily2号-本地联动】启动本地联动服务
|
||||
initializeOnlineTracker();
|
||||
initializeLocalLinkage();
|
||||
|
||||
// 【V146.4】自动初始化超级记忆系统
|
||||
setTimeout(() => {
|
||||
initializeSuperMemory();
|
||||
}, 3000); // 延迟3秒以确保 ST 环境完全就绪
|
||||
setTimeout(() => initializeSuperMemory(), 3000);
|
||||
|
||||
initializeRenderer();
|
||||
|
||||
@@ -941,25 +885,70 @@ jQuery(async () => {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
loadAndApplyStyles();
|
||||
|
||||
const importThemeBtn = document.getElementById('amily2-import-theme-btn');
|
||||
const exportThemeBtn = document.getElementById('amily2-export-theme-btn');
|
||||
const resetThemeBtn = document.getElementById('amily2-reset-theme-btn');
|
||||
|
||||
if (importThemeBtn) importThemeBtn.addEventListener('click', importStyles);
|
||||
if (exportThemeBtn) exportThemeBtn.addEventListener('click', exportStyles);
|
||||
if (resetThemeBtn) resetThemeBtn.addEventListener('click', resetToDefaultStyles);
|
||||
|
||||
log('【凤凰阁】内联主题系统已通过延迟加载成功初始化并绑定事件。', 'success');
|
||||
} catch (error) {
|
||||
log(`【凤凰阁】内联主题系统初始化失败: ${error}`, 'error');
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Amily2 核心部署流程(开国大典)。
|
||||
* 只有当 SillyTavern 基础 UI 加载完成后才会执行此函数。
|
||||
* 负责按顺序初始化插件的各个子系统。
|
||||
*/
|
||||
async function runAmily2Deployment() {
|
||||
console.log("[Amily2号-帝国枢密院] SillyTavern宫殿主体已确认,开国大典正式开始!");
|
||||
try {
|
||||
console.log("[Amily2号-开国大典] 步骤一:为宫殿披上华服...");
|
||||
loadPluginStyles();
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤二:皇家仪仗队就位...");
|
||||
await registerSlashCommands();
|
||||
|
||||
console.log("[Amily2号-开国大典] 步骤三:开始召唤府邸...");
|
||||
createDrawer();
|
||||
|
||||
waitForGlossaryPanelAndBindEvents();
|
||||
waitForCwbPanelAndInitialize();
|
||||
registerTableMacros();
|
||||
|
||||
registerEventListeners();
|
||||
initializeRagAndInjection();
|
||||
performPostDeploymentTasks();
|
||||
|
||||
} catch (error) {
|
||||
console.error("!!!【开国大典失败】在执行系列法令时发生严重错误:", error);
|
||||
}
|
||||
}
|
||||
|
||||
jQuery(async () => {
|
||||
console.log("[Amily2号-帝国枢密院] 开始执行开国大典...");
|
||||
|
||||
loadExternalLibraries();
|
||||
initializeContextOptimizer();
|
||||
await initializeMiZheSi();
|
||||
|
||||
registerAllApiHandlers();
|
||||
initializeAmilyHelper();
|
||||
mergePluginSettings();
|
||||
initializeAmilyBus();
|
||||
|
||||
let attempts = 0;
|
||||
const maxAttempts = 100;
|
||||
const checkInterval = 100;
|
||||
const targetSelector = "#sys-settings-button";
|
||||
|
||||
const deploymentInterval = setInterval(async () => {
|
||||
if ($(targetSelector).length > 0) {
|
||||
clearInterval(deploymentInterval);
|
||||
await runAmily2Deployment();
|
||||
} else {
|
||||
attempts++;
|
||||
if (attempts >= maxAttempts) {
|
||||
|
||||
Reference in New Issue
Block a user