const ERROR_RE = /\b(?:error|failed|failure|missing|undefined|exception)\b/i; const LOCATION_RE = /\b(?:at\s+.+:\d+(?::\d+)?)\b|(?:[A-Za-z0-9_./-]+\.(?:ts|tsx|js|mjs|json|md):\d+(?::\d+)?)/i; const MAX_SUMMARY_LENGTH = 320; const MAX_LINES = 2; function unique(lines: string[]): string[] { return lines.filter((line, index) => lines.indexOf(line) === index); } function pickSalientLines(content: string): string[] { const lines = content .split(/\n+/) .map((line) => line.trim()) .filter(Boolean); if (lines.length === 0) { return []; } const important = unique(lines.filter((line) => ERROR_RE.test(line))); const location = unique(lines.filter((line) => LOCATION_RE.test(line))); const fallback = unique(lines); const selected: string[] = []; for (const line of [...important, ...location, ...fallback]) { if (selected.includes(line)) { continue; } selected.push(line); if (selected.length >= MAX_LINES) { break; } } return selected; } export function distillToolResult(input: { toolName?: string; content: string }): string | undefined { const picked = pickSalientLines(input.content); if (picked.length === 0) { return undefined; } const prefix = `[distilled ${input.toolName ?? "tool"} output]`; return `${prefix} ${picked.join("; ")}`.slice(0, MAX_SUMMARY_LENGTH); }