/gi,
(tableHtml) => `${tableHtml}
`,
)
}
const STANDALONE_STRONG_PARAGRAPH_RE =
/\s*((?:(?!<\/strong>)[\s\S])*?)<\/strong>\s*<\/p>/g
/**
* Tag paragraphs whose entire content is a single bold run (e.g. a model that
* emits `**小节标题:**` instead of a real heading) so they can be styled as a
* subtitle deterministically.
*
* This replaces the CSS `p:has(> strong:only-child)` heuristic, which was
* streaming-unstable: CSS `:only-child` ignores text nodes, so a normal
* paragraph that momentarily contained exactly one completed `**bold**` run
* (surrounded by plenty of body text) matched it and gained a large top margin,
* then lost it once a second bold run finished — a visible spacing jump
* mid-stream. Matching the whole paragraph content here only fires when the
* bold run truly is the entire paragraph.
*/
export function markStandaloneStrongParagraphs(html: string): string {
if (!html || !html.includes('')) return html
return html.replace(
STANDALONE_STRONG_PARAGRAPH_RE,
(match: string, inner: string, offset: number, full: string) => {
// A `` that is a list item's content is list text, not a standalone
// subtitle. Marking it adds a large margin that shifts sibling items when
// a streamed list flips from tight to loose, so leave list paragraphs to
// the list's own (zero) margins.
if (/
\s*$/.test(full.slice(0, offset))) return match
return `${inner}
`
},
)
}
export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkdownOptions): string {
const rawText = typeof rawMarkdown === 'string' ? rawMarkdown : String(rawMarkdown || '')
if (!rawText.trim()) return ''
configureMarkedForChatMarkdown()
const streamingSafeText = options.streaming
? stripTrailingStreamingListMarker(stripTrailingStreamingHorizontalRule(rawText))
: rawText
const imageContextSafeText = normalizeLegacyImageContextMarkup(
streamingSafeText,
Boolean(options.streaming),
)
const citationSafeText = stripIncompleteCitationTag(imageContextSafeText)
const { text: tagSafe, tags } = preserveCitationTags(citationSafeText)
const normalizedImageMarkdown = normalizeFullwidthMarkdownImageParentheses(tagSafe)
const imageSafe = replaceIncompleteImageWithPlaceholder(normalizedImageMarkdown)
const mathSafe = preprocessMathDelimiters(imageSafe)
const restoredTags = restoreCitationTags(mathSafe, tags)
const inlineTags = joinCitationTagsToPreviousLine(restoredTags)
// Run the list-marker guard again after emphasis balancing: closing/hiding a
// dangling `*`/`**` (the first chars of the next bullet's bold) can re-expose a
// bare ` - `, which would otherwise flash an empty nested item under the
// previous line right as the next item starts streaming.
const balancedInline = options.streaming
? stripTrailingStreamingListMarker(closeDanglingStreamingEmphasis(inlineTags))
: inlineTags
const preparedMarkdown = options.prepareMarkdown
? options.prepareMarkdown(balancedInline, options.cachedMermaidSvgHtml)
: balancedInline
const flankingSafeMarkdown = repairFlankingEmphasis(preparedMarkdown)
// Convert //wiki tags to HTML placeholders before escapeMarkdown so
// agent sanitizers (e.g. UUID stripping) cannot damage chunk_id attributes.
const { content: markdownWithPlaceholders, htmlSnippets } =
extractCitationHtmlPlaceholders(flankingSafeMarkdown, options.knowledgeReferences)
const escapedMarkdown = options.escapeMarkdown(markdownWithPlaceholders)
const html = marked.parse(markdownWithPlaceholders, {
renderer: options.renderer,
breaks: true,
async: false,
}) as string
const restoredHtml = restoreCitationHtmlPlaceholders(html, htmlSnippets)
const citationHtml = options.collapseStandaloneCitations === false
? restoredHtml
: collapseStandaloneCitationParagraphs(restoredHtml)
const tableWrappedHtml = wrapChatMarkdownTables(citationHtml)
const strongTitleHtml = markStandaloneStrongParagraphs(tableWrappedHtml)
const sanitized = options.sanitizeHtml(strongTitleHtml)
const withMermaid = options.injectCachedMermaidSvg
? options.injectCachedMermaidSvg(sanitized, options.cachedMermaidSvgHtml)
: sanitized
return options.streaming ? applyStreamingTailFade(withMermaid) : withMermaid
}