|
| 1 | +import * as fs from 'fs/promises'; |
| 2 | +import * as path from 'path'; |
| 3 | +import { MCPContentType, type MCPContent, type MCPToolResult } from './types'; |
| 4 | + |
| 5 | +const MAX_BYTES = 32 * 1024; |
| 6 | + |
| 7 | +export interface TruncateToolResultOptions { |
| 8 | + spillDir: string; |
| 9 | + toolCallId: string; |
| 10 | + toolName: string; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * 对单条 tool result 中的文本块做 head+tail 截断;超限部分整段写入 spillDir |
| 15 | + * 下的临时文件,截断标记中带上文件绝对路径,便于人工/工具回查。 |
| 16 | + * |
| 17 | + * - 仅处理 MCPContentType.Text 块;image/audio/document 块原样保留 |
| 18 | + * - 单个 text 块字节数 ≤ MAX_BYTES 时不动 |
| 19 | + * - 落盘失败时降级为不带路径的截断,保证主链路不中断 |
| 20 | + */ |
| 21 | +export async function truncateMCPToolResult( |
| 22 | + result: MCPToolResult, |
| 23 | + opts: TruncateToolResultOptions, |
| 24 | +): Promise<MCPToolResult> { |
| 25 | + let touched = false; |
| 26 | + const newContent: MCPContent[] = []; |
| 27 | + let textBlockIdx = 0; |
| 28 | + |
| 29 | + for (const block of result.content) { |
| 30 | + if (block.type !== MCPContentType.Text) { |
| 31 | + newContent.push(block); |
| 32 | + continue; |
| 33 | + } |
| 34 | + // 防御:normalizeToMCPResult 在某些边界(比如 tool 返回 undefined)会把 text 写成非 string; |
| 35 | + // Buffer.byteLength(undefined) 会抛 TypeError,这里直接跳过让外层逻辑去处理即可。 |
| 36 | + if (typeof block.text !== 'string') { |
| 37 | + newContent.push(block); |
| 38 | + textBlockIdx++; |
| 39 | + continue; |
| 40 | + } |
| 41 | + const fullText = block.text; |
| 42 | + const fullLen = Buffer.byteLength(fullText, 'utf8'); |
| 43 | + if (fullLen <= MAX_BYTES) { |
| 44 | + newContent.push(block); |
| 45 | + textBlockIdx++; |
| 46 | + continue; |
| 47 | + } |
| 48 | + |
| 49 | + const filename = `${sanitizeName(opts.toolName)}-${sanitizeName(opts.toolCallId)}-${textBlockIdx}.txt`; |
| 50 | + const filePath = path.join(opts.spillDir, filename); |
| 51 | + let spillNote: string; |
| 52 | + try { |
| 53 | + await fs.writeFile(filePath, fullText, 'utf8'); |
| 54 | + spillNote = `full output saved to ${filePath}`; |
| 55 | + } catch (err: any) { |
| 56 | + spillNote = `spill failed: ${err?.message ?? err}`; |
| 57 | + } |
| 58 | + |
| 59 | + newContent.push({ |
| 60 | + type: MCPContentType.Text, |
| 61 | + text: headTailWithMarker(fullText, fullLen, MAX_BYTES, spillNote), |
| 62 | + }); |
| 63 | + touched = true; |
| 64 | + textBlockIdx++; |
| 65 | + } |
| 66 | + |
| 67 | + if (!touched) return result; |
| 68 | + return { ...result, content: newContent }; |
| 69 | +} |
| 70 | + |
| 71 | +function headTailWithMarker(text: string, fullLen: number, maxBytes: number, note: string): string { |
| 72 | + // 上界估算:所有数字都用 fullLen 占位,实际 marker 一定 ≤ 这个长度(其他三个数都 ≤ fullLen) |
| 73 | + const markerEstimate = `\n\n…[truncated: bytes ${fullLen}..${fullLen} of ${fullLen} omitted (${fullLen} bytes); ${note}]…\n\n`; |
| 74 | + const markerLen = Buffer.byteLength(markerEstimate, 'utf8'); |
| 75 | + const budget = Math.max(0, maxBytes - markerLen); |
| 76 | + const headBudget = Math.floor(budget / 2); |
| 77 | + const tailBudget = budget - headBudget; |
| 78 | + |
| 79 | + const head = takeBytesFromStart(text, headBudget); |
| 80 | + const tail = takeBytesFromEnd(text, tailBudget); |
| 81 | + const headBytes = Buffer.byteLength(head, 'utf8'); |
| 82 | + const tailBytes = Buffer.byteLength(tail, 'utf8'); |
| 83 | + const omitted = fullLen - headBytes - tailBytes; |
| 84 | + const tailStart = fullLen - tailBytes; |
| 85 | + // 暴露字节区间,方便有 read_file 工具的 LLM 直接 offset=headBytes、limit=omitted 精准捞缺失部分 |
| 86 | + const marker = `\n\n…[truncated: bytes ${headBytes}..${tailStart} of ${fullLen} omitted (${omitted} bytes); ${note}]…\n\n`; |
| 87 | + return head + marker + tail; |
| 88 | +} |
| 89 | + |
| 90 | +// 按字节截取并对齐到 UTF-8 字符边界(避免出现半截多字节字符) |
| 91 | +function takeBytesFromStart(text: string, maxBytes: number): string { |
| 92 | + if (maxBytes <= 0) return ''; |
| 93 | + const buf = Buffer.from(text, 'utf8'); |
| 94 | + if (buf.length <= maxBytes) return text; |
| 95 | + let end = maxBytes; |
| 96 | + while (end > 0 && (buf[end] & 0xC0) === 0x80) end--; |
| 97 | + return buf.slice(0, end).toString('utf8'); |
| 98 | +} |
| 99 | + |
| 100 | +function takeBytesFromEnd(text: string, maxBytes: number): string { |
| 101 | + if (maxBytes <= 0) return ''; |
| 102 | + const buf = Buffer.from(text, 'utf8'); |
| 103 | + if (buf.length <= maxBytes) return text; |
| 104 | + let start = buf.length - maxBytes; |
| 105 | + while (start < buf.length && (buf[start] & 0xC0) === 0x80) start++; |
| 106 | + return buf.slice(start).toString('utf8'); |
| 107 | +} |
| 108 | + |
| 109 | +function sanitizeName(s: string): string { |
| 110 | + return (s || 'unknown').replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64); |
| 111 | +} |
0 commit comments