Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(chat): strip model orchestration on every surface, not only Code

purplee1311cb9313f
diff --git a/src/components/chat/ABCompare.tsx b/src/components/chat/ABCompare.tsx
index bba017e8..fbbb3d61 100644
--- a/src/components/chat/ABCompare.tsx
+++ b/src/components/chat/ABCompare.tsx
@@ -1,8 +1,9 @@
-import { useState, useRef, useEffect } from 'react'
+import { useState, useRef, useEffect, useMemo } from 'react'
import { useCompareStore } from '../../stores/compareStore'
import { useModels } from '../../hooks/useModels'
import { useABCompare } from '../../hooks/useABCompare'
import { MarkdownRenderer } from './MarkdownRenderer'
+import { stripModelNoise } from '../../lib/strip-model-noise'
import { ArrowLeft, Send, Square, Zap, Clock, Hash } from 'lucide-react'
export function ABCompare() {
@@ -41,6 +42,16 @@ export function ABCompare() {
setInput('')
}
+ // Cleaned assistant text per pane. Memoised on a length signature because
+ // both panes stream at once and the strip would otherwise re-run its whole
+ // regex set over every message on every token.
+ const sig = (ms: typeof messagesA) => ms.reduce((n, m) => n + (m.content || '').length, 0) + ':' + ms.length
+ const sigA = sig(messagesA), sigB = sig(messagesB)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const cleanA = useMemo(() => new Map(messagesA.map((m) => [m.id, stripModelNoise(m.content || '')])), [sigA])
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const cleanB = useMemo(() => new Map(messagesB.map((m) => [m.id, stripModelNoise(m.content || '')])), [sigB])
+
return (
<div className="h-full flex flex-col">
{/* Header */}
@@ -103,7 +114,7 @@ export function ABCompare() {
{messagesA.map(msg => (
<div key={msg.id} className={`text-[0.7rem] ${msg.role === 'user' ? 'text-gray-400 italic' : 'text-gray-200'}`}>
{msg.role === 'assistant' ? (
- <MarkdownRenderer content={msg.content || (isStreamingA ? '...' : '')} />
+ <MarkdownRenderer content={cleanA.get(msg.id) || (isStreamingA ? '...' : '')} />
) : (
<p>{msg.content}</p>
)}
@@ -128,7 +139,7 @@ export function ABCompare() {
{messagesB.map(msg => (
<div key={msg.id} className={`text-[0.7rem] ${msg.role === 'user' ? 'text-gray-400 italic' : 'text-gray-200'}`}>
{msg.role === 'assistant' ? (
- <MarkdownRenderer content={msg.content || (isStreamingB ? '...' : '')} />
+ <MarkdownRenderer content={cleanB.get(msg.id) || (isStreamingB ? '...' : '')} />
) : (
<p>{msg.content}</p>
)}
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 01d134dd..d985cc0d 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -22,68 +22,11 @@ import { SlashStepsBlock } from './SlashStepsBlock'
import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { checkGitInstalled, openExternal, type GitStatus } from '../../api/backend'
-import { extractToolCallsWithRanges, stripRanges } from '../../lib/tool-call-repair'
import { CodexConfirmDialog } from './CodexConfirmDialog'
+import { stripModelNoise } from '../../lib/strip-model-noise'
-function stripChannelTags(text: string): string {
- let t = text
- .replace(/<\|?channel>?\s*thought\s*/gi, '')
- .replace(/<\|?channel\|?>/gi, '')
- .replace(/<channel\|>/gi, '')
- // ChatML / special-token delimiters. A degenerating local model can spew its
- // own template tokens as content — qwen2.5-coder:14b emitted a burst of
- // <|im_start|> mid-stream 2026-06-02. <|im_start|>, <|im_end|>, <|endoftext|>,
- // <|assistant|> etc. are NEVER real answer text, so strip any <|word|> token.
- t = t.replace(/<\|[a-z0-9_]+\|>/gi, '')
- // Display safety net (David 2026-06-02): the user must only ever see real
- // prose answers + the rendered tool-call BLOCKS — never raw tool-call JSON,
- // hermes orchestration tags, or our own continue-nudge echoed back as prose.
- // The engine strips most of this upstream, but this guarantees a leak can
- // never surface in the chat regardless of which weak model is driving.
- //
- // 1) tool_call / tool_response / tool_result tags + their content. qwen2.5-
- // coder:7b (confirmed live 2026-06-02) HALLUCINATES hermes-style
- // <tool_response> Error: … </tool_response> blocks INTO its prose. Native
- // tool results are role:'tool' messages and never reach assistant content,
- // so anything matching these tags is noise meant only for the model.
- t = t.replace(/<tool_call>[\s\S]*?<\/tool_call>/gi, '').replace(/<\/?tool_call>/gi, '')
- t = t.replace(/<tool_response>[\s\S]*?<\/tool_response>/gi, '').replace(/<\/?tool_response>/gi, '')
- t = t.replace(/<tool_result>[\s\S]*?<\/tool_result>/gi, '').replace(/<\/?tool_result>/gi, '')
- // 1b) The same tag with its opening bracket already eaten. Captured off
- // the wire 2026-07-25: Qwen3-32B through LU Cloud sends
- // `</think>\n\nool_call>` as content next to a valid tool_calls array —
- // the PROVIDER's parser drops the `<t`, so a pattern anchored on `<`
- // cannot see the remainder. Line-anchored so prose is never touched.
- t = t.replace(/^[ \t]*<?[|/]*t?ool_(?:call|calls|response|result)s?[|/]*>[ \t]*$/gim, '')
- // 1c) The /loop control markers. They are protocol between the driver and
- // the model, not something the user needs to read.
- // The template asks for a reason after the marker, so drop the whole line
- // rather than leaving a dangling "(verified by …)".
- t = t.replace(/^[ \t]*LOOP_(?:DONE|CONTINUE)\b.*$/gm, '')
- // 2) The autonomous-continue NUDGE, if a weak model parrots it back as its
- // own answer (qwen2.5-coder:7b did this verbatim). It is OUR fixed
- // instruction from useCodex — strip from its opening clause ("…continue
- // working autonomously…") through the closing "finished and verified."
- // so the orchestration sentence never reads as a real LLM answer.
- t = t.replace(/(?:please wait[,;:]?\s*(?:while\s+)?i\s+(?:will\s+)?)?continue working autonomously[\s\S]*?finished and verified\.?/gi, '')
- // 3) Tool-call JSON the model emitted as CONTENT, PARSE-FREE. The structured
- // extractor below relies on JSON.parse via repairJson — which FAILS when
- // the model puts LITERAL newlines inside a string value (qwen2.5-coder:14b
- // emitted ```json {"name":"file_write","arguments":{"content":"line1<real
- // newline>line2"}}``` 2026-06-02), so that whole blob would leak as the
- // "answer". Strip it by pattern, no parsing:
- // (a) a fenced ```…``` block whose body is a "name"+"arguments" tool call.
- t = t.replace(/```[a-z]*\s*\n?\s*\{[\s\S]*?["']name["']\s*:[\s\S]*?["']arguments["']\s*:[\s\S]*?```/gi, '')
- // (b) an unfenced / truncated {"name":"…","arguments": … blob — strip from
- // the header to end of text (a tool-call dump is never real prose, and
- // a truncated one has no clean close for the brace-balancer to find).
- t = t.replace(/\{\s*["']?(?:name|tool|function)["']?\s*:\s*["'][a-z0-9_]+["']\s*,\s*["']?(?:arguments|args|parameters|input)["']?\s*:[\s\S]*$/i, '')
- try {
- const { ranges } = extractToolCallsWithRanges(t)
- if (ranges.length) t = stripRanges(t, ranges)
- } catch { /* ignore — never let a strip error hide the answer */ }
- return t.trim()
-}
+// Code always drives a tool loop, so the aggressive tier applies here.
+const stripChannelTags = (text: string) => stripModelNoise(text, { aggressive: true })
// Code-Mode renders EVERY between-tool answer as normal, always-visible prose
// now (David 2026-06-04: "kein Collapse, das soll ganz normal wie eine Antwort
@@ -310,7 +253,7 @@ export function CodexView() {
key={block.id}
className="px-2 py-1.5 rounded border border-gray-200 dark:border-white/10 bg-gray-50/60 dark:bg-white/[0.02] text-[0.7rem] text-gray-700 dark:text-gray-300"
>
- <MarkdownRenderer content={block.content} />
+ <MarkdownRenderer content={stripModelNoise(block.content)} />
</div>
))}
</div>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index d4e73814..0637e778 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -9,6 +9,7 @@ import { VramSwitchCard } from './VramSwitchCard'
import { SpeakerButton } from './SpeakerButton'
import { ChatArtifactCard } from './ChatArtifactCard'
import type { Message } from '../../types/chat'
+import { stripModelNoise } from '../../lib/strip-model-noise'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { useChatStore } from '../../stores/chatStore'
import { useModelStore } from '../../stores/modelStore'
@@ -80,6 +81,33 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
// banner can't flash mid-stream while a visible thinking phase runs.
const thoughtOnly = !isUser && !(message.content || '').trim() && !!(message.thinking || '').trim()
&& (!isLast || !!message.usage)
+
+ // Orchestration strip for everything this bubble renders (2.5.9). Memoised:
+ // the regex set is not cheap and a long agent chat re-renders these bubbles
+ // often. Aggressive tier only while a tool loop drives the turn — in plain
+ // chat a {"name": …, "arguments": …} block is often the answer itself.
+ // Signature, not the array itself: a streaming turn may grow a block's
+ // content in place, leaving the array reference identical. Keying on the
+ // total length re-runs the strip on every token while still skipping the
+ // work on unrelated re-renders.
+ const blockSig = (message.agentBlocks ?? []).reduce((n, b) => n + b.content.length, 0)
+ + ':' + (message.agentBlocks?.length ?? 0)
+ const cleanBlocks = useMemo(() => {
+ const map = new Map<string, string>()
+ for (const b of message.agentBlocks ?? []) {
+ if (b.phase === 'answer') map.set(b.id, stripModelNoise(b.content, { aggressive: true }))
+ }
+ return map
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [blockSig])
+ // Aggressive while a tool loop drives the turn, same as Code. In plain chat
+ // the gentle tier only, because a {"name": …, "arguments": …} block there can
+ // be exactly the answer the user asked the model to print.
+ const toolLoopDriven = isAgentActive || !!message.agentBlocks?.length
+ const cleanContent = useMemo(
+ () => (isUser ? '' : stripModelNoise(message.content || '', { aggressive: toolLoopDriven })),
+ [isUser, message.content, toolLoopDriven],
+ )
const thoughtOnlyToolIntent = useMemo(
() => thoughtOnly && !isAgentActive && !chatToolsEnabled && looksLikeToolIntent(message.thinking || ''),
[thoughtOnly, isAgentActive, chatToolsEnabled, message.thinking],
@@ -194,10 +222,14 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
return <ReflectionBlock key={block.id} content={block.content} />
}
if (block.phase === 'answer') {
+ // A block that was ONLY orchestration (a bare LOOP_DONE line,
+ // a stray ool_call>) renders nothing, not an empty bubble.
+ const clean = cleanBlocks.get(block.id) ?? ''
+ if (!clean) return null
return (
<div key={block.id} className="px-1 py-0.5">
<div className="text-[0.8rem] leading-relaxed">
- <MarkdownRenderer content={block.content} />
+ <MarkdownRenderer content={clean} />
</div>
</div>
)
@@ -275,13 +307,14 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
// a duplicate dump at the bottom. Falls back to message.content
// for legacy chats / non-agent messages without answer blocks.
(() => {
- const hasAnswerBlock = !!message.agentBlocks?.some(
- (b) => b.phase === 'answer' && b.content.trim(),
- )
+ // Judge "has a real answer block" on the STRIPPED text: a block
+ // holding nothing but a LOOP_DONE line must not suppress the
+ // fallback, or the turn renders blank.
+ const hasAnswerBlock = [...cleanBlocks.values()].some(Boolean)
if (hasAnswerBlock) return null
return (
<div className="text-[0.78rem] leading-relaxed">
- <MarkdownRenderer content={message.content} />
+ <MarkdownRenderer content={cleanContent} />
{thoughtOnly && (
thoughtOnlyToolIntent && activeModel && isAgentCompatible(activeModel) ? (
<div className="mt-1 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">
diff --git a/src/components/chat/ReflectionBlock.tsx b/src/components/chat/ReflectionBlock.tsx
index 5c69e513..f04a51c5 100644
--- a/src/components/chat/ReflectionBlock.tsx
+++ b/src/components/chat/ReflectionBlock.tsx
@@ -2,6 +2,7 @@ import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { ChevronDown, MessageSquare } from 'lucide-react'
import { MarkdownRenderer } from './MarkdownRenderer'
+import { stripModelNoise } from '../../lib/strip-model-noise'
interface Props {
content: string
@@ -18,7 +19,9 @@ interface Props {
*/
export function ReflectionBlock({ content }: Props) {
const [open, setOpen] = useState(false)
- const trimmed = content.trim()
+ // Strip orchestration BEFORE the guard and the preview headline, or a
+ // reflection that was only a stray tag still shows a header full of noise.
+ const trimmed = stripModelNoise(content || '')
if (!trimmed) return null
const firstLine = trimmed.split('\n', 1)[0]
diff --git a/src/components/chat/ThinkingBlock.tsx b/src/components/chat/ThinkingBlock.tsx
index dffa78db..829eb14b 100644
--- a/src/components/chat/ThinkingBlock.tsx
+++ b/src/components/chat/ThinkingBlock.tsx
@@ -1,7 +1,8 @@
-import { useState, useEffect } from 'react'
+import { useState, useEffect, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { ChevronDown, Brain } from 'lucide-react'
import { MarkdownRenderer } from './MarkdownRenderer'
+import { stripModelNoise } from '../../lib/strip-model-noise'
interface Props {
thinking: string
@@ -18,7 +19,13 @@ export function ThinkingBlock({ thinking, streaming }: Props) {
// When the turn ends, drop the manual override so the NEXT turn auto-expands.
useEffect(() => { if (!streaming) setUserToggled(null) }, [streaming])
- if (!thinking) return null
+ // Strip orchestration out of the reasoning too (2.5.9): Qwen3-32B writes
+ // its planned call as a raw <tool_call> tag inside the thought, and that
+ // call is already rendered properly as its own block right below. Guard on
+ // the CLEANED text so a thought that was nothing but a tag does not leave
+ // an empty "Thinking" header behind.
+ const cleaned = useMemo(() => stripModelNoise(thinking || ''), [thinking])
+ if (!cleaned) return null
return (
<div className="mb-0.5">
@@ -46,7 +53,7 @@ export function ThinkingBlock({ thinking, streaming }: Props) {
>
<div className="pl-4 pb-1 pt-0.5">
<div className="text-[0.65rem] leading-relaxed italic text-blue-200/40">
- <MarkdownRenderer content={thinking} />
+ <MarkdownRenderer content={cleaned} />
</div>
</div>
</motion.div>
diff --git a/src/lib/__tests__/strip-model-noise.test.ts b/src/lib/__tests__/strip-model-noise.test.ts
new file mode 100644
index 00000000..ea896625
--- /dev/null
+++ b/src/lib/__tests__/strip-model-noise.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect } from 'vitest'
+import { stripModelNoise } from '../strip-model-noise'
+
+describe('stripModelNoise', () => {
+ it('drops the truncated ool_call> line David saw twice', () => {
+ const wire = 'Here is the answer.\nool_call>\nMore prose.'
+ expect(stripModelNoise(wire)).toBe('Here is the answer.\n\nMore prose.')
+ })
+
+ it('drops a LOOP_DONE line with its trailing reason', () => {
+ const answer = 'README.md now documents greet.\nLOOP_DONE (verified by reading the file)'
+ expect(stripModelNoise(answer)).toBe('README.md now documents greet.')
+ })
+
+ it('drops LOOP_CONTINUE too', () => {
+ expect(stripModelNoise('Still working.\nLOOP_CONTINUE')).toBe('Still working.')
+ })
+
+ it('strips channel and ChatML tokens', () => {
+ expect(stripModelNoise('<|channel|>answer<|im_end|>')).toBe('answer')
+ })
+
+ it('strips hallucinated hermes tags with their content', () => {
+ const t = 'Reply.<tool_response>Error: nope</tool_response>'
+ expect(stripModelNoise(t)).toBe('Reply.')
+ })
+
+ it('leaves ordinary prose that merely mentions a marker word alone', () => {
+ const prose = 'The loop ends when the model writes LOOP_DONE at the end of a line.'
+ // Not line-anchored at the start, so the sentence survives intact.
+ expect(stripModelNoise(prose)).toBe(prose)
+ })
+
+ it('keeps legitimate tool-call JSON in plain chat (non aggressive)', () => {
+ const lesson = 'OpenAI expects:\n```json\n{"name": "get_weather", "arguments": {"city": "Berlin"}}\n```'
+ expect(stripModelNoise(lesson)).toContain('get_weather')
+ })
+
+ it('strips the same JSON when a tool loop is driving (aggressive)', () => {
+ const leak = '```json\n{"name": "file_write", "arguments": {"path": "a.js", "content": "x"}}\n```'
+ expect(stripModelNoise(leak, { aggressive: true })).toBe('')
+ })
+
+ // Captured verbatim off a live /loop turn on the 2.5.9 ship build. A loop
+ // answer routinely NAMES the tool that proved it, so neither tier may treat
+ // that sentence as a call and drop it. Pinned in both tiers because Agent and
+ // Code send the same text down different paths.
+ it.each([[{}], [{ aggressive: true }]])('keeps a real loop answer that names a tool in prose (%j)', (opts) => {
+ const real = 'There are 2 files in the current directory: `greet.js` and `README.md`.\n\nLOOP_DONE\nCheck: file_list confirmed 2 files in the folder.'
+ const out = stripModelNoise(real, opts)
+ expect(out).toContain('There are 2 files')
+ expect(out).toContain('Check: file_list confirmed 2 files')
+ expect(out).not.toContain('LOOP_DONE')
+ })
+
+ it('returns empty for a block that was nothing but orchestration', () => {
+ expect(stripModelNoise('LOOP_DONE')).toBe('')
+ expect(stripModelNoise('ool_call>')).toBe('')
+ })
+})
diff --git a/src/lib/strip-model-noise.ts b/src/lib/strip-model-noise.ts
new file mode 100644
index 00000000..b26dd235
--- /dev/null
+++ b/src/lib/strip-model-noise.ts
@@ -0,0 +1,81 @@
+/**
+ * Display safety net: the user must only ever see real prose answers plus the
+ * rendered tool-call BLOCKS, never raw orchestration.
+ *
+ * This lived inside CodexView until 2.5.9, which meant it protected the Code
+ * tab ONLY. Agent mode and plain chat render through MessageBubble and were
+ * getting the raw string — so the exact leak David reported twice
+ * (`ool_call>` from Qwen3-32B through LU Cloud) was still on screen after the
+ * "fix", because the fix was in the other view. Shared module now: one strip,
+ * every surface.
+ *
+ * Two tiers on purpose:
+ * - The default set removes text that is NEVER a legitimate answer.
+ * - `aggressive` additionally removes tool-call JSON dumps. That is right
+ * while a tool loop is driving (Code, Agent), but wrong in plain chat,
+ * where `{"name": …, "arguments": …}` can be exactly what the user asked
+ * the model to print.
+ */
+
+import { extractToolCallsWithRanges, stripRanges } from './tool-call-repair'
+
+export interface StripOptions {
+ /** Also strip tool-call JSON emitted as prose. On for Code + Agent. */
+ aggressive?: boolean
+}
+
+export function stripModelNoise(text: string, opts: StripOptions = {}): string {
+ let t = text
+ .replace(/<\|?channel>?\s*thought\s*/gi, '')
+ .replace(/<\|?channel\|?>/gi, '')
+ .replace(/<channel\|>/gi, '')
+ // ChatML / special-token delimiters. A degenerating local model can spew its
+ // own template tokens as content — qwen2.5-coder:14b emitted a burst of
+ // <|im_start|> mid-stream 2026-06-02. <|im_start|>, <|im_end|>, <|endoftext|>,
+ // <|assistant|> etc. are NEVER real answer text, so strip any <|word|> token.
+ t = t.replace(/<\|[a-z0-9_]+\|>/gi, '')
+ // tool_call / tool_response / tool_result tags + their content. qwen2.5-
+ // coder:7b (confirmed live 2026-06-02) HALLUCINATES hermes-style
+ // <tool_response> Error: … </tool_response> blocks INTO its prose. Native
+ // tool results are role:'tool' messages and never reach assistant content,
+ // so anything matching these tags is noise meant only for the model.
+ t = t.replace(/<tool_call>[\s\S]*?<\/tool_call>/gi, '').replace(/<\/?tool_call>/gi, '')
+ t = t.replace(/<tool_response>[\s\S]*?<\/tool_response>/gi, '').replace(/<\/?tool_response>/gi, '')
+ t = t.replace(/<tool_result>[\s\S]*?<\/tool_result>/gi, '').replace(/<\/?tool_result>/gi, '')
+ // The same tag with its opening bracket already eaten. Captured off the wire
+ // 2026-07-25: Qwen3-32B through LU Cloud sends `</think>\n\nool_call>` as
+ // content next to a valid tool_calls array — the PROVIDER's parser drops the
+ // `<t`, so a pattern anchored on `<` cannot see the remainder. Line-anchored
+ // so prose is never touched.
+ t = t.replace(/^[ \t]*<?[|/]*t?ool_(?:call|calls|response|result)s?[|/]*>[ \t]*$/gim, '')
+ // The /loop control markers. They are protocol between the driver and the
+ // model, not something the user needs to read. The template asks for a reason
+ // after the marker, so drop the whole line rather than leaving a dangling
+ // "(verified by …)".
+ t = t.replace(/^[ \t]*LOOP_(?:DONE|CONTINUE)\b.*$/gm, '')
+ // The autonomous-continue NUDGE, if a weak model parrots it back as its own
+ // answer (qwen2.5-coder:7b did this verbatim). It is OUR fixed instruction,
+ // so the orchestration sentence never reads as a real answer.
+ t = t.replace(/(?:please wait[,;:]?\s*(?:while\s+)?i\s+(?:will\s+)?)?continue working autonomously[\s\S]*?finished and verified\.?/gi, '')
+
+ if (opts.aggressive) {
+ // Tool-call JSON the model emitted as CONTENT, PARSE-FREE. The structured
+ // extractor relies on JSON.parse via repairJson — which FAILS when the
+ // model puts LITERAL newlines inside a string value (qwen2.5-coder:14b
+ // emitted ```json {"name":"file_write","arguments":{"content":"line1<real
+ // newline>line2"}}``` 2026-06-02), so that whole blob would leak as the
+ // "answer". Strip it by pattern, no parsing:
+ // (a) a fenced ```…``` block whose body is a "name"+"arguments" tool call.
+ t = t.replace(/```[a-z]*\s*\n?\s*\{[\s\S]*?["']name["']\s*:[\s\S]*?["']arguments["']\s*:[\s\S]*?```/gi, '')
+ // (b) an unfenced / truncated {"name":"…","arguments": … blob — strip from
+ // the header to end of text (a tool-call dump is never real prose, and
+ // a truncated one has no clean close for the brace-balancer to find).
+ t = t.replace(/\{\s*["']?(?:name|tool|function)["']?\s*:\s*["'][a-z0-9_]+["']\s*,\s*["']?(?:arguments|args|parameters|input)["']?\s*:[\s\S]*$/i, '')
+ try {
+ const { ranges } = extractToolCallsWithRanges(t)
+ if (ranges.length) t = stripRanges(t, ranges)
+ } catch { /* ignore — never let a strip error hide the answer */ }
+ }
+
+ return t.trim()
+}