diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 6e5f3f8..c7c9709 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -144,6 +144,13 @@ itself. the agent or magpie can try again. A call whose JSON is whole when the stream ends without its close is still the call; a tag in code or prose stays text. +- A call written in Anthropic's or Qwen's tags with no `` + around it (since 0.2.36, #323), `` around one or more + `v`, or + `v`, is a call too, + but only for a tool the request declared; for any other, or in + backticks or a code fence, it stays text. A parameter's value is JSON + unless the tool's schema says string, in these and in ``. **Errors** diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index f16ca63..99dc912 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -1273,8 +1273,9 @@ const FUNC = /\x3cfunction=([^>]+)\x3e([\s\S]*?)\x3c\/function\x3e/ const PARAM = /\x3cparameter=([^>]+)\x3e([\s\S]*?)\x3c\/parameter\x3e/g // parseCall reads one tool-call block: JSON {name, arguments}, or the XML -// function/parameter form. -function parseCall(v) { +// function/parameter form, its values typed as the tool's schema says +// (xmlArgs). +function parseCall(v, tools = []) { try { const f = JSON.parse(v.trim()) if (String(f?.name ?? "").trim() && f.arguments && typeof f.arguments === "object" && !Array.isArray(f.arguments)) @@ -1282,18 +1283,106 @@ function parseCall(v) { } catch {} const m = FUNC.exec(v) if (!m || !m[1].trim()) return null + const name = m[1].trim() + const props = propsOf(tools, name) const args = {} for (const pm of m[2].matchAll(PARAM)) { const key = pm[1].trim() if (!key) continue - const val = pm[2].trim() - try { - args[key] = JSON.parse(val) - } catch { - args[key] = val - } + args[key] = valueOf(pm[2].trim(), props[key]) } - return { name: m[1].trim(), args: JSON.stringify(args) } + return { name, args: JSON.stringify(args) } +} + +// propsOf is the parameters the request declared for tool name +const propsOf = (tools, name) => (tools.find((t) => (t.function ?? t)?.name === name)?.function ?? {}).parameters?.properties ?? {} + +// valueOf is a parameter's value: its text where the tool's schema says +// string, else its JSON (an array a tool takes), else its text (#323: a +// string holding [1, 2] became an array) +function valueOf(v, prop) { + if (prop?.type === "string") return v + try { + return JSON.parse(v.trim()) + } catch { + return v + } +} + +// Anthropic's and Qwen's call tags, written bare (no around +// them), as Kimi, MiMo and Qwen models may (#323, as trae's since 0.2.19): +// where one starts, an opener still being written, the openers a wrapper +// is followed by, the next call's opener, a parameter's opener, and what +// is left after a call +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 = ["", "", ...XML_STARTS] +const XML_NEXT = /<(?:antml:)?invoke\s+name\s*=|]+))\s*>/g +const XML_CLOSES = ["", "", "", "", ""] +const XML_LEFT = /^(?:\s+|<\/(?:antml:)?(?:function_calls|invoke|function)>)+/ + +// xmlArgs reads the parameters of an invoke or function body, typed by +// the tool's schema; closed is whether every one was closed +function xmlArgs(s, props) { + const opens = [...s.matchAll(XML_PARAM)] + const args = {} + let closed = opens.length > 0 + opens.forEach((m, k) => { + let v = s.slice(m.index + m[0].length, k + 1 < opens.length ? opens[k + 1].index : s.length) + const c = v.search(/<\/(?:antml:)?parameter>/) + if (c >= 0) v = v.slice(0, c) + else closed = false + args[m[1] ?? m[2]] = valueOf(v.replace(/^\r?\n|\r?\n$/g, ""), props[m[1] ?? m[2]]) + }) + return { args, closed } +} + +// xmlCall reads a bare call 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. Only +// a declared tool's call counts: these tags are common in prose. +function xmlCall(s, end, tools) { + 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 } + s = rest + } + 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) { + if (!end && (XML_STARTS.some((k) => k.startsWith(s)) || /^<(?:antml:)?(?:invoke\s|function=)[^<>]{0,300}$/.test(s))) return { wait: true } + return { text: true } + } + const name = m[1].trim() + if (!tools.some((t) => (t.function ?? t)?.name === 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 p = xmlArgs(body.slice(0, stop), propsOf(tools, name)) + if (!whole && !p.closed) { + // no parameter and no close: a tag named in passing; a parameter + // left open: the call cut short + if (!/<(?:antml:)?parameter\b/.test(body.slice(0, stop))) return { text: true } + return { error: CUT_SHORT } + } + return { call: { name, args: JSON.stringify(p.args) }, rest: whole ? body.slice(stop + c[0].length) : body.slice(stop) } } // quoted says text ends inside a code fence or an inline code span: a @@ -1316,31 +1405,96 @@ const UNREADABLE = "the model's tool call, written as text, can't be read; it is // that the stream ended inside, is an error, never the answer (plugins#132, // as trae's since plugins#38): the turn fails so it can be tried again. A // block whose JSON is whole when the stream ends without its close is still -// the call; one that is no call at all, or one in code, stays text. +// the call; one that is no call at all, or one in code, stays text. A bare +// call in Anthropic's or Qwen's tags (xmlCall) is a call too, for a tool +// the request declared (tools). class Splitter { textBuf = "" callBuf = "" inCall = false sawTool = false + after = false // a bare call just ended: the closes and blanks after it are dropped sent = "" // the text given out so far, to tell a block in code from a call + constructor(tools = []) { + this.tools = tools.filter((t) => (t?.function ?? t)?.name) + } text(out, t) { this.sent += t out.push({ text: t }) } + // bare reads text that may hold a bare call, comb starting at its tag x: + // the input left to read, null when comb is held for more, or false + // when the turn ended in an error + bare(out, comb, x, end) { + const head = comb.slice(0, x) + const at = comb.slice(x) + const opener = at.match(/^<[^<>]*>?/)[0] + if (quoted(this.sent + head)) { + this.text(out, head + opener) + return at.slice(opener.length) + } + const b = xmlCall(at, end, this.tools) + if (b.wait) { + if (head) this.text(out, head) + this.textBuf = at + return null + } + if (b.text) { + this.text(out, head + opener) + return at.slice(opener.length) + } + if (head) this.text(out, head) + if (b.error) { + out.push({ error: b.error }) + return false + } + this.sawTool = true + out.push({ call: b.call }) + this.after = true + return b.rest + } + // left drops what is left after a bare call; null while it may still be + // one of its closes + left(comb, end) { + const rest = comb.replace(XML_LEFT, "") + if (!end && (!rest || XML_CLOSES.some((c) => c.length > rest.length && c.startsWith(rest)))) return null + this.after = false + return rest + } feed(input) { const out = [] while (input) { if (!this.inCall) { - const comb = this.textBuf + input + let comb = this.textBuf + input this.textBuf = "" + if (this.after) { + const rest = this.left(comb, false) + if (rest === null) { + this.textBuf = comb + break + } + comb = rest + if (!comb) break + } const i = comb.indexOf(CALL_OPEN) + const x = this.tools.length ? comb.search(XML_AT) : -1 + if (x >= 0 && (i < 0 || x < i)) { + const next = this.bare(out, comb, x, false) + if (next === false) return out + if (next === null) break + input = next + continue + } if (i < 0) { let keep = 0 - for (let n = CALL_OPEN.length - 1; n > 0; n--) - if (comb.endsWith(CALL_OPEN.slice(0, n))) { - keep = n - break - } + for (const mark of this.tools.length ? [CALL_OPEN, ...XML_MARKS] : [CALL_OPEN]) + for (let n = Math.min(mark.length - 1, comb.length); n > keep; n--) + if (comb.endsWith(mark.slice(0, n))) { + keep = n + break + } + const h = this.tools.length ? comb.search(XML_HOLD) : -1 + if (h >= 0) keep = Math.max(keep, comb.length - h) if (keep < comb.length) this.text(out, comb.slice(0, comb.length - keep)) this.textBuf = comb.slice(comb.length - keep) break @@ -1358,7 +1512,7 @@ class Splitter { break } const body = comb.slice(0, j) - const c = parseCall(body) + const c = parseCall(body, this.tools) if (c) { this.sawTool = true out.push({ call: c }) @@ -1378,7 +1532,7 @@ class Splitter { this.inCall = false this.callBuf = "" if (callish(body) && !quoted(this.sent)) { - const c = parseCall(body) + const c = parseCall(body, this.tools) if (!c) return [{ error: CUT_SHORT }] this.sawTool = true return [{ call: c }] @@ -1388,10 +1542,23 @@ class Splitter { return [{ text: t }] } if (this.textBuf) { - const t = this.textBuf + let t = this.textBuf this.textBuf = "" - this.sent += t - return [{ text: t }] + if (this.after) t = this.left(t, true) + // what was held for a bare call, read to its end: calls, then the + // text left, or the error of one cut short + const out = [] + while (t) { + const x = this.tools.length ? t.search(XML_AT) : -1 + if (x < 0) { + this.text(out, t) + break + } + const next = this.bare(out, t, x, true) + if (next === false) break + t = this.after ? this.left(next, true) : next + } + return out } return [] } @@ -1414,8 +1581,8 @@ async function* sseLines(body) { // events turns Qoder's SSE into chat completion pieces: each data line's // envelope has a "body" that is an OpenAI chunk, whose content may hold // tool calls to lift out. -async function* events(body) { - const a = new Splitter() +async function* events(body, tools = []) { + const a = new Splitter(tools) let index = -1 // the tool call being given const native = new Map() // upstream index -> call and its output index // one piece of the split text as an event: a call, text, or a call that @@ -1513,8 +1680,8 @@ async function* events(body) { // opened is a chat reply's events and the first of them, read before // anything is answered: a refusal in the stream (Qoder's queue among them) // comes first. -async function opened(res) { - const it = events(res.body) +async function opened(res, tools) { + const it = events(res.body, tools) return { it, first: await it.next() } } @@ -2365,7 +2532,7 @@ const makePlugin = (site) => async ({ client }) => { let res, open try { res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal }) - if (res.ok) open = await opened(res) + if (res.ok) open = await opened(res, chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : []) } catch (e) { return errorResponse({ status: 502, message: e.message }) } @@ -2621,4 +2788,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) { export const protocol = { makePlugin, deviceSignIn, openapi, siteOf } // for tests -export const _internal = { typedUnions, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState } +export const _internal = { typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index f281d4e..fbc6401 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.35", + "version": "0.2.36", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/xmlcall.test.mjs b/packages/qoder/xmlcall.test.mjs new file mode 100644 index 0000000..bd00642 --- /dev/null +++ b/packages/qoder/xmlcall.test.mjs @@ -0,0 +1,159 @@ +// #323: a call a model writes in Anthropic's tags ( around +// ) or Qwen's (), with no around +// it, went to the agent as its reply text; and a parameter's value was +// JSON-parsed whatever the tool's schema said. The samples are trae's +// (01huadalang on magpie's Discord, Kimi K3 and MiMo 2.6 Pro under dsh, +// trae 0.2.19): no Qoder model has been seen writing them yet. +import { afterEach, expect, test } from "bun:test" +import { QoderAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +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), and as the model would have ended it +const S1_SHOWN = '[{"endId": "m03680", "endRef": "m03680", "startId": "m03485", "startRef": "m03485", "summary": "TASK AS OF THIS BLOCK(历史): ...' +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 }]) +// sample 2 with the tags' namespace, as Claude-trained models write them +const NS = "ant" + "ml:" +const S2_NS = S2.replace(/<(\/?)(function_calls|invoke|parameter)\b/g, `<$1${NS}$2`) + +// what the Splitter makes of the pieces, given in order, then the end +function readPieces(pieces, tools = TOOLS) { + const s = new _internal.Splitter(tools) + const out = { text: "", calls: [], error: null } + for (const f of [...pieces.flatMap((p) => s.feed(p)), ...s.flush()]) { + if (out.error) break + if (f.text) out.text += f.text + if (f.call) out.calls.push([f.call.name, JSON.parse(f.call.args)]) + if (f.error) out.error = f.error + } + 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) +const splits = (s) => Array.from({ length: s.length - 1 }, (_, k) => [s.slice(0, k + 1), s.slice(k + 1)]) + +test("the two samples 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 }) + expect(read(S2_NS, size)).toEqual({ text: "", calls: S2_CALLS, error: null }) + 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 its text where the tool's schema says string, bare or in ", () => { + expect(read("[1, 2]").calls).toEqual([["bash", { command: "[1, 2]" }]]) + expect(read("[1, 2]").calls).toEqual([["bash", { command: "[1, 2]" }]]) + expect(read(S1).calls[0][1].content).toBeArray() +}) + +test("Anthropic's with the closes left off between invokes: each invoke is a call", () => { + for (const size of [0, 1, 4]) + 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", () => { + 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") + } + } + 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") + } + expect(read(S1_SHOWN + '"}]')).toEqual({ text: "", calls: [["compress", S1_ARGS]], error: null }) +}) + +test("a tool the request didn't declare, or no tools at all, 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 }) + expect(read(S2, size, [])).toEqual({ text: S2, calls: [], error: null }) + } +}) + +test("prose about the tags 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, `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200, statusCode: "OK" })}\n\n` +const chunk = (delta, extra = {}) => line({ choices: [{ delta, index: 0, ...extra }], object: "chat.completion.chunk" }) + +async function ask(reply, stream, tools = TOOLS) { + const auth = { type: "oauth", access: "jt", refresh: "rt", expires: Date.now() + 3_600_000, accountId: "one@x", uid: "u1", machineId: "m1" } + globalThis.fetch = async (url) => + new URL(String(url)).pathname.endsWith("/model/list") + ? new Response(JSON.stringify(LISTING), { headers: { "Content-Type": "application/json" } }) + : new Response(reply, { headers: { "Content-Type": "text/event-stream" } }) + const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) + const l = await hooks.auth.loader(async () => auth) + const body = { model: "efficient", tools, messages: [{ role: "user", content: "hi" }], ...(stream ? { stream: true } : {}) } + return l.fetch(API_CHAT, { method: "POST", body: JSON.stringify(body) }) +} + +test("through the plugin, streamed and not: sample 2's three calls, finished as tool calls", async () => { + const cut = [17, 60, 61, 140, 250, 300] + const parts = cut.map((c, k) => S2.slice(k ? cut[k - 1] : 0, c)).concat(S2.slice(cut.at(-1))) + const reply = parts.map((p) => chunk({ content: p })).join("") + chunk({}, { finish_reason: "stop" }) + + const res = await ask(reply, true) + expect(res.status).toBe(200) + const frames = (await res.text()) + .split("\n") + .filter((l) => l.startsWith("data: ") && l !== "data: [DONE]") + .map((l) => JSON.parse(l.slice(6))) + const deltas = frames.filter((f) => f.choices?.length).map((f) => f.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(S2_CALLS) + expect(frames.filter((f) => f.choices?.[0]?.finish_reason).map((f) => f.choices[0].finish_reason)).toEqual(["tool_calls"]) + + const whole = await ask(reply, false) + expect(whole.status).toBe(200) + const m = (await whole.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") + + // no tool declared: the tags are text + const off = await ask(reply, false, []) + expect((await off.json()).choices[0].message.content).toBe(S2) +})