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(agent): calls in Qwen's XML form and calls stranded in the reasoning channel run (C59 A3)

purplef25c3db8b23d
diff --git a/src/api/hermes-tool-calling.ts b/src/api/hermes-tool-calling.ts
index f167599e..7d71b905 100644
--- a/src/api/hermes-tool-calling.ts
+++ b/src/api/hermes-tool-calling.ts
@@ -143,6 +143,43 @@ export interface ParsedToolCall {
* Looks for <tool_call>...</tool_call> XML tags containing JSON.
* Returns array of parsed tool calls (can be 0 or more).
*/
+/**
+ * The XML call format of Qwen3-Coder and Qwen3.5 templates (C59 A3):
+ *
+ * <function=file_read>
+ * <parameter=path>
+ * notes.txt
+ * </parameter>
+ * </function>
+ *
+ * usually inside <tool_call>…</tool_call>, sometimes without it. A server whose
+ * parser does not know the format (llama.cpp issues #20260/#20837, Ollama
+ * #14745) hands it through as plain text, and the run stopped on it. A value
+ * that reads as JSON (number, true/false, object, array) is taken as that,
+ * everything else as the string between the tags, trimmed of the one newline
+ * the template puts on each side.
+ */
+const FUNCTION_XML = /<function=([A-Za-z0-9_.:-]+)>\s*([\s\S]*?)\s*<\/function>/g
+const PARAMETER_XML = /<parameter=([A-Za-z0-9_.-]+)>\n?([\s\S]*?)\n?<\/parameter>/g
+
+export function parseFunctionXmlCalls(text: string): ParsedToolCall[] {
+ const calls: ParsedToolCall[] = []
+ for (const m of text.matchAll(FUNCTION_XML)) {
+ const args: ToolArgs = {}
+ for (const p of m[2].matchAll(PARAMETER_XML)) {
+ const raw = p[2]
+ const trimmed = raw.trim()
+ let value: unknown = raw
+ if (/^(-?\d+(\.\d+)?|true|false|null)$/.test(trimmed) || /^[[{]/.test(trimmed)) {
+ try { value = JSON.parse(trimmed) } catch { value = raw }
+ }
+ args[p[1]] = value as ToolArgs[string]
+ }
+ calls.push({ name: m[1], arguments: args })
+ }
+ return calls
+}
+
export function parseHermesToolCalls(output: string): ParsedToolCall[] {
const calls: ParsedToolCall[] = []
@@ -152,6 +189,11 @@ export function parseHermesToolCalls(output: string): ParsedToolCall[] {
while ((match = regex.exec(output)) !== null) {
const jsonStr = match[1].trim()
+ // Qwen's XML form inside the wrapper (see parseFunctionXmlCalls).
+ if (/^<function=/.test(jsonStr)) {
+ calls.push(...parseFunctionXmlCalls(jsonStr))
+ continue
+ }
// Try direct parse, then repair
const parsed = repairJson(jsonStr)
if (parsed && parsed.name) {
@@ -173,6 +215,8 @@ export function parseHermesToolCalls(output: string): ParsedToolCall[] {
}
}
}
+ // The same XML form without the <tool_call> wrapper.
+ if (!calls.length && output.includes('<function=')) calls.push(...parseFunctionXmlCalls(output))
return calls
}
@@ -183,6 +227,7 @@ export function parseHermesToolCalls(output: string): ParsedToolCall[] {
export function stripToolCallTags(output: string): string {
return output
.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '')
+ .replace(/<function=[A-Za-z0-9_.:-]+>[\s\S]*?<\/function>/g, '')
.replace(/<tool_response>[\s\S]*?<\/tool_response>/g, '')
.trim()
}
diff --git a/src/hooks/codex/tool-call-recovery.ts b/src/hooks/codex/tool-call-recovery.ts
index aef6dcb6..c35f8398 100644
--- a/src/hooks/codex/tool-call-recovery.ts
+++ b/src/hooks/codex/tool-call-recovery.ts
@@ -1,4 +1,5 @@
import { extractToolCallsWithRanges, stripRanges } from '../../lib/tool-call-repair'
+import { toolCallsFromReasoning } from '../../lib/loose-tool-parse'
import type { ToolCall } from '../../api/providers/types'
/**
@@ -111,3 +112,18 @@ export function recoverKnownToolCallsFromContent(
})
return allKnown ? recovered : { toolCalls, content, extractedFromContent: false }
}
+
+/**
+ * C59 A3: the calls of a turn that sat in the reasoning channel while the
+ * answer stayed empty (lib/loose-tool-parse.ts, toolCallsFromReasoning).
+ * Unchanged when there is an answer or a call already.
+ */
+export function recoverToolCallsFromReasoning(
+ toolCalls: ToolCall[],
+ content: string,
+ thinking: string | undefined,
+ known: readonly string[],
+): ToolCall[] {
+ const lifted = toolCallsFromReasoning(thinking ?? '', content, toolCalls.length, known)
+ return lifted.length ? lifted.map((c) => ({ function: { name: c.name, arguments: c.arguments } })) : toolCalls
+}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6744b8dc..61223199 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -48,7 +48,7 @@ import { stripVisionFeedbackMessages, reportMultimodalRefusal } from '../lib/vis
import { log } from '../lib/logger'
import { gatePlanTool, planToolAllowed } from '../lib/plan-gate'
import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
-import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, repairToolCall } from '../lib/loose-tool-parse'
+import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, repairToolCall, toolCallsFromReasoning } from '../lib/loose-tool-parse'
import { isMediaTool, mediaCallSucceeded } from '../lib/media-result'
import { mediaTurnCaps, droppedMediaNote } from '../lib/media-turn-caps'
import { isLocalModelByName } from '../api/agents/model-locality'
@@ -2449,6 +2449,16 @@ export function useAgentChat() {
}
}
+ // C59 A3: the calls sat in the reasoning channel and the answer is
+ // empty (a server that took the model for a thinking model).
+ {
+ const fromReasoning = toolCallsFromReasoning(turnThinking, turnContent, toolCalls.length, [...knownToolNames, ...(compactRun ? [TOOL_SEARCH] : [])])
+ if (fromReasoning.length) {
+ toolCalls = fromReasoning.map((c) => ({ function: { name: c.name, arguments: c.arguments } }))
+ log.info('agent.reasoning_tool_call_recovered', { count: toolCalls.length, names: toolCalls.map((t) => t.function.name) })
+ }
+ }
+
// Clean any tool-call text the model echoed into its prose (the owner
// 2026-06-04) — raw JSON like {"name":"image_generate",…} was leaking
// into the chat as a "notes"/JSON block. Runs even when a proper native
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 1b8da8a6..58c002d2 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -118,7 +118,7 @@ import { createLivePaint } from './codex/live-paint'
import { seedEstimatedUsage, reportTurnUsage } from './codex/turn-usage'
import { lastRequestUsageNotice, requestUsageTracker } from '../lib/request-usage'
import { shouldDowngradeThinking, engineDeniedThinking } from './codex/thinking-downgrade'
-import { recoverToolCallsFromContent, recoverKnownToolCallsFromContent } from './codex/tool-call-recovery'
+import { recoverToolCallsFromContent, recoverKnownToolCallsFromContent, recoverToolCallsFromReasoning } from './codex/tool-call-recovery'
import { codexStallVerdict } from './codex/stall-verdict'
import { createStagedWriter } from './codex/staged-writes'
import { codexCutoffNote, dropCutOffCall } from './codex/turn-cutoff'
@@ -136,6 +136,11 @@ function isCodexTool(name: string, args: Record<string, unknown>): boolean {
return tools.some((t) => t.name === repaired)
}
+/** Every name a call lifted out of the reasoning channel may carry (C59 A3). */
+function codexKnownNames(): string[] {
+ return [...toolRegistry.getAll().map((t) => t.name), TOOL_SEARCH]
+}
+
// Why a run ended, or was pushed on, belongs in the support log. This used to
// be a no-op, and a run that never finished its task left nothing to read on
// the user's machine: which guard ended each run was unknowable. The run-shaping tags go out as warn,
@@ -1740,6 +1745,7 @@ export function useCodex() {
const recovered = recoverToolCallsFromContent(toolCalls, turnContent)
toolCalls = recovered.toolCalls
turnContent = recovered.content
+ toolCalls = recoverToolCallsFromReasoning(toolCalls, turnContent, turn.thinking, codexKnownNames())
}
} else {
// ── Streaming path for OpenAI-compat / Anthropic / LU Cloud ──
@@ -1786,6 +1792,7 @@ export function useCodex() {
const recovered = recoverKnownToolCallsFromContent(toolCalls, turnContent, isCodexTool)
toolCalls = recovered.toolCalls
turnContent = recovered.content
+ toolCalls = recoverToolCallsFromReasoning(toolCalls, turnContent, turn.thinking, codexKnownNames())
}
if (keepThinking && turn.thinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinking
diff --git a/src/lib/__tests__/tool-call-hardening.test.ts b/src/lib/__tests__/tool-call-hardening.test.ts
new file mode 100644
index 00000000..5a6ba536
--- /dev/null
+++ b/src/lib/__tests__/tool-call-hardening.test.ts
@@ -0,0 +1,87 @@
+/**
+ * C59 A3: two ways a local model's call got lost on the way.
+ *
+ * 1. Qwen3-Coder / Qwen3.5 templates write calls as XML
+ * (<function=name><parameter=k>v</parameter></function>). A server whose
+ * parser does not know the form hands it through as text.
+ * 2. A server that takes the model for a thinking model puts the call into the
+ * reasoning channel, and the answer stays empty (llama.cpp #20809).
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { parseFunctionXmlCalls, parseHermesToolCalls, stripToolCallTags } from '../../api/hermes-tool-calling'
+import { parseLooseToolCalls, toolCallsFromReasoning } from '../loose-tool-parse'
+import { recoverToolCallsFromReasoning } from '../../hooks/codex/tool-call-recovery'
+
+const QWEN_XML = `<tool_call>
+<function=file_write>
+<parameter=path>
+summary.md
+</parameter>
+<parameter=content>
+- Dach neu decken
+- Heizung warten
+</parameter>
+</function>
+</tool_call>`
+
+describe("Qwen's XML call form", () => {
+ it('becomes a call with its arguments, multi-line values kept', () => {
+ expect(parseHermesToolCalls(QWEN_XML)).toEqual([
+ { name: 'file_write', arguments: { path: 'summary.md', content: '- Dach neu decken\n- Heizung warten' } },
+ ])
+ })
+
+ it('works without the <tool_call> wrapper and reads JSON-looking values as JSON', () => {
+ const text = '<function=file_read>\n<parameter=path>\nbig.txt\n</parameter>\n<parameter=offset>\n1200\n</parameter>\n</function>'
+ expect(parseHermesToolCalls(text)).toEqual([{ name: 'file_read', arguments: { path: 'big.txt', offset: 1200 } }])
+ expect(parseFunctionXmlCalls('<function=f><parameter=x>\n{"a":1}\n</parameter></function>')[0].arguments).toEqual({ x: { a: 1 } })
+ })
+
+ it('the loose parser lifts it out of prose, for known names only', () => {
+ const prose = `Ich schreibe die Datei.\n${QWEN_XML}`
+ expect(parseLooseToolCalls(prose, ['file_write']).calls.map((c) => c.name)).toEqual(['file_write'])
+ expect(parseLooseToolCalls(prose, ['file_read']).calls).toEqual([])
+ })
+
+ it('is stripped from the visible text', () => {
+ expect(stripToolCallTags(`Okay.\n<function=a>\n<parameter=b>\nc\n</parameter>\n</function>`).trim()).toBe('Okay.')
+ })
+
+ it('JSON inside <tool_call> still parses as before', () => {
+ expect(parseHermesToolCalls('<tool_call>{"name":"file_list","arguments":{"path":"."}}</tool_call>'))
+ .toEqual([{ name: 'file_list', arguments: { path: '.' } }])
+ })
+})
+
+describe('a call stranded in the reasoning channel', () => {
+ const thinking = `The user wants a summary. I will read the file.\n<tool_call>\n{"name": "file_read", "arguments": {"path": "notes.txt"}}\n</tool_call>`
+
+ it('is lifted when the turn has no call and no answer', () => {
+ expect(toolCallsFromReasoning(thinking, '', 0, ['file_read'])).toEqual([{ name: 'file_read', arguments: { path: 'notes.txt' } }])
+ })
+
+ it('stays where it is when the turn answered or called something', () => {
+ expect(toolCallsFromReasoning(thinking, 'Here is the summary.', 0, ['file_read'])).toEqual([])
+ expect(toolCallsFromReasoning(thinking, '', 1, ['file_read'])).toEqual([])
+ })
+
+ it('never reads prose or unknown names as a call', () => {
+ expect(toolCallsFromReasoning('Maybe I should call file_read(path="x") first.', '', 0, ['file_read'])).toEqual([])
+ expect(toolCallsFromReasoning(thinking, '', 0, ['file_write'])).toEqual([])
+ })
+
+ it('the Code tab uses the same rule', () => {
+ expect(recoverToolCallsFromReasoning([], '', thinking, ['file_read']))
+ .toEqual([{ function: { name: 'file_read', arguments: { path: 'notes.txt' } } }])
+ const native = [{ function: { name: 'file_list', arguments: { path: '.' } } }]
+ expect(recoverToolCallsFromReasoning(native, '', thinking, ['file_read'])).toBe(native)
+ })
+
+ it('both loops call it', () => {
+ const src = (p: string) => readFileSync(resolve(__dirname, '..', '..', p), 'utf8')
+ expect(src('hooks/useAgentChat.ts')).toMatch(/toolCallsFromReasoning\(turnThinking, turnContent, toolCalls\.length/)
+ expect(src('hooks/useCodex.ts').match(/recoverToolCallsFromReasoning\(toolCalls, turnContent, turn\.thinking/g)?.length).toBe(2)
+ })
+})
diff --git a/src/lib/loose-tool-parse.ts b/src/lib/loose-tool-parse.ts
index b8d1d2df..97b58f96 100644
--- a/src/lib/loose-tool-parse.ts
+++ b/src/lib/loose-tool-parse.ts
@@ -413,3 +413,31 @@ export function stripToolCallText(text: string, known: string[]): string {
.replace(/\n{3,}/g, '\n\n')
.trim()
}
+
+/**
+ * Calls that landed in the reasoning channel instead of the answer (C59 A3).
+ *
+ * A server that takes a model for a thinking model puts everything up to the
+ * end of the turn into `reasoning_content`, the calls included (llama.cpp
+ * #20809, Qwen3-2507; the same seen with Qwen3.5 templates). The turn then
+ * reads as "thought, said nothing, called nothing" and the run ended or got
+ * a continue steer the model could not act on.
+ *
+ * Deliberately narrow, because reasoning is where a model THINKS about calls
+ * it may not make: only when the turn has no call and no answer at all, only
+ * the structured forms (a <tool_call> block or Qwen's <function=…> XML), never
+ * the prose `name(arg=…)` form, and only names the run knows.
+ */
+export function toolCallsFromReasoning(
+ thinking: string,
+ answer: string,
+ existingCalls: number,
+ known: readonly string[],
+): LooseToolCall[] {
+ if (existingCalls > 0 || answer.trim() || !thinking) return []
+ if (!/<tool_call>|<function=/.test(thinking)) return []
+ const calls = parseHermesToolCalls(thinking)
+ return calls
+ .filter((c) => known.includes(c.name))
+ .map((c) => ({ name: c.name, arguments: (isRecord(c.arguments) ? c.arguments : {}) as Record<string, unknown> }))
+}