chore: bump version to 0.14.14

This commit is contained in:
thzxx
2026-07-10 21:34:15 +08:00
parent 91a30193a7
commit e5224e4a8d
14 changed files with 218 additions and 103 deletions
+49 -26
View File
@@ -114,12 +114,27 @@ function getOSEnvironment() {
const ALWAYS_PARALLEL = new Set([
'read_file', 'list_directory', 'search_files', 'get_file_info', 'tree',
'web_search', 'browser_screenshot', 'browser_extract', 'browser_evaluate',
'memory_search', 'session_list', 'session_read',
'memory', 'session_list', 'session_read',
'diff_files', 'git',
'datetime', 'calculator',
'random', 'uuid', 'json_format', 'hash',
]);
/** D4: 有副作用的工具 — 同轮次去重时不返回缓存,需实际执行 */
const SIDE_EFFECT_TOOLS = new Set([
'write_file', 'edit_file', 'create_directory', 'delete_file',
'move_file', 'copy_file', 'replace_in_files', 'download_file',
'run_command', 'git', 'compress',
'browser_open', 'browser_click', 'browser_type', 'browser_close',
]);
/** D2/D3: 只读工具白名单 — 允许同参数重复调用(验证场景:写文件后重读、git status、run_command 监控等) */
const RE_READ_ALLOWED = new Set([
'read_file', 'list_directory', 'search_files', 'get_file_info', 'tree',
'web_search', 'git', 'session_list', 'session_read', 'diff_files',
'browser_screenshot', 'browser_extract', 'run_command',
]);
/** P0-2: 检测工具调用之间是否存在路径依赖(写入 → 读取/写入同一路径) */
function hasPathDependency(call: ToolCall, prevBatch: ToolCall[]): boolean {
const callPath = extractWritePath(call);
@@ -412,6 +427,7 @@ const CACHE_TTL_MAP: Record<string, number> = {
session_list: 60_000,
session_read: 60_000,
diff_files: 2 * 60_000,
memory: 10_000, // M2: 记忆搜索 10s 过期(短TTL,避免 add 后搜索过期)
default: 60_000, // 默认 60s,不再永久缓存
};
@@ -557,9 +573,9 @@ function formatToolResultForModel(toolName: string, result: ToolResult): string
}
case 'memory': {
// 去重文字信号(触发 handleObserving 的⛔终止
// D1: 去重信号改为软提醒,不触发⛔强制终止
if ((result as any).duplicate) {
return `⚠️ 重复添加: ${(result as any).message || '相同内容已存在'}\n✅ 记忆操作已全部完成,不要再调用 memory 工具,直接输出最终回答。`;
return JSON.stringify({ success: true, action: 'add', duplicate: true, message: `${(result as any).message || '相同内容已存在'}` });
}
// read_all / search 结果:包裹在 JSON 中以保持与其他工具一致的格式
if ((result as any).action === 'read_all') {
@@ -1494,7 +1510,9 @@ async function handleExecuting(
const hasFailedInPrev = ctx.allToolRecords
.filter(r => ctx.prevLoopSuccessKeys.includes(getToolCacheKey(r.name, r.arguments)))
.some(r => r.status !== 'success');
if (!hasFailedInPrev) {
// D2: 只读工具全部相同时不阻断(如反复 git status、read_file 验证)
const allReadOnly = ctx.toolCalls.every(c => RE_READ_ALLOWED.has(c.function.name));
if (!hasFailedInPrev && !allReadOnly) {
logWarn('检测到连续两轮工具调用完全相同且全部成功,注入提醒而非终止');
// ── 取消工具卡片:卡片已在 THINKING 阶段设为 pending,这里需要收尾 ──
for (const call of ctx.toolCalls) {
@@ -1507,7 +1525,11 @@ async function handleExecuting(
transition(ctx, S.THINKING);
return;
}
logInfo('检测到重复调用但上一轮有失败,允许重试');
if (!hasFailedInPrev && allReadOnly) {
logInfo('跨轮次重复但全部为只读工具,允许执行');
} else {
logInfo('检测到重复调用但上一轮有失败,允许重试');
}
}
// ── 工具并行执行:智能批次划分(P0修复:检测实际数据依赖)──
@@ -1538,13 +1560,18 @@ async function handleExecuting(
const cacheKey = getToolCacheKey(call.function.name, call.function.arguments);
if (isDuplicateCall(call, ctx.toolCalls)) {
logWarn(`跳过重复工具调用: ${call.function.name}`);
const cached = toolResultCache.get(cacheKey);
if (cached) {
return [{
name: call.function.name, arguments: call.function.arguments,
result: cached.result, status: 'success' as const, timestamp: Date.now()
}, null];
// D4: 有副作用的工具不返回缓存,需实际执行(如 write_file、run_command
if (!SIDE_EFFECT_TOOLS.has(call.function.name)) {
logWarn(`跳过重复工具调用: ${call.function.name}`);
const cached = toolResultCache.get(cacheKey);
if (cached) {
return [{
name: call.function.name, arguments: call.function.arguments,
result: cached.result, status: 'success' as const, timestamp: Date.now()
}, null];
}
} else {
logInfo(`有副作用的工具重复调用,实际执行: ${call.function.name}`);
}
}
@@ -1772,9 +1799,8 @@ async function handleObserving(
}
}
// ── 通用重复调用检测:工具结果含去重信号 或 同工具同参数连续成功 2+ 次 ──
const lastToolContents = ctx.messages.filter(m => m.role === 'tool').slice(-3).map(m => m.content || '');
const hasDedupSignal = lastToolContents.some(c => c.includes('⚠️ 重复添加') || c.includes('已跳过') || c.includes('duplicate'));
// ── 通用重复调用检测:同工具同参数连续成功 2+ 次 ──
// D1: 移除 hasDedupSignal 触发路径 — memory duplicate 改为软提醒,不强制终止
const recentSuccess = ctx.allToolRecords.filter(r => r.status === 'success').slice(-2);
// P0 修复:仅当工具名 AND 参数完全相同时才判定为重复(避免读两个不同文件被误杀)
const allSameTool = recentSuccess.length >= 2
@@ -1782,20 +1808,15 @@ async function handleObserving(
&& getToolCacheKey(recentSuccess[0].name, recentSuccess[0].arguments) === getToolCacheKey(recentSuccess[1].name, recentSuccess[1].arguments);
// P0-1 优化:只读工具允许同名同参数重复调用(验证场景:写文件后重读、git status 等)
// 仅当 hasDedupSignal(工具自身报告重复)或写类工具同名同参数重复时才注入⛔
const RE_READ_ALLOWED = new Set([
'read_file', 'list_directory', 'search_files', 'get_file_info', 'tree',
'web_search', 'git', 'session_list', 'session_read', 'diff_files',
'browser_screenshot', 'browser_extract',
]);
// D3: 添加 run_command 到白名单(监控场景:反复执行同命令检查状态变化)
const isReadOnlyRepeat = allSameTool && recentSuccess.length > 0 && RE_READ_ALLOWED.has(recentSuccess[0].name);
if (hasDedupSignal || (allSameTool && !isReadOnlyRepeat)) {
if (allSameTool && !isReadOnlyRepeat) {
ctx.messages.push({
role: 'user',
content: `⛔ 检测到重复的工具调用${hasDedupSignal ? '(系统已跳过重复内容)' : ''}。「${recentSuccess[0]?.name || 'memory'}」操作已经完成,立即输出最终回答,绝对不要再调用任何工具。`,
content: `⛔ 检测到重复的工具调用。「${recentSuccess[0]?.name || 'memory'}」操作已经完成,立即输出最终回答,绝对不要再调用任何工具。`,
});
logInfo(`重复调用检测: ${recentSuccess[0]?.name || 'memory'}${hasDedupSignal ? ' (去重信号)' : ''},注入⛔终止信号`);
logInfo(`重复调用检测: ${recentSuccess[0]?.name},注入⛔终止信号`);
ctx.maxLoops = Math.min(ctx.maxLoops, ctx.loopCount + 1);
// 不要 transition 到 REFLECTING,直接在这里就已经注入了信号,下一轮 THINKING 会看到
} else if (isReadOnlyRepeat) {
@@ -2013,13 +2034,15 @@ async function handleReflecting(
if (!abortController?.signal.aborted) {
const _api = state.get<OllamaAPI>(KEYS.API);
const _model = state.get<string>('_defaultModel', '');
const msgsForMemory = ctx.messages
// A1: 使用完整会话消息而非压缩后的 ctx.messages
const _session = state.get<ChatSession | null>(KEYS.CURRENT_SESSION);
const msgsForMemory = (_session?.messages || ctx.messages)
.filter(m => m.role === 'user' || m.role === 'assistant')
.map(m => ({ role: m.role, content: m.content || '' }));
// 使用 setTimeout 延迟执行,确保 onDone 先触发,用户先看到回复
setTimeout(() => {
import('./memory-service.js').then(({ extractAndSaveMemories }) => {
extractAndSaveMemories(msgsForMemory, _api, _model).catch(() => {});
extractAndSaveMemories(msgsForMemory, _api, _model, abortController?.signal).catch(() => {});
}).catch(() => {});
}, 500);
}
+31 -39
View File
@@ -293,12 +293,16 @@ export function searchMemory(entries: MemoryEntry[], query: string, limit = 0):
const queryWords = queryLower.split(/[\s,,。!?、;:""''()\[\]{}<>`~@#$%^&*+=|\\/.]+/).filter(w => w.length > 1);
// rule 和 preference 类型的记忆全局生效,始终注入
// M5: 限制全局注入数量,避免大量 rule/preference 膨胀搜索结果
const MAX_GLOBAL_INJECT = 10;
const alwaysInclude: MemorySearchResult[] = [];
const scored: MemorySearchResult[] = [];
for (const entry of entries) {
if (entry.type === 'rule' || entry.type === 'preference') {
alwaysInclude.push({ ...entry, score: 100 + entry.importance });
if (alwaysInclude.length < MAX_GLOBAL_INJECT) {
alwaysInclude.push({ ...entry, score: 100 + entry.importance });
}
continue;
}
@@ -529,9 +533,9 @@ export async function addEntry(
* M9: 要求 oldText 至少 5 个字符,减少误匹配 */
export async function replaceEntry(oldText: string, newContent: string): Promise<{ success: boolean; message: string }> {
return withWriteLock(async () => {
// M9: 提高最小匹配长度到 5
if (!oldText || oldText.length < 5) {
return { success: false, message: 'old_text 不能为空且至少 5 个字符(提高精确度)' };
// M4: 提高最小匹配长度到 8,减少误匹配
if (!oldText || oldText.length < 8) {
return { success: false, message: 'old_text 不能为空且至少 8 个字符(提高精确度)' };
}
if (!newContent || newContent.length < 2) {
return { success: false, message: 'new_content 不能为空且至少 2 个字符' };
@@ -575,12 +579,12 @@ export async function replaceEntry(oldText: string, newContent: string): Promise
/** 删除记忆(子串匹配)
* M8: 使用写入锁串行化
* M9: 要求 oldText 至少 5 个字符,减少误匹配 */
* M4: 要求 oldText 至少 8 个字符,减少误匹配 */
export async function removeEntry(oldText: string): Promise<{ success: boolean; message: string }> {
return withWriteLock(async () => {
// M9: 提高最小匹配长度到 5
if (!oldText || oldText.length < 5) {
return { success: false, message: 'old_text 不能为空且至少 5 个字符(提高精确度)' };
// M4: 提高最小匹配长度到 8
if (!oldText || oldText.length < 8) {
return { success: false, message: 'old_text 不能为空且至少 8 个字符(提高精确度)' };
}
const entries = await loadAllEntries();
@@ -830,7 +834,7 @@ ${conversationText.slice(0, 5000)}
1. 仅提取用户**明确陈述**的个人信息(项目名、技术栈、偏好、习惯),禁止推断
2. 必须是**跨会话有用**的长期信息,临时需求不提取
3. 每条内容 ≤40 字,精炼具体
4. importance 7-10,只有真正重要的才给 7+
4. importance 6-10,只有真正重要的才给 6+
5. tags 2-3 个精确关键词
6. 禁止自动提取 rule 类型
@@ -845,11 +849,13 @@ ${conversationText.slice(0, 5000)}
try {
// ── 调用 LLM 提取 ──
// A2: 传递 abortSignal 给 api.chat
const response = await api.chat({
model,
messages: [{ role: 'user', content: extractPrompt }],
think: false,
options: { num_ctx: 8192, temperature: 0.1 }
options: { num_ctx: 8192, temperature: 0.1 },
signal: abortSignal,
});
// 检查中止信号
@@ -866,9 +872,7 @@ ${conversationText.slice(0, 5000)}
JSON.parse(jsonMatch[1] || jsonMatch[0]);
if (!parsed.entries?.length) return 0;
// ── 加载已有记忆用于去重 ──
const existingEntries = await loadAllEntries();
// A7: 去重逻辑已移至 addEntry 内部,无需预先加载已有记忆
let count = 0;
const MAX_PER_EXTRACT = 2;
@@ -887,38 +891,25 @@ ${conversationText.slice(0, 5000)}
continue;
}
// ── 过滤 3: 泛化检测(过于宽泛的表述)──
const genericPatterns = [
/^用户是/, /^用户喜欢/, /^用户正在/, /^用户需要/,
/^用户想要/, /^用户希望/, /^用户使用/, /^用户做/,
];
const isGeneric = genericPatterns.some(p => p.test(entry.content)) && entry.content.length < 15;
// ── 过滤 3: 泛化检测(内容长度 + 关键词组合检测)──
// A5: 不再单纯靠前缀模式,改为结合内容长度和泛化关键词检测
const GENERIC_KEYWORDS = ['喜欢', '正在', '需要', '想要', '希望', '使用', '做', '是', '有'];
const startsWithGeneric = GENERIC_KEYWORDS.some(kw => entry.content.startsWith(kw));
const isGeneric = startsWithGeneric && entry.content.length < 20;
if (isGeneric) {
logDebug('自动记忆过滤: 过于泛化', entry.content);
continue;
}
// ── 过滤 4: importance 门槛(>= 7)──
// ── 过滤 4: importance 门槛(>= 6)──
// A3: 从 7 降到 6,覆盖更多有价值的记忆
const importance = Math.min(10, Math.max(1, entry.importance || 5));
if (importance < 7) {
if (importance < 6) {
logDebug('自动记忆过滤: importance 不足', `${importance}`);
continue;
}
// ── 过滤 5: 去重(规范化后比较)──
const normalizedNew = normalizeForDedup(entry.content);
const isDuplicate = existingEntries.some(e => {
const normalizedExisting = normalizeForDedup(e.content);
const prefixLen = Math.min(30, normalizedNew.length, normalizedExisting.length);
if (prefixLen > 10 && normalizedNew.slice(0, prefixLen) === normalizedExisting.slice(0, prefixLen)) return true;
if (normalizedNew.length < 40 && normalizedExisting.includes(normalizedNew)) return true;
if (normalizedExisting.length < 40 && normalizedNew.includes(normalizedExisting)) return true;
return simpleSimilarity(normalizedExisting, normalizedNew) > 0.6;
});
if (isDuplicate) {
logDebug('自动记忆过滤: 重复', entry.content.slice(0, 40));
continue;
}
// A7: 移除重复去重检查 — addEntry 内部已有完善的去重逻辑,无需重复
// ── 保存 ──
try {
@@ -928,10 +919,6 @@ ${conversationText.slice(0, 5000)}
importance,
(entry.tags || []).slice(0, 3)
);
existingEntries.push({
id: '', type: entry.type as MemoryType, content: entry.content.trim(),
importance, tags: (entry.tags || []).slice(0, 3),
});
count++;
} catch (err) {
logDebug('自动记忆保存失败', (err as Error).message);
@@ -940,6 +927,11 @@ ${conversationText.slice(0, 5000)}
if (count > 0) {
logInfo('🧠 自动记忆提取完成', `从对话中提取了 ${count} 条有价值记忆`);
// A6: 显示 toast 通知用户记忆已自动保存
try {
const { showToast } = await import('../components/toast.js');
showToast(`🧠 已自动保存 ${count} 条记忆`, 'success', 4000);
} catch {}
}
return count;
} catch (err) {
+3 -3
View File
@@ -371,14 +371,14 @@ CRITICAL: For add action, you MUST include both "type" (fact/preference/rule) an
type: 'object',
required: ['action'],
properties: {
action: { type: 'string', enum: ['search', 'add', 'replace', 'remove', 'read_all'], description: 'Which operation to perform.' },
query: { type: 'string', description: '[search] Keywords to search for.' },
action: { type: 'string', enum: ['search', 'add', 'replace', 'remove', 'read_all'], description: 'Which operation to perform. Note: "add" requires "type"+"content", "replace" requires "old_text"+"new_content", "remove" requires "old_text", "search" requires "query".' },
query: { type: 'string', description: '[search REQUIRED] Keywords to search for.' },
limit: { type: 'integer', description: '[search] Max results. Default: 8.' },
type: { type: 'string', enum: ['fact', 'preference', 'rule'], description: '[add REQUIRED] Memory type. fact=user info, preference=user preference, rule=behavior rule.' },
content: { type: 'string', description: '[add REQUIRED, replace] Memory text. Keep it concise (8-100 chars).' },
importance: { type: 'integer', description: '[add] Priority 1-10. Default: 5. Use 8+ for critical info.' },
tags: { type: 'array', items: { type: 'string' }, description: '[add] 2-5 keywords for search matching.' },
old_text: { type: 'string', description: '[replace, remove REQUIRED] Unique substring to identify the entry.' },
old_text: { type: 'string', description: '[replace, remove REQUIRED] Unique substring to identify the entry. Must be ≥8 chars for precision.' },
new_content: { type: 'string', description: '[replace REQUIRED] New text to replace with.' }
}
}