Skip to content

Commit 576a7a2

Browse files
committed
perf(markdown): reuse streamed parsing and rendered chunks
1 parent be5e79c commit 576a7a2

6 files changed

Lines changed: 115 additions & 61 deletions

File tree

‎docs/concepts/markdown-formatting.md‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,21 @@ splits formatting mid-span.
2020
ranges align with its API directly. Tables parse only when the channel
2121
opts into a table mode.
2222
2. **Chunk the IR** (`chunkMarkdownIR` / `renderMarkdownIRChunksWithinLimit`)
23-
- splitting happens on IR text before rendering, so inline styles and
24-
links are sliced per chunk instead of breaking across a boundary.
23+
- style and link spans are sliced with the text. The rendered-size chunker
24+
measures each candidate after channel escaping and link rewriting, and
25+
returns the accepted source slice together with its rendered payload.
2526
3. **Render per channel** (`renderMarkdownWithMarkers`) - a style-marker map
2627
turns spans into the channel's native markup.
2728

28-
| Channel | Renderer | Notes |
29-
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
30-
| Matrix | HTML tags, including native tables | Automatic replies, direct sends, and media captions use the same formatter |
31-
| Slack | mrkdwn tokens (`*bold*`, `_italic_`, `` `code` ``, code fences) | Links become `<url\|label>`; autolink disabled during parse to avoid double-linking |
32-
| Telegram | HTML tags (`<b>`, `<i>`, `<s>`, `<code>`, `<pre><code>`, `<a href>`, `<tg-spoiler>`) | Also supports rich-message tables and headings (`<h1>`-`<h6>`) when `richMessages` is on |
33-
| Signal | plain text + `text-style` ranges | Links render as `label (url)` when the label differs from the URL |
34-
| Discord, WhatsApp, iMessage, Microsoft Teams, and other channels | plain text | No IR-based styling; Markdown table conversion still runs via `convertMarkdownTables` |
29+
Examples of shared IR renderers:
30+
31+
| Channel | Renderer | Notes |
32+
| -------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
33+
| Matrix | HTML tags, including native tables | Automatic replies, direct sends, and media captions use the same formatter |
34+
| Signal | plain text + `text-style` ranges | Links render as `label (url)` when the label differs from the URL |
35+
| Slack | mrkdwn tokens (`*bold*`, `_italic_`, `` `code` ``, code fences) | Links become `<url\|label>`; autolink disabled during parse to avoid double-linking |
36+
| Telegram | HTML tags (`<b>`, `<i>`, `<s>`, `<code>`, `<pre><code>`, `<a href>`, `<tg-spoiler>`) | Also supports rich-message tables and headings (`<h1>`-`<h6>`) when `richMessages` is on |
37+
| WhatsApp | WhatsApp style markers | Uses shared IR; styled chunks are measured after rendering |
3538

3639
## IR example
3740

@@ -82,8 +85,9 @@ channels:
8285
8386
## Chunking rules
8487
85-
- Chunk limits come from channel adapters/config and apply to IR text, not
86-
rendered output.
88+
- Chunk limits come from channel adapters/config. `chunkMarkdownIR` limits IR
89+
text; `renderMarkdownIRChunksWithinLimit` measures the final payload in the
90+
transport's size unit, including escaping and rewritten links.
8791
- Fenced code blocks are kept as one block with a trailing newline so
8892
channels render the closing fence correctly.
8993
- List and blockquote prefixes are part of the IR text, so chunking never
@@ -123,7 +127,8 @@ content is hidden or lost.
123127
2. **Render** with `renderMarkdownWithMarkers(...)` and a style-marker map (or
124128
custom style-range logic for transports like Signal).
125129
3. **Chunk** with `chunkMarkdownIR(...)` or
126-
`renderMarkdownIRChunksWithinLimit(...)` before rendering each chunk.
130+
`renderMarkdownIRChunksWithinLimit(...)`. The latter returns the measured
131+
`rendered` payload; use it directly instead of rendering the source again.
127132
4. **Wire the adapter** to call the new chunker and renderer from the
128133
outbound send path.
129134
5. **Test** with format tests plus an outbound delivery test if the channel

