diff --git a/packages/trae/README.md b/packages/trae/README.md
index 17a7c87..4720d5f 100644
--- a/packages/trae/README.md
+++ b/packages/trae/README.md
@@ -128,7 +128,16 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`:
- GLM also writes its own template, `namek
v` (a string kept as written, other
types read as JSON), and sometimes a whole call into a native call's
- name; both are read as the call.
+ name; both are read as the call. A name that holds the wrapper with
+ GLM's tags where its service stopped mid-call — `{"name":"bash",
+ "arguments":{"commandls` — is read too:
+ the tags are the service's own handoff, so what stands between them is
+ the model's text (a quote left unescaped read as the quote it is, a
+ comma inside a value kept, a field's closing tag ending the value before
+ it), and the fields the native call did carry are kept beside the ones
+ the name's own text fills in. A name whose tool the request doesn't
+ have, or one no field can be read from, goes on as written, as any other
+ unknown tool does.
- A block is read as models get it wrong too: every quote escaped
(`{\"name\":…}`), quotes or backslashes in a string left unescaped, an
opener with the name as an attribute (`` with
diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs
index 7010bae..d8b2916 100644
--- a/packages/trae/index.mjs
+++ b/packages/trae/index.mjs
@@ -1493,6 +1493,165 @@ function glmCall(s, tools = []) {
return { name, arguments: args }
}
+// Trae reads a model's call for it and hands a call it could not read on as
+// the native call: the wrapper the client's prompt asked for, with GLM's own
+// template tags where the model wrote them and a field's close left behind
+// (``{"name":"bash","arguments":{"commandls``).
+// The name then holds the call the model meant, and the call's own arguments
+// — where the model wrote them — hold the rest of it.
+const NAMECALL = /^\s*\{\s*"name"\s*:\s*"([^"\\]*)"\s*,\s*"(?:arguments|input|parameters)"\s*:\s*\{/
+// a wrapper the service put text in front of (`bash_abstract_command_0>{…}`):
+// the same shape, wherever it starts
+const NAMEHEAD = /\{\s*"name"\s*:\s*"([^"\\]*)"\s*,\s*"(?:arguments|input|parameters)"\s*:\s*\{/
+const NAMETAG = /<\/?arg_(?:key|value)\s*>/
+
+// nameCall is the call a name holds when it is one the model wrote there
+// ({name, arguments}), null when it isn't: a name without the wrapper, one
+// whose tool the request doesn't have, or one no field could be read from.
+// The wrapper and the tags are the service's own handoff, so what stands
+// between them is the model's text as it wrote it — a quote it left
+// unescaped is read as the quote it is, the way repairedJSON reads a file's
+// content. A value is JSON where the tool's schema says the field is no
+// string and the text is one; else the text, cut where the value was cut.
+function nameCall(s, tools = []) {
+ const text = String(s ?? "")
+ // a wrapper the service put text in front of (`bash_abstract_command_0>{…}`)
+ // is the call it holds, that text being no name the request has
+ const at = text.indexOf("{")
+ if (at < 0) return null
+ const m = NAMECALL.exec(text.slice(at))
+ if (!m) return null
+ const name = m[1]
+ const tool = tools.map((t) => t.function ?? t).find((t) => t?.name === name)
+ if (!tool) return null
+ const fields = nameFields(text.slice(at + m[0].length))
+ const args = {}
+ for (const [key, value] of fields) {
+ // a field the schema says is no string is its JSON where it is one (a
+ // number the model wrote, an object), else the text it is
+ if (tool.parameters?.properties?.[key]?.type !== "string") {
+ try {
+ args[key] = JSON.parse(value.trim())
+ continue
+ } catch {}
+ }
+ args[key] = value
+ }
+ return Object.keys(args).length ? { name, arguments: args } : null
+}
+
+// nameFields reads a wrapper's body as its fields: a key, then its value.
+// A tag stands where the service cut a colon or a quote, so a value ends at
+// the tag that ends it, at the next key, or at the structure that closes it
+// — and at a closing tag (``) whose name is a field's, because
+// what follows such a tag is the service's own text, not the model's.
+// What none of those reached is no field's text and is left out, so a call
+// cut in the middle keeps what it has.
+function nameFields(body) {
+ const out = []
+ let i = 0
+ for (let n = 0; n < 64 && i < body.length; n++) {
+ // between fields: blanks, a comma, or the tags that stand for either
+ i += (body.slice(i).match(/^[\s,]+|^<\/?[a-z_]+\s*>/) || [""])[0].length
+ if (body[i] !== '"') break
+ const key = nameString(body, i, () => true)
+ i = key.i
+ if (!key.text) break
+ const colon = body.slice(i).match(/^\s*:\s*/)
+ if (colon) i += colon[0].length
+ // a value the service cut at its tag: what stands after the tag is the
+ // model's text (limit55)
+ i += (body.slice(i).match(/^(?:<\/?[a-z_]+\s*>)+/) || [""])[0].length
+ let value
+ if (body[i] === '"') {
+ const v = nameString(body, i, (rest) => endsValue(rest))
+ value = v.text
+ i = v.i
+ if (!value && !v.closed) break // an open quote with nothing in it
+ } else {
+ const rest = body.slice(i)
+ const stop = valueEnd(rest)
+ value = rest.slice(0, stop).replace(/^[\s,:]+/, "")
+ // the field's own close: the structure that follows it, and a quote
+ // the service cut it at where an escape isn't what stands before it
+ value = value.replace(/[\s,}\]]+$/, "").replace(/(?)/.test(rest)) return true
+ return /^\s*"(?:[^"\\]|\\.)*"\s*(?::|<\/?[a-z_]+\s*>)/.test(rest)
+}
+
+// valueEnd is where an unquoted value runs out: the next key, a tag that
+// ends it, or the structure that closes the field. A comma inside it is the
+// model's own (sed -n 1,9p), so only a brace or a bracket closes a field.
+function valueEnd(rest) {
+ const stops = [
+ rest.search(/"(?:(?:[^"\\<>]*)"\s*(?::|,|\s*<\/?[a-z_]+\s*>)|[^"\\<>]*<\/?[a-z_]+\s*>)/),
+ rest.search(/<\/?[a-z_]+\s*>/),
+ rest.search(/[}\]]/),
+ ].filter((x) => x >= 0)
+ return stops.length ? Math.min(...stops) : rest.length
+}
+
+// nameString reads the string at s[i] === '"', its escapes kept as written.
+// ends says, for what follows a quote, whether that quote ended the string:
+// a quote the model left unescaped inside a value is escaped as read on.
+// `closed` is whether the model's own quote ended it, where the read ran
+// into a tag or the end of the text.
+function nameString(s, i, ends) {
+ i++ // the opening quote
+ let src = ""
+ while (i < s.length) {
+ const ch = s[i]
+ if (ch === "\\") {
+ src += s[i] + (s[i + 1] ?? "")
+ i += 2
+ continue
+ }
+ if (ch === "<") {
+ // a tag ends the run: the service cut the value at it, whether it is
+ // one of its own (``) or a field's (``),
+ // for neither is text the model wrote
+ if (/^<\/?[a-z_][\w-]*\s*>/.test(s.slice(i))) break
+ }
+ if (ch === '"') {
+ if (ends(s.slice(i + 1))) {
+ i++
+ return { text: decode(src), i, closed: true }
+ }
+ src += '\\"'
+ i++
+ continue
+ }
+ src += ch
+ i++
+ }
+ return { text: decode(src), i, closed: false }
+}
+
+// decode is a string's own source as the string: the escapes the model wrote
+// are the characters they stand for, a newline among them
+function decode(src) {
+ try {
+ return JSON.parse('"' + escapeRaw(src) + '"')
+ } catch {
+ return src
+ }
+}
+
// toolNamed is the request's own name for a tool a model named otherwise
// (Read for read, list-files for list_files); name itself when the request
// has none like it. A tool it has none of goes on as named: the agent tells
@@ -1684,12 +1843,21 @@ class NativeCalls {
}
take(tools = []) {
return this.calls.filter((c) => c.name).map(({ id, name, arguments: a }) => {
- // a name that holds the whole call, as JSON or in GLM's template:
- // that call, its arguments the name's when it gave none of its own
- const w = name.trimStart().startsWith("{") ? looseJSON(name) : name.includes("") ? glmCall(name, tools) : null
+ // a name that holds the whole call, as the client's wrapper or in
+ // GLM's template: that call, its arguments the name's when it gave
+ // none of its own. The wrapper is read as JSON where it is whole —
+ // its nesting is its own — and as the service's handoff where it was
+ // left mid-call, a wrapper written with a space (`{ "name"`) whole
+ // like any other
+ const w = name.trimStart().startsWith("{") ? looseJSON(name) ?? nameCall(name, tools)
+ : NAMEHEAD.test(name) ? nameCall(name, tools)
+ : name.includes("") ? glmCall(name, tools) : null
if (w?.name) {
name = String(w.name)
- if (!a || a.trim() === "{}") a = callArgs(w)
+ // the name's own arguments are the model's; what the name read fills
+ // the fields they left (the wrapper's text is the whole call where
+ // Trae moved the arguments with it, and the rest where it did not)
+ a = nameArgs(a, w)
}
const v = a && !done(a) ? looseJSON(a) : null
return { id: id || callId(), name, arguments: v ? JSON.stringify(v) : a || "{}" }
@@ -1697,6 +1865,25 @@ class NativeCalls {
}
}
+// nameArgs is the arguments of a call a name held: the native call's own
+// where it carried them, else the name's, and the two together where each
+// has a field the other hasn't — the service moves the arguments it read
+// into the native call and leaves the rest in the name. The name's side is
+// read the way main reads a whole name (`callArgs`: `arguments`, `input`,
+// `parameters`, arguments given as a string, or the flat fields), so what
+// main already read keeps reading the same. The two stand together only as
+// two sets of fields; a call's own arguments that are not that — text the
+// service cut, or a value that isn't a call's fields — go on as they stand,
+// which is what main passed on and what the agent can answer.
+function nameArgs(native, fromName) {
+ const a = typeof native === "string" ? native.trim() : ""
+ const named = callArgs(fromName)
+ if (!a || a === "{}") return named
+ const own = looseJSON(a), side = looseJSON(named)
+ if (!own || !side || typeof own !== "object" || typeof side !== "object" || Array.isArray(own) || Array.isArray(side)) return a
+ return JSON.stringify({ ...side, ...own })
+}
+
// resent says next is the call's whole arguments sent again after a
// partial snapshot, not a piece of them: Trae resends a snapshot whose
// punctuation isn't the first one's (− for -, ′ for '), so it doesn't
@@ -2496,4 +2683,4 @@ const makePlugin = (site) => async ({ client }) => {
export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"])
export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"])
-export const _internal = { traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID }
+export const _internal = { traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID }
diff --git a/packages/trae/namecall.test.mjs b/packages/trae/namecall.test.mjs
new file mode 100644
index 0000000..a514360
--- /dev/null
+++ b/packages/trae/namecall.test.mjs
@@ -0,0 +1,157 @@
+// Trae reads a model's call for it and hands what it could not read on as a
+// native call: the tool would be the JSON wrapper the prompt asked for, with
+// GLM's own / tags and the text where its service stopped.
+// The call is the client's, so it is read here rather than passed on as a
+// tool nobody declared (2026-10-13, trae-cn/glm-5.3 under a coding agent:
+// 28 of 54 calls, twelve steps in a row).
+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: "bash", parameters: { type: "object", properties: { command: { type: "string" }, description: { type: "string" }, workdir: { type: "string" } } } } },
+ { type: "function", function: { name: "read", parameters: { type: "object", properties: { file_path: { type: "string" }, limit: { type: "number" }, offset: { type: "number" } } } } },
+]
+
+// what a name the model wrote a call into reads as, through take()
+function read(name, args = "{}") {
+ const nc = new _internal.NativeCalls()
+ nc.push({ id: "c1", function: { name, arguments: args } })
+ return nc.take(TOOLS)[0]
+}
+
+test("a name holding the wrapper with GLM's tags is that call: the tags stand for the punctuation they replaced", () => {
+ const c = read('{"name":"bash","arguments":{"commandls -la')
+ expect([c.name, JSON.parse(c.arguments)]).toEqual(["bash", { command: "ls -la" }])
+})
+
+test("a value the service cut at its tag keeps the text it got, and the quotes the model didn't escape are read", () => {
+ const cut = read('{"name":"bash","arguments":{"command":"grep -n \\"x\\" a.ts | head -3')
+ expect(JSON.parse(cut.arguments)).toEqual({ command: 'grep -n "x" a.ts | head -3' })
+ const raw = read('{"name":"bash","arguments":{"command":"grep -n "x" a.ts; echo ---; grep -n "\'y\'" b.ts | head -5')
+ expect(JSON.parse(raw.arguments)).toEqual({ command: 'grep -n "x" a.ts; echo ---; grep -n "\'y\'" b.ts | head -5' })
+})
+
+test("the native call's own arguments are kept, and the fields the name carries are filled in beside them", () => {
+ const c = read('{"name":"bash","arguments":{"commandsed -n 1,9p a.ts', '{"description":"Read a.ts","workdir":"/tmp"}')
+ expect(JSON.parse(c.arguments)).toEqual({ command: "sed -n 1,9p a.ts", description: "Read a.ts", workdir: "/tmp" })
+})
+
+test("the whole call in the wrapper, its arguments closed by a quote the model left unescaped", () => {
+ const c = read('{"name":"bash","arguments":{"command":"grep -n "x" a.ts; echo ---; grep -n "\'y\'" b.ts | head -5","description":"Find x","workdir":"/repo"}}')
+ expect(JSON.parse(c.arguments)).toEqual({ command: 'grep -n "x" a.ts; echo ---; grep -n "\'y\'" b.ts | head -5', description: "Find x", workdir: "/repo" })
+})
+
+test("a field the schema says is no string is its JSON where the text is one, and its text where it isn't", () => {
+ const c = read('{"name":"read","arguments":{"file_path":"/a/b.ts","limit":55,"offset405"}}')
+ expect(JSON.parse(c.arguments)).toEqual({ file_path: "/a/b.ts", limit: 55, offset: 405 })
+ const cut = read('{"name":"read","arguments":{"file_path":"/a/b.ts","limit55')
+ expect(JSON.parse(cut.arguments)).toEqual({ file_path: "/a/b.ts", limit: 55 })
+})
+
+test("a field's closing tag ends the value before it, and the text after it is left out", () => {
+ // the service cut the value's quote and left the next field's name and
+ // close behind: what follows is its own text, not the model's, so the
+ // command goes out whole and the description is dropped
+ const c = read('bash_abstract_command_0>{"name":"bash","arguments":{"command":"cd /x && node scan.mjsRe-run scan', "{}")
+ expect(JSON.parse(c.arguments)).toEqual({ command: "cd /x && node scan.mjs" })
+})
+
+test("a comma inside a value is the model's own", () => {
+ const c = read('{"name":"bash","arguments":{"commandsed -n 1,9p a.ts', "{}")
+ expect(JSON.parse(c.arguments)).toEqual({ command: "sed -n 1,9p a.ts" })
+})
+
+test("a name in front of the wrapper is the name the service put there, not one the request has", () => {
+ const c = read('bash_abstract_command_0>{"name":"bash","arguments":{"command":"node scan.mjs')
+ expect([c.name, JSON.parse(c.arguments)]).toEqual(["bash", { command: "node scan.mjs" }])
+})
+
+test("a wrapper around a tool the request hasn't is left as written, for the agent to answer", () => {
+ const name = '{"name":"nope","arguments":{"commandls'
+ expect(read(name).name).toBe(name)
+})
+
+test("a wrapper no field can be read from is left as written, not guessed at", () => {
+ const name = '{"name":"bash","arguments":{'
+ expect(read(name).name).toBe(name)
+ // cut at a key, at a colon, at an open quote: nothing stands for a value
+ // there, and an empty call read out of one would be a call the model
+ // never wrote
+ for (const cut of ['{"name":"bash","arguments":{"command', '{"name":"bash","arguments":{"command":', '{"name":"bash","arguments":{"command":"']) {
+ expect([read(cut).name, read(cut).arguments]).toEqual([cut, "{}"])
+ }
+ // where the model's own quote closed the value, it is that value, empty
+ // as it stands
+ expect(read('{"name":"bash","arguments":{"command":"","description":"x"}}').arguments).toBe('{"command":"","description":"x"}')
+})
+
+test("a streamed call Trae could not read reaches the agent as the call, not as an unknown tool", async () => {
+ f = fakeTrae()
+ f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
+ ["output", { tool_calls: [{ id: "n1", function: { name: '{"name":"bash","arguments":{"commandgrep -n x a.ts', arguments: '{"description":"Find x"}' } }] }],
+ ["done", { finish_reason: "tool_calls" }],
+ ]))
+ const hooks = await TraeCNAuthPlugin({ client: {} })
+ const opts = await hooks.auth.loader(async () => signedIn())
+ const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "glm-5.3", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] }) })
+ const calls = (await res.text()).split("\n").filter((l) => l.startsWith("data: {")).map((l) => JSON.parse(l.slice(6))).filter((x) => x.choices?.length).flatMap((x) => x.choices[0].delta.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)])
+ expect(calls).toEqual([["bash", { command: "grep -n x a.ts", description: "Find x" }]])
+})
+
+// the shapes as they arrived, from the run this was found in (trae-cn/glm-5.3,
+// 2026-10-13): the fields each name carries, and the native call's own beside
+// them — the service moves the arguments it read and leaves the rest behind
+const REAL = [
+ ['{"name":"bash","arguments":{"commandgrep -n x a.ts', '{"description":"Find x"}', "bash", { command: "grep -n x a.ts", description: "Find x" }],
+ ['{"name":"read","arguments":{"file_path":"/a/b.ts","limit":55,"offset405"}}', "{}", "read", { file_path: "/a/b.ts", limit: 55, offset: 405 }],
+]
+
+test("the payloads themselves: every field each name carries is read, and the native call's own kept", () => {
+ for (const [name, args, tool, want] of REAL) {
+ const nc = new _internal.NativeCalls()
+ nc.push({ id: "c1", function: { name, arguments: args } })
+ const c = nc.take(TOOLS)[0]
+ expect([c.name, JSON.parse(c.arguments)]).toEqual([tool, want])
+ }
+})
+
+// what main already read of a whole name keeps reading the same: `input`,
+// `parameters`, arguments given as a string, the flat fields, and a wrapper
+// written with a space. The new reading is only for the name it could not
+// read before.
+test("a whole name main read keeps reading: input, parameters, a string, the flat fields, a space", () => {
+ expect(read('{"name":"bash","input":{"command":"ls"}}').arguments).toBe('{"command":"ls"}')
+ expect(read('{"name":"bash","parameters":{"command":"ls"}}').arguments).toBe('{"command":"ls"}')
+ expect(read('{"name":"bash","arguments":"{\\"command\\":\\"ls\\"}"}').arguments).toBe('{"command":"ls"}')
+ expect(read('{"name":"bash","command":"ls"}').arguments).toBe('{"command":"ls"}')
+ expect(read('{ "name": "bash", "arguments": { "command": "ls" } }').arguments).toBe('{"command":"ls"}')
+})
+
+// the native call's own arguments win where both have the field, and the
+// name's fill in what they left — whichever side of the wrapper they came
+// from
+test("a name's fields and the native call's own are merged with the native call's winning", () => {
+ const c = read('{"name":"bash","arguments":{"command":"ls","description":"from the name"}}', '{"command":"pwd","workdir":"/tmp"}')
+ expect(JSON.parse(c.arguments)).toEqual({ command: "pwd", description: "from the name", workdir: "/tmp" })
+})
+
+// a call's own arguments that don't read as a set of fields are the model's
+// text and go on as they stand, as main passed them: the agent can report
+// them or recover, where an empty call would run and do nothing
+test("a call's own arguments that aren't fields go on as they stand, not dropped for the name's side", () => {
+ expect(read('{"name":"bash"}', '{"command": "ls -la').arguments).toBe('{"command": "ls -la')
+ expect(read('{"name":"bash"}', "not json at all <<").arguments).toBe("not json at all <<")
+ expect(read('{"name":"bash","arguments":{}}', "command=ls").arguments).toBe("command=ls")
+})
+
+// and the same holds for a call's own arguments that read as JSON but are no
+// set of fields: a call's fields are the only thing the name's side joins
+test("a call's own arguments that aren't a set of fields are passed on, not merged into", () => {
+ expect(read('{"name":"bash","arguments":{"command":"ls"}}', "[1,2]").arguments).toBe("[1,2]")
+ expect(read('{"name":"bash","arguments":{"command":"ls"}}', '"ls -la"').arguments).toBe('"ls -la"')
+})