Skip to content

Commit cb1f220

Browse files
committed
fix(gateway): sanitize assistant reasoning in chat history
1 parent 0c33f4e commit cb1f220

5 files changed

Lines changed: 198 additions & 7 deletions

File tree

‎src/gateway/chat-display-projection.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
parseAssistantTextSignature,
1919
resolveAssistantMessagePhase,
2020
} from "../shared/chat-message-content.js";
21+
import { sanitizeAssistantVisibleTextWithProfile } from "../shared/text/assistant-visible-text.js";
2122
import { isOpenClawDeliveryMirrorAssistantMessage } from "../shared/transcript-only-openclaw-assistant.js";
2223
import { stripInlineDirectiveTagsForDisplay } from "../utils/directive-tags.js";
2324
import { stripEnvelopeFromMessages } from "./chat-sanitize.js";
@@ -61,6 +62,15 @@ function truncateChatHistoryText(
6162
};
6263
}
6364

65+
function sanitizeAssistantHistoryDisplayText(text: string): { text: string; changed: boolean } {
66+
const stripped = stripInlineDirectiveTagsForDisplay(text);
67+
const sanitized = sanitizeAssistantVisibleTextWithProfile(stripped.text, "history");
68+
return {
69+
text: sanitized,
70+
changed: stripped.changed || sanitized !== stripped.text,
71+
};
72+
}
73+
6474
/** Return true for known tool-call/tool-result block type spellings in transcripts. */
6575
export function isToolHistoryBlockType(type: unknown): boolean {
6676
if (typeof type !== "string") {
@@ -251,7 +261,7 @@ export function augmentChatHistoryWithCanvasBlocks(messages: unknown[]): unknown
251261

252262
function sanitizeChatHistoryContentBlock(
253263
block: unknown,
254-
opts?: { preserveExactToolPayload?: boolean; maxChars?: number },
264+
opts?: { assistantDisplayText?: boolean; preserveExactToolPayload?: boolean; maxChars?: number },
255265
): { block: unknown; changed: boolean } {
256266
if (!block || typeof block !== "object") {
257267
return { block, changed: false };
@@ -261,8 +271,12 @@ function sanitizeChatHistoryContentBlock(
261271
const preserveExactToolPayload =
262272
opts?.preserveExactToolPayload === true || isToolHistoryBlockType(entry.type);
263273
const maxChars = opts?.maxChars ?? DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS;
274+
const sanitizeAssistantDisplayText =
275+
opts?.assistantDisplayText === true && !preserveExactToolPayload;
264276
if (typeof entry.text === "string") {
265-
const stripped = stripInlineDirectiveTagsForDisplay(entry.text);
277+
const stripped = sanitizeAssistantDisplayText
278+
? sanitizeAssistantHistoryDisplayText(entry.text)
279+
: stripInlineDirectiveTagsForDisplay(entry.text);
266280
if (preserveExactToolPayload) {
267281
entry.text = stripped.text;
268282
changed ||= stripped.changed;
@@ -273,7 +287,9 @@ function sanitizeChatHistoryContentBlock(
273287
}
274288
}
275289
if (typeof entry.content === "string") {
276-
const stripped = stripInlineDirectiveTagsForDisplay(entry.content);
290+
const stripped = sanitizeAssistantDisplayText
291+
? sanitizeAssistantHistoryDisplayText(entry.content)
292+
: stripInlineDirectiveTagsForDisplay(entry.content);
277293
if (preserveExactToolPayload) {
278294
entry.content = stripped.text;
279295
changed ||= stripped.changed;
@@ -383,7 +399,7 @@ function projectAssistantTextFromMixedToolContent(
383399
if (entry.type !== "text" || typeof entry.text !== "string" || !entry.text.trim()) {
384400
continue;
385401
}
386-
const stripped = stripInlineDirectiveTagsForDisplay(entry.text);
402+
const stripped = sanitizeAssistantHistoryDisplayText(entry.text);
387403
const truncated = truncateChatHistoryText(stripped.text, maxChars);
388404
if (truncated.text.trim()) {
389405
textBlocks.push({ type: "text", text: truncated.text });
@@ -504,8 +520,13 @@ function sanitizeChatHistoryMessage(
504520
}
505521
}
506522

523+
const isAssistant = entry.role === "assistant";
524+
const sanitizeAssistantDisplayText = isAssistant && !preserveExactToolPayload;
525+
507526
if (typeof entry.content === "string") {
508-
const stripped = stripInlineDirectiveTagsForDisplay(entry.content);
527+
const stripped = sanitizeAssistantDisplayText
528+
? sanitizeAssistantHistoryDisplayText(entry.content)
529+
: stripInlineDirectiveTagsForDisplay(entry.content);
509530
if (preserveExactToolPayload) {
510531
entry.content = stripped.text;
511532
changed ||= stripped.changed;
@@ -516,7 +537,11 @@ function sanitizeChatHistoryMessage(
516537
}
517538
} else if (Array.isArray(entry.content)) {
518539
const updated = entry.content.map((block) =>
519-
sanitizeChatHistoryContentBlock(block, { preserveExactToolPayload, maxChars }),
540+
sanitizeChatHistoryContentBlock(block, {
541+
assistantDisplayText: isAssistant,
542+
preserveExactToolPayload,
543+
maxChars,
544+
}),
520545
);
521546
if (updated.some((item) => item.changed)) {
522547
entry.content = updated.map((item) => item.block);
@@ -541,7 +566,9 @@ function sanitizeChatHistoryMessage(
541566
}
542567

543568
if (typeof entry.text === "string") {
544-
const stripped = stripInlineDirectiveTagsForDisplay(entry.text);
569+
const stripped = sanitizeAssistantDisplayText
570+
? sanitizeAssistantHistoryDisplayText(entry.text)
571+
: stripInlineDirectiveTagsForDisplay(entry.text);
545572
if (preserveExactToolPayload) {
546573
entry.text = stripped.text;
547574
changed ||= stripped.changed;

‎src/gateway/server-methods/server-methods.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,68 @@ describe("sanitizeChatHistoryMessages", () => {
845845
]);
846846
});
847847

848+
it("sanitizes assistant reasoning tags before truncating history text", () => {
849+
const visibleAnswer = "Visible answer ".repeat(12);
850+
const result = sanitizeChatHistoryMessages(
851+
[
852+
{
853+
role: "assistant",
854+
text: ["<thinking>", "private chain of thought", "<final>", visibleAnswer].join("\n"),
855+
timestamp: 1,
856+
},
857+
],
858+
48,
859+
) as Array<{ text?: string }>;
860+
861+
expect(result[0]?.text).toContain("Visible answer");
862+
expect(result[0]?.text).toContain("...(truncated)...");
863+
expect(result[0]?.text).not.toContain("private chain of thought");
864+
expect(result[0]?.text).not.toContain("<thinking>");
865+
expect(result[0]?.text).not.toContain("<final>");
866+
});
867+
868+
it("sanitizes assistant reasoning tags in content blocks before history truncation", () => {
869+
const visibleAnswer = "Block visible answer ".repeat(12);
870+
const result = sanitizeChatHistoryMessages(
871+
[
872+
{
873+
role: "assistant",
874+
content: [
875+
{
876+
type: "text",
877+
text: ["<thinking>", "private block reasoning", "<final>", visibleAnswer].join("\n"),
878+
},
879+
],
880+
timestamp: 1,
881+
},
882+
],
883+
54,
884+
) as Array<{ content?: Array<{ text?: string }> }>;
885+
886+
const text = result[0]?.content?.[0]?.text;
887+
expect(text).toContain("Block visible answer");
888+
expect(text).toContain("...(truncated)...");
889+
expect(text).not.toContain("private block reasoning");
890+
expect(text).not.toContain("<thinking>");
891+
expect(text).not.toContain("<final>");
892+
});
893+
894+
it("preserves tool payload text that looks like reasoning markup", () => {
895+
const result = sanitizeChatHistoryMessages(
896+
[
897+
{
898+
role: "tool",
899+
toolName: "read",
900+
content: "<thinking>payload tag from tool output</thinking>",
901+
timestamp: 1,
902+
},
903+
],
904+
12,
905+
) as Array<{ content?: string }>;
906+
907+
expect(result[0]?.content).toBe("<thinking>payload tag from tool output</thinking>");
908+
});
909+
848910
it("drops commentary-only assistant entries when phase exists only in textSignature", () => {
849911
const result = sanitizeChatHistoryMessages([
850912
{

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2176,6 +2176,37 @@ describe("gateway server chat", () => {
21762176
});
21772177
});
21782178

2179+
test("chat.history sanitizes assistant reasoning before applying maxChars", async () => {
2180+
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
2181+
const sessionDir = await prepareMainHistoryHarness({ ws, createSessionDir });
2182+
const visibleAnswer = "Visible answer after reasoning. ".repeat(20);
2183+
await writeMainSessionTranscript(sessionDir, [
2184+
JSON.stringify({
2185+
message: {
2186+
role: "assistant",
2187+
content: [
2188+
{
2189+
type: "text",
2190+
text: ["<thinking>", "private reload reasoning", "<final>", visibleAnswer].join(
2191+
"\n",
2192+
),
2193+
},
2194+
],
2195+
timestamp: Date.now(),
2196+
},
2197+
}),
2198+
]);
2199+
2200+
const messages = await fetchHistoryMessages(ws, { maxChars: 96 });
2201+
const serialized = JSON.stringify(messages);
2202+
expect(serialized).toContain("Visible answer after reasoning");
2203+
expect(serialized).toContain("...(truncated)...");
2204+
expect(serialized).not.toContain("private reload reasoning");
2205+
expect(serialized).not.toContain("<thinking>");
2206+
expect(serialized).not.toContain("<final>");
2207+
});
2208+
});
2209+
21792210
test("chat.history keeps visible assistant progress text from mixed tool-use transcript messages", async () => {
21802211
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
21812212
const sessionDir = await prepareMainHistoryHarness({ ws, createSessionDir });

‎src/shared/text/assistant-visible-text.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,34 @@ describe("sanitizeAssistantVisibleText", () => {
873873
);
874874
});
875875

876+
it("uses final tags as the visible boundary for unclosed reasoning", () => {
877+
const input = ["<thinking>", "private chain of thought", "<final>", "Visible answer"].join(
878+
"\n",
879+
);
880+
881+
expect(sanitizeAssistantVisibleText(input)).toBe("Visible answer");
882+
});
883+
884+
it("uses self-closing final tags as the visible boundary for unclosed reasoning", () => {
885+
const input = ["<thinking>", "private chain of thought", "<final/>", "Visible answer"].join(
886+
"\n",
887+
);
888+
889+
expect(sanitizeAssistantVisibleText(input)).toBe("Visible answer");
890+
});
891+
892+
it("continues to sanitize reasoning tags after a recovered final boundary", () => {
893+
const input = [
894+
"<thinking>",
895+
"private chain of thought",
896+
"<final>",
897+
"Visible answer",
898+
"<think>second private note</think>",
899+
].join("\n");
900+
901+
expect(sanitizeAssistantVisibleText(input)).toBe("Visible answer");
902+
});
903+
876904
it("keeps unclosed trailing reasoning hidden when visible text already exists", () => {
877905
expect(sanitizeAssistantVisibleText("Visible prefix <think>private reasoning tail")).toBe(
878906
"Visible prefix",
@@ -896,6 +924,34 @@ describe("sanitizeAssistantVisibleTextWithProfile", () => {
896924
).toBe(" Visible answer");
897925
});
898926

927+
it("uses the history profile to preserve visible-answer whitespace after unclosed reasoning", () => {
928+
const input = ["<thinking>", "private chain of thought", "<final>", " Visible answer"].join(
929+
"\n",
930+
);
931+
932+
expect(sanitizeAssistantVisibleTextWithProfile(input, "history")).toBe("\n Visible answer");
933+
});
934+
935+
it("uses the history profile to recover after self-closing final tags", () => {
936+
const input = ["<thinking>", "private chain of thought", "<final/>", " Visible answer"].join(
937+
"\n",
938+
);
939+
940+
expect(sanitizeAssistantVisibleTextWithProfile(input, "history")).toBe("\n Visible answer");
941+
});
942+
943+
it("uses the history profile to sanitize reasoning after a recovered final boundary", () => {
944+
const input = [
945+
"<thinking>",
946+
"private chain of thought",
947+
"<final>",
948+
" Visible answer",
949+
"<think>second private note</think>",
950+
].join("\n");
951+
952+
expect(sanitizeAssistantVisibleTextWithProfile(input, "history")).toBe("\n Visible answer\n");
953+
});
954+
899955
it("uses the internal-scaffolding profile to preserve downgraded tool text behavior", () => {
900956
const input = [
901957
"[Tool Call: read (ID: toolu_1)]",

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ export function stripReasoningTagsFromText(
4545
const trimMode = options?.trim ?? "both";
4646

4747
let cleaned = text;
48+
const originalCleaned = cleaned;
4849
const matches = findFinalTagMatches(cleaned);
4950
THINKING_TAG_RE.lastIndex = 0;
5051
const hasThinkingTag = THINKING_TAG_RE.test(cleaned);
@@ -130,6 +131,20 @@ export function stripReasoningTagsFromText(
130131
firstUnclosedContentIndex !== undefined &&
131132
cleaned.trim()
132133
) {
134+
const originalCodeRegions = findCodeRegions(originalCleaned);
135+
const finalBoundary = matches.find(
136+
(match) =>
137+
!match.isClose &&
138+
match.index >= firstUnclosedContentIndex &&
139+
!isInsideCode(match.index, originalCodeRegions),
140+
);
141+
if (finalBoundary) {
142+
const visibleTail = stripReasoningTagsFromText(
143+
originalCleaned.slice(finalBoundary.index + finalBoundary.text.length),
144+
{ mode, trim: "none" },
145+
);
146+
return applyTrim(visibleTail, trimMode);
147+
}
133148
return applyTrim(cleaned.slice(firstUnclosedContentIndex), trimMode);
134149
}
135150

0 commit comments

Comments
 (0)