Repository navigation
Description
Problem
OpenClaw 3.11 implemented a fix for GLM-5 token leakage (stripModelSpecialTokens), but the fix is not applied to the main chat output path, so users still see token leakage in their conversations.
Analysis
✅ Fix Implemented
The fix exists in ./src/agents/pi-embedded-utils.ts:
```typescript
// Match both ASCII pipe <|...|> and full-width pipe <|...|> (U+FF5C) variants.
const MODEL_SPECIAL_TOKEN_RE = /<[||][^||]*[||]>/g;
export function stripModelSpecialTokens(text: string): string {
if (!text) {
return text;
}
if (!MODEL_SPECIAL_TOKEN_RE.test(text)) {
return text;
}
MODEL_SPECIAL_TOKEN_RE.lastIndex = 0;
return text.replace(MODEL_SPECIAL_TOKEN_RE, " ").replace(/ +/g, " ").trim();
}
```
❌ Problem: Fix Not Applied to Main Output Path
The main output path (resolveFinalAssistantText in ./src/tui/tui-formatters.ts) directly returns text without sanitization:
```typescript
export function resolveFinalAssistantText(params: {
finalText?: string | null;
streamedText?: string | null;
errorMessage?: string | null;
}) {
const finalText = params.finalText ?? "";
if (finalText.trim()) {
return finalText; // ← No sanitization!
}
const streamedText = params.streamedText ?? "";
if (streamedText.trim()) {
return streamedText; // ← No sanitization!
}
const errorMessage = params.errorMessage ?? "";
if (errorMessage.trim()) {
return formatRawAssistantErrorForUi(errorMessage);
}
return "(no output)";
}
```
📍 Where Fix Is Applied
stripModelSpecialTokens is only called in:
- Sessions tool (
sessions-helpers.ts) - Subagent announce (
subagent-announce.ts) - Pi-Embedded Runner (
pi-embedded-utils.ts)
Main chat output path does NOT call sanitization!
Suggested Fix
Modify resolveFinalAssistantText to apply sanitization:
```typescript
import { sanitizeTextContent } from "../agents/tools/sessions-helpers.js";
export function resolveFinalAssistantText(params: {
finalText?: string | null;
streamedText?: string | null;
errorMessage?: string | null;
}) {
const finalText = params.finalText ?? "";
if (finalText.trim()) {
return sanitizeTextContent(finalText); // ← Add sanitization
}
const streamedText = params.streamedText ?? "";
if (streamedText.trim()) {
return sanitizeTextContent(streamedText); // ← Add sanitization
}
const errorMessage = params.errorMessage ?? "";
if (errorMessage.trim()) {
return formatRawAssistantErrorForUi(errorMessage);
}
return "(no output)";
}
```
Impact
- Users still see GLM-5 and DeepSeek token leakage in chat responses
- Fix exists but is not applied to the primary user-facing output
Environment
- OpenClaw version: 2026.3.11
- Model: GLM-5 (zai/glm-5)
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
openclaw-barnacle commentedon Apr 28, 2026
This issue has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.
clawsweeper commentedon Apr 28, 2026
Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.
Summary
Keep this open: current main still has source-level paths where model special tokens can reach visible assistant output, and the TUI-only fix PR was closed unmerged. The later
openclaw agent --jsonevidence usefully broadens the needed fix beyond the original TUI resolver.Reproducibility: yes. A high-confidence source-level reproduction exists on current main: token-bearing
finalTextor fallbackstreamedTextpassed toresolveFinalAssistantTextis returned unchanged, and internal agent command payload text can be projected to JSON or transcripts withoutsanitizeAssistantVisibleText.Next step
This is a narrow, valid user-visible bug with clear source paths, an existing shared sanitizer, a closed unmerged prior PR, and focused regression coverage options.
Review details
Best possible solution:
Centralize the existing assistant-visible sanitizer at final display/result/transcript boundaries, with regression coverage for TUI final/fallback text,
openclaw agent --jsonpayloads, and CLI transcript persistence.Do we have a high-confidence way to reproduce the issue?
Yes. A high-confidence source-level reproduction exists on current main: token-bearing
finalTextor fallbackstreamedTextpassed toresolveFinalAssistantTextis returned unchanged, and internal agent command payload text can be projected to JSON or transcripts withoutsanitizeAssistantVisibleText.Is this the best way to solve the issue?
No to the original TUI-only patch boundary; yes to reusing the shared
sanitizeAssistantVisibleTextpipeline at the shared assistant-visible output boundaries. That avoids duplicating regexes and covers the later JSON/transcript evidence without adding provider-specific logic.Acceptance criteria:
What I checked:
resolveFinalAssistantTextstill returns non-emptyfinalTextand fallbackstreamedTextdirectly, with no call to the shared assistant-visible sanitizer. (src/tui/tui-formatters.ts:157, a90be474f441)resolveFinalAssistantTextand returns that value as the final TUI text. (src/tui/tui-stream-assembler.ts:192, a90be474f441)sanitizeAssistantVisibleTextroutes through a pipeline that callsstripModelSpecialTokens, whose regex matches both ASCII and full-width pipe model tokens while preserving code regions. (src/shared/text/assistant-visible-text.ts:691, a90be474f441)normalizeAgentCommandReplyPayloadsreturns payloads as-is, and JSON projection writesentry.parts.textdirectly intoresult.payloads[].text. (src/agents/command/delivery.ts:119, a90be474f441)finalAssistantVisibleTextis absent,resolveCliTranscriptReplyTextjoins non-error payload text without assistant-visible sanitization before transcript persistence. (src/agents/command/attempt-execution.ts:245, a90be474f441)resolveFinalAssistantVisibleTexttrimsextractAssistantVisibleText, andextractAssistantVisibleTextdoes not pass a sanitizer option toextractAssistantTextForPhase. (src/agents/pi-embedded-runner/run/helpers.ts:177, a90be474f441)Likely related people:
src/tui/tui-formatters.ts,src/tui/tui-stream-assembler.ts,src/shared/text/assistant-visible-text.ts)src/agents/command/attempt-execution.ts,src/agents/pi-embedded-runner/run/helpers.ts,src/agents/pi-embedded-runner/run/payloads.ts)src/tui/tui-formatters.ts,src/tui/tui-stream-assembler.ts)Remaining risk / open question:
Codex review notes: model gpt-5.5, reasoning high; reviewed against a90be474f441.
camerono commentedon May 1, 2026
Adding evidence that this same root cause —
stripModelSpecialTokensexists but isn't on the main output path — also affects theopenclaw agent --jsoninvocation path, not just the TUI. Posting as a duplicate confirmation rather than a new issue since the existing analysis here already nails the diagnosis.Stack:
127.0.0.1:18789.127.0.0.1:8002(--enable-auto-tool-choice --tool-call-parser hermes).scripts/test/t2-integration.sh) that just invokesopenclaw agent --session-id <id> -m <prompt> --jsonper row.A session jsonl from a 2026-05-01 run (full path:
~/.openclaw/agents/main/sessions/c75ad1a9-7acb-4802-92b5-cbc2b7bdd3be.jsonl) contains a single assistantmessage.content[0].textwhose body is verbatim:The leaked
<|end_of_text|>and<|begin_of_text|>are exactly the ASCII-pipe variant the existingMODEL_SPECIAL_TOKEN_REregex would match. They're reaching the assistanttextcontent emitted byopenclaw agent --json(and into the run report'sresult.payloads[0].text) becausestripModelSpecialTokens/sanitizeAssistantVisibleTextisn't called on this path.Beyond the TUI
resolveFinalAssistantTextpath the original report calls out, the leak also reaches:openclaw agent --jsonfinal result envelope (result.payloads[].text)message.content[].text), which means downstream consumers — cron run history, harness inspectors, log shippers — all see the leaked tokens too.The clawsweeper review from 2026-04-28 is right that
sanitizeAssistantVisibleTextis the right place to wire this in. From this evidence the wiring needs to happen at the agent-message-finalization layer rather than at the TUI render layer specifically, otherwise the non-TUI invocation paths keep leaking even after the TUI is fixed.Also worth noting: original report and clawsweeper's tests focus on GLM-5 and Kimi/DeepSeek tokens. This evidence shows Hermes-3-Llama-3.1-8B served via vLLM with
--tool-call-parser hermesalso emits the same ASCII-pipe special tokens under particular prompt shapes (multi-tool surface plus a "do not pass argument X" guidance line in the user message). Same regex would catch it; just the call-site is missing.Cross-link: this evidence was generated alongside an exact-match repro for #45049 (agent loop accepting simulated tool calls as text). The two intersect — leaked special tokens framed a fabricated
execinvocation that #45049's strict-protocol enforcement would also need to reject. Either fix alone leaves the other reachable. Comment posted there too with the same evidence.I can share the the full session jsonl, harness output, and run config if any of that's useful for regression coverage.
steipete commentedon May 7, 2026
Closing as fixed on current
main.Proof:
src/shared/text/assistant-visible-text.tsappliesstripModelSpecialTokenson the assistant-visible text path.src/shared/text/assistant-visible-text.test.tscovers GLM/Kimi-style tokens such as<|assistant|>/<|end|>in normal output, mixed output, and reasoning-tag combinations, while preserving code spans/blocks.src/agents/pi-embedded-utils.strip-model-special-tokens.test.tscovers the shared utility directly.Verification run:
pnpm test src/shared/text/assistant-visible-text.test.ts src/agents/pi-embedded-utils.strip-model-special-tokens.test.tsCanonical fix lineage includes
309162f9a2(fix: strip leaked model control tokens from user-facing text (#42173)) and2514746b32(fix: sanitize LLM special tokens in external content).