diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 77ed87e..ebe287f 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -1015,7 +1015,7 @@ async function* sseLines(body) { 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 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 // can't be read, which ends the turn as a 502 const piece = (f) => @@ -1055,16 +1055,29 @@ async function* events(body) { // 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 + const name = typeof tc.function?.name === "string" ? tc.function.name.trim() : "" + const args = tc.function?.arguments ?? "" + if (!tc.id && !name && !args) continue + let call = native.get(i) + if (!call) { + call = { id: "", args: "" } + native.set(i, call) + } + if (tc.id) call.id = tc.id + if (call.index === undefined) { + // An id or arguments can arrive before the name. Never emit an + // unnamed tool: clients persist it and other providers reject it. + call.args += args + if (!name) continue 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 } } + call.index = ++index + yield { tool: { index: call.index, id: call.id || "call_" + hexID(), name, args: call.args } } + } else if (args) yield { args: { index: call.index, text: args } } } fr = chunk?.choices?.[0]?.finish_reason || fr // the usage comes in a chunk of its own after the finish, with no @@ -1085,6 +1098,10 @@ async function* events(body) { yield e if (e.error) return } + if ([...native.values()].some((call) => call.index === undefined)) { + yield { error: { status: 502, message: "the model's native tool call has no name; it is not sent on as a tool" } } + return + } yield { stop: a.sawTool ? "tool_calls" : fr === "length" ? "length" : "stop", usage } } @@ -1111,7 +1128,7 @@ async function answer(res, chat) { if (e.text) msg.content += e.text if (e.reasoning) reasoning += e.reasoning if (e.tool) calls.push({ id: e.tool.id, type: "function", function: { name: e.tool.name, arguments: e.tool.args } }) - if (e.args) calls[calls.length - 1].function.arguments += e.args.text + if (e.args) calls[e.args.index].function.arguments += e.args.text if (e.stop) [stop, usage] = [e.stop, e.usage] } if (reasoning) msg.reasoning_content = reasoning diff --git a/packages/qoder/native-tools.test.mjs b/packages/qoder/native-tools.test.mjs new file mode 100644 index 0000000..2bcd72f --- /dev/null +++ b/packages/qoder/native-tools.test.mjs @@ -0,0 +1,185 @@ +import { afterEach, expect, test } from "bun:test" +import { _internal, QoderAuthPlugin } from "./index.mjs" + +const realFetch = globalThis.fetch +afterEach(() => (globalThis.fetch = realFetch)) + +const line = (body) => + `data:${JSON.stringify({ body: typeof body === "string" ? body : JSON.stringify(body), statusCodeValue: 200 })}\n\n` +const chunk = (delta, finish_reason) => line({ choices: [{ index: 0, delta, finish_reason }] }) +const finish = chunk({}, "tool_calls") + line("[DONE]") +const textCall = '{"name":"Bash","arguments":{"command":"pwd"}}' + +async function collect(reply) { + const out = [] + for await (const event of _internal.events(new Response(reply).body)) out.push(event) + return out +} + +function callsFrom(events) { + const calls = [] + for (const event of events) { + if (event.tool) calls[event.tool.index] = { ...event.tool } + if (event.args) calls[event.args.index].args += event.args.text + } + return calls +} + +async function ask(reply, stream) { + const auth = { + type: "oauth", access: "fixture-job-token", refresh: "fixture-refresh-token", + expires: Date.now() + 3_600_000, accountId: "native-tools@example.test", + uid: "native-tools", machineId: "fixture-machine", + } + globalThis.fetch = async (url) => + new URL(String(url)).pathname.endsWith("/model/list") + ? Response.json({ chat: [{ key: "efficient", display_name: "Efficient", enable: true }] }) + : new Response(reply, { headers: { "Content-Type": "text/event-stream" } }) + const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => auth) + return loader.fetch("https://api3.qoder.sh/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "efficient", messages: [{ role: "user", content: "hi" }], stream }), + }) +} + +async function framesFrom(response) { + return (await response.text()).split("\n") + .filter((s) => s.startsWith("data: ") && s !== "data: [DONE]") + .map((s) => JSON.parse(s.slice(6))) +} + +test("an empty native placeholder before a text call does not create an unnamed tool", async () => { + const events = await collect( + chunk({ tool_calls: [{ index: 0, function: { name: "", arguments: "" } }] }) + + chunk({ content: textCall }) + finish, + ) + const calls = callsFrom(events) + expect(calls).toHaveLength(1) + expect(calls[0]).toMatchObject({ index: 0, name: "Bash", args: '{"command":"pwd"}' }) + expect(events.at(-1)?.stop).toBe("tool_calls") +}) + +test("empty and null native placeholders leave an ordinary text answer alone", async () => { + for (const placeholder of [ + { index: 0 }, + { index: 0, function: { name: null, arguments: null } }, + { index: 0, function: { name: " ", arguments: "" } }, + ]) { + const events = await collect( + chunk({ tool_calls: [placeholder] }) + chunk({ content: "Hello" }, "stop") + line("[DONE]"), + ) + expect(callsFrom(events)).toEqual([]) + expect(events.filter((e) => e.error)).toEqual([]) + expect(events.map((e) => e.text ?? "").join("")).toBe("Hello") + expect(events.at(-1)?.stop).toBe("stop") + } +}) + +test("an id and argument prefix wait for the native tool name", async () => { + const events = await collect( + chunk({ tool_calls: [{ index: 0, id: "call_delayed", type: "function" }] }) + + chunk({ tool_calls: [{ index: 0, function: { arguments: '{"command":' } }] }) + + chunk({ tool_calls: [{ index: 0, function: { name: "Bash", arguments: '"pwd"}' } }] }) + + finish, + ) + expect(callsFrom(events)).toEqual([ + { index: 0, id: "call_delayed", name: "Bash", args: '{"command":"pwd"}' }, + ]) + expect(events.filter((e) => e.error)).toEqual([]) +}) + +test("a native call that never supplies its name is an error, not an empty-name tool", async () => { + for (const tool of [ + { index: 0, id: "call_missing" }, + { index: 0, function: { arguments: "{}" } }, + { index: 0, id: "call_blank", function: { name: " ", arguments: "{}" } }, + ]) { + const events = await collect(chunk({ tool_calls: [tool] }) + finish) + expect(callsFrom(events)).toEqual([]) + expect(events.filter((e) => e.stop)).toEqual([]) + expect(events.at(-1)?.error).toMatchObject({ status: 502 }) + expect(events.at(-1).error.message).toMatch(/tool call.*name/) + } +}) + +const interleaved = + chunk({ tool_calls: [ + { index: 0, id: "call_first", function: { name: "Read", arguments: '{"path":' } }, + { index: 1, id: "call_second", function: { name: "Bash", arguments: '{"command":' } }, + ] }) + + chunk({ tool_calls: [{ index: 0, function: { arguments: '"a.go"}' } }] }) + + chunk({ tool_calls: [{ index: 1, function: { arguments: '"pwd"}' } }] }) + + finish + +test("interleaved native argument deltas keep their original call indexes", async () => { + expect(callsFrom(await collect(interleaved))).toEqual([ + { index: 0, id: "call_first", name: "Read", args: '{"path":"a.go"}' }, + { index: 1, id: "call_second", name: "Bash", args: '{"command":"pwd"}' }, + ]) +}) + +test("a delayed native name can follow a text call without stealing its arguments", async () => { + const events = await collect( + chunk({ tool_calls: [{ index: 0, id: "call_later", function: { arguments: '{"path":' } }] }) + + chunk({ content: textCall }) + + chunk({ tool_calls: [{ index: 0, function: { name: "Read", arguments: '"a.go"}' } }] }) + + finish, + ) + expect(callsFrom(events)).toMatchObject([ + { index: 0, name: "Bash", args: '{"command":"pwd"}' }, + { index: 1, id: "call_later", name: "Read", args: '{"path":"a.go"}' }, + ]) +}) + +test("the non-streaming adapter rejects an unnamed native call with 502", async () => { + const response = await ask(chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, false) + expect(response.status).toBe(502) + const body = await response.json() + expect(body.error.message).toMatch(/tool call.*name/) + expect(body.choices).toBeUndefined() +}) + +test("the streaming adapter rejects an unnamed call before emitting any answer", async () => { + const response = await ask(chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, true) + expect(response.status).toBe(502) +}) + +test("an unnamed call after reasoning ends the stream with an error and no tool or finish", async () => { + const response = await ask( + chunk({ reasoning_content: "Thinking" }) + + chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, + true, + ) + expect(response.status).toBe(200) + const frames = await framesFrom(response) + expect(frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])).toEqual([]) + expect(frames.filter((f) => f.choices?.[0]?.finish_reason)).toEqual([]) + expect(frames.at(-1)?.error.message).toMatch(/tool call.*name/) +}) + +test("the non-streaming adapter assembles interleaved calls by output index", async () => { + const response = await ask(interleaved, false) + expect(response.status).toBe(200) + const choice = (await response.json()).choices[0] + expect(choice.finish_reason).toBe("tool_calls") + expect(choice.message.tool_calls).toEqual([ + { id: "call_first", type: "function", function: { name: "Read", arguments: '{"path":"a.go"}' } }, + { id: "call_second", type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' } }, + ]) +}) + +test("the streaming adapter emits only the named text call after a native placeholder", async () => { + const response = await ask( + chunk({ tool_calls: [{ index: 0, function: { name: "", arguments: "" } }] }) + + chunk({ content: textCall }) + finish, + true, + ) + expect(response.status).toBe(200) + const frames = await framesFrom(response) + const tools = frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? []) + expect(tools).toHaveLength(1) + expect(tools[0]).toMatchObject({ + index: 0, type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' }, + }) +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 2b131fb..2ceb836 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.19", + "version": "0.2.20", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs",