import type { LoopEvent, Message, Provider, ToolCallContext } from '../types.js'; import { forceCompact, findTailWithCompleteToolChains } from './compact.js'; import { countMessagesTokens } from './tokenCounter.js'; import type { chat } from '../llm/client.js'; /** Per-run bridge: compact only completed history, preserve the in-flight tool batch. */ export function createConversationOptimizer(options: { history: Message[]; provider: Provider; chat: typeof chat; promptCache?: ToolCallContext['promptCache']; protectedImageUserIds?: () => ReadonlySet; replaceHistory: (messages: Message[]) => void; onCompacted: (event: Extract) => void; hasQueuedInput?: () => boolean; }): NonNullable { let attempted = false; return async (toolCallId, signal) => { if (signal?.aborted) return { ok: false, error: 'aborted' }; if (attempted) return { ok: false, error: '本回合已尝试优化对话,请继续任务,不要重复调用。' }; const { history } = options; const boundary = history.findIndex(message => message.role === 'assistant' && message.tool_calls?.some(call => call.id === toolCallId)); if (boundary < 0) return { ok: false, error: '缺少当前工具调用边界,未修改历史。' }; const prefix = history.slice(0, boundary); const pendingBatch = history[boundary]; const nonSystem = prefix.filter(message => message.role !== 'system'); const tail = findTailWithCompleteToolChains(nonSystem); if (nonSystem.length <= tail.length || countMessagesTokens(prefix) < 2_000) { return { ok: true, content: '无需优化:可压缩历史较少,已保留原上下文。继续当前任务。' }; } attempted = true; try { const compact = await forceCompact(prefix, options.provider, signal, options.chat, options.promptCache, { strict: true, protectedImageUserIds: options.protectedImageUserIds?.() }); if (signal?.aborted) return { ok: false, error: 'aborted' }; if (options.hasQueuedInput?.()) return { ok: false, error: '收到新输入,已取消优化并保留原历史。' }; // A host must not overwrite history changed while awaiting the summary. if (history[boundary] !== pendingBatch || prefix.some((message, index) => history[index] !== message)) { return { ok: false, error: '历史已变化,已放弃优化。' }; } if (compact.after >= compact.before) { return { ok: true, content: '优化没有减少上下文占用,已保留原历史。继续任务,不要重复调用。' }; } options.replaceHistory([...compact.messages, ...history.slice(boundary)]); options.onCompacted({ type: 'compact_done', trigger: 'manual', mode: compact.mode, degraded: false, before: compact.before, after: compact.after, messagesRemoved: compact.messagesRemoved, tokensFreed: compact.tokensFreed, }); return { ok: true, content: `已优化对话:已完成历史的估算 token 从 ${compact.before} 降至 ${compact.after},释放 ${compact.tokensFreed}。近期消息和当前工具调用保留;历史证据保留在本机会话中;顾问评审时会一并展开这些原始记录。本结果不是一手证据。继续未完成任务,无需复述摘要。` }; } catch { return { ok: false, error: signal?.aborted ? 'aborted' : '优化未成功生成有效摘要,原历史保持不变。继续任务,不要重复调用。' }; } }; }