‎packages/markdown-core/src/code-spans.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,14 @@ function parseInlineCodeSpans(
6363
let openStart = open ? 0 : -1;
6464

6565
let i = 0;
66+
// The scanner emits ordered, disjoint fences and the input cursor only advances.
67+
// Retire each fence once instead of searching all prior fences at every character.
68+
let fenceIndex = 0;
6669
while (i < text.length) {
67-
const fence = findFenceSpanAtInclusive(fenceSpans, i);
68-
if (fence) {
70+
const fence = fenceSpans[fenceIndex];
71+
if (fence && i >= fence.start) {
6972
i = fence.end;
73+
fenceIndex += 1;
7074
continue;
7175
}
7276

@@ -107,10 +111,6 @@ function parseInlineCodeSpans(
107111
};
108112
}
109113

110-
function findFenceSpanAtInclusive(spans: FenceSpan[], index: number): FenceSpan | undefined {
111-
return spans.find((span) => index >= span.start && index < span.end);
112-
}
113-
114114
function isInsideFenceSpan(index: number, spans: FenceSpan[]): boolean {
115115
return spans.some((span) => index >= span.start && index < span.end);
116116
}

‎packages/markdown-core/src/render-aware-chunking.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { describe, expect, it } from "vitest";
33
import type { MarkdownIR } from "./ir.js";
44
import { markdownToIR } from "./ir.js";
5+
import { renderMarkdownWithAttributedRanges } from "./render-attributed.js";
56
import { renderMarkdownIRChunksWithinLimit } from "./render-aware-chunking.js";
67
import { renderMarkdownWithMarkers } from "./render.js";
78

@@ -98,6 +99,36 @@ describe("renderMarkdownIRChunksWithinLimit", () => {
9899
expect(chunks.every((chunk) => chunk.rendered.length <= 1)).toBe(true);
99100
});
100101

102+
it("drops temporary boundary annotations when whitespace is coalesced", () => {
103+
const chunks = renderMarkdownIRChunksWithinLimit({
104+
ir: {
105+
text: `alpha${" ".repeat(19)}\nuser[t] ok`,
106+
styles: [],
107+
links: [{ start: 25, end: 32, href: "https://example.test" }],
108+
},
109+
limit: 20,
110+
assistantTranscriptRoleMessageBoundaries: true,
111+
renderChunk: (source) => ({
112+
source,
113+
...renderMarkdownWithAttributedRanges(source, {
114+
styleMap: {},
115+
annotationStyleMap: { assistant_transcript_role: "MONOSPACE" },
116+
}),
117+
}),
118+
measureRendered: (rendered) => rendered.text.length,
119+
});
120+
121+
expect(chunks.map((chunk) => chunk.rendered.text)).toEqual([
122+
`alpha${" ".repeat(15)}`,
123+
" \nuser[t] ok",
124+
]);
125+
const final = chunks[1];
126+
expect(final?.source.annotations).toBeUndefined();
127+
expect(final?.source.links).toEqual([{ start: 5, end: 12, href: "https://example.test" }]);
128+
expect(final?.rendered.ranges).toEqual([]);
129+
expect(final?.rendered.source).toBe(final?.source);
130+
});
131+
101132
it("keeps astral characters whole when a positive limit reaches their pair", () => {
102133
const chunks = renderMarkdownIRChunksWithinLimit({
103134
ir: markdownToIR("A😀B"),

‎packages/markdown-core/src/render-aware-chunking.ts‎

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ export type RenderMarkdownIRChunksWithinLimitOptions<TRendered> = {
3737
assistantTranscriptRoleMessageBoundaries?: boolean;
3838
};
3939

40+
type RenderedCandidate<TRendered> = {
41+
rawSource: MarkdownIR;
42+
output: RenderedMarkdownChunk<TRendered>;
43+
};
44+
4045
type RenderResolver<TRendered> = Pick<
4146
RenderMarkdownIRChunksWithinLimitOptions<TRendered>,
4247
"measureRendered" | "renderChunk"
@@ -51,6 +56,14 @@ function prepareChunkForMessageBoundary<TRendered>(
5156
: chunk;
5257
}
5358

59+
function renderCandidate<TRendered>(
60+
options: RenderMarkdownIRChunksWithinLimitOptions<TRendered>,
61+
rawSource: MarkdownIR,
62+
): RenderedCandidate<TRendered> {
63+
const source = prepareChunkForMessageBoundary(options, rawSource);
64+
return { rawSource, output: { source, rendered: options.renderChunk(source) } };
65+
}
66+
5467
/** Chunks Markdown IR by rendered size while preserving styles, links, and whitespace. */
5568
export function renderMarkdownIRChunksWithinLimit<TRendered>(
5669
options: RenderMarkdownIRChunksWithinLimitOptions<TRendered>,
@@ -76,24 +89,27 @@ export function renderMarkdownIRChunksWithinLimit<TRendered>(
7689
// The initial reverse keeps the final order stable while avoiding shift/unshift
7790
// moving every remaining chunk for long messages.
7891
const pending = splitMarkdownIRPreserveWhitespace(options.ir, normalizedLimit).toReversed();
79-
const finalized: MarkdownIR[] = [];
92+
const finalized: RenderedCandidate<TRendered>[] = [];
8093

8194
while (pending.length > 0) {
8295
const chunk = pending.pop();
8396
if (!chunk) {
8497
continue;
8598
}
8699

87-
const rendered = renderResolver.renderChunk(chunk);
88-
if (renderResolver.measureRendered(rendered) <= normalizedLimit || chunk.text.length <= 1) {
89-
finalized.push(chunk);
100+
const candidate = renderCandidate(options, chunk);
101+
if (
102+
options.measureRendered(candidate.output.rendered) <= normalizedLimit ||
103+
chunk.text.length <= 1
104+
) {
105+
finalized.push(candidate);
90106
continue;
91107
}
92108

93109
const split = splitMarkdownIRByRenderedLimit(chunk, normalizedLimit, renderResolver);
94110
if (split.length <= 1) {
95111
// Worst-case safety: avoid retry loops and keep the original chunk.
96-
finalized.push(chunk);
112+
finalized.push(candidate);
97113
continue;
98114
}
99115
for (let index = split.length - 1; index >= 0; index -= 1) {
@@ -104,11 +120,8 @@ export function renderMarkdownIRChunksWithinLimit<TRendered>(
104120
}
105121
}
106122

107-
return coalesceWhitespaceOnlyMarkdownIRChunks(finalized, normalizedLimit, renderResolver).map(
108-
(chunk) => {
109-
const source = prepareChunkForMessageBoundary(options, chunk);
110-
return { source, rendered: options.renderChunk(source) };
111-
},
123+
return coalesceWhitespaceOnlyMarkdownIRChunks(finalized, normalizedLimit, options).map(
124+
(chunk) => chunk.output,
112125
);
113126
}
114127

@@ -337,11 +350,11 @@ function mergeMarkdownIRChunks(left: MarkdownIR, right: MarkdownIR): MarkdownIR
337350
}
338351

339352
function coalesceWhitespaceOnlyMarkdownIRChunks<TRendered>(
340-
chunks: MarkdownIR[],
353+
chunks: RenderedCandidate<TRendered>[],
341354
renderedLimit: number,
342-
options: RenderResolver<TRendered>,
343-
): MarkdownIR[] {
344-
const coalesced: MarkdownIR[] = [];
355+
options: RenderMarkdownIRChunksWithinLimitOptions<TRendered>,
356+
): RenderedCandidate<TRendered>[] {
357+
const coalesced: RenderedCandidate<TRendered>[] = [];
345358
let index = 0;
346359

347360
while (index < chunks.length) {
@@ -350,31 +363,37 @@ function coalesceWhitespaceOnlyMarkdownIRChunks<TRendered>(
350363
index += 1;
351364
continue;
352365
}
353-
if (chunk.text.trim().length > 0) {
366+
if (chunk.rawSource.text.trim().length > 0) {
354367
coalesced.push(chunk);
355368
index += 1;
356369
continue;
357370
}
358371

359372
const prev = coalesced.at(-1);
360373
const next = chunks[index + 1];
361-
const chunkLength = chunk.text.length;
374+
const chunkLength = chunk.rawSource.text.length;
362375

363-
const canMerge = (candidate: MarkdownIR) =>
364-
options.measureRendered(options.renderChunk(candidate)) <= renderedLimit;
376+
// Keep raw IR for merges: a new boundary annotation may no longer apply
377+
// after whitespace joins neighbors. Retain the exact measured output pair.
378+
const renderIfFits = (source: MarkdownIR) => {
379+
const candidate = renderCandidate(options, source);
380+
return options.measureRendered(candidate.output.rendered) <= renderedLimit
381+
? candidate
382+
: undefined;
383+
};
365384

366385
if (prev) {
367-
const mergedPrev = mergeMarkdownIRChunks(prev, chunk);
368-
if (canMerge(mergedPrev)) {
386+
const mergedPrev = renderIfFits(mergeMarkdownIRChunks(prev.rawSource, chunk.rawSource));
387+
if (mergedPrev) {
369388
coalesced[coalesced.length - 1] = mergedPrev;
370389
index += 1;
371390
continue;
372391
}
373392
}
374393

375394
if (next) {
376-
const mergedNext = mergeMarkdownIRChunks(chunk, next);
377-
if (canMerge(mergedNext)) {
395+
const mergedNext = renderIfFits(mergeMarkdownIRChunks(chunk.rawSource, next.rawSource));
396+
if (mergedNext) {
378397
chunks[index + 1] = mergedNext;
379398
index += 1;
380399
continue;
@@ -385,11 +404,12 @@ function coalesceWhitespaceOnlyMarkdownIRChunks<TRendered>(
385404
// Split pure whitespace between neighbors before dropping it so list,
386405
// paragraph, and quote spacing survives when both sides still fit.
387406
for (let prefixLength = chunkLength - 1; prefixLength >= 1; prefixLength -= 1) {
388-
const prefix = sliceMarkdownIR(chunk, 0, prefixLength);
389-
const suffix = sliceMarkdownIR(chunk, prefixLength, chunkLength);
390-
const mergedPrev = mergeMarkdownIRChunks(prev, prefix);
391-
const mergedNext = mergeMarkdownIRChunks(suffix, next);
392-
if (canMerge(mergedPrev) && canMerge(mergedNext)) {
407+
const prefix = sliceMarkdownIR(chunk.rawSource, 0, prefixLength);
408+
const suffix = sliceMarkdownIR(chunk.rawSource, prefixLength, chunkLength);
409+
const mergedPrev = renderIfFits(mergeMarkdownIRChunks(prev.rawSource, prefix));
410+
const mergedNext =
411+
mergedPrev && renderIfFits(mergeMarkdownIRChunks(suffix, next.rawSource));
412+
if (mergedPrev && mergedNext) {
393413
coalesced[coalesced.length - 1] = mergedPrev;
394414
chunks[index + 1] = mergedNext;
395415
break;

‎src/agents/embedded-agent-subscribe.stream-rendering.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,10 @@ export function createStreamRendering({
156156
if (!scanText) {
157157
return "";
158158
}
159-
const codeSpans = buildCodeSpanIndex(scanText, inlineStateStart, fenceStateStart);
159+
const codeSpans =
160+
scanText === fenceInput
161+
? initialCodeSpans
162+
: buildCodeSpanIndex(scanText, inlineStateStart, fenceStateStart);
160163

161164
let processed = "";
162165
THINKING_TAG_SCAN_RE.lastIndex = 0;
@@ -253,7 +256,10 @@ export function createStreamRendering({
253256
// If enforcement is disabled, we still strip the tags themselves to prevent
254257
// hallucinations (e.g. Minimax copying the style) from leaking, but we
255258
// do not enforce buffering/extraction logic.
256-
const finalCodeSpans = buildCodeSpanIndex(processed, inlineStateStart, fenceStateStart);
259+
const finalCodeSpans =
260+
processed === scanText
261+
? codeSpans
262+
: buildCodeSpanIndex(processed, inlineStateStart, fenceStateStart);
257263
if (!params.enforceFinalTag) {
258264
stateLocal.inlineCode = finalCodeSpans.inlineState;
259265
stateLocal.fence = finalCodeSpans.fenceState;

‎src/shared/text/reasoning-tags.ts‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { expectDefined } from "@openclaw/normalization-core";
21
import {
32
scanReasoningTags,
43
stripReasoningTagsFromMarkdown,
@@ -52,23 +51,16 @@ export function stripReasoningTagsFromText(
5251
return text;
5352
}
5453
if (matches.length > 0) {
55-
const finalMatches: Array<{ start: number; length: number; inCode: boolean }> = [];
5654
const preCodeRegions = findCodeRegions(cleaned);
55+
let visible = "";
56+
let lastIndex = 0;
5757
for (const match of matches) {
58-
const start = match.index;
59-
finalMatches.push({
60-
start,
61-
length: match.text.length,
62-
inCode: isInsideCode(start, preCodeRegions),
63-
});
64-
}
65-
66-
for (let i = finalMatches.length - 1; i >= 0; i--) {
67-
const m = expectDefined(finalMatches[i], "final matches capture group i");
68-
if (!m.inCode) {
69-
cleaned = cleaned.slice(0, m.start) + cleaned.slice(m.start + m.length);
58+
if (!isInsideCode(match.index, preCodeRegions)) {
59+
visible += cleaned.slice(lastIndex, match.index);
60+
lastIndex = match.index + match.text.length;
7061
}
7162
}
63+
cleaned = visible + cleaned.slice(lastIndex);
7264
}
7365

7466
return applyTrim(stripReasoningTagsFromMarkdown(cleaned, { mode, scope }), trimMode);

0 commit comments

Comments
 (0)