trae 0.2.19: Qwen's <function=…> and Anthropic's <function_calls><invoke> calls written as text are read as calls

01huadalang (magpie's Discord, trae 0.2.18, dsh, Kimi K3 and MiMo 2.6
Pro, sometimes): tool calls came back as the reply's text. The two
screenshots show the shapes:

  <function=compress><parameter=content>[{"endId": "m03680", …
  <function_calls><invoke name="mcp__magpie-image__generation_result">
  <parameter name="id">image-6636-24</parameter> </invoke> … </function_calls>

Root cause: TextTools only knew <tool_call> blocks (JSON, GLM's
arg_key/arg_value, name-attribute + <parameter>) and DeepSeek's DSML.
Neither shape opens with <tool_call>, so both went through as text; a
Qwen <function=…> inside <tool_call> lost the opener and leaked too.

- TextTools.xmlCall reads <function_calls> around one or more
  <invoke name="…"><parameter name="k">v</parameter></invoke> (each
  invoke a call; closes left off between invokes still split them), and
  Qwen's <function=name><parameter=k>v</parameter></function>, bare or
  in <tool_call>. Values go through paramArgs: text where the tool's
  schema says string, else JSON (compress's content array is an array).
- Only for a tool the request declared (toolNamed's match); an
  undeclared name, no tools at all, a tag in backticks or a code fence,
  or a tag with no parameter and no close stays text. This is stricter
  than <tool_call>, whose block is a call under any name: these tags
  are common in prose about the formats.
- Held back while streaming (MARKS, XML_HOLD), so a tag split across
  chunks never reaches the text; the closes and the wrapper are dropped
  as leftovers after a call. A parameter left open when the stream ends
  is cut short: the turn ends with the error plugins#38 gives, never text.
- README says so.

Sibling: qoder has its own Splitter that reads <function=…> only inside
<tool_call> and neither shape bare; not changed here, filed as
plugins#323. No other package parses text-written calls.

Run at this commit (base origin/main 1b06308), sandbox HOME/TMPDIR:
- packages/trae: bun test, 183 pass 0 fail (20 files; new
  xmlcall.test.mjs, 8 tests). Fixtures are the reporter's literal bytes:
  both samples whole and in pieces of 1/2/3/5/7/13/64, each split in two
  at every offset, sample 1 as shown (cut) and closed, a cut inside the
  second invoke, undeclared tools, prose/backticks/fence mentions, and
  sample 2 through the plugin over the fake Trae streamed and not
  (finish tool_calls, no text).
- bun scripts/check.mjs: 21 packages ok.
- Broken by hand, each red then restored: XML_AT never matching (6 of 8
  red), the declared-tool check removed (undeclared test red), the
  closes dropped from LEFTOVER (samples test red), XML_AT/XML_HOLD left
  out of the stream hold (5 of 8 red).

Not tried: a real Kimi K3 or MiMo 2.6 Pro turn on Trae; dsh's compress
tool schema wasn't found locally, so the test declares content as an
array (a string schema would keep it as text, as declared).
This commit is contained in:
yetone
2026-10-23 00:26:05 +08:00
parent 1b06308fad
commit 26e3e5f91a
4 changed files with 267 additions and 8 deletions
+8
View File
@@ -165,6 +165,14 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`:
or is cut short, is never sent on as the answer: the reply ends with an
error (a 502 without a stream), so the gateway can try again
(plugins#38). A `<tool_call>` in backticks or a code fence is text.
- Kimi and MiMo sometimes write a call in the tags they were trained on:
Qwen's `<function=name><parameter=k>v</parameter></function>` (bare or
inside `<tool_call>`), or Anthropic's `<function_calls>` around one or
more `<invoke name="…"><parameter name="k">v</parameter></invoke>`.
Each is read as a call, a parameter's value as JSON unless the tool's
schema says string, and one cut short is an error as above. These
tags are read only for a tool the request declared; for any other, or
in backticks or a code fence, they stay text.
- Calls from either source become OpenAI `tool_calls`. A name matching a
requested tool but for case or punctuation (`Read`) goes on as the
request's (`read`); any other goes on as written, so the agent can say
+101 -7
View File
@@ -1332,7 +1332,8 @@ class TextTools {
const r = this.buf.search(REASON_AT)
const sm = this.buf.match(STRAY_AT)
const s = sm ? sm.index : -1
if (s >= 0 && [i, d, r].every((x) => x < 0 || s < x)) {
const x = this.buf.search(XML_AT)
if (s >= 0 && [i, d, r, x].every((y) => y < 0 || s < y)) {
// a close with no call open, with what GLM left before it
// (}}</tool_call>, magpie#1945): not the answer, dropped; in code,
// shown
@@ -1351,7 +1352,7 @@ class TextTools {
this.after = true
continue
}
if (r >= 0 && (i < 0 || r < i) && (d < 0 || r < d)) {
if (r >= 0 && (i < 0 || r < i) && (d < 0 || r < d) && (x < 0 || r < x)) {
const o = objectEnd(this.buf, r)
if (o === -1 && !end) {
// not whole yet: held, the text before it sent
@@ -1371,7 +1372,39 @@ class TextTools {
this.buf = this.buf.slice(r + 1)
continue
}
if (i < 0 && d < 0) break
if (i < 0 && d < 0 && x < 0) break
if (x >= 0 && (i < 0 || x < i) && (d < 0 || x < d)) {
// Anthropic's <function_calls><invoke name="…"> or Qwen's
// <function=…>, as Kimi and MiMo write a call (01huadalang on
// magpie's Discord, dsh): a call only for a tool the request
// declared, and never in a code fence or backticks
const head = this.buf.slice(0, x)
const at = this.buf.slice(x)
const opener = at.match(/^<[^<>]*>?/)[0]
if (quoted(this.sent + text + head)) {
text += head + opener
this.buf = at.slice(opener.length)
continue
}
const b = this.xmlCall(at, end)
if (b.wait) break
if (b.text) {
text += head + opener
this.buf = at.slice(opener.length)
continue
}
text += head
if (b.error) {
this.buf = ""
this.sent += text
return { text, calls, reasoning, error: b.error }
}
calls.push(b.call)
this.mark = this.sent.length + text.length
this.buf = b.rest
this.after = true
continue
}
if (d >= 0 && (i < 0 || d < i)) {
text += this.buf.slice(0, d)
this.buf = this.buf.slice(d)
@@ -1462,7 +1495,7 @@ class TextTools {
this.buf = ""
} else {
// keep back an opened block, or what may be the start of one
const at = [this.buf.search(OPEN_AT), this.buf.search(OPEN_HOLD), this.buf.search(DSML_AT), this.buf.search(REASON_AT)].filter((x) => x >= 0)
const at = [this.buf.search(OPEN_AT), this.buf.search(OPEN_HOLD), this.buf.search(DSML_AT), this.buf.search(REASON_AT), this.buf.search(XML_AT), this.buf.search(XML_HOLD)].filter((x) => x >= 0)
let keep = at.length ? this.buf.length - Math.min(...at) : 0
if (!keep) for (let k = Math.min(MARK_MAX - 1, this.buf.length); k > 0; k--) if (MARKS.some((m) => m.startsWith(this.buf.slice(-k)))) { keep = k; break }
// and braces, brackets, quotes or a > a close may still come after
@@ -1475,6 +1508,60 @@ class TextTools {
return { text, calls, reasoning }
}
// xmlCall reads a call written in Anthropic's tags (<function_calls>
// around one or more <invoke name="…"><parameter name="k">v</parameter>
// </invoke>) or Qwen's (<function=…><parameter=k>v</parameter>
// </function>), s starting at its first tag: {call, rest}, {wait}
// while it may still become one, {text} when it is no call (a tool the
// request didn't declare, a tag named in prose), {error} for one cut
// short. Each invoke is a call of its own; the tags between them are
// dropped as the leftovers of one.
xmlCall(s, end) {
const w = s.match(/^<(?:antml:)?function_calls>/)
if (w) {
const rest = s.slice(w[0].length).replace(/^\s+/, "")
if (!end && (!rest || XML_STARTS.some((k) => k.startsWith(rest)))) return { wait: true }
return this.xmlInvoke(rest, end)
}
return this.xmlInvoke(s, end)
}
xmlInvoke(s, end) {
let m = s.match(/^<(?:antml:)?invoke\s+name\s*=\s*"([^"<>]+)"\s*>/)
let closeRe = /<\/(?:antml:)?invoke\s*>/
if (!m) {
m = s.match(/^<function=([^\s<>]+?)\s*>/)
closeRe = /<\/function\s*>/
}
if (!m) {
// an opener still being written
if (!end && (XML_STARTS.some((k) => k.startsWith(s)) || /^<(?:antml:)?(?:invoke\s|function=)[^<>]{0,300}$/.test(s))) return { wait: true }
return { text: true }
}
const declared = this.tools.map((t) => (t.function ?? t)?.name).filter(Boolean)
const name = toolNamed(m[1].trim(), this.tools)
if (!declared.includes(name)) return { text: true }
const body = s.slice(m[0].length)
const c = body.match(closeRe)
const n = body.search(XML_NEXT)
let stop = c ? c.index : -1
if (n >= 0 && (stop < 0 || n < stop)) stop = n
if (stop < 0) {
if (!end) return { wait: true }
stop = body.length
}
const whole = !!c && c.index === stop
const region = body.slice(0, stop).replace(/<(\/?)antml:parameter\b/g, "<$1parameter")
const p = paramArgs(region, name, this.tools)
if (!whole && !p.closed) {
// no parameter and no close: a tag named in passing; a parameter
// left open: the call cut short (plugins#38)
if (!/<parameter\b/.test(region)) return { text: true }
return { error: CUT_SHORT }
}
return { call: { name, arguments: JSON.stringify(p.args) }, rest: whole ? body.slice(stop + c[0].length) : body.slice(stop) }
}
// block reads what follows a <tool_call> opener: {call, rest} for a
// call, {wait} while it may still become one, {text} when it is no call
// at all, {error} for one that can't be read: cut short, or not JSON
@@ -1960,11 +2047,18 @@ const DSML_INVOKE = new RegExp(String.raw`^<\s*[||][\s||]*DSML[\s||]*invok
const DSML_INVOKE_AT = new RegExp(String.raw`<\s*[||][\s||]*DSML[\s||]*invoke\s+name\s*=`)
const DSML_CLOSE = new RegExp(String.raw`<\s*\/\s*[||][\s||]*DSML[\s||]*invoke\s*>`)
const DSML_PARAM = new RegExp(String.raw`<\s*[||][\s||]*DSML[\s||]*parameter\s+name\s*=\s*"([^"]+)"((?:\s+\w+\s*=\s*"[^"]*")*)\s*>([\s\S]*?)` + DSML + String.raw`parameter\s*>`, "g")
// Anthropic's and Qwen's call tags (xmlCall): where one starts, an
// opener still being written, the openers a wrapper is followed by, and
// the next call's opener
const XML_AT = /<(?:antml:)?(?:function_calls>|invoke\s+name\s*=|function=)/
const XML_HOLD = /<(?:antml:)?(?:invoke\s[^<>]{0,300}|function=[^<>]{0,300})$/
const XML_STARTS = ["<invoke ", "<antml:invoke ", "<function="]
const XML_NEXT = /<(?:antml:)?invoke\s+name\s*=|<function=/
// what is left after a call: blanks, our close, DeepSeek's tags but the
// next call's
const LEFTOVER = new RegExp(String.raw`^(?:\s+|<\/tool_?calls?>|<tool_?calls>|` + DSML + String.raw`(?![\s||]*invoke\b)[^<>]*>)+`)
// next call's, the closes of Anthropic's and Qwen's
const LEFTOVER = new RegExp(String.raw`^(?:\s+|<\/tool_?calls?>|<tool_?calls>|<\/(?:antml:)?(?:function_calls|invoke|function)>|` + DSML + String.raw`(?![\s||]*invoke\b)[^<>]*>)+`)
// what text may be the start of, so held back
const MARKS = [OPEN, CLOSE, "<toolcall>", "</toolcall>", "<|DSML|", "<|DSML|", "</|DSML|", "</|DSML|", '{"reasoning_content"']
const MARKS = [OPEN, CLOSE, "<toolcall>", "</toolcall>", "<|DSML|", "<|DSML|", "</|DSML|", "</|DSML|", '{"reasoning_content"', "<function_calls>", "</function_calls>", "<antml:function_calls>", "</antml:function_calls>", "<invoke ", "<antml:invoke ", "</invoke>", "</antml:invoke>", "<function=", "</function>"]
// reasoning a model wrote into its text as JSON
const REASON_AT = /\{\s*"reasoning_content"\s*:/
const MARK_MAX = Math.max(...MARKS.map((m) => m.length))
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-trae-auth",
"version": "0.2.18",
"version": "0.2.19",
"description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in",
"type": "module",
"main": "./index.mjs",
+157
View File
@@ -0,0 +1,157 @@
// Kimi K3 and MiMo 2.6 Pro on Trae, under dsh, sometimes write a call in
// the tags their training has: Qwen's <function=…><parameter=k>…, or
// Anthropic's <function_calls><invoke name="…">…. Neither was read, so the
// call went to the agent as its reply text (01huadalang on magpie's
// Discord, trae 0.2.18). The two samples are the reporter's screenshots,
// as transcribed; the first was cut by the screenshot, so it is read both
// as shown and closed.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { TraeCNAuthPlugin, _internal } from "./index.mjs"
import { fakeTrae, signedIn, sse } from "./fake.mjs"
let f
afterEach(() => f?.close())
const TOOLS = [
{ type: "function", function: { name: "compress", parameters: { type: "object", properties: { content: { type: "array", items: { type: "object" } } } } } },
{ type: "function", function: { name: "mcp__magpie-image__generation_result", parameters: { type: "object", properties: { id: { type: "string" } } } } },
{ type: "function", function: { name: "bash", parameters: { type: "object", properties: { command: { type: "string" } } } } },
]
// sample 1, as the screenshot shows it (cut there)
const S1_SHOWN = '<function=compress><parameter=content>[{"endId": "m03680", "endRef": "m03680", "startId": "m03485", "startRef": "m03485", "summary": "TASK AS OF THIS BLOCK(历史): ...'
// and as the model would have ended it
const S1 = S1_SHOWN + '"}]</parameter></function>'
const S1_ARGS = { content: [{ endId: "m03680", endRef: "m03680", startId: "m03485", startRef: "m03485", summary: "TASK AS OF THIS BLOCK(历史): ..." }] }
// sample 2, whole in its screenshot
const S2 =
'<function_calls><invoke name="mcp__magpie-image__generation_result"> <parameter name="id">image-6636-24</parameter> </invoke> <invoke name="mcp__magpie-image__generation_result"> <parameter name="id">image-6636-25</parameter> </invoke> <invoke name="mcp__magpie-image__generation_result"> <parameter name="id">image-6636-26</parameter> </invoke> </function_calls>'
const S2_CALLS = ["24", "25", "26"].map((n) => ["mcp__magpie-image__generation_result", { id: "image-6636-" + n }])
// what TextTools makes of the pieces, given in order, then the end
function readPieces(pieces, tools = TOOLS) {
const t = new _internal.TextTools(tools)
const out = { text: "", calls: [], error: null }
for (const [k, p] of [...pieces, ""].entries()) {
const r = t.push(p, k === pieces.length)
out.text += r.text
out.calls.push(...r.calls.map((c) => [c.name, JSON.parse(c.arguments)]))
if (r.error) {
out.error = r.error
break
}
}
return out
}
const read = (s, size = 0, tools = TOOLS) =>
readPieces(size ? Array.from({ length: Math.ceil(s.length / size) }, (_, k) => s.slice(k * size, (k + 1) * size)) : [s], tools)
// every split of s in two
const splits = (s) => Array.from({ length: s.length - 1 }, (_, k) => [s.slice(0, k + 1), s.slice(k + 1)])
test("the reporter's two replies are calls, whole and in pieces of every size", () => {
for (const size of [0, 1, 2, 3, 5, 7, 13, 64]) {
expect(read(S1, size)).toEqual({ text: "", calls: [["compress", S1_ARGS]], error: null })
expect(read(S2, size)).toEqual({ text: "", calls: S2_CALLS, error: null })
// with the text a model writes before them
expect(read("先压缩一下上下文。\n" + S1, size)).toEqual({ text: "先压缩一下上下文。\n", calls: [["compress", S1_ARGS]], error: null })
expect(read("取回三张图。\n" + S2 + "\n", size)).toEqual({ text: "取回三张图。\n", calls: S2_CALLS, error: null })
}
})
test("split in two at any point, each is still its calls and no tag reaches the text", () => {
for (const [a, b] of splits(S1)) expect(readPieces([a, b])).toEqual({ text: "", calls: [["compress", S1_ARGS]], error: null })
for (const [a, b] of splits(S2)) expect(readPieces([a, b])).toEqual({ text: "", calls: S2_CALLS, error: null })
})
test("a parameter's value is JSON where the tool's schema says array or object, its text where it says string", () => {
expect(read('<function=bash><parameter=command>[1, 2]</parameter></function>').calls).toEqual([["bash", { command: "[1, 2]" }]])
expect(read(S1).calls[0][1].content).toBeArray()
})
test("Qwen's form inside <tool_call>, and Anthropic's with the closes left off between invokes, are calls too", () => {
for (const size of [0, 1, 4]) {
expect(read("<tool_call>\n<function=bash>\n<parameter=command>\nls -la\n</parameter>\n</function>\n</tool_call>", size)).toEqual({ text: "", calls: [["bash", { command: "ls -la" }]], error: null })
expect(read('<function_calls>\n<invoke name="bash">\n<parameter name="command">ls</parameter>\n<invoke name="bash">\n<parameter name="command">pwd</parameter>\n</function_calls>', size)).toEqual({ text: "", calls: [["bash", { command: "ls" }], ["bash", { command: "pwd" }]], error: null })
}
})
test("a call the stream ends inside is cut short, never text: sample 1 as the screenshot shows it", () => {
for (const s of [S1_SHOWN, S2.slice(0, 95), '<function_calls><invoke name="bash"><parameter name="command">ls -']) {
for (const size of [0, 1, 6]) {
const r = read("Working.\n" + s, size)
expect(r.text).toBe("Working.\n")
expect(r.calls).toEqual([])
expect(r.error).toContain("cut short")
}
}
// cut inside the second invoke: the first is still a call, then the error
for (const size of [0, 1, 6]) {
const r = read(S2.slice(0, 200), size)
expect([r.text, r.calls]).toEqual(["", S2_CALLS.slice(0, 1)])
expect(r.error).toContain("cut short")
}
// its parameter closed, the close of the function left off: the call
expect(read(S1_SHOWN + '"}]</parameter>')).toEqual({ text: "", calls: [["compress", S1_ARGS]], error: null })
})
test("a tool the request didn't declare is no call: the text stays as written", () => {
const s = '<function_calls><invoke name="delete_everything"><parameter name="path">/</parameter></invoke></function_calls>'
for (const size of [0, 1, 5]) {
expect(read(s, size)).toEqual({ text: s, calls: [], error: null })
expect(read("<function=nope><parameter=x>1</parameter></function>", size)).toEqual({ text: "<function=nope><parameter=x>1</parameter></function>", calls: [], error: null })
// no tools declared at all
expect(read(S2, size, [])).toEqual({ text: S2, calls: [], error: null })
}
})
test("prose about <function_calls> stays text: in a sentence, in backticks, in a code fence", () => {
for (const s of [
"Claude wraps its calls in <function_calls> tags; each one is an <invoke> block.",
"Use `<function_calls><invoke name=\"bash\"><parameter name=\"command\">ls</parameter></invoke></function_calls>` to call it.",
'Example:\n```xml\n<function_calls>\n<invoke name="bash">\n<parameter name="command">ls</parameter>\n</invoke>\n</function_calls>\n```\nThat is the format.',
"Qwen writes `<function=bash>` and then its parameters.",
'The <invoke name="bash"> tag names a tool, and the call ends later.',
"a < b and c > d, <function_calls without a close",
]) {
for (const size of [0, 1, 3, 8]) expect(read(s, size)).toEqual({ text: s, calls: [], error: null })
}
})
async function ask(body, auth = signedIn()) {
const hooks = await TraeCNAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => auth)
return opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) })
}
async function chunks(res) {
const out = []
for (const line of (await res.text()).split("\n")) {
if (!line.startsWith("data: ")) continue
const d = line.slice(6)
out.push(d === "[DONE]" ? d : JSON.parse(d))
}
return out
}
const deltasOf = (c) => c.filter((x) => x !== "[DONE]" && x.choices?.length).map((x) => x.choices[0].delta)
test("through the plugin, streamed and not: sample 2's three calls, finished as tool calls", async () => {
f = fakeTrae()
const cut = [17, 60, 61, 140, 250, 300]
const pieces = cut.map((c, k) => S2.slice(k ? cut[k - 1] : 0, c)).concat(S2.slice(cut.at(-1)))
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([...pieces.map((p) => ["output", { response: p }]), ["done", { finish_reason: "stop" }]]))
const body = { model: "kimi-k3", tools: TOOLS, messages: [{ role: "user", content: "hi" }] }
const c = await chunks(await ask({ ...body, stream: true }))
const d = deltasOf(c)
expect(d.map((x) => x.content ?? "").join("")).toBe("")
expect(d.flatMap((x) => x.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)])).toEqual(S2_CALLS)
expect(c.filter((x) => x !== "[DONE]" && x.choices?.[0]?.finish_reason).map((x) => x.choices[0].finish_reason)).toEqual(["tool_calls"])
const res = await ask(body)
expect(res.status).toBe(200)
const m = (await res.json()).choices[0]
expect(m.message.content ?? "").toBe("")
expect(m.message.tool_calls.map((t) => [t.function.name, JSON.parse(t.function.arguments)])).toEqual(S2_CALLS)
expect(m.finish_reason).toBe("tool_calls")
})