diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index c50fc90..fb7a925 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -1022,6 +1022,7 @@ class TextTools { this.tools = tools this.sent = "" // the text given out so far, to tell a block in code from a call this.bad = new Set() // where the waiting block's JSON was tried and not read, not tried again + this.mark = 0 // where in sent the text after the last call starts } push(s, end = false) { this.buf += s @@ -1044,6 +1045,27 @@ class TextTools { const i = om ? om.index : -1 const d = this.buf.search(DSML_AT) 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)) { + // a close with no call open, with what GLM left before it + // (}}, magpie#1945): not the answer, dropped; in code, + // shown + const head = this.buf.slice(0, s) + // only a tail: a close with nothing before it since the last call + // (or the start), or with GLM's braces, quotes or > right before + // it; a close a sentence names in passing stays + const tail = /^[}\]"'>]/.test(sm[0]) || !(this.sent + text + head).slice(this.mark).trim() + if (!tail || quoted(this.sent + text + head)) { + text += this.buf.slice(0, s + sm[0].length) + this.buf = this.buf.slice(s + sm[0].length) + continue + } + text += head + this.buf = this.buf.slice(s + sm[0].length) + this.after = true + continue + } if (r >= 0 && (i < 0 || r < i) && (d < 0 || r < d)) { const o = objectEnd(this.buf, r) if (o === -1 && !end) { @@ -1095,6 +1117,7 @@ class TextTools { stop = body.length } calls.push({ name: inv[1], arguments: dsmlArgs(body.slice(0, stop)) }) + this.mark = this.sent.length + text.length this.buf = body.slice(c && c.index === stop ? stop + c[0].length : stop) this.after = true continue @@ -1136,6 +1159,7 @@ class TextTools { 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 } @@ -1156,6 +1180,9 @@ class TextTools { 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) 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 + const sh = this.buf.slice(0, this.buf.length - keep).match(STRAY_HOLD) + if (sh) keep = this.buf.length - sh.index text += this.buf.slice(0, this.buf.length - keep) this.buf = this.buf.slice(this.buf.length - keep) } @@ -1205,8 +1232,27 @@ class TextTools { const v = callJSON(body.slice(0, o)) // a name alone may have its parameters still to come if (v && !end && Object.keys(v).length === 1 && "?\s*/, ""))) return { wait: true } - if (v) return { call: { name: String(v.name), arguments: callArgs(v) }, rest: body.slice(o) } - this.bad.add(":" + o) + if (v) { + // what follows the object up to the close: GLM leaves braces, + // brackets, quotes or a > of its own there (}}, + // ">, magpie#1945), dropped with the close; held + // while only those have come + const tail = body.slice(o) + const junk = tail.match(TAIL_JUNK)[0] + const next = tail.slice(junk.length) + const call = { name: String(v.name), arguments: callArgs(v) } + if (!end && (!next || ["", ""].some((k) => k.startsWith(next)))) return { wait: true } + const [c, n] = closeAt(next) + if (c === 0) return { call, rest: next.slice(n) } + // after blanks alone, or with no close to come: the call, and + // what follows read on as before. Other text before the close + // right after the object means the object ended early, at a + // quote inside a string left unescaped: that cut is wrong (a + // heredoc's command cut short, magpie#1945), so it is read up to + // the close below, or not at all + if (!/\S/.test(junk) && !/^[^\s<]/.test(next)) return { call, rest: tail } + if (close < 0 && end) return { call, rest: tail } + } else this.bad.add(":" + o) } // not whole, or not JSON as it stands: read up to a close (a file's // content may hold one), or at the end all of it @@ -1241,6 +1287,14 @@ const UNREADABLE = "the model's tool call, written as text, can't be read; it is // also writes it without the underscore, (plugins#38) const OPEN_AT = /{}]*)?>|(?=\s*\{))/ const OPEN_HOLD = /{}\n]{0,200})?$/ +// what GLM leaves between a call's JSON and its close: blanks, closing +// braces and brackets, quotes, a > (magpie#1945) +const TAIL_JUNK = /^[\s}\]"'>]*/ +// a close with no call open, and that leftover before it: the tail of a +// call Trae's service read itself, or of one already read (magpie#1945) +const STRAY_AT = /[}\]"'>]*\s*<\/tool_?calls?>/ +// the end of text that may be such a tail still being written +const STRAY_HOLD = /[}\]"'>][\s}\]"'>]*$/ // closeAt is where the next close is from i, or , // and its length: [-1, 0] when there is none function closeAt(s, i = 0) { diff --git a/packages/trae/package.json b/packages/trae/package.json index c1e8967..4bb7aab 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.10", + "version": "0.2.11", "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/tailjunk.test.mjs b/packages/trae/tailjunk.test.mjs new file mode 100644 index 0000000..d716140 --- /dev/null +++ b/packages/trae/tailjunk.test.mjs @@ -0,0 +1,92 @@ +// magpie#1945 (XcodeFish, trae-cn/glm-5.3-flash under Codex): the tail of +// a tool call went out as an answer of its own, beside the call: the eight +// texts below are the ones the issue lists, as Codex showed them. And a +// heredoc's command, its quotes left unescaped, was cut at a quote that +// closed an object early, the rest sent on as text. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { TraeCNAuthPlugin, _internal } from "./index.mjs" +import { fakeTrae, signedIn, sse } from "./fake.mjs" + +const LEAKED = ["]", "", "}", ']}]}}"}}}}', "}}", '">'] + +const TOOLS = [{ type: "function", function: { name: "exec_command", parameters: { type: "object", properties: { cmd: { type: "string" }, yield_time_ms: { type: "number" } } } } }] + +// what TextTools makes of s given whole, and given a piece at a time +function read(s, size = 0) { + const t = new _internal.TextTools(TOOLS) + const pieces = size ? Array.from({ length: Math.ceil(s.length / size) }, (_, k) => s.slice(k * size, (k + 1) * size)) : [s] + 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 CALL = '{"name":"exec_command","arguments":{"cmd":"ls","yield_time_ms":180000}}' + +test("what GLM leaves between a call and its close is dropped with the close, not sent on as text", () => { + for (const tail of LEAKED) + for (const size of [0, 1, 3, 7]) { + expect(read("Listing it.\n" + CALL + tail, size)).toEqual({ text: "Listing it.\n", calls: [["exec_command", { cmd: "ls", yield_time_ms: 180000 }]], error: null }) + // and the same tail again after the call's own close + expect(read(CALL + "\n" + tail + "\nDone.", size)).toEqual({ text: "Done.", calls: [["exec_command", { cmd: "ls", yield_time_ms: 180000 }]], error: null }) + } +}) + +test("a tail alone, from a call Trae's service read itself, is no text", () => { + for (const tail of LEAKED) for (const size of [0, 1, 4]) expect(read(tail, size)).toEqual({ text: "", calls: [], error: null }) +}) + +test("a call Trae's service read, its tail in the text: the call, and no text beside it", async () => { + const f = fakeTrae() + try { + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([ + ["output", { tool_calls: [{ id: "n1", function: { name: "exec_command", arguments: '{"cmd":"ls","yield_time_ms":180000}' } }] }], + ["output", { response: "}" }], + ["output", { response: "}" }], + ["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-flash", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] }) }) + const deltas = (await res.text()).split("\n").filter((l) => l.startsWith("data: {")).map((l) => JSON.parse(l.slice(6))).filter((x) => x.choices?.length).map((x) => x.choices[0].delta) + expect(deltas.map((d) => d.content ?? "").join("")).toBe("") + expect(deltas.flatMap((d) => d.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)])).toEqual([["exec_command", { cmd: "ls", yield_time_ms: 180000 }]]) + } finally { + f.close() + } +}) + +test("a heredoc whose quotes were left unescaped is read whole, not cut where an object closed early", () => { + // one quote unescaped (after y): the object read as {"cmd":"…\"y"}} + // ended there, and the rest went out as text + const raw = String.raw`{"name":"exec_command","arguments":{"cmd":"python3 - <<'PY'\nimport json\nprint(json.dumps({\"名\": 'v', \"n\": {\"x\": \"y"}}))\nPY\n | tail -8","yield_time_ms":180000}}` + const cmd = `python3 - <<'PY'\nimport json\nprint(json.dumps({"名": 'v', "n": {"x": "y"}}))\nPY\n | tail -8` + for (const size of [0, 1, 5, 13]) expect(read("" + raw + "", size)).toEqual({ text: "", calls: [["exec_command", { cmd, yield_time_ms: 180000 }]], error: null }) +}) + +test("a call followed by text that can't be part of it, before its close, fails rather than going out guessed", () => { + for (const size of [0, 1, 6]) { + const r = read(CALL + "x\n", size) + expect(r.calls).toEqual([]) + expect(r.error).toContain("can't be read") + } +}) + +test("braces, quotes and closes that aren't a call's tail stay text", () => { + for (const s of [ + 'The map is {"a": [1, {"b": 2}]}', + 'He said "done" >', + "The tag ends a call.", + "Call it like `{\"x\": 1}` in the prompt.", + ]) + for (const size of [0, 1, 5]) expect(read(s, size)).toEqual({ text: s, calls: [], error: null }) +})