import type { Message } from "../agent/conversation" /** * Microcompact: reduce token usage by stripping verbose tool results * and compressing old messages. Ported from Clawd-Code compact_service/microcompact.py. */ export function microcompactMessages(messages: Message[]): { compacted: Message[] tokensSaved: number } { let tokensSaved = 0 const compacted: Message[] = [] for (const msg of messages) { if (msg.role === "tool") { const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content) if (text.length > 2000) { const compressed = compressToolResult(text) tokensSaved += Math.ceil((text.length - compressed.length) / 4) compacted.push({ ...msg, content: compressed }) continue } } if (msg.role === "assistant" && msg.content) { const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content) if (text.length > 10000) { const truncated = text.slice(0, 5000) + "\n... [truncated for compaction]" tokensSaved += Math.ceil((text.length - truncated.length) / 4) compacted.push({ ...msg, content: truncated }) continue } } compacted.push(msg) } return { compacted, tokensSaved } } function compressToolResult(text: string): string { // Keep first 500 chars and last 500 chars of large tool results if (text.length <= 2000) return text const head = text.slice(0, 500) const tail = text.slice(-500) const lines = text.split("\n").length return `${head}\n\n... [${lines} lines compressed, ${text.length} chars total] ...\n\n${tail}` }