diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index f9d5e8b..3f5744c 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -2036,6 +2036,71 @@ function quoted(text) { // the XML function form const callish = (v) => v.trimStart().startsWith("{") || v.includes("\x3cfunction=") +// plugins#1113: a reply that is one JSON object holding OpenAI's own +// tool_calls array, written as text ({"tool_calls":[{"name", "arguments"}]}), +// is those calls. It is told apart from text by where it starts: a line of +// its own whose object opens with the "tool_calls" key, outside code. +const JSON_KEY = '{"tool_calls"' +const JSON_AT_ALL = /(^|\n)[ \t]*\{\s*"tool_calls"\s*:/g + +// jsonHold is how much of comb's end may still become JSON_KEY on a line +// of its own (start says comb starts a line), so it is held for more +function jsonHold(comb, start) { + const n = comb.lastIndexOf("\n") + if (n < 0 && !start) return 0 + const line = comb.slice(n + 1) + const s = line.replace(/\s+/g, "") + if (!JSON_KEY.startsWith(s)) return 0 + return line.length +} + +// jsonEnd is where the JSON object at the start of v ends, -1 while it is +// not whole yet +function jsonEnd(v) { + let depth = 0 + let str = false + for (let k = 0; k < v.length; k++) { + const c = v[k] + if (str) { + if (c === "\\") k++ + else if (c === '"') str = false + } else if (c === '"') str = true + else if (c === "{" || c === "[") depth++ + else if (c === "}" || c === "]") { + if (--depth === 0) return k + 1 + } + } + return -1 +} + +// jsonCalls reads a whole {"tool_calls": [...]} object: its calls, null +// when it holds none (it stays text), or false when one can't be read +function jsonCalls(v) { + let f + try { + f = JSON.parse(v) + } catch { + return false + } + const list = f?.tool_calls + if (!Array.isArray(list) || !list.length) return null + const calls = [] + for (const e of list) { + const fn = e?.function ?? e + let args = fn?.arguments + if (typeof args === "string") { + try { + args = JSON.parse(args) + } catch { + return false + } + } + if (!String(fn?.name ?? "").trim() || !args || typeof args !== "object" || Array.isArray(args)) return false + calls.push({ name: fn.name.trim(), args: JSON.stringify(args) }) + } + return calls +} + const CUT_SHORT = "the model's tool call, written as text, was cut short; it is not sent on as the answer" const UNREADABLE = "the model's tool call, written as text, can't be read; it is not sent on as the answer" @@ -2054,6 +2119,7 @@ class Splitter { 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 + jsonBuf = null // a {"tool_calls": ...} object being read (plugins#1113) constructor(tools = []) { this.tools = tools.filter((t) => (t?.function ?? t)?.name) } @@ -2100,9 +2166,43 @@ class Splitter { this.after = false return rest } + // json reads the {"tool_calls": ...} object held in jsonBuf: the input + // left after it, null while it is not whole, or false when the turn + // ended in an error + json(out, end) { + const v = this.jsonBuf + const e = jsonEnd(v) + if (e < 0) { + if (!end) return null + this.jsonBuf = null + out.push({ error: CUT_SHORT }) + return false + } + this.jsonBuf = null + const calls = jsonCalls(v.slice(0, e)) + if (calls === false) { + out.push({ error: UNREADABLE }) + return false + } + if (!calls) { + this.text(out, v.slice(0, e)) + return v.slice(e) + } + this.sawTool = true + for (const c of calls) out.push({ call: c }) + return v.slice(e).replace(/^\s+/, "") + } feed(input) { const out = [] while (input) { + if (this.jsonBuf !== null) { + this.jsonBuf += input + const next = this.json(out, false) + if (next === false) return out + if (next === null) break + input = next + continue + } if (!this.inCall) { let comb = this.textBuf + input this.textBuf = "" @@ -2117,6 +2217,25 @@ class Splitter { } const i = comb.indexOf(CALL_OPEN) const x = this.tools.length ? comb.search(XML_AT) : -1 + const start = !this.sent || this.sent.endsWith("\n") + let k = -1 + for (const jm of comb.matchAll(JSON_AT_ALL)) { + const at = jm.index + jm[1].length + if ((jm[1] || start) && !quoted(this.sent + comb.slice(0, at))) { + k = at + break + } + } + if (k >= 0 && (i < 0 || k < i) && (x < 0 || k < x)) { + if (k > 0) this.text(out, comb.slice(0, k)) + this.jsonBuf = comb.slice(k).replace(/^[ \t]+/, "") + input = "" + const next = this.json(out, false) + if (next === false) return out + if (next === null) break + input = next + continue + } if (x >= 0 && (i < 0 || x < i)) { const next = this.bare(out, comb, x, false) if (next === false) return out @@ -2134,6 +2253,7 @@ class Splitter { } const h = this.tools.length ? comb.search(XML_HOLD) : -1 if (h >= 0) keep = Math.max(keep, comb.length - h) + keep = Math.max(keep, jsonHold(comb, !this.sent || this.sent.endsWith("\n"))) if (keep < comb.length) this.text(out, comb.slice(0, comb.length - keep)) this.textBuf = comb.slice(comb.length - keep) break @@ -2166,6 +2286,12 @@ class Splitter { return out } flush() { + if (this.jsonBuf !== null) { + const out = [] + const next = this.json(out, true) + if (next) this.text(out, next) + return out + } if (this.inCall) { const body = this.callBuf this.inCall = false diff --git a/packages/qoder/jsoncall.test.mjs b/packages/qoder/jsoncall.test.mjs new file mode 100644 index 0000000..529e615 --- /dev/null +++ b/packages/qoder/jsoncall.test.mjs @@ -0,0 +1,134 @@ +// plugins#1113: a reply that was one JSON object in OpenAI's own wire shape, +// {"tool_calls":[{"name","arguments"}]}, written as text, went out as the +// answer with "stop", the calls lost. The replies are the issue's, byte for +// byte; the object is now those calls, finished tool_calls. One cut short, +// or with an entry that can't be read, ends the turn as an error (as +// plugins#132's block does); JSON in prose or code stays text. +import { afterEach, expect, test } from "bun:test" +import { QoderAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const API_CHAT = "https://api3.qoder.sh/v1/chat/completions" +const LISTING = { chat: [{ key: "efficient", display_name: "Efficient", enable: true }] } +const line = (body) => `data:${JSON.stringify({ headers: {}, body: typeof body === "string" ? body : JSON.stringify(body), statusCodeValue: 200, statusCode: "OK" })}\n\n` +const chunk = (delta, extra = {}) => line({ choices: [{ delta, index: 0, ...extra }], object: "chat.completion.chunk" }) +const pieces = (content, size = 3) => Array.from({ length: Math.ceil(content.length / size) }, (_, k) => chunk({ content: content.slice(k * size, (k + 1) * size) })).join("") +const STOP = chunk({}, { finish_reason: "stop" }) + +// the issue's replies +const BARE = '{"tool_calls":[{"name":"read_file","arguments":{"path":"a.go"}},{"name":"viking_search","arguments":{"query":"x"}}]}' +const CALLS = [ + ["read_file", { path: "a.go" }], + ["viking_search", { query: "x" }], +] + +async function ask(reply, stream) { + 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", messages: [{ role: "user", content: "hi" }], ...(stream ? { stream: true } : {}) } + return l.fetch(API_CHAT, { method: "POST", body: JSON.stringify(body) }) +} + +async function streamed(res) { + expect(res.status).toBe(200) + const frames = (await res.text()) + .split("\n") + .filter((l) => l.startsWith("data: ")) + .map((l) => l.slice(6)) + .filter((d) => d !== "[DONE]") + .map((d) => JSON.parse(d)) + const deltas = frames.filter((f) => f.choices?.length).map((f) => f.choices[0].delta) + return { + text: deltas.map((d) => d.content ?? "").join(""), + calls: deltas.flatMap((d) => d.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)]), + finish: frames.filter((f) => f.choices?.[0]?.finish_reason).map((f) => f.choices[0].finish_reason), + errors: frames.filter((f) => f.error).map((f) => f.error.message), + } +} + +async function whole(reply) { + const res = await ask(reply, false) + expect(res.status).toBe(200) + const c = (await res.json()).choices[0] + return { text: c.message.content ?? "", calls: (c.message.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)]), finish: c.finish_reason } +} + +for (const [label, prose] of [ + ["bare JSON, no wrapper", ""], + ["bare JSON after a line of prose", "Let me read that.\n"], +]) { + test(`${label}: the calls, finished tool_calls, streamed and not`, async () => { + const replies = [(prose ? chunk({ content: prose }) : "") + chunk({ content: BARE }) + STOP, pieces(prose + BARE) + STOP, pieces(prose + BARE, 1) + STOP] + for (const r of replies) { + const out = await streamed(await ask(r, true)) + expect(out.text).toBe(prose) + expect(out.calls).toEqual(CALLS) + expect(out.finish).toEqual(["tool_calls"]) + expect(out.errors).toEqual([]) + expect(await whole(r)).toEqual({ text: prose, calls: CALLS, finish: "tool_calls" }) + } + }) +} + +test("the control: the same call inside is still the call", async () => { + const r = chunk({ content: '{"name":"read_file","arguments":{"path":"a.go"}}' }) + chunk({}, { finish_reason: "tool_calls" }) + const out = await streamed(await ask(r, true)) + expect(out.calls).toEqual([CALLS[0]]) + expect(out.finish).toEqual(["tool_calls"]) +}) + +test("arguments as a JSON string, and the function wrapper, are read too", async () => { + const content = '{"tool_calls":[{"name":"read_file","arguments":"{\\"path\\":\\"a.go\\"}"},{"type":"function","function":{"name":"viking_search","arguments":{"query":"x"}}}]}\n' + const out = await streamed(await ask(chunk({ content }) + STOP, true)) + expect(out.calls).toEqual(CALLS) + expect(out.text).toBe("") + expect(out.finish).toEqual(["tool_calls"]) +}) + +for (const [label, content] of [ + ["cut short", "Let me read that.\n" + BARE.slice(0, 60)], + ["an entry with no name", 'Let me read that.\n{"tool_calls":[{"arguments":{"path":"a.go"}}]}'], + ["arguments that aren't an object", 'Let me read that.\n{"tool_calls":[{"name":"read_file","arguments":"a.go"}]}'], + ["not JSON once whole", 'Let me read that.\n{"tool_calls":[{"name":"read_file","arguments":{"path":}}]}'], +]) { + test(`${label}: the turn ends as an error, not the block as the answer`, async () => { + for (const r of [chunk({ content }) + STOP, pieces(content) + STOP]) { + const out = await streamed(await ask(r, true)) + expect(out.text).toBe("Let me read that.\n") + expect(out.calls).toEqual([]) + expect(out.finish).toEqual([]) + expect(out.errors).toHaveLength(1) + const res = await ask(r, false) + expect(res.status).toBe(502) + expect((await res.json()).error.message).toMatch(/tool call/) + } + }) +} + +test("JSON in prose, in code, or not a tool_calls object stays text", async () => { + for (const content of [ + 'Reply with {"tool_calls":[{"name":"read_file","arguments":{"path":"a.go"}}]} to call it.', + "An example:\n```json\n" + BARE + "\n```\n", + "Inline: `" + BARE + "`", + '{"tool_calls":[]}', + '{"answer":42}', + "{tool_calls are how a model asks}", + "{", + ]) { + for (const r of [chunk({ content }) + STOP, pieces(content) + STOP]) { + const out = await streamed(await ask(r, true)) + expect(out.text).toBe(content) + expect(out.calls).toEqual([]) + expect(out.finish).toEqual(["stop"]) + expect(out.errors).toEqual([]) + expect(await whole(r)).toEqual({ text: content, calls: [], finish: "stop" }) + } + } +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 5cb279d..58d185e 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.67", + "version": "0.2.68", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains", "type": "module", "main": "./opencode.mjs",