diff --git a/packages/qoder/README.md b/packages/qoder/README.md index cbe1115..c9a95c5 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -78,6 +78,12 @@ itself. reasoning and usage. - Tool calls Qoder writes as XML or JSON in its text become tool calls. Tool calls it sends the OpenAI way keep Qoder's id. +- A call written in the text that can't be read, or that the stream ends + inside, is never sent on as the answer (since 0.2.16, #132): the turn + ends as an error, a 502 or the stream's error frame with no finish, so + 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. **Errors** diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 035ad90..25af4ec 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -884,13 +884,37 @@ function parseCall(v) { return { name: m[1].trim(), args: JSON.stringify(args) } } +// quoted says text ends inside a code fence or an inline code span: a +// there is prose about one, not a call +function quoted(text) { + if ((text.match(/```/g)?.length ?? 0) % 2) return true + const line = text.slice(text.lastIndexOf("\n") + 1).replace(/```/g, "") + return (line.match(/`/g)?.length ?? 0) % 2 === 1 +} + +// callish says a block was on its way to being a call: its JSON began, or +// the XML function form +const callish = (v) => v.trimStart().startsWith("{") || v.includes("\x3cfunction=") + +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" + // Splitter holds text until a whole tool-call block has come, then gives -// it as a call. +// it as a call. A block on its way to being a call that can't be read, or +// 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. class Splitter { textBuf = "" callBuf = "" inCall = false sawTool = false + sent = "" // the text given out so far, to tell a block in code from a call + text(out, t) { + this.sent += t + out.push({ text: t }) + } feed(input) { const out = [] while (input) { @@ -905,11 +929,11 @@ class Splitter { keep = n break } - if (keep < comb.length) out.push({ text: comb.slice(0, comb.length - keep) }) + if (keep < comb.length) this.text(out, comb.slice(0, comb.length - keep)) this.textBuf = comb.slice(comb.length - keep) break } - if (i > 0) out.push({ text: comb.slice(0, i) }) + if (i > 0) this.text(out, comb.slice(0, i)) input = comb.slice(i + CALL_OPEN.length) this.inCall = true continue @@ -921,11 +945,16 @@ class Splitter { this.callBuf = comb break } - const c = parseCall(comb.slice(0, j)) + const body = comb.slice(0, j) + const c = parseCall(body) if (c) { this.sawTool = true out.push({ call: c }) - } else out.push({ text: CALL_OPEN + comb.slice(0, j) + CALL_CLOSE }) + } else if (callish(body) && !quoted(this.sent)) { + this.inCall = false + out.push({ error: UNREADABLE }) + return out + } else this.text(out, CALL_OPEN + body + CALL_CLOSE) input = comb.slice(j + CALL_CLOSE.length) this.inCall = false } @@ -933,14 +962,23 @@ class Splitter { } flush() { if (this.inCall) { - const t = CALL_OPEN + this.callBuf + const body = this.callBuf this.inCall = false this.callBuf = "" + if (callish(body) && !quoted(this.sent)) { + const c = parseCall(body) + if (!c) return [{ error: CUT_SHORT }] + this.sawTool = true + return [{ call: c }] + } + const t = CALL_OPEN + body + this.sent += t return [{ text: t }] } if (this.textBuf) { const t = this.textBuf this.textBuf = "" + this.sent += t return [{ text: t }] } return [] @@ -968,9 +1006,10 @@ async function* events(body) { const a = new Splitter() let index = -1 // the tool call being given let native = -1 // the native tool call being assembled - const flushed = function* () { - for (const f of a.flush()) if (f.text) yield { text: f.text } - } + // one piece of the split text as an event: a call, text, or a call that + // can't be read, which ends the turn as a 502 + const piece = (f) => + f.call ? { tool: { index: ++index, id: "call_" + hexID(), name: f.call.name, args: f.call.args } } : f.error ? { error: { status: 502, message: f.error } } : { text: f.text } let usage let fr = "" for await (const line of sseLines(body)) { @@ -998,15 +1037,21 @@ async function* events(body) { if (delta.reasoning_content) yield { reasoning: delta.reasoning_content } if (typeof delta.content === "string") for (const f of a.feed(delta.content)) { - if (f.call) yield { tool: { index: ++index, id: "call_" + hexID(), name: f.call.name, args: f.call.args } } - else if (f.text) yield { text: f.text } + if (!f.call && !f.error && !f.text) continue + const e = piece(f) + yield e + if (e.error) return } // tool calls served the OpenAI way keep Qoder's id: a result answers it for (const tc of delta.tool_calls ?? []) { const i = Number(tc.index ?? 0) if (i !== native) { native = i - yield* flushed() + for (const f of a.flush()) { + const e = piece(f) + yield e + if (e.error) return + } a.sawTool = true yield { tool: { index: ++index, id: tc.id || "call_" + hexID(), name: tc.function?.name ?? "", args: tc.function?.arguments ?? "" } } } else if (tc.function?.arguments) yield { args: { index, text: tc.function.arguments } } @@ -1025,7 +1070,11 @@ async function* events(body) { ...(u.completion_tokens_details?.reasoning_tokens ? { completion_tokens_details: { reasoning_tokens: u.completion_tokens_details.reasoning_tokens } } : {}), } } - yield* flushed() + for (const f of a.flush()) { + const e = piece(f) + yield e + if (e.error) return + } yield { stop: a.sawTool ? "tool_calls" : fr === "length" ? "length" : "stop", usage } } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index c8ee333..e55e5d1 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.15", + "version": "0.2.16", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/textcall.test.mjs b/packages/qoder/textcall.test.mjs new file mode 100644 index 0000000..7abf187 --- /dev/null +++ b/packages/qoder/textcall.test.mjs @@ -0,0 +1,145 @@ +// plugins#132: a tool call the model wrote into its text that couldn't be +// read (JSON not whole, or a stream that ended inside the block) went out +// as the answer, the call lost, with a 200 and "stop" nothing could fail +// over on. The frames are the issue's, byte for byte; the turn now ends as +// an error, as trae's has since plugins#38: the stream with the error frame +// and no finish, a request not streamed with a 502. +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" }) + +// the issue's three replies +const CLOSED_BAD = chunk({ content: 'Sure.\n{"name":"read","arguments":{"path":}}' }) +const CUT_SHORT = chunk({ content: 'Reading.\n{"name":"read","arguments":{"path":"a.go"' }) +const READABLE = chunk({ content: 'Reading.\n{"name":"read","arguments":{"path":"a.go"}}' }) + chunk({}, { finish_reason: "tool_calls" }) + +// a reply's content given a few characters per frame, as a stream may +const pieces = (content, size = 3) => Array.from({ length: Math.ceil(content.length / size) }, (_, k) => chunk({ content: content.slice(k * size, (k + 1) * size) })).join("") + +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) }) +} + +// what a streamed reply said: its text, calls, finishes and errors +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), + last: frames.at(-1), + } +} + +for (const [label, reply, text] of [ + ["closed, its JSON not whole", CLOSED_BAD, "Sure.\n"], + ["the stream ends inside the block", CUT_SHORT, "Reading.\n"], +]) { + test(`${label}: streamed, the turn ends with the error frame and no finish`, async () => { + for (const r of [reply, pieces(JSON.parse(JSON.parse(reply.slice(5)).body).choices[0].delta.content)]) { + const out = await streamed(await ask(r, true)) + expect(out.text).toBe(text) + expect(out.text).not.toContain("") + expect(out.calls).toEqual([]) + expect(out.finish).toEqual([]) + expect(out.errors).toHaveLength(1) + expect(out.last.error).toBeTruthy() + } + }) + + test(`${label}: not streamed, a 502 and not the block as the answer`, async () => { + const res = await ask(reply, false) + expect(res.status).toBe(502) + const body = await res.json() + expect(body.error.message).toMatch(/tool call/) + expect(body.choices).toBeUndefined() + }) +} + +test("a block that's only the error is a 502 streamed too: nothing was sent before it", async () => { + const res = await ask(chunk({ content: '{"name":"read","arguments":{"path":}}' }), true) + expect(res.status).toBe(502) +}) + +test("readable, the control: the call, streamed and not", async () => { + for (const r of [READABLE, pieces('Reading.\n{"name":"read","arguments":{"path":"a.go"}}')]) { + const out = await streamed(await ask(r, true)) + expect(out.text).toBe("Reading.\n") + expect(out.calls).toEqual([["read", { path: "a.go" }]]) + expect(out.finish).toEqual(["tool_calls"]) + expect(out.errors).toEqual([]) + } + const res = await ask(READABLE, false) + expect(res.status).toBe(200) + const msg = (await res.json()).choices[0] + expect(msg.finish_reason).toBe("tool_calls") + expect(msg.message.content).toBe("Reading.\n") + expect(msg.message.tool_calls.map((t) => [t.function.name, JSON.parse(t.function.arguments)])).toEqual([["read", { path: "a.go" }]]) +}) + +test("a block whose JSON is whole when the stream ends without its close is still the call", async () => { + const content = 'Reading.\n{"name":"read","arguments":{"path":"a.go"}}' + for (const r of [chunk({ content }), pieces(content)]) { + const out = await streamed(await ask(r, true)) + expect(out.calls).toEqual([["read", { path: "a.go" }]]) + expect(out.finish).toEqual(["tool_calls"]) + expect(out.errors).toEqual([]) + } + const res = await ask(chunk({ content }), false) + expect(res.status).toBe(200) + expect((await res.json()).choices[0].finish_reason).toBe("tool_calls") +}) + +test("the XML form: whole is the call, cut short or unreadable is the error", async () => { + const whole = "a.go" + const out = await streamed(await ask(chunk({ content: whole }), true)) + expect(out.calls).toEqual([["read", { path: "a.go" }]]) + for (const bad of ["Reading.\na.go", "Reading.\na.go"]) { + const s = await streamed(await ask(chunk({ content: bad }), true)) + expect(s.text).toBe("Reading.\n") + expect(s.finish).toEqual([]) + expect(s.errors).toHaveLength(1) + expect((await ask(chunk({ content: bad }), false)).status).toBe(502) + } +}) + +test("text that only looks like a tag stays text", async () => { + for (const content of [ + "Use incomplete", + "A block is name in prose.", + 'Write it as `{"name":` then the rest.', + 'An example:\n```\n{"name":"read","arguments":{"path":}}\n```\n', + "Ends on