/** * ============================================================ * src/ui/markdown.ts —— assistant 最终答案的 markdown → 终端展示行 * ------------------------------------------------------------ * 借鉴 Claude Code 的管线(marked lexer 分词 + 自研 token→ANSI 格式化), * 按 minimal-agent 减法原则收敛。核心裁决: * * ★ 代码块「零装饰」(复制即用的全部保障): * `code` token 的每一行 = 原文逐字节输出——无边框、无背景、无缩进、无前缀、 * 不按宽度重排;渲染层配 wrap='end'(Ink 原样输出,不注入换行),超宽交给 * 终端软换行(现代终端复制时还原为整行)。任何"美化"都会污染复制。 * * ★ 删除线主动禁用:模型常用 ~xxx~ 表示"约等于",渲染成删除线是灾难 * (捐赠方同款裁决),del token 原样输出 raw。 * * ★ 只在 commit 时调用(write-once,每条消息一生解析一次, * <1ms 无重解析压力);live 流式区不跑 markdown。 * * 已知取舍: * - dim 与 bold 的 SGR 关闭码同为 22,嵌套会提前关闭外层——本文件不在 * bold 内嵌 dim(捐赠方同样接受此约束)。 * - 超过终端宽度的 code 行交终端软换行显示(视觉上折行、复制仍是整行); * TODO:后续可为超宽 code 提供 /show 式展开。 * - 表格按显示宽度对齐;窄窗口改为带列名的逐项展示。 * ============================================================ */ import { lexer, type Token, type Tokens } from 'marked'; import { figures } from './figures.js'; import { displayWidth } from './liveViewport.js'; import { terminalText } from './terminalText.js'; // ---------------- ANSI 内联样式(手写 SGR,不引 chalk) ---------------- // Ink 的 Text 渲染管线(wrap-ansi / cli-truncate)是 ANSI-aware 的, // 字符串内嵌 SGR 与 wrap='end' 兼容(捐赠方同款做法)。 const sgr = (open: number, close: number) => (s: string) => `\x1b[${open}m${s}\x1b[${close}m`; const bold = sgr(1, 22); const italic = sgr(3, 23); const underline = sgr(4, 24); const dim = sgr(2, 22); const cyan = sgr(36, 39); export type MdLineKind = /** 普通文字行(可含 ANSI 内联样式;渲染层加 ⏺/缩进前缀) */ | 'prose' /** 代码行 = 原文逐字节(渲染层零前缀零染色,复制安全断言点) */ | 'code' /** ``` 围栏行(渲染层染 dim,与代码本体区分) */ | 'fence'; export interface MdLine { text: string; kind: MdLineKind; } /** * 快判:文本里没有任何 markdown 语法特征 → 跳过 lexer,直接按 \n 切 prose * (旧行为快路径;也避免纯中文叙述被 lexer 意外重排)。 */ export function looksLikeMarkdown(text: string): boolean { return ( /(^|\n)\s*\|?.+\|.+\n\s*\|?\s*:?-{3,}/.test(text) || /(^|\n)\s{0,3}(#{1,6}\s|```|>\s|[-*+]\s|\d+\.\s|(-{3,}|\*{3,})\s*(\n|$))/.test(text) || // 块级:标题/围栏/引用/列表/hr /`[^`\n]+`|\*\*[^*\n]+\*\*|\[[^\]\n]+\]\([^)\n]+\)/.test(text) // 行内:codespan/加粗/链接 ); } /** * marked tokenizer 对 codespan/escape/text 做 HTML 实体转义 * (`a && b` → 'a && b')——终端不是 HTML,必须还原。 * 注意 & 最后替换(否则 &lt; 会被二次解码)。 */ export function unescapeEntities(text: string): string { return text .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, '&'); } /** 行内 tokens → 单条含 ANSI 的字符串。 */ export function formatInlineTokens(tokens: Token[]): string { let out = ''; for (const token of tokens) { switch (token.type) { case 'strong': out += bold(formatInlineTokens((token as Tokens.Strong).tokens)); break; case 'em': out += italic(formatInlineTokens((token as Tokens.Em).tokens)); break; case 'codespan': out += cyan(unescapeEntities((token as Tokens.Codespan).text)); break; case 'del': // 删除线禁用:~xxx~ 常是"约等于",原样输出 out += (token as Tokens.Del).raw; break; case 'link': { const link = token as Tokens.Link; const label = link.tokens ? formatInlineTokens(link.tokens) : link.text; out += label === link.href ? label : `${label} ${dim(`(${link.href})`)}`; break; } case 'image': out += `[图: ${(token as Tokens.Image).text}]`; break; case 'br': out += '\n'; break; case 'escape': out += unescapeEntities((token as Tokens.Escape).text); break; case 'text': { const t = token as Tokens.Text; out += t.tokens ? formatInlineTokens(t.tokens) : unescapeEntities(t.text); break; } default: out += 'raw' in token ? (token as { raw: string }).raw : ''; break; } } return out; } /** 把(可能含 ANSI 的)多行字符串切成 prose 行。 */ function proseLines(text: string): MdLine[] { return text.split('\n').map((line) => ({ text: line, kind: 'prose' as const })); } /** 单个块级 token → 展示行(导出供单测逐 token 断言)。 */ export function formatBlockToken(token: Token): MdLine[] { switch (token.type) { case 'code': { // ★ 复制安全核心路径:代码行 = token.text 逐字节,围栏行单独标 kind const code = token as Tokens.Code; return [ { text: `\`\`\`${code.lang ?? ''}`, kind: 'fence' }, ...code.text.split('\n').map((line) => ({ text: line, kind: 'code' as const })), { text: '```', kind: 'fence' }, ]; } case 'heading': { const heading = token as Tokens.Heading; const inner = formatInlineTokens(heading.tokens); return [{ text: heading.depth === 1 ? bold(underline(inner)) : bold(inner), kind: 'prose' }]; } case 'paragraph': return proseLines(formatInlineTokens((token as Tokens.Paragraph).tokens)); case 'list': { const list = token as Tokens.List; const lines: MdLine[] = []; const start = typeof list.start === 'number' ? list.start : 1; list.items.forEach((item, i) => { const bullet = list.ordered ? `${start + i}. ` : '- '; const pad = ' '.repeat(bullet.length); let firstLineDone = false; for (const sub of item.tokens) { if (sub.type === 'code') { // 列表内代码块:零装饰优先于列表对齐(不缩进,保住复制安全) lines.push(...formatBlockToken(sub)); continue; } if (sub.type === 'list') { // 嵌套列表:整体缩进对齐父 bullet(不走 firstLine 逻辑,避免双重缩进) lines.push( ...formatBlockToken(sub).map((l) => l.kind === 'prose' ? { ...l, text: `${pad}${l.text}` } : l, ), ); continue; } const subLines = proseLines( sub.type === 'text' || sub.type === 'paragraph' ? formatInlineTokens((sub as Tokens.Text).tokens ?? [sub]) : 'raw' in sub ? (sub as { raw: string }).raw : '', ); for (const l of subLines) { if (l.kind !== 'prose') { lines.push(l); } else if (!firstLineDone) { lines.push({ text: `${bullet}${l.text}`, kind: 'prose' }); firstLineDone = true; } else { lines.push({ text: `${pad}${l.text}`, kind: 'prose' }); } } } if (!firstLineDone) lines.push({ text: bullet.trimEnd(), kind: 'prose' }); }); return lines; } case 'blockquote': { const quote = token as Tokens.Blockquote; const inner = quote.tokens.flatMap(formatBlockToken); // 引用竖条只加在 prose 行;引用内代码块保持零装饰 return inner.map((l) => l.kind === 'prose' ? { ...l, text: `${dim(`${figures.quote} `)}${l.text}` } : l, ); } case 'space': return [{ text: '', kind: 'prose' }]; case 'hr': return [{ text: dim(figures.hr.repeat(20)), kind: 'prose' }]; case 'table': { const table = token as Tokens.Table; const cellWidth = (text: string) => displayWidth(text.replace(/\x1b\[[0-9;]*m/g, '')); const rows = [table.header, ...table.rows].map(row => row.map(cell => formatInlineTokens(cell.tokens))); const widths = table.header.map((_, index) => Math.max(...rows.map(row => cellWidth(row[index] ?? '')))); const width = widths.reduce((sum, value) => sum + value, 0) + (widths.length - 1) * displayWidth(' │ '); if (width > (process.stdout.columns ?? 80) - 6) { return table.rows.flatMap(row => [ ...row.map((cell, index) => ({ kind: 'prose' as const, text: `${bold(rows[0][index])}:${formatInlineTokens(cell.tokens)}` })), { kind: 'prose' as const, text: '' }, ]); } const line = (row: string[]) => row.map((cell, i) => cell + ' '.repeat(Math.max(0, widths[i] - cellWidth(cell)))).join(' │ '); return [line(rows[0]), widths.map(w => '─'.repeat(w)).join('─┼─'), ...rows.slice(1).map(line)].map(text => ({ kind: 'prose' as const, text })); } default: return 'raw' in token ? proseLines((token as { raw: string }).raw.replace(/\n+$/, '')) : []; } } /** * 主入口:assistant 正文 → 展示行。 * 纯文本走快路径(与旧渲染逐行一致);lexer 意外抛错时兜底回退原文 * (模型输出任意性防御——格式化是锦上添花,绝不能让渲染崩掉消息)。 */ export function renderMarkdownLines(src: string): MdLine[] { src = terminalText(src); if (src.length === 0) return []; if (!looksLikeMarkdown(src)) return proseLines(src); try { return lexer(src).flatMap(formatBlockToken); } catch { return proseLines(src); } }