Skip to content

GLM-5 token leak: stripModelSpecialTokens not applied to main output path #44179

Closed

Description

@king33yoyo

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:

  1. Sessions tool (sessions-helpers.ts)
  2. Subagent announce (subagent-announce.ts)
  3. 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)

Activity

  1. openclaw-barnacle commented on Apr 28, 2026

    @openclaw-barnacle

    This issue has been automatically marked as stale due to inactivity.
    Please add updates or it will be closed.

  2. added
    stale
    on Apr 28, 2026
  3. clawsweeper commented on Apr 28, 2026

    @clawsweeper
    Contributor

    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 --json evidence usefully broadens the needed fix beyond the original TUI resolver.

    Reproducibility: yes. A high-confidence source-level reproduction exists on current main: token-bearing finalText or fallback streamedText passed to resolveFinalAssistantText is returned unchanged, and internal agent command payload text can be projected to JSON or transcripts without sanitizeAssistantVisibleText.

    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 --json payloads, 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 finalText or fallback streamedText passed to resolveFinalAssistantText is returned unchanged, and internal agent command payload text can be projected to JSON or transcripts without sanitizeAssistantVisibleText.

    Is this the best way to solve the issue?

    No to the original TUI-only patch boundary; yes to reusing the shared sanitizeAssistantVisibleText pipeline 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:

    • pnpm test src/tui/tui.test.ts src/tui/tui-formatters.test.ts src/tui/tui-stream-assembler.test.ts src/shared/text/assistant-visible-text.test.ts src/agents/command/delivery.test.ts src/agents/command/attempt-execution.cli.test.ts src/agents/pi-embedded-runner/run/helpers.test.ts src/agents/pi-embedded-runner/run/payloads.test.ts
    • pnpm exec oxfmt --check --threads=1 src/tui/tui-formatters.ts src/tui/tui.test.ts src/tui/tui-formatters.test.ts src/tui/tui-stream-assembler.test.ts src/shared/text/assistant-visible-text.ts src/shared/text/assistant-visible-text.test.ts src/agents/command/delivery.ts src/agents/command/delivery.test.ts src/agents/command/attempt-execution.ts src/agents/command/attempt-execution.cli.test.ts src/agents/pi-embedded-runner/run/helpers.ts src/agents/pi-embedded-runner/run/helpers.test.ts src/agents/pi-embedded-runner/run/payloads.ts src/agents/pi-embedded-runner/run/payloads.test.ts CHANGELOG.md
    • pnpm check:changed

    What I checked:

    • TUI resolver returns raw final text: resolveFinalAssistantText still returns non-empty finalText and fallback streamedText directly, with no call to the shared assistant-visible sanitizer. (src/tui/tui-formatters.ts:157, a90be474f441)
    • TUI finalization uses the raw resolver result: The stream assembler passes final/fallback display text through resolveFinalAssistantText and returns that value as the final TUI text. (src/tui/tui-stream-assembler.ts:192, a90be474f441)
    • Shared sanitizer already strips this token class: sanitizeAssistantVisibleText routes through a pipeline that calls stripModelSpecialTokens, whose regex matches both ASCII and full-width pipe model tokens while preserving code regions. (src/shared/text/assistant-visible-text.ts:691, a90be474f441)
    • Internal agent command payloads bypass sanitizer: For internal/no-delivery channels, normalizeAgentCommandReplyPayloads returns payloads as-is, and JSON projection writes entry.parts.text directly into result.payloads[].text. (src/agents/command/delivery.ts:119, a90be474f441)
    • CLI transcript fallback can persist payload text directly: When finalAssistantVisibleText is absent, resolveCliTranscriptReplyText joins non-error payload text without assistant-visible sanitization before transcript persistence. (src/agents/command/attempt-execution.ts:245, a90be474f441)
    • Final visible text helper extracts without sanitizer: resolveFinalAssistantVisibleText trims extractAssistantVisibleText, and extractAssistantVisibleText does not pass a sanitizer option to extractAssistantTextForPhase. (src/agents/pi-embedded-runner/run/helpers.ts:177, a90be474f441)

    Likely related people:

    • steipete: Current blame in this grafted checkout points Peter Steinberger at the central touched files, CODEOWNERS routes repository ownership to @steipete for ownership rules, and the prior ClawSweeper review tied him to sanitizer unification and adjacent TUI phase handling. (role: recent sanitizer, TUI, and agent-output maintainer; confidence: high; commits: b37fba7c07a7, 712479eea1a1, 2fef1ccbe76d; files: src/tui/tui-formatters.ts, src/tui/tui-stream-assembler.ts, src/shared/text/assistant-visible-text.ts)
    • Vincent Koc: Local log history includes recent agent sanitizer and current-main repair work by Vincent Koc near the agent output surface, making him a plausible follow-up reviewer for the CLI/transcript side. (role: recent adjacent agent sanitizer maintainer; confidence: medium; commits: 35664d5447a4, a52725e81a27, a90be474f441; files: src/agents/command/attempt-execution.ts, src/agents/pi-embedded-runner/run/helpers.ts, src/agents/pi-embedded-runner/run/payloads.ts)
    • vignesh07: The prior ClawSweeper review connected Vignesh Natarajan to final-event error rendering and render sanitization changes in the TUI display path where final assistant text is surfaced. (role: adjacent TUI rendering maintainer; confidence: medium; commits: 6084c26d0046; files: src/tui/tui-formatters.ts, src/tui/tui-stream-assembler.ts)

    Remaining risk / open question:

    • No live GLM-5/Hermes run or test execution was performed in this read-only review, so the fix PR should prove the behavior with focused regression tests.
    • Sanitizer placement must preserve error formatting, silent replies, media/reply directives, and code-region examples while stripping model control tokens from visible assistant text.

    Codex review notes: model gpt-5.5, reasoning high; reviewed against a90be474f441.

  4. removed
    stale
    on Apr 29, 2026
  5. camerono commented on May 1, 2026

    @camerono

    Adding evidence that this same root cause — stripModelSpecialTokens exists but isn't on the main output path — also affects the openclaw agent --json invocation 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:

    • OpenClaw 2026.4.9, gateway via systemd-user on 127.0.0.1:18789.
    • vLLM Hermes-3-Llama-3.1-8B on 127.0.0.1:8002 (--enable-auto-tool-choice --tool-call-parser hermes).
    • Caller is a test harness in our repo (scripts/test/t2-integration.sh) that just invokes openclaw agent --session-id <id> -m <prompt> --json per 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 assistant message.content[0].text whose body is verbatim:

    NO_REPLY
    <|end_of_text|><|begin_of_text|>://exec: exec(command='cat /tmp/no-such-file-zxqj-7777-t2c84',
      workdir='', env={}, yieldMs=10000, background=False, timeout=0, pty=False,
      elevated=False, host='auto', security='default', ask='') ->
      {"exitCode": 1, "stdout": "",
       "stderr": "cat: /tmp/no-such-file-zxqj-7777-t2c84: No such file or directory"}
    

    The leaked <|end_of_text|> and <|begin_of_text|> are exactly the ASCII-pipe variant the existing MODEL_SPECIAL_TOKEN_RE regex would match. They're reaching the assistant text content emitted by openclaw agent --json (and into the run report's result.payloads[0].text) because stripModelSpecialTokens / sanitizeAssistantVisibleText isn't called on this path.

    Beyond the TUI resolveFinalAssistantText path the original report calls out, the leak also reaches:

    • openclaw agent --json final result envelope (result.payloads[].text)
    • The session jsonl itself (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 sanitizeAssistantVisibleText is 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 hermes also 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 exec invocation 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.

  6. steipete commented on May 7, 2026

    @steipete
    Contributor

    Closing as fixed on current main.

    Proof:

    • src/shared/text/assistant-visible-text.ts applies stripModelSpecialTokens on the assistant-visible text path.
    • src/shared/text/assistant-visible-text.test.ts covers 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.ts covers 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.ts

    Canonical fix lineage includes 309162f9a2 (fix: strip leaked model control tokens from user-facing text (#42173)) and 2514746b32 (fix: sanitize LLM special tokens in external content).

  7. locked as resolved and limited conversation to collaborators on May 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions