mirror of
https://github.com/Wx-2025/ST-Amily2-Chat-Optimisation.git
synced 2026-06-06 08:05:49 +00:00
### 新功能
- **Function Call 填表**:
- FC 首次请求时对 DeepSeek 系模型自动附加 `thinking: { type: "disabled" }`,避免思考模式与 tool_choice 冲突
- 操作列表为空时在日志面板输出原始响应 JSON,便于区分"AI 判断无需变更"、"格式校验全部不通过"和"JSON 解析失败"三种情况
### 修复
- **剧情优化**:移除剧情优化页面遗留的 Jqyh 直连配置字段(URL / Key / Model),统一走 API 连接配置功能分配槽位
- **表格**:
- 补全 `batch-filling-threshold` 批处理阈值的持久化绑定(页面刷新后不再还原为默认值 30)
- 修复分步填表并发锁与 async/await 时序问题
- 修复外层多余 `try...finally` 导致的插件加载报错
- **Rerank**:
- 修复选择连接配置后报"API Key 未配置"的问题(`apiMode` 现从设置读取而非硬编码 `custom`)
- 补全 `hly-rerank-api-mode` 加载绑定及默认值
- **翰林院 RAG**:补全 `priorityRetrieval.sources` 各来源条目的缺失键,修复设置面板回填 TypeError
- **二次填表**:
- 修复 `secondary-filler.js` 把哈希/重试次数写入非持久化的 `msg.metadata` 字段(ST 标准位是 `msg.extra`),导致刷新后去重与重试计数失效
- 修复扫描深度重复计入 `bufferSize`(`contextLimit + buffer + batch + redundancy` → `contextLimit + batch + redundancy`),避免越过预期窗口
- SWIPED 事件改走扫描路径,不再用 `targetMessage` bypass 强填最末条,`保留缓冲区(bufferSize)` 设置在滑动场景下正确生效(手动"回退重填"按钮仍保留 bypass,意图明确)
- 修复 FC(Function Call)路径下成功填表与"AI 判断无需修改"两种结果均未写回 `amily2_process_hash` 与 `saveChat()` 的问题——之前导致 FC 模式去重完全失效,最旧的未处理楼层会被每次扫描重复发给 AI;现统一回写路径为 `markTargetsProcessed`
- FC 空操作时同步输出原始响应 JSON 到控制台(与批量回填日志面板保持一致),便于区分"无需变更"/"格式校验失败"/"JSON 解析失败"
- 修复 `fillWithSecondaryApi` 入口处过早设置 `secondaryFillerRunning = true`,导致防抖/总开关关闭/聊天过短/非分步模式/系统瘫痪五条早返路径均不解锁的死锁问题(特别是防抖路径——锁住后 setTimeout 回调撞上自己的锁,永久跳过后续触发)。锁的获取已挪到所有早返检查之后、`try` 块之前
- **填表设置面板**:新增"手动解除填表锁"按钮(位于触发延迟下方),用于兜底应急——若仍遇到"分步填表正在进行中,跳过本次触发"反复刷屏,可手动点击释放
- **API 调用层全面支持 AbortController**(`callAI` / `callAIForTools` / `callNccsAI` 及其全部下游 provider):
- 新增 `options.signal` 透传,OpenAI 兼容 / OpenAI(测试) / Google 直连 / ST 后端 / FC 等所有 `fetch` 调用均接受 `AbortSignal`
- `callSillyTavernBackend` 由 `$.ajax` 改写为 `fetch`,以原生支持 signal
- `callSillyTavernPreset` / `callNccsSillyTavernPreset` 通过 `raceAgainstSignal` 兜底,外部不可终止的 `ConnectionManagerRequestService.sendRequest` 也能在 signal 触发时即时返回 AbortError
- 全部 catch 块识别 `AbortError`,rethrow 而不弹错误 toast;FC 重试逻辑识别中断后跳过重试
- **填表设置面板**:在"手动解除填表锁"旁新增"强制中断当前填表"按钮——通过 AbortController 真正掐断 fetch 连接(fetch 立即抛错),结果会被丢弃,不会污染表格 / hash / `saveChat`
419 lines
16 KiB
JavaScript
419 lines
16 KiB
JavaScript
import { extension_settings, getContext } from "/scripts/extensions.js";
|
||
import { characters, this_chid, getRequestHeaders, saveSettingsDebounced, eventSource, event_types } from "/script.js";
|
||
import { extensionName } from "../../utils/settings.js";
|
||
import { amilyHelper } from '../../core/tavern-helper/main.js';
|
||
import { getSlotProfile, providerToApiMode } from './api-resolver.js';
|
||
import { configManager } from '../../utils/config/ConfigManager.js';
|
||
import { detectVendor } from '../../utils/api-vendor.js';
|
||
|
||
let ChatCompletionService = undefined;
|
||
try {
|
||
const module = await import('/scripts/custom-request.js');
|
||
ChatCompletionService = module.ChatCompletionService;
|
||
console.log('[Amily2号-Nccs外交部] 已成功召唤"皇家信使"(ChatCompletionService)。');
|
||
} catch (e) {
|
||
console.warn("[Amily2号-Nccs外交部] 未能召唤“皇家信使”,部分高级功能(如Claw代理)将受限。请考虑更新SillyTavern版本。", e);
|
||
}
|
||
|
||
let nccsCtx = null;
|
||
// 尝试连接总线
|
||
if (window.Amily2Bus) {
|
||
try {
|
||
// 注册 'NccsApi' 身份,获取专属上下文
|
||
nccsCtx = window.Amily2Bus.register('NccsApi');
|
||
|
||
// 【联动】暴露 Nccs 的核心调用能力,允许其他插件通过 query('NccsApi') 借用此通道
|
||
nccsCtx.expose({
|
||
call: callNccsAI,
|
||
getSettings: getNccsApiSettings
|
||
});
|
||
|
||
nccsCtx.log('Init', 'info', 'NccsApi 已连接至 Amily2Bus,网络通道准备就绪。');
|
||
} catch (e) {
|
||
// 如果是热重载导致重复注册,尝试降级获取(注意:严格锁模式下无法获取旧Context,这里仅做日志提示)
|
||
// 在生产环境中,页面刷新会重置 Bus,不会有问题。
|
||
console.warn('[Amily2-Nccs] Bus 注册警告 (可能是热重载):', e);
|
||
}
|
||
} else {
|
||
console.error('[Amily2-Nccs] 严重警告: Amily2Bus 未找到,NccsApi 网络层将无法工作!');
|
||
toastr.error("核心组件 Amily2Bus 丢失,请检查安装。", "Nccs-System");
|
||
}
|
||
|
||
export async function getNccsApiSettings() {
|
||
const s = extension_settings[extensionName] || {};
|
||
|
||
// 优先读取 'nccs' 槽位分配的 Profile(profile 一旦分配即权威,旧 slider 残值不再覆盖)
|
||
const profile = await getSlotProfile('nccs');
|
||
if (profile) {
|
||
return {
|
||
nccsEnabled: true,
|
||
apiMode: providerToApiMode(profile.provider),
|
||
apiUrl: profile.apiUrl,
|
||
apiKey: profile.apiKey ?? '',
|
||
model: profile.model,
|
||
maxTokens: profile.maxTokens ?? 65500,
|
||
temperature: profile.temperature ?? 1.0,
|
||
customParams: profile.customParams ?? {},
|
||
tavernProfile: '',
|
||
useFakeStream: s.nccsFakeStreamEnabled ?? false,
|
||
};
|
||
}
|
||
|
||
// 降级:读旧 extension_settings 字段
|
||
return {
|
||
nccsEnabled: s.nccsEnabled || false,
|
||
apiMode: s.nccsApiMode || 'openai_test',
|
||
apiUrl: s.nccsApiUrl?.trim() || '',
|
||
apiKey: configManager.get('nccsApiKey') || '',
|
||
model: s.nccsModel || '',
|
||
maxTokens: s.nccsMaxTokens ?? 8192,
|
||
temperature: s.nccsTemperature ?? 1,
|
||
customParams: {},
|
||
tavernProfile: s.nccsTavernProfile || '',
|
||
useFakeStream: s.nccsFakeStreamEnabled || false,
|
||
};
|
||
}
|
||
|
||
// =================================================================================================
|
||
// 核心调用入口 (Legacy First Mode)
|
||
// =================================================================================================
|
||
|
||
export async function callNccsAI(messages, options = {}) {
|
||
if (window.AMILY2_SYSTEM_PARALYZED === true) {
|
||
console.error("[Amily2-Nccs制裁] 系统完整性已受损,所有外交活动被无限期中止。");
|
||
return null;
|
||
}
|
||
|
||
const settings = await getNccsApiSettings();
|
||
const finalOptions = {
|
||
...settings,
|
||
signal: options.signal,
|
||
...options
|
||
};
|
||
|
||
// 确保 stream 标志位存在
|
||
finalOptions.stream = finalOptions.useFakeStream ?? false;
|
||
|
||
if (finalOptions.apiMode !== 'sillytavern_preset') {
|
||
if (!finalOptions.apiUrl || !finalOptions.model || !finalOptions.apiKey) {
|
||
console.warn("[Amily2-Nccs外交部] API配置不完整,无法调用AI");
|
||
toastr.error("并发模块(NCCS)未配置 API 连接配置,请前往 API 连接配置面板分配 profile 或填写 NCCS 独立设置。", "Amily2-NCCS 未配置");
|
||
return null;
|
||
}
|
||
} else {
|
||
// [限制] 预设模式暂不支持流式
|
||
if (finalOptions.stream) {
|
||
console.warn("[Amily2-Nccs] 预设模式目前尚不支持流式处理方案,已自动切换为标准模式。");
|
||
toastr.warning("SillyTavern预设模式目前暂不支持流式处理(假流式),已为您切换为标准请求模式。该功能将在后续版本中支持。", "Nccs-外交部");
|
||
finalOptions.stream = false;
|
||
}
|
||
}
|
||
|
||
try {
|
||
let responseContent;
|
||
switch (finalOptions.apiMode) {
|
||
case 'openai_test':
|
||
responseContent = await callNccsOpenAITest(messages, finalOptions);
|
||
break;
|
||
case 'sillytavern_preset':
|
||
responseContent = await callNccsSillyTavernPreset(messages, finalOptions);
|
||
break;
|
||
default:
|
||
console.error(`未支持的 API 模式: ${finalOptions.apiMode}`);
|
||
return null;
|
||
}
|
||
return responseContent;
|
||
} catch (error) {
|
||
if (error?.name === 'AbortError') {
|
||
console.warn('[Amily2-Nccs] API 调用被用户中断。');
|
||
throw error;
|
||
}
|
||
console.error(`[Amily2-Nccs] API 调用失败:`, error);
|
||
toastr.error(`调用失败: ${error.message}`, "Nccs API Error");
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function raceAgainstSignal(promise, signal) {
|
||
if (!signal) return promise;
|
||
if (signal.aborted) {
|
||
const err = new Error('Aborted');
|
||
err.name = 'AbortError';
|
||
return Promise.reject(err);
|
||
}
|
||
return new Promise((resolve, reject) => {
|
||
const onAbort = () => {
|
||
signal.removeEventListener('abort', onAbort);
|
||
const err = new Error('Aborted');
|
||
err.name = 'AbortError';
|
||
reject(err);
|
||
};
|
||
signal.addEventListener('abort', onAbort, { once: true });
|
||
promise.then(
|
||
(v) => { signal.removeEventListener('abort', onAbort); resolve(v); },
|
||
(e) => { signal.removeEventListener('abort', onAbort); reject(e); },
|
||
);
|
||
});
|
||
}
|
||
|
||
async function fetchFakeStream(url, opts, signal) {
|
||
const res = await fetch(url, { ...opts, signal });
|
||
if (!res.ok) throw new Error(`Stream HTTP ${res.status}: ${await res.text()}`);
|
||
|
||
const reader = res.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let fullContent = "";
|
||
let buffer = "";
|
||
|
||
try {
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
|
||
buffer += decoder.decode(value, { stream: true });
|
||
const lines = buffer.split('\n');
|
||
buffer = lines.pop();
|
||
|
||
for (const line of lines) {
|
||
const trimmed = line.trim();
|
||
if (!trimmed || trimmed === 'data: [DONE]') continue;
|
||
if (trimmed.startsWith('data: ')) {
|
||
try {
|
||
const json = JSON.parse(trimmed.substring(6));
|
||
const delta = json.choices?.[0]?.delta?.content;
|
||
if (delta) fullContent += delta;
|
||
} catch (e) {
|
||
console.warn('[NccsApi] SSE Parse Error:', e);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} finally {
|
||
reader.releaseLock();
|
||
}
|
||
|
||
if (!fullContent && buffer) {
|
||
try {
|
||
const data = JSON.parse(buffer);
|
||
return data.choices?.[0]?.message?.content || data.content || buffer;
|
||
} catch { return buffer; }
|
||
}
|
||
return fullContent;
|
||
}
|
||
|
||
// =================================================================================================
|
||
// Legacy Implementations
|
||
// =================================================================================================
|
||
|
||
function normalizeApiResponse(responseData) {
|
||
let data = responseData;
|
||
if (typeof data === 'string') {
|
||
try { data = JSON.parse(data); } catch (e) { return data; }
|
||
}
|
||
if (data?.choices?.[0]?.message?.content) return data.choices[0].message.content.trim();
|
||
if (data?.content) return data.content.trim();
|
||
return typeof data === 'object' ? JSON.stringify(data) : data;
|
||
}
|
||
|
||
async function callNccsOpenAITest(messages, options) {
|
||
const isGoogleApi = (await detectVendor(options.apiUrl)) === 'google';
|
||
const body = {
|
||
top_p: options.top_p || 1,
|
||
...(options.customParams || {}),
|
||
chat_completion_source: 'openai',
|
||
messages: messages,
|
||
model: options.model,
|
||
reverse_proxy: options.apiUrl,
|
||
proxy_password: options.apiKey,
|
||
stream: !!options.stream,
|
||
max_tokens: 8192,
|
||
temperature: 1,
|
||
};
|
||
|
||
if (!isGoogleApi) {
|
||
Object.assign(body, {
|
||
custom_prompt_post_processing: 'strict',
|
||
presence_penalty: 0.12,
|
||
});
|
||
}
|
||
|
||
const fetchOpts = {
|
||
method: 'POST',
|
||
headers: { ...getRequestHeaders(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(body)
|
||
};
|
||
|
||
if (options.stream) {
|
||
return await fetchFakeStream('/api/backends/chat-completions/generate', fetchOpts, options.signal);
|
||
}
|
||
|
||
const response = await fetch('/api/backends/chat-completions/generate', { ...fetchOpts, signal: options.signal });
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
|
||
return normalizeApiResponse(await response.json());
|
||
}
|
||
|
||
async function callNccsSillyTavernPreset(messages, options) {
|
||
const context = getContext();
|
||
if (!context) throw new Error('SillyTavern context unavailable');
|
||
|
||
const profileId = options.tavernProfile;
|
||
if (!profileId) throw new Error('No profile ID configured');
|
||
|
||
const originalProfile = await amilyHelper.triggerSlash('/profile');
|
||
const targetProfile = context.extensionSettings?.connectionManager?.profiles?.find(p => p.id === profileId);
|
||
|
||
if (!targetProfile) throw new Error(`Profile ${profileId} not found`);
|
||
|
||
try {
|
||
if (originalProfile !== targetProfile.name) {
|
||
await amilyHelper.triggerSlash(`/profile await=true "${targetProfile.name.replace(/"/g, '\\"')}"`);
|
||
}
|
||
|
||
if (!context.ConnectionManagerRequestService) throw new Error('ConnectionManagerRequestService unavailable');
|
||
|
||
const sendPromise = context.ConnectionManagerRequestService.sendRequest(
|
||
targetProfile.id,
|
||
messages,
|
||
8192,
|
||
options.customParams || {}
|
||
);
|
||
|
||
const result = await raceAgainstSignal(sendPromise, options.signal);
|
||
return normalizeApiResponse(result);
|
||
|
||
} finally {
|
||
// Restore profile
|
||
const current = await amilyHelper.triggerSlash('/profile');
|
||
if (originalProfile && originalProfile !== current) {
|
||
await amilyHelper.triggerSlash(`/profile await=true "${originalProfile.replace(/"/g, '\\"')}"`);
|
||
}
|
||
}
|
||
}
|
||
export async function fetchNccsModels() {
|
||
console.log('[Amily2号-Nccs外交部] 开始获取模型列表');
|
||
|
||
const apiSettings = await getNccsApiSettings();
|
||
|
||
try {
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
// SillyTavern预设模式:获取当前预设的模型
|
||
const context = getContext();
|
||
if (!context?.extensionSettings?.connectionManager?.profiles) {
|
||
throw new Error('无法获取SillyTavern配置文件列表');
|
||
}
|
||
|
||
const targetProfile = context.extensionSettings.connectionManager.profiles.find(p => p.id === apiSettings.tavernProfile);
|
||
if (!targetProfile) {
|
||
throw new Error(`未找到配置文件ID: ${apiSettings.tavernProfile}`);
|
||
}
|
||
|
||
const models = [];
|
||
if (targetProfile.openai_model) {
|
||
models.push({ id: targetProfile.openai_model, name: targetProfile.openai_model });
|
||
}
|
||
|
||
if (models.length === 0) {
|
||
throw new Error('当前预设未配置模型');
|
||
}
|
||
|
||
console.log('[Amily2号-Nccs外交部] SillyTavern预设模式获取到模型:', models);
|
||
return models;
|
||
} else {
|
||
if (!apiSettings.apiUrl || !apiSettings.apiKey) {
|
||
throw new Error('API URL或Key未配置');
|
||
}
|
||
|
||
const response = await fetch('/api/backends/chat-completions/status', {
|
||
method: 'POST',
|
||
headers: {
|
||
...getRequestHeaders(),
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
reverse_proxy: apiSettings.apiUrl,
|
||
proxy_password: apiSettings.apiKey,
|
||
chat_completion_source: 'openai'
|
||
})
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||
}
|
||
|
||
const rawData = await response.json();
|
||
const models = Array.isArray(rawData) ? rawData : (rawData.data || rawData.models || []);
|
||
|
||
if (!Array.isArray(models)) {
|
||
const errorMessage = rawData.error?.message || 'API未返回有效的模型列表数组';
|
||
throw new Error(errorMessage);
|
||
}
|
||
|
||
const formattedModels = models
|
||
.map(m => {
|
||
// 从name字段中提取模型名称,去掉"models/"前缀
|
||
const modelIdRaw = m.name || m.id || m.model || m;
|
||
const modelName = String(modelIdRaw).replace(/^models\//, '');
|
||
return {
|
||
id: modelName,
|
||
name: modelName
|
||
};
|
||
})
|
||
.filter(m => m.id)
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
||
|
||
console.log('[Amily2号-Nccs外交部] 全兼容模式获取到模型:', formattedModels);
|
||
return formattedModels;
|
||
}
|
||
} catch (error) {
|
||
console.error('[Amily2号-Nccs外交部] 获取模型列表失败:', error);
|
||
toastr.error(`获取模型列表失败: ${error.message}`, 'Nccs API');
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
export async function testNccsApiConnection() {
|
||
console.log('[Amily2号-Nccs外交部] 开始API连接测试');
|
||
|
||
const apiSettings = await getNccsApiSettings();
|
||
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
if (!apiSettings.tavernProfile) {
|
||
toastr.error('未配置SillyTavern预设ID', 'Nccs API连接测试失败');
|
||
return false;
|
||
}
|
||
} else {
|
||
if (!apiSettings.apiUrl || !apiSettings.apiKey || !apiSettings.model) {
|
||
toastr.error('API配置不完整,请检查URL、Key和模型', 'Nccs API连接测试失败');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
try {
|
||
toastr.info('正在发送测试消息"你好!"...', 'Nccs API连接测试');
|
||
|
||
const userName = window.SillyTavern.getContext?.()?.name1 || '用户';
|
||
const systemPrompt = `接下来用户会使用测试按钮测试api连接是否正常,请回复ta连接是正常的,称呼用户为:“${userName}大人”,并复述群号1060183271,告知ta,本扩展开发者:“诗与酒.”正静待ta的入驻。`;
|
||
|
||
const testMessages = [
|
||
{ role: 'system', content: systemPrompt },
|
||
{ role: 'user', content: '你好!' }
|
||
];
|
||
|
||
const response = await callNccsAI(testMessages);
|
||
|
||
if (response && response.trim()) {
|
||
console.log('[Amily2号-Nccs外交部] 测试消息响应:', response);
|
||
const formattedResponse = response.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
|
||
toastr.success(`连接测试成功!AI回复: "${formattedResponse}"`, 'Nccs API连接测试成功', { "escapeHtml": false });
|
||
return true;
|
||
} else {
|
||
throw new Error('API未返回有效响应');
|
||
}
|
||
|
||
} catch (error) {
|
||
console.error('[Amily2号-Nccs外交部] 连接测试失败:', error);
|
||
toastr.error(`连接测试失败: ${error.message}`, 'Nccs API连接测试失败');
|
||
return false;
|
||
}
|
||
}
|