qoder 0.2.51: a native tool call that never gets its name no longer fails the turn (#579)

bigstage915 (Qoder CN, qoder-cn/qfmodel through ZCode) saw qfmodel now and
then begin a native tool call and never send its function name. events()
then ended the stream with "the model's native tool call has no name", an
SSE error frame on a 200, which ZCode reads as not retryable: the whole
turn died, with the reasoning and text already shown (9 incidents in four
days, after reasoning-end and after a named call's tool-input-start and
argument deltas).

An unnamed call is still never given, and its held arguments go nowhere,
not into the text. Now:
- Nothing of the answer said before it (no text, reasoning or call): the
  reply is the same 502 as before, marked nameless, and ask sends the
  request once more under a new request_id. A second such reply goes back
  as the 502, before any byte, which magpie's gateway retries or fails
  over (retryable: status >= 500).
- The answer had begun: the call is dropped and the answer ends as it
  would have without it, tool_calls beside a named call, stop (or length)
  otherwise, and console.warn says so (the host's stderr, in magpie's
  log). The non-streaming reply is the same: named calls kept, the
  unnamed one left out.

Tests (native-tools.test.mjs): the after-reasoning test now expects the
reasoning kept, no tool frame, finish stop and the warning; new cases for
an unnamed call after a named call's start and argument deltas (stream),
beside a named one (non-streaming, unnamed first and after), after text,
and nothing-said (asked twice, then 502; asked twice, second answer
given). The two 502 tests now also count two chat requests.

Run, on the WSL2 box (magpie-desktop, Bun 1.4.2; mote at load ~120):
- native-tools.test.mjs: 15 pass.
- The new test file against origin/main's index.mjs: the 7 new or
  changed tests fail, the 8 others pass.
- Broken by hand: the in-plugin retry off, 3 fail (the retry tests);
  reasoning not counted as said, 1 fails (after-reasoning).
- Full `HOME=$(mktemp -d) bun test` at this tree: 4469 pass, 1 fail,
  agent-office's "midnight and metadata-only changes do not read JSONL
  again", red alone on untouched origin/main 26864ec too, in UTC and
  Asia/Shanghai: filed as #580. `bun scripts/check.mjs`: ok.

Siblings: no other package has this guard (grep of the error text and an
unnamed-call check over packages/). magpie's own chatTidy already drops a
call whose first fragment has no name and ends stop (#1475), the same
choice.

Not tried: a real Qoder CN account; the failure is the model's and not
reproducible on demand.
This commit is contained in:
yetone
2026-11-01 07:06:57 +08:00
parent 26864ec9b0
commit 5403c21484
4 changed files with 163 additions and 18 deletions
+7
View File
@@ -153,6 +153,13 @@ itself.
reasoning and usage. reasoning and usage.
- Tool calls Qoder writes as XML or JSON in its text become tool calls. - 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. Tool calls it sends the OpenAI way keep Qoder's id.
- A call sent the OpenAI way that never gets its function name is never
sent on, and its arguments go nowhere (since 0.2.51, #579). If nothing
of the answer came before it, the request is sent once more; a second
such reply is a 502 that magpie can retry or fail over. If the answer
had begun (text, reasoning or a named call), the unnamed call is dropped
and the answer ends as it would have without it (`tool_calls` beside a
named call, `stop` otherwise), with a warning in magpie's log.
- A call written in the text that can't be read, or that the stream ends - 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 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 ends as an error, a 502 or the stream's error frame with no finish, so
+37 -4
View File
@@ -1711,6 +1711,9 @@ async function* events(body, tools = []) {
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 } 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 usage
let fr = "" let fr = ""
// said: something of the answer has been given (text, reasoning or a
// call), which a client may already show
let said = false
for await (const line of sseLines(body)) { for await (const line of sseLines(body)) {
if (!line.startsWith("data:")) continue if (!line.startsWith("data:")) continue
const payload = line.slice(5).trim() const payload = line.slice(5).trim()
@@ -1733,13 +1736,17 @@ async function* events(body, tools = []) {
continue continue
} }
const delta = chunk?.choices?.[0]?.delta ?? {} const delta = chunk?.choices?.[0]?.delta ?? {}
if (delta.reasoning_content) yield { reasoning: delta.reasoning_content } if (delta.reasoning_content) {
said = true
yield { reasoning: delta.reasoning_content }
}
if (typeof delta.content === "string") if (typeof delta.content === "string")
for (const f of a.feed(delta.content)) { for (const f of a.feed(delta.content)) {
if (!f.call && !f.error && !f.text) continue if (!f.call && !f.error && !f.text) continue
const e = piece(f) const e = piece(f)
yield e yield e
if (e.error) return if (e.error) return
said = true
} }
// tool calls served the OpenAI way keep Qoder's id: a result answers it // tool calls served the OpenAI way keep Qoder's id: a result answers it
for (const tc of delta.tool_calls ?? []) { for (const tc of delta.tool_calls ?? []) {
@@ -1763,7 +1770,7 @@ async function* events(body, tools = []) {
yield e yield e
if (e.error) return if (e.error) return
} }
a.sawTool = true a.sawTool = said = true
call.index = ++index call.index = ++index
yield { tool: { index: call.index, id: call.id || "call_" + hexID(), name, args: call.args } } yield { tool: { index: call.index, id: call.id || "call_" + hexID(), name, args: call.args } }
} else if (args) yield { args: { index: call.index, text: args } } } else if (args) yield { args: { index: call.index, text: args } }
@@ -1786,14 +1793,31 @@ async function* events(body, tools = []) {
const e = piece(f) const e = piece(f)
yield e yield e
if (e.error) return if (e.error) return
said = true
} }
if ([...native.values()].some((call) => call.index === undefined)) { // A native call the model began and never named is never given: a
yield { error: { status: 502, message: "the model's native tool call has no name; it is not sent on as a tool" } } // client keeps an unnamed tool in its history and other providers
// refuse it. Its arguments, held while it waited for the name, go
// nowhere, not into the text either. With nothing said before it, the
// reply is no answer: a 502 (nameless) that ask sends once more, then
// the gateway's to retry or fail over. After an answer began, the call
// is dropped and the answer ends as it would have without it, so the
// text, reasoning and named calls already given are kept: qoder-cn's
// qfmodel did this now and then, and the whole turn failed with an
// error the client didn't retry (plugins#579).
const nameless = [...native.values()].filter((call) => call.index === undefined).length
if (nameless && !said) {
yield { error: { status: 502, message: NAMELESS, nameless: true } }
return return
} }
if (nameless) console.warn(`qoder: dropped ${nameless} native tool call${nameless > 1 ? "s" : ""} the model never named (plugins#579)`)
yield { stop: a.sawTool ? "tool_calls" : fr === "length" ? "length" : "stop", usage } yield { stop: a.sawTool ? "tool_calls" : fr === "length" ? "length" : "stop", usage }
} }
// NAMELESS is the error of a reply whose only answer was a native tool
// call the model never named.
const NAMELESS = "the model's native tool call has no name; it is not sent on as a tool"
// answer turns Qoder's reply into the chat completion OpenAI's API gives. // answer turns Qoder's reply into the chat completion OpenAI's API gives.
// A failure before the answer keeps its status; one after it ends the // A failure before the answer keeps its status; one after it ends the
// stream with an error. // stream with an error.
@@ -2880,6 +2904,7 @@ const makePlugin = (site) => async ({ client }) => {
asked.cred = cred asked.cred = cred
let m let m
let relogged = false let relogged = false
let renamed = false
const listed = (ms) => ms.find((x) => x.key === chat.model) const listed = (ms) => ms.find((x) => x.key === chat.model)
try { try {
m = listed(await models(cred)) ?? listed(await models(cred, true)) m = listed(await models(cred)) ?? listed(await models(cred, true))
@@ -2954,6 +2979,14 @@ const makePlugin = (site) => async ({ client }) => {
continue continue
} }
} }
// a reply whose only answer was a native tool call the model never
// named (plugins#579): nothing of it was given, so it is asked once
// more, under a new request_id; a second one is the gateway's 502 to
// retry or fail over
if (f?.nameless && !renamed) {
renamed = true
continue
}
// an answered call moves its task on, as Qoder's client moves it // an answered call moves its task on, as Qoder's client moves it
if (!f) task.answered = true if (!f) task.answered = true
// with another account, provider or group member after this one // with another account, provider or group member after this one
+118 -13
View File
@@ -25,16 +25,21 @@ function callsFrom(events) {
return calls return calls
} }
// chats counts the chat requests ask's fetch was sent; a list of replies
// answers them in turn, its last one every request after
let chats = 0
async function ask(reply, stream) { async function ask(reply, stream) {
const auth = { const auth = {
type: "oauth", access: "fixture-job-token", refresh: "fixture-refresh-token", type: "oauth", access: "fixture-job-token", refresh: "fixture-refresh-token",
expires: Date.now() + 3_600_000, accountId: "native-tools@example.test", expires: Date.now() + 3_600_000, accountId: "native-tools@example.test",
uid: "native-tools", machineId: "fixture-machine", uid: "native-tools", machineId: "fixture-machine",
} }
const replies = [reply].flat()
chats = 0
globalThis.fetch = async (url) => globalThis.fetch = async (url) =>
new URL(String(url)).pathname.endsWith("/model/list") new URL(String(url)).pathname.endsWith("/model/list")
? Response.json({ chat: [{ key: "efficient", display_name: "Efficient", enable: true }] }) ? Response.json({ chat: [{ key: "efficient", display_name: "Efficient", enable: true }] })
: new Response(reply, { headers: { "Content-Type": "text/event-stream" } }) : new Response(replies[Math.min(chats++, replies.length - 1)], { headers: { "Content-Type": "text/event-stream" } })
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
const loader = await hooks.auth.loader(async () => auth) const loader = await hooks.auth.loader(async () => auth)
return loader.fetch("https://api3.qoder.sh/v1/chat/completions", { return loader.fetch("https://api3.qoder.sh/v1/chat/completions", {
@@ -132,30 +137,130 @@ test("a delayed native name can follow a text call without stealing its argument
]) ])
}) })
test("the non-streaming adapter rejects an unnamed native call with 502", async () => { const unnamedOnly = chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish
const response = await ask(chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, false)
test("the non-streaming adapter rejects an unnamed native call with 502 after asking once more", async () => {
const response = await ask(unnamedOnly, false)
expect(response.status).toBe(502) expect(response.status).toBe(502)
const body = await response.json() const body = await response.json()
expect(body.error.message).toMatch(/tool call.*name/) expect(body.error.message).toMatch(/tool call.*name/)
expect(body.choices).toBeUndefined() expect(body.choices).toBeUndefined()
// nothing of either reply was given: the plugin asked twice, then the
// gateway has a 502 before any byte to retry or fail over (plugins#579)
expect(chats).toBe(2)
}) })
test("the streaming adapter rejects an unnamed call before emitting any answer", async () => { test("the streaming adapter rejects an unnamed call before emitting any answer, after asking once more", async () => {
const response = await ask(chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, true) const response = await ask(unnamedOnly, true)
expect(response.status).toBe(502) expect(response.status).toBe(502)
expect(chats).toBe(2)
}) })
test("an unnamed call after reasoning ends the stream with an error and no tool or finish", async () => { test("an unnamed call with nothing said before it is asked once more, and the second answer is given", async () => {
for (const stream of [true, false]) {
const response = await ask([unnamedOnly, chunk({ content: "Hello" }, "stop") + line("[DONE]")], stream)
expect(response.status).toBe(200)
expect(chats).toBe(2)
if (stream) {
const frames = await framesFrom(response)
expect(frames.map((f) => f.choices?.[0]?.delta?.content ?? "").join("")).toBe("Hello")
expect(frames.at(-1).choices[0].finish_reason).toBe("stop")
expect(frames.filter((f) => f.error)).toEqual([])
} else {
const choice = (await response.json()).choices[0]
expect(choice.message.content).toBe("Hello")
expect(choice.finish_reason).toBe("stop")
}
}
})
test("an unnamed call after reasoning is dropped and the stream finishes stop, the reasoning kept", async () => {
const warn = console.warn
const warned = []
console.warn = (...xs) => warned.push(xs.join(" "))
try {
const response = await ask(
chunk({ reasoning_content: "Thinking" })
+ chunk({ tool_calls: [{ index: 0, id: "call_missing", function: { arguments: '{"command":"rm' } }] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: ' -rf x"}' } }] }) + finish,
true,
)
expect(response.status).toBe(200)
expect(chats).toBe(1)
const text = await response.text()
expect(text).not.toContain("-rf")
expect(text).not.toContain('"command')
const frames = text.split("\n").filter((s) => s.startsWith("data: ") && s !== "data: [DONE]").map((s) => JSON.parse(s.slice(6)))
expect(frames.map((f) => f.choices?.[0]?.delta?.reasoning_content ?? "").join("")).toBe("Thinking")
expect(frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])).toEqual([])
expect(frames.filter((f) => f.error)).toEqual([])
expect(frames.at(-1).choices[0].finish_reason).toBe("stop")
expect(text.trimEnd().endsWith("data: [DONE]")).toBe(true)
expect(warned.join("\n")).toMatch(/dropped 1 native tool call the model never named/)
} finally {
console.warn = warn
}
})
// a named call is under way (tool-input-start, then its arguments), and a
// second one never gets its name: its arguments go nowhere
const namedThenUnnamed =
chunk({ tool_calls: [{ index: 0, id: "call_read", function: { name: "Read", arguments: '{"path":' } }] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '"a.go"}' } }] })
+ chunk({ tool_calls: [{ index: 1, id: "call_nameless", function: { arguments: '{"secret":' } }] })
+ chunk({ tool_calls: [{ index: 1, function: { arguments: '"LEAKED"}' } }] })
+ finish
test("an unnamed call after a named call's start and arguments is dropped; the named one finishes tool_calls", async () => {
const response = await ask(namedThenUnnamed, true)
expect(response.status).toBe(200)
const text = await response.text()
expect(text).not.toContain("LEAKED")
expect(text).not.toContain("secret")
const frames = text.split("\n").filter((s) => s.startsWith("data: ") && s !== "data: [DONE]").map((s) => JSON.parse(s.slice(6)))
const calls = []
for (const tc of frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])) {
if (tc.function?.name) calls[tc.index] = { id: tc.id, name: tc.function.name, args: tc.function.arguments }
else calls[tc.index].args += tc.function.arguments
}
expect(calls).toEqual([{ id: "call_read", name: "Read", args: '{"path":"a.go"}' }])
expect(frames.map((f) => f.choices?.[0]?.delta?.content ?? "").join("")).toBe("")
expect(frames.filter((f) => f.error)).toEqual([])
expect(frames.at(-1).choices[0].finish_reason).toBe("tool_calls")
expect(chats).toBe(1)
})
test("the non-streaming adapter drops an unnamed call beside a named one", async () => {
// the unnamed one first, upstream index 0, and the named one after it
const response = await ask( const response = await ask(
chunk({ reasoning_content: "Thinking" }) chunk({ tool_calls: [{ index: 0, id: "call_nameless", function: { arguments: '{"secret":"LEAKED"}' } }] })
+ chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish, + chunk({ tool_calls: [{ index: 1, id: "call_bash", function: { name: "Bash", arguments: '{"command":"pwd"}' } }] })
true, + finish,
false,
) )
expect(response.status).toBe(200) expect(response.status).toBe(200)
const frames = await framesFrom(response) const text = await response.text()
expect(frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])).toEqual([]) expect(text).not.toContain("LEAKED")
expect(frames.filter((f) => f.choices?.[0]?.finish_reason)).toEqual([]) const choice = JSON.parse(text).choices[0]
expect(frames.at(-1)?.error.message).toMatch(/tool call.*name/) expect(choice.finish_reason).toBe("tool_calls")
expect(choice.message.content).toBe("")
expect(choice.message.tool_calls).toEqual([
{ id: "call_bash", type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' } },
])
const streamed = await ask(namedThenUnnamed, false)
const named = (await streamed.json()).choices[0]
expect(named.finish_reason).toBe("tool_calls")
expect(named.message.tool_calls.map((c) => c.function.name)).toEqual(["Read"])
})
test("an unnamed call after text is dropped; the text ends stop", async () => {
const events = await collect(
chunk({ content: "Let me look." })
+ chunk({ tool_calls: [{ index: 0, id: "call_missing", function: { arguments: '{"x":1}' } }] }) + finish,
)
expect(events.filter((e) => e.error || e.tool || e.args)).toEqual([])
expect(events.map((e) => e.text ?? "").join("")).toBe("Let me look.")
expect(events.at(-1)?.stop).toBe("stop")
}) })
test("the non-streaming adapter assembles interleaved calls by output index", async () => { test("the non-streaming adapter assembles interleaved calls by output index", async () => {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@magpie-community/opencode-qoder-auth", "name": "@magpie-community/opencode-qoder-auth",
"version": "0.2.50", "version": "0.2.51",
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
"type": "module", "type": "module",
"main": "./index.mjs", "main": "./index.mjs",