Skip to content

Commit e582955

Browse files
steipetelicheer-zte
andcommitted
fix(markdown): unify reasoning tag parsing
Co-authored-by: 李琪0668001400 <[email protected]>
1 parent ed4ff90 commit e582955

13 files changed

Lines changed: 1826 additions & 707 deletions

‎packages/ai/src/utils/reasoning-tag-text-partitioner.test.ts‎

Lines changed: 587 additions & 145 deletions
Large diffs are not rendered by default.
Lines changed: 5 additions & 368 deletions
Original file line numberDiff line numberDiff line change
@@ -1,368 +1,5 @@
1-
// Reasoning tag partitioner helpers split text around reasoning tag regions.
2-
import {
3-
buildCodeSpanIndex,
4-
createInlineCodeState,
5-
type InlineCodeState,
6-
} from "@openclaw/markdown-core/code-spans";
7-
import type { FenceScanState } from "@openclaw/markdown-core/fences";
8-
9-
export type ReasoningTagTextDelta =
10-
| { kind: "text"; text: string }
11-
| { kind: "thinking"; text: string };
12-
13-
const REASONING_TAG_RE =
14-
/<\s*(\/?)\s*(?:(?:antml:|mm:)?(?:think(?:ing)?|thought|reasoning)|antthinking)\b[^<>]*>/gi;
15-
const REASONING_TAG_NAMES = [
16-
"think",
17-
"thinking",
18-
"thought",
19-
"reasoning",
20-
"antthinking",
21-
"antml:think",
22-
"antml:thinking",
23-
"antml:thought",
24-
"antml:reasoning",
25-
"mm:think",
26-
"mm:thinking",
27-
"mm:thought",
28-
"mm:reasoning",
29-
] as const;
30-
31-
export interface ReasoningTagTextPartitioner {
32-
markStrict(): void;
33-
push(chunk: string): ReasoningTagTextDelta[];
34-
pushVisible(chunk: string): ReasoningTagTextDelta[];
35-
flush(): ReasoningTagTextDelta[];
36-
hasPending(): boolean;
37-
isInsideReasoning(): boolean;
38-
}
39-
40-
export function createReasoningTagTextPartitioner(): ReasoningTagTextPartitioner {
41-
let buffer = "";
42-
let reasoningDepth = 0;
43-
let strictMode = false;
44-
let emittedVisibleText = false;
45-
let inlineCodeState: InlineCodeState = createInlineCodeState();
46-
let fenceState: FenceScanState | undefined;
47-
let hiddenInlineCodeState: InlineCodeState = createInlineCodeState();
48-
let hiddenFenceState: FenceScanState | undefined;
49-
let recoverableOpenTagText: string | undefined;
50-
51-
const consume = (final: boolean, recoverFullUnclosed: boolean): ReasoningTagTextDelta[] => {
52-
const output: ReasoningTagTextDelta[] = [];
53-
const emit = (kind: ReasoningTagTextDelta["kind"], text: string) => {
54-
if (!text) {
55-
return;
56-
}
57-
if (kind === "text" && text.trim().length > 0) {
58-
emittedVisibleText = true;
59-
}
60-
if (kind === "text") {
61-
const nextCode = buildCodeSpanIndex(text, inlineCodeState, fenceState);
62-
inlineCodeState = nextCode.inlineState;
63-
fenceState = nextCode.fenceState;
64-
} else {
65-
const nextCode = buildCodeSpanIndex(text, hiddenInlineCodeState, hiddenFenceState);
66-
hiddenInlineCodeState = nextCode.inlineState;
67-
hiddenFenceState = nextCode.fenceState;
68-
}
69-
const previous = output[output.length - 1];
70-
if (previous?.kind === kind) {
71-
previous.text += text;
72-
return;
73-
}
74-
output.push({ kind, text });
75-
};
76-
77-
while (buffer) {
78-
const activeInlineCodeState = reasoningDepth === 0 ? inlineCodeState : hiddenInlineCodeState;
79-
const activeFenceState = reasoningDepth === 0 ? fenceState : hiddenFenceState;
80-
const codeSpans = buildCodeSpanIndex(buffer, activeInlineCodeState, activeFenceState);
81-
const hasUnclosedCode =
82-
reasoningDepth === 0 && Boolean(codeSpans.inlineState.open || codeSpans.fenceState.open);
83-
const hasRawReasoning = hasRawReasoningTag(buffer);
84-
const tag = findNextReasoningTag(buffer, (index) =>
85-
final && hasUnclosedCode && hasRawReasoning ? false : codeSpans.isInside(index),
86-
);
87-
if (!tag) {
88-
if (final) {
89-
const recoverAsText =
90-
reasoningDepth > 0 && recoverFullUnclosed && !hasRawReasoningCloseTag(buffer);
91-
const recoveredText =
92-
recoverAsText && recoverableOpenTagText ? recoverableOpenTagText + buffer : buffer;
93-
emit(reasoningDepth > 0 && !recoverAsText ? "thinking" : "text", recoveredText);
94-
buffer = "";
95-
reasoningDepth = 0;
96-
recoverableOpenTagText = undefined;
97-
return output;
98-
}
99-
if (
100-
reasoningDepth > 0 &&
101-
recoverFullUnclosed &&
102-
(!emittedVisibleText || recoverableOpenTagText)
103-
) {
104-
return output;
105-
}
106-
if (hasUnclosedCode && hasRawReasoning) {
107-
const openCodeIndex =
108-
inlineCodeState.open || fenceState?.open ? 0 : findOpenCodeContextStart(buffer);
109-
if (openCodeIndex !== -1) {
110-
emit("text", buffer.slice(0, openCodeIndex));
111-
buffer = buffer.slice(openCodeIndex);
112-
return output;
113-
}
114-
}
115-
const trailingFenceStart = findTrailingFenceFragmentStart(
116-
buffer,
117-
activeInlineCodeState,
118-
activeFenceState,
119-
);
120-
if (trailingFenceStart !== -1) {
121-
emit(reasoningDepth > 0 ? "thinking" : "text", buffer.slice(0, trailingFenceStart));
122-
buffer = buffer.slice(trailingFenceStart);
123-
return output;
124-
}
125-
const keepFrom = reasoningTagPrefixSuffixIndex(buffer, (index) =>
126-
codeSpans.isInside(index),
127-
);
128-
if (keepFrom === -1) {
129-
emit(reasoningDepth > 0 ? "thinking" : "text", buffer);
130-
buffer = "";
131-
return output;
132-
}
133-
if (
134-
reasoningDepth === 0 &&
135-
keepFrom > 0 &&
136-
buffer.slice(0, keepFrom).trim().length > 0 &&
137-
isReasoningCloseTagPrefix(buffer.slice(keepFrom))
138-
) {
139-
return output;
140-
}
141-
if (keepFrom > 0) {
142-
emit(reasoningDepth > 0 ? "thinking" : "text", buffer.slice(0, keepFrom));
143-
buffer = buffer.slice(keepFrom);
144-
}
145-
return output;
146-
}
147-
148-
const beforeTag = buffer.slice(0, tag.index);
149-
const afterTag = buffer.slice(tag.index + tag.text.length);
150-
if (tag.isClose && reasoningDepth === 0) {
151-
if (recoverFullUnclosed && beforeTag.trim().length > 0 && afterTag.trim().length > 0) {
152-
emit("text", beforeTag + tag.text);
153-
buffer = afterTag;
154-
continue;
155-
}
156-
if (beforeTag.trim().length > 0 && afterTag.trim().length === 0 && !final) {
157-
return output;
158-
}
159-
if (beforeTag.trim().length === 0 || afterTag.trim().length === 0) {
160-
emit("text", beforeTag);
161-
}
162-
buffer = afterTag;
163-
continue;
164-
}
165-
166-
emit(reasoningDepth > 0 ? "thinking" : "text", buffer.slice(0, tag.index));
167-
buffer = afterTag;
168-
if (tag.isClose) {
169-
reasoningDepth = Math.max(0, reasoningDepth - 1);
170-
if (reasoningDepth === 0) {
171-
recoverableOpenTagText = undefined;
172-
hiddenInlineCodeState = createInlineCodeState();
173-
hiddenFenceState = undefined;
174-
}
175-
} else {
176-
if (reasoningDepth === 0) {
177-
recoverableOpenTagText = recoverFullUnclosed && emittedVisibleText ? tag.text : undefined;
178-
hiddenInlineCodeState = createInlineCodeState();
179-
hiddenFenceState = undefined;
180-
}
181-
reasoningDepth += 1;
182-
}
183-
}
184-
return output;
185-
};
186-
187-
return {
188-
markStrict() {
189-
strictMode = true;
190-
},
191-
push(chunk: string) {
192-
strictMode = true;
193-
buffer += chunk;
194-
return consume(false, false);
195-
},
196-
pushVisible(chunk: string) {
197-
buffer += chunk;
198-
return consume(false, true);
199-
},
200-
flush() {
201-
return consume(true, !strictMode);
202-
},
203-
hasPending() {
204-
return buffer.length > 0 || reasoningDepth > 0;
205-
},
206-
isInsideReasoning() {
207-
return reasoningDepth > 0;
208-
},
209-
};
210-
}
211-
212-
function hasRawReasoningTag(text: string): boolean {
213-
REASONING_TAG_RE.lastIndex = 0;
214-
return REASONING_TAG_RE.test(text);
215-
}
216-
217-
function hasRawReasoningCloseTag(text: string): boolean {
218-
REASONING_TAG_RE.lastIndex = 0;
219-
for (;;) {
220-
const match = REASONING_TAG_RE.exec(text);
221-
if (!match) {
222-
return false;
223-
}
224-
if (match[1] === "/") {
225-
return true;
226-
}
227-
}
228-
}
229-
230-
function findNextReasoningTag(
231-
text: string,
232-
isIndexInsideCode: (index: number) => boolean,
233-
): { index: number; text: string; isClose: boolean } | null {
234-
REASONING_TAG_RE.lastIndex = 0;
235-
for (;;) {
236-
const match = REASONING_TAG_RE.exec(text);
237-
if (!match) {
238-
return null;
239-
}
240-
if (!isIndexInsideCode(match.index)) {
241-
return {
242-
index: match.index,
243-
text: match[0],
244-
isClose: match[1] === "/",
245-
};
246-
}
247-
}
248-
}
249-
250-
function reasoningTagPrefixSuffixIndex(
251-
text: string,
252-
isIndexInsideCode: (index: number) => boolean,
253-
): number {
254-
for (let index = text.lastIndexOf("<"); index >= 0;) {
255-
if (!isIndexInsideCode(index) && isReasoningTagPrefix(text.slice(index))) {
256-
return index;
257-
}
258-
if (index === 0) {
259-
break;
260-
}
261-
index = text.lastIndexOf("<", index - 1);
262-
}
263-
return -1;
264-
}
265-
266-
function isReasoningTagPrefix(text: string): boolean {
267-
const name = normalizeReasoningTagPrefixName(text);
268-
return REASONING_TAG_NAMES.some((tagName) => {
269-
if (tagName.startsWith(name)) {
270-
return true;
271-
}
272-
if (!name.startsWith(tagName)) {
273-
return false;
274-
}
275-
const rest = name.slice(tagName.length);
276-
return rest.length === 0 || /^[\s/>]/.test(rest);
277-
});
278-
}
279-
280-
function isReasoningCloseTagPrefix(text: string): boolean {
281-
const normalized = text
282-
.replace(/^<\s*/, "<")
283-
.replace(/^<\s*\//, "</")
284-
.replace(/^<\/\s*/, "</")
285-
.toLowerCase();
286-
return normalized.startsWith("</") && isReasoningTagPrefix(text);
287-
}
288-
289-
function normalizeReasoningTagPrefixName(text: string): string {
290-
const normalized = text
291-
.replace(/^<\s*/, "<")
292-
.replace(/^<\s*\//, "</")
293-
.replace(/^<\/\s*/, "</")
294-
.toLowerCase();
295-
const rawName = normalized.startsWith("</") ? normalized.slice(2) : normalized.slice(1);
296-
return rawName.trimStart();
297-
}
298-
299-
function findOpenCodeContextStart(text: string): number {
300-
const fence = findOpenFenceStart(text);
301-
const inline = findOpenInlineCodeStart(text);
302-
if (fence === -1) {
303-
return inline;
304-
}
305-
if (inline === -1) {
306-
return fence;
307-
}
308-
return Math.min(fence, inline);
309-
}
310-
311-
function findOpenInlineCodeStart(text: string): number {
312-
let openStart = -1;
313-
let openTicks = 0;
314-
let index = 0;
315-
while (index < text.length) {
316-
if (text.charAt(index) !== "`") {
317-
index += 1;
318-
continue;
319-
}
320-
const runStart = index;
321-
let runLength = 0;
322-
while (index < text.length && text.charAt(index) === "`") {
323-
runLength += 1;
324-
index += 1;
325-
}
326-
if (openStart === -1) {
327-
openStart = runStart;
328-
openTicks = runLength;
329-
} else if (runLength === openTicks) {
330-
openStart = -1;
331-
openTicks = 0;
332-
}
333-
}
334-
return openStart;
335-
}
336-
337-
function findOpenFenceStart(text: string): number {
338-
const fenceRe = /(^|\n)(```|~~~)[^\n]*(?:\n|$)/g;
339-
let open: { marker: string; index: number } | null = null;
340-
for (const match of text.matchAll(fenceRe)) {
341-
const prefix = match.at(1);
342-
const marker = match.at(2);
343-
if (prefix === undefined || marker === undefined) {
344-
continue;
345-
}
346-
const index = (match.index ?? 0) + prefix.length;
347-
if (open !== null && open.marker === marker) {
348-
open = null;
349-
} else if (!open) {
350-
open = { marker, index };
351-
}
352-
}
353-
return open?.index ?? -1;
354-
}
355-
356-
function findTrailingFenceFragmentStart(
357-
text: string,
358-
inlineState: InlineCodeState,
359-
fenceState: FenceScanState | undefined,
360-
): number {
361-
if (inlineState.open || fenceState?.open) {
362-
return -1;
363-
}
364-
const lineStart = Math.max(text.lastIndexOf("\n") + 1, 0);
365-
const line = text.slice(lineStart);
366-
const match = line.match(/^( {0,3})(`{1,2}|~{1,2})$/);
367-
return match ? lineStart : -1;
368-
}
1+
export {
2+
createReasoningTagTextPartitioner,
3+
type ReasoningTagTextDelta,
4+
type ReasoningTagTextPartitioner,
5+
} from "../../../markdown-core/src/reasoning-tags.js";

‎packages/markdown-core/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,11 @@
5757
},
5858
"dependencies": {
5959
"@openclaw/normalization-core": "workspace:*",
60+
"mdast-util-from-markdown": "2.0.3",
61+
"mdast-util-gfm-table": "2.0.0",
6062
"markdown-it": "14.3.0",
6163
"markdown-it-cjk-friendly": "2.0.2",
64+
"micromark-extension-gfm-table": "2.1.1",
6265
"yaml": "2.9.0"
6366
}
6467
}

0 commit comments

Comments
 (0)