/** * ============================================================ * src/context/microCompactLite.ts —— 工具结果微压缩(v4) * ------------------------------------------------------------ * 对齐 kakadeai 的 microCompact 设计,纯规则实现,零 LLM 调用。 * * 核心思路: * 工具执行结果在写入 history 前经过一道"单向检查门", * 用规则压缩冗余内容,减少 token 消耗但不丢失关键信息。 * * 对齐 kakadeai 的三条有效路径(本实现对高价值工具更保守): * Path A: Cached MC → 本方案用 SHA-1 进程缓存 + 计数淘汰实现 * Path B: Time-based MC → 本方案用轮次衰减实现 * Path C: 批量回收 → reclaimOldToolResults:低风险工具结果数超阈值时, * 只保留最近几条的完整内容,其余按模式处理: * - inline(默认,全 provider 可用):本地 history 原地替换为占位符。 * wire token 真实减少,代价是前缀缓存从被改消息起失效。 * - cacheEdits(v4,Anthropic 格式 + provider.cacheEdits 开启):本地 * history **不改**,删除目标记入 CacheEditsState,由 anthropicFormat * 组装 cache_edits block 随请求发送——对齐 kakadeai Cached MC 的 * triggerThreshold/keepRecent 语义与服务端原地删除效果:模型看到 * 的上下文变短、前缀缓存完整保留。 * * kakadeai 已删除 Legacy LLM path → 本方案不实现 LLM 压缩 * * 为什么需要 Path C:SHA-1 去重要求内容完全相同才计数, * 而真实工具结果带行号/时间戳/文件内容,几乎不会完全重复——去重路径 * 形同虚设,工具结果实际全部永久留在 history 里。这是 minimal-agent * 上下文膨胀比 kakadeai 快得多的根因(工具结果 token 占比 60-80%)。 * ============================================================ */ import { createHash, randomUUID } from 'node:crypto'; import type { CacheEditsState, ToolResultPolicy } from '../types.js'; import { countTextTokens } from './tokenCounter.js'; import { clearToolResultArchive } from './toolResultArchive.js'; import { safeSlice } from '../utils/safeText.js'; // ==================== 配置常量 ==================== /** 同一内容最多原样保留多少次,之后用压缩引用替代 */ const MAX_REPEAT_COUNT = 3; /** 触发截断的字符数阈值(仅白名单内的工具) */ const MAX_RESULT_SIZE = 4000; /** 截断时保留的头部字符数 */ const HEAD_KEEP_CHARS = 2000; /** 截断时保留的尾部字符数 */ const TAIL_KEEP_CHARS = 1000; /** 时间衰减:条目首次出现后超过多少轮自动清理 */ const MAX_KEEP_ROUNDS = 10; /** 短内容阈值:不超过此长度的内容直接放行(不做任何处理) */ const SHORT_CONTENT_THRESHOLD = 200; /** Path C 批量回收:可回收工具结果的存活数量超过该值时触发回收 */ const RECLAIM_TRIGGER_THRESHOLD = 8; /** Path C 批量回收:触发后保留最近多少条完整内容(热尾部) */ const RECLAIM_KEEP_RECENT = 4; /** * Path C 批量回收的占位符前缀。用 startsWith 检测已回收的消息, * 保证幂等(不会重复计数、重复替换)。刻意与去重标记 `[↑ `、 * 截断标记 `[... 省略了` 不同字形,避免互相误判。 */ const RECLAIM_MARKER_PREFIX = '[旧工具结果已回收'; // ==================== 类型定义 ==================== interface CacheEntry { /** 出现次数 */ count: number; /** 首次出现的工具名(用于生成压缩提示) */ firstToolName: string; /** 首次出现的轮次号(用于时间衰减判断) */ firstSeenTurn: number; } // ==================== Session 级状态 ==================== /** * 微压缩的运行时状态。模块级 defaultState 用于单进程场景(TUI / print), * 多并发场景(HTTP server per-request)调 createMicroCompactState() 拿独立一份。 */ export interface MicroCompactState { turn: number; cache: Map; /** Path C 批量回收累计:已回收的结果条数 */ reclaimedCount: number; /** * Path C 批量回收累计:被替换掉的上下文字符数(观测用)。 * 口径 = 回收时 history 里实际占着的字符数(可能已被 Rule 3 截断过), * 不含占位符自身 ~60 字符的成本——精确净节省 ≈ reclaimedChars − 60 × reclaimedCount。 */ reclaimedChars: number; /** 每个会话独立的工具结果归档命名空间。 */ archiveKey: string; /** * cacheEdits 模式的运行时状态(inline 模式下恒为空对象,不参与任何逻辑)。 * 生命周期:同一会话持续累积;autoCompact / clearCache 时随 resetCacheEdits 清空。 */ cacheEdits: CacheEditsState; } function createEmptyCacheEdits(): CacheEditsState { return { deletedToolIds: new Set(), pinned: [], pendingNew: [], activeDeletedTokens: 0 }; } export function createMicroCompactState(): MicroCompactState { return { turn: 0, cache: new Map(), reclaimedCount: 0, reclaimedChars: 0, archiveKey: randomUUID(), cacheEdits: createEmptyCacheEdits(), }; } const defaultState: MicroCompactState = createMicroCompactState(); export function incrementTurn(state: MicroCompactState = defaultState): void { state.turn++; } export function resetTurn(state: MicroCompactState = defaultState): void { state.turn = 0; } /** 缓存统计信息 */ export interface MicroCompactStats { totalEntries: number; repeatedCount: number; compressedCount: number; expiredCount: number; truncatedCount: number; totalCharsSaved: number; /** Path C 批量回收累计条数 */ reclaimedCount: number; /** Path C 批量回收累计:被替换掉的上下文字符数(口径见 MicroCompactState 同名字段) */ reclaimedChars: number; } /** 获取当前缓存统计 */ export function getCacheStats(state: MicroCompactState = defaultState): MicroCompactStats { let compressedCount = 0; let expiredCount = 0; let truncatedCount = 0; let totalCharsSaved = 0; let repeatedCount = 0; for (const entry of state.cache.values()) { if (entry.count > 1) repeatedCount++; if (entry.count > MAX_REPEAT_COUNT) { compressedCount++; totalCharsSaved += (entry.count - MAX_REPEAT_COUNT) * 500; } if (state.turn - entry.firstSeenTurn > MAX_KEEP_ROUNDS) { expiredCount++; } } return { totalEntries: state.cache.size, repeatedCount, compressedCount, expiredCount, truncatedCount, totalCharsSaved, reclaimedCount: state.reclaimedCount, reclaimedChars: state.reclaimedChars, }; } /** 清空缓存(供 /new 命令或测试使用) */ export function clearCache(state: MicroCompactState = defaultState): void { state.cache.clear(); state.turn = 0; state.reclaimedCount = 0; state.reclaimedChars = 0; void clearToolResultArchive(state.archiveKey); state.archiveKey = randomUUID(); resetCacheEdits(state); } /** * 重置 cacheEdits 状态。调用时机(漏掉任何一个都会造成下标错位或重复删除): * - autoCompact / 手动 compact 之后:history 被砍头重写,pinned 的翻译后下标 * 全部失义,服务端缓存前缀也已失效,编辑指令没有继续存在的意义。 * - /new 新会话(clearCache 内已调用)。 */ export function resetCacheEdits(state: MicroCompactState = defaultState): void { state.cacheEdits.deletedToolIds.clear(); state.cacheEdits.pinned.length = 0; state.cacheEdits.pendingNew.length = 0; // 有效删除量一并清零:compact 后历史被重写,旧删除账目对应的内容可能已不在 // 新历史里,不清零会让 autoCompact 校正过度(判据虚低 -> 该压不压撑爆上下文)。 state.cacheEdits.activeDeletedTokens = 0; } // ==================== 工具白名单 ==================== /** * 只有低风险观察工具的返回值参与长度截断(SHA-1 去重对所有工具生效)。 * * Read/Edit/Write/Bash/WebSearch 默认不截断:它们可能包含源码中段、diff、 * 一次性诊断或不可复现证据。超大结果由 toolResultArchive 先保存原文并提供可恢复引用。 * 低风险工具仍保留头尾截断,以控制普通搜索结果的上下文成本。 */ const COMPRESSIBLE_TOOLS = new Set([ 'Grep', 'WebFetch', 'Glob', ]); // ==================== 核心函数 ==================== /** * 对一条工具执行结果进行微压缩处理。 * * 这是整个模块唯一的对外接口。loop.ts 在把 tool_result 塞入 history 之前调用它。 * * 处理流水线(按优先级): * Rule 0: 错误/短内容 → 原样放行 * Rule 1: SHA-1 去重 → 相同内容第 4 次起压缩为引用标记 * Rule 2: 时间衰减 → 超过 N 轮未再出现的内容清理掉 * Rule 3: 长度截断 → 白名单工具超长内容保留头尾 + 省略标记 * * @param toolName 工具名 * @param content 工具返回的原始内容 * @returns 处理后的内容(可能被压缩、截断、或原样返回) */ export function microCompact( toolName: string, content: string, state: MicroCompactState = defaultState, policy: ToolResultPolicy = getToolResultPolicy(toolName), ): string { if (!content) return content; // Rule 0: 错误信息原样保留 if (content.startsWith('Error:') || content.startsWith('错误')) { return content; } // Rule 0b: 短内容直接放行 if (content.length <= SHORT_CONTENT_THRESHOLD) { return content; } // Rule 1: SHA-1 去重 const hash = sha1(content); const existing = state.cache.get(hash); if (existing) { existing.count++; if (existing.count > MAX_REPEAT_COUNT) { return `[↑ ${existing.firstToolName} 结果已重复出现 ${existing.count} 次(相同内容已省略)]`; } return content; } // 首次看到此内容 state.cache.set(hash, { count: 1, firstToolName: toolName, firstSeenTurn: state.turn }); // Rule 2: 不需要——首次出现不存在时间衰减问题 // Rule 3: 长度截断(仅低风险工具;高价值结果禁止不可逆中段丢弃) if (!policy.highValue && content.length > MAX_RESULT_SIZE && COMPRESSIBLE_TOOLS.has(toolName)) { return truncateContent(content); } return content; } /** * 清理过期条目(每轮开始前调用)。 * 将超过 MAX_KEEP_ROUNDS 未被再次访问的条目标记为过期, * 后续如果这些条目的 hash 再次命中,会作为"新内容"重新计数。 */ export function expireOldEntries(state: MicroCompactState = defaultState): number { let expired = 0; for (const [hash, entry] of state.cache) { if (state.turn - entry.firstSeenTurn > MAX_KEEP_ROUNDS) { state.cache.delete(hash); expired++; } } return expired; } // ==================== Path C: 批量回收旧工具结果 ==================== /** * 可回收的工具集合:仅保留低风险观察工具。即便这些工具通常可重放, * 高价值结果也可通过 tool_result_policy 显式保护,不会因为工具名而强行清掉。 * * 刻意排除高价值/不可稳定重放的工具: * - Bash / WebSearch:一次性诊断和外部搜索结果可能无法复现 * - Read / Edit / Write:源码中段、diff 或生成内容可能是后续推理证据 * - Ask / AskUserQuestion:用户答案不可重放,清了就永远丢了 * - Task / agent 系:子任务结论昂贵且常被后续轮次引用 * - PresentResult:最终交付物清单,是本轮对话的核心产出 */ const RECLAIMABLE_TOOLS = new Set([ 'Grep', 'Glob', 'WebFetch', ]); /** * 批量回收所需的最小 history 消息结构(结构化类型,真实 Message 天然满足)。 * 不直接 import Message 是为了让本模块保持零项目内依赖、测试可用裸对象。 */ export interface ReclaimableMessage { role: string; /** 真实 Message 里 user 消息可为多模态数组;本函数只消费 string 形态 */ content: string | null | readonly unknown[]; tool_calls?: Array<{ id?: string; function?: { name?: string } }>; tool_call_id?: string; tool_result_policy?: ToolResultPolicy; } /** 一次批量回收的结果统计 */ export interface ReclaimStats { reclaimedCount: number; reclaimedChars: number; } const EMPTY_RECLAIM_STATS: ReclaimStats = { reclaimedCount: 0, reclaimedChars: 0 }; /** * Path C:批量回收旧工具结果(每轮 LLM 调用前执行)。 * * 语义(对齐 kakadeai Cached MC 的 triggerThreshold / keepRecent): * history 中"存活"的可回收工具结果数量 > RECLAIM_TRIGGER_THRESHOLD 时, * 只保留最近 RECLAIM_KEEP_RECENT 条的完整内容(热尾部),其余按 mode 处理: * - 'inline'(默认):原地替换为占位符(含工具名与被替换的字符数, * 模型需要时可重新调用该工具)。 * - 'cacheEdits':**不改 history**——删除目标(tool_call_id)记入 * state.cacheEdits.pendingNew,由 anthropicFormat 组装 cache_edits block * 随请求发送,服务端在 KV 缓存内原地删除。 * * 设计约束与取舍: * 1. inline 只改 tool 消息的 content,tool_call_id / display_metadata 原样保留—— * API 协议完整性不受影响,且 display_metadata 在发送 Provider 前本就 * 被剥离(仅本地展示用),所以 UI 渲染不受影响。 * 2. 幂等:inline 用占位符前缀(RECLAIM_MARKER_PREFIX)检测已回收消息; * cacheEdits 用 deletedToolIds 集合检测。已回收的不计入候选、不二次处理。 * 触发频率 = 每攒 (阈值-保留数) 条新结果触发一次。 * 3. 跳过 Error 结果(短且常是排障线索)和 ≤200 字符的短结果 * (占位符本身就有 ~60 字符,清短结果纯亏)。 * 4. 缓存代价(模式差异的核心): * inline 直接改 history,前缀缓存从被改消息起失效——换 wire token 真实 * 削减,一次缓存重建几轮就回本,适用于无 cache_edits 能力的端点(含全部 * OpenAI 格式 provider)。 * cacheEdits 本地不动、服务端原地删——前缀 hash 不变、缓存命中完整保留; * 代价是 wire 上完整内容仍要发送(省的是服务端 KV 驻留与模型注意力窗口, * 不是请求体积)。reclaimedChars 在此模式下统计的是"服务端删除的内容量"。 * 5. tool_call_id → 工具名的映射来自 assistant 消息的 tool_calls 数组, * 扫一遍 history 即得,不需要额外状态。 * 6. cacheEdits 模式下本函数只做决策不做协议——它不认识 Anthropic 消息形状, * 翻译后下标由 anthropicFormat 的组装函数负责回填(见其 pinned 逻辑)。 * * @param history 完整会话历史(inline 模式原地修改命中的 tool 消息;cacheEdits 模式只读) * @param state 微压缩状态(累计统计写入 reclaimedCount / reclaimedChars;cacheEdits 模式另写 pendingNew) * @param mode 'inline'(默认)| 'cacheEdits'(Anthropic 格式 + provider.cacheEdits) * @returns 本次回收的条数与字符数(未触发时全为 0) */ export function reclaimOldToolResults( history: ReclaimableMessage[], state: MicroCompactState = defaultState, mode: 'inline' | 'cacheEdits' = 'inline', ): ReclaimStats { // 1. 建立 tool_call_id → 工具名 映射 const toolNameById = new Map(); for (const msg of history) { if (msg.role !== 'assistant' || !msg.tool_calls) continue; for (const tc of msg.tool_calls) { if (tc.id && tc.function?.name) toolNameById.set(tc.id, tc.function.name); } } // 2. 收集可回收候选:白名单工具 + 存活(未回收过)+ 非错误 + 非短内容 // 存活判据按模式分叉:inline 看占位符前缀,cacheEdits 看 deletedToolIds。 const candidates: Array<{ msg: ReclaimableMessage & { content: string }; toolCallId: string; chars: number }> = []; for (const msg of history) { if (msg.role !== 'tool' || typeof msg.content !== 'string') continue; const content = msg.content; if (content.startsWith(RECLAIM_MARKER_PREFIX)) continue; if (content.startsWith('Error:') || content.startsWith('错误')) continue; if (content.length <= SHORT_CONTENT_THRESHOLD) continue; const toolCallId = msg.tool_call_id; const toolName = toolCallId ? toolNameById.get(toolCallId) : undefined; const policy = msg.tool_result_policy ?? (toolName ? getToolResultPolicy(toolName) : undefined); if ( !toolCallId || !toolName || !RECLAIMABLE_TOOLS.has(toolName) || !policy?.reclaimable || policy.highValue ) continue; if (mode === 'cacheEdits' && state.cacheEdits.deletedToolIds.has(toolCallId)) continue; candidates.push({ msg: msg as ReclaimableMessage & { content: string }, toolCallId, chars: content.length }); } // 3. 未超阈值不动(> 而非 >=:恰好等于阈值视为健康水位) if (candidates.length <= RECLAIM_TRIGGER_THRESHOLD) { return EMPTY_RECLAIM_STATS; } // 4. 保留热尾部(按消息顺序的最后 KEEP_RECENT 条),其余按模式处理 const toClear = candidates.slice(0, candidates.length - RECLAIM_KEEP_RECENT); let reclaimedChars = 0; if (mode === 'cacheEdits') { for (const { msg, toolCallId, chars } of toClear) { state.cacheEdits.deletedToolIds.add(toolCallId); state.cacheEdits.pendingNew.push(toolCallId); // 累计有效删除量(token 估算,与 tokenCounter 同一套系数): // autoCompact 判据用它校正「本地 history 未瘦身」造成的虚高估算。 state.cacheEdits.activeDeletedTokens += countTextTokens(msg.content); reclaimedChars += chars; } } else { for (const { msg, toolCallId, chars } of toClear) { const toolName = toolNameById.get(toolCallId) ?? 'tool'; reclaimedChars += chars; const archiveHint = msg.tool_result_policy?.archiveRef ? ` | 完整原文可用 Read 读取:${msg.tool_result_policy.archiveRef}` : ''; msg.content = `${RECLAIM_MARKER_PREFIX} | ${toolName} | 原本 ${chars.toLocaleString()} 字符${archiveHint} | ` + `如需再次查看请重新调用该工具]`; } } // 5. 累计统计(getCacheStats 可查,观测回收效果) state.reclaimedCount += toClear.length; state.reclaimedChars += reclaimedChars; return { reclaimedCount: toClear.length, reclaimedChars }; } // ==================== 内部函数 ==================== function sha1(str: string): string { return createHash('sha1').update(str).digest('hex'); } export function getToolResultPolicy(toolName: string): ToolResultPolicy { // Bash/WebSearch/Read/Edit/Write 等结果可能包含一次性诊断、关键源码或不可复现证据, // 默认高价值且不可回收;低风险观察工具才进入 Path C。 const reclaimable = RECLAIMABLE_TOOLS.has(toolName); return { reclaimable, highValue: !reclaimable, }; } function truncateContent(content: string): string { const omitted = content.length - HEAD_KEEP_CHARS - TAIL_KEEP_CHARS; return ( safeSlice(content, 0, HEAD_KEEP_CHARS) + `\n\n[... 省略了 ${omitted.toLocaleString()} 字符 ...]\n\n` + safeSlice(content, -TAIL_KEEP_CHARS) ); }