From 26e3e5f91a9e5fcb0ade29341b189ae2febf05ce Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 23 Oct 2026 00:26:05 +0800 Subject: [PATCH] =?UTF-8?q?trae=200.2.19:=20Qwen's=20=20and=20Anthropic's=20=20calls=20wr?= =?UTF-8?q?itten=20as=20text=20are=20read=20as=20calls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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: [{"endId": "m03680", … image-6636-24 … Root cause: TextTools only knew blocks (JSON, GLM's arg_key/arg_value, name-attribute + ) and DeepSeek's DSML. Neither shape opens with , so both went through as text; a Qwen inside lost the opener and leaked too. - TextTools.xmlCall reads around one or more v (each invoke a call; closes left off between invokes still split them), and Qwen's v, bare or in . 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 , 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 only inside 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). --- packages/trae/README.md | 8 ++ packages/trae/index.mjs | 108 +++++++++++++++++++++-- packages/trae/package.json | 2 +- packages/trae/xmlcall.test.mjs | 157 +++++++++++++++++++++++++++++++++ 4 files changed, 267 insertions(+), 8 deletions(-) create mode 100644 packages/trae/xmlcall.test.mjs diff --git a/packages/trae/README.md b/packages/trae/README.md index 5f04870..c0bd36d 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -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 `` in backticks or a code fence is text. + - Kimi and MiMo sometimes write a call in the tags they were trained on: + Qwen's `v` (bare or + inside ``), or Anthropic's `` around one or + more `v`. + 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 diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index b08be21..7737888 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -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 // (}}, 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 or Qwen's + // , 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 ( + // around one or more v + // ) or Qwen's (v + // ), 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(/^]+?)\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 (!/ 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 = ["", "", "<|DSML|", "<|DSML|", "", "", "<|DSML|", "<|DSML|", "", "", "", "", "", "", ""] // 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)) diff --git a/packages/trae/package.json b/packages/trae/package.json index 96c852d..9545564 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -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", diff --git a/packages/trae/xmlcall.test.mjs b/packages/trae/xmlcall.test.mjs new file mode 100644 index 0000000..6320d62 --- /dev/null +++ b/packages/trae/xmlcall.test.mjs @@ -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 …, or +// Anthropic's …. 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 = '[{"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 + '"}]' +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 = + ' image-6636-24 image-6636-25 image-6636-26 ' +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('[1, 2]').calls).toEqual([["bash", { command: "[1, 2]" }]]) + expect(read(S1).calls[0][1].content).toBeArray() +}) + +test("Qwen's form inside , and Anthropic's with the closes left off between invokes, are calls too", () => { + for (const size of [0, 1, 4]) { + expect(read("\n\n\nls -la\n\n\n", size)).toEqual({ text: "", calls: [["bash", { command: "ls -la" }]], error: null }) + expect(read('\n\nls\n\npwd\n', 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), '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 + '"}]')).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 = '/' + for (const size of [0, 1, 5]) { + expect(read(s, size)).toEqual({ text: s, calls: [], error: null }) + expect(read("1", size)).toEqual({ text: "1", calls: [], error: null }) + // no tools declared at all + expect(read(S2, size, [])).toEqual({ text: S2, calls: [], error: null }) + } +}) + +test("prose about stays text: in a sentence, in backticks, in a code fence", () => { + for (const s of [ + "Claude wraps its calls in tags; each one is an block.", + "Use `ls` to call it.", + 'Example:\n```xml\n\n\nls\n\n\n```\nThat is the format.', + "Qwen writes `` and then its parameters.", + 'The tag names a tool, and the call ends later.', + "a < b and c > d, 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") +})