qoder 0.2.65: two tool calls at one index with their own ids are two (#930)
Qoder Ultimate sent two native tool calls at tool_calls[].index 0, each
with its own id and name. events() kept one call per upstream index, so
the second call's arguments were sent as more of the first:
{"key":"A"}{"key":"B"}, which the client refused as unparseable JSON.
A fragment with a non-empty id that differs from the open call's id at
that index now starts a new call with an output index of its own. A
fragment with no id, or the open call's id, still goes on with the open
call (OpenAI's argument fragments, and relays that repeat the id). A call
pushed aside before it got a name still counts as nameless (#579).
After two ids at one index, id-less fragments go to the newer call; the
report suggested failing there instead, but OpenAI streams each call's
fragments right after its start, so the newest is the one open.
Siblings with the same index-keyed fold, fixed the same way:
- zed 0.1.19: chatWhole (a streamed chat reply folded for stream:false).
- codearts 0.3.7: completionFromChunks.
- zen-free 0.1.27: stream.mjs chatAccumulator, and tool-response.mjs's
chat buffer, which gives each call its own index when two collided.
- page-chat 0.1.13: lib/server.mjs folds through toolCallFolder.
Looked at and left: codearts' stream name restorer and kimi-desktop's
Agent hold pass fragments through unchanged and join no arguments;
zed's streaming path passes Zed's chunks through, and magpie's gateway
already starts a new call on a new id (internal/gateway/chat.go).
Run (WSL magpie-desktop, bun 1.4.2, node 22):
- pedh's repro.mjs with his fixture: [0,0] gave one tool event plus an
args event on 0.2.64; now two tool events (index 0 and 1), each with
valid JSON. [0,1] unchanged.
- HOME=$(mktemp -d) bun test packages/qoder packages/zed
packages/codearts packages/zen-free packages/chat: 987 pass, 0 fail,
1 skip (the epub reader's, as before). bun scripts/check.mjs: every
package and registry.json ok.
Broken by hand:
- qoder back to index-only: 3 of the new tests fail (two ids, id-less
after a second id, streaming adapter).
- qoder starting a call on any fragment without the open id: 8 fail,
the id-less continuation test among them.
- qoder treating any id as new: the repeated-id test fails.
- zed, codearts, zen-free (both) on main's code and chat keyed by index
only: each new collision test fails (5 of 5).
Not tried: a real Qoder account (no Qoder Ultimate here), real Zed,
CodeArts or OpenCode Zen replies with a collision, and the chat page
in a browser.
Reported-by: pedh <pedh@users.noreply.github.com>
This commit is contained in:
@@ -210,6 +210,33 @@ function firstLine(messages) {
|
||||
let OWN = new Set();
|
||||
let HOSTS = new Set();
|
||||
const TOKEN = randomBytes(32).toString("hex");
|
||||
// toolCallFolder puts a streamed reply's tool call fragments together. A
|
||||
// fragment with a new id at an index in use is a new call, not more of the
|
||||
// open one: two calls at one index ran together as {"a"}{"b"}
|
||||
// (plugins#930). No id, or the same one, goes on with the open call.
|
||||
export function toolCallFolder() {
|
||||
const open = new Map(); // index -> the call being written there
|
||||
const all = [];
|
||||
return {
|
||||
add(tc) {
|
||||
const i = tc.index ?? 0;
|
||||
let cur = open.get(i);
|
||||
if (!cur || (tc.id && cur.id && tc.id !== cur.id)) {
|
||||
cur = { id: "", name: "", args: "" };
|
||||
open.set(i, cur);
|
||||
all.push(cur);
|
||||
}
|
||||
if (tc.id) cur.id = tc.id;
|
||||
if (tc.function?.name) cur.name += tc.function.name;
|
||||
if (tc.function?.arguments) cur.args += tc.function.arguments;
|
||||
},
|
||||
get size() {
|
||||
return all.length;
|
||||
},
|
||||
list: () => all,
|
||||
};
|
||||
}
|
||||
|
||||
export const TOKEN_HEADER = "x-magpie-chat-token";
|
||||
|
||||
function originAllowed(req) {
|
||||
@@ -466,7 +493,7 @@ async function runChat({ res, body, settings, store, options }, controllers) {
|
||||
|
||||
let content = "";
|
||||
let reasoning = "";
|
||||
const calls = new Map(); // index -> { id, name, args }
|
||||
const calls = toolCallFolder();
|
||||
let finish = "";
|
||||
|
||||
for await (const chunk of sseChunks(upstream)) {
|
||||
@@ -482,19 +509,12 @@ async function runChat({ res, body, settings, store, options }, controllers) {
|
||||
const d = choice.delta || {};
|
||||
if (d.reasoning_content) { reasoning += d.reasoning_content; sse(res, "reasoning", { text: d.reasoning_content }); }
|
||||
if (d.content) { content += d.content; sse(res, "delta", { text: d.content }); }
|
||||
for (const tc of d.tool_calls || []) {
|
||||
const i = tc.index ?? 0;
|
||||
const cur = calls.get(i) || { id: "", name: "", args: "" };
|
||||
if (tc.id) cur.id = tc.id;
|
||||
if (tc.function?.name) cur.name += tc.function.name;
|
||||
if (tc.function?.arguments) cur.args += tc.function.arguments;
|
||||
calls.set(i, cur);
|
||||
}
|
||||
for (const tc of d.tool_calls || []) calls.add(tc);
|
||||
if (choice.finish_reason) finish = choice.finish_reason;
|
||||
}
|
||||
|
||||
if (calls.size && (finish === "tool_calls" || finish === "stop")) {
|
||||
const made = [...calls.values()].filter((c) => c.name).map((c, i) => {
|
||||
const made = calls.list().filter((c) => c.name).map((c, i) => {
|
||||
let id = c.id;
|
||||
if (!id || callIds.has(id)) {
|
||||
id = `call_${round}_${i}`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-chat",
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.13",
|
||||
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
|
||||
"author": "Magic_zero (https://github.com/Magiczerowxy)",
|
||||
"files": [
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// How a streamed reply's tool call fragments are put together: two calls
|
||||
// that share an index but have their own ids are two calls, not one with
|
||||
// {"a"}{"b"} arguments (plugins#930). Fragments with no id, or the same
|
||||
// id, go on with the open call.
|
||||
import { expect, test } from "bun:test";
|
||||
import { toolCallFolder } from "./lib/server.mjs";
|
||||
|
||||
const fold = (fragments) => {
|
||||
const calls = toolCallFolder();
|
||||
for (const tc of fragments) calls.add(tc);
|
||||
return calls.list();
|
||||
};
|
||||
const A = { index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":"A"}' } };
|
||||
const B = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":"B"}' } });
|
||||
const both = [{ id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' }, { id: "call_fixture_B", name: "fixture_beta", args: '{"key":"B"}' }];
|
||||
|
||||
test("two ids at one index are two calls", () => {
|
||||
const calls = fold([A, B(0)]);
|
||||
expect(calls).toEqual(both);
|
||||
for (const c of calls) expect(() => JSON.parse(c.args)).not.toThrow();
|
||||
});
|
||||
|
||||
test("calls at their own indexes stay two calls", () => {
|
||||
expect(fold([A, B(1)])).toEqual(both);
|
||||
});
|
||||
|
||||
test("fragments with no id, or the same id, go on with the open call", () => {
|
||||
expect(fold([
|
||||
{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"ke' } },
|
||||
{ index: 0, function: { arguments: 'y":' } },
|
||||
{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } },
|
||||
])).toEqual([{ id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' }]);
|
||||
});
|
||||
@@ -1427,6 +1427,7 @@ function completionFromChunks(events) {
|
||||
const content = []
|
||||
const reasoning = []
|
||||
const toolCalls = []
|
||||
const open = new Map() // upstream index -> the call being written there
|
||||
let finish = null
|
||||
let usage = null
|
||||
let model = first.model
|
||||
@@ -1440,7 +1441,17 @@ function completionFromChunks(events) {
|
||||
if (typeof delta.content === "string") content.push(delta.content)
|
||||
if (typeof delta.reasoning_content === "string") reasoning.push(delta.reasoning_content)
|
||||
for (const call of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
|
||||
const slot = (toolCalls[num(call.index)] ??= { id: "", type: "function", function: { name: "", arguments: "" } })
|
||||
// a new id at an index in use is a new call, not more of the open
|
||||
// one: two calls at one index ran together as {"a"}{"b"}
|
||||
// (plugins#930). No id, or the same one, goes on with it.
|
||||
let slot = open.get(num(call.index))
|
||||
const id = typeof call.id === "string" ? call.id : ""
|
||||
if (!slot || (id && slot.id && id !== slot.id)) {
|
||||
slot = { id: "", type: "function", function: { name: "", arguments: "" } }
|
||||
if (toolCalls[num(call.index)]) toolCalls.push(slot)
|
||||
else toolCalls[num(call.index)] = slot
|
||||
open.set(num(call.index), slot)
|
||||
}
|
||||
if (typeof call.id === "string" && call.id) slot.id = call.id
|
||||
if (typeof call.type === "string" && call.type) slot.type = call.type
|
||||
if (typeof call.function?.name === "string") slot.function.name += call.function.name
|
||||
|
||||
@@ -3874,3 +3874,23 @@ test("a removed OfficeAce record is not written back when no restart separates t
|
||||
await ca2.auth.refresh(store.get(keyOf("codearts")))
|
||||
assert.equal(store.has(keyOf("officeace")), false, "a single removed record must stay removed without a restart")
|
||||
})
|
||||
|
||||
// plugins#930: a streamed reply folded into one for a client that asked for
|
||||
// it whole. Two calls with their own ids at one index are two calls, not
|
||||
// one with {"a"}{"b"} arguments; fragments with no id, or the same id, go on
|
||||
// with the open call.
|
||||
test("folding a stream keeps two ids at one index as two calls", () => {
|
||||
const ev = (call) => ({ id: "c1", model: "GLM-5.2", choices: [{ index: 0, delta: { tool_calls: [call] }, finish_reason: null }] })
|
||||
const A = { index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":"A"}' } }
|
||||
const B = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":"B"}' } })
|
||||
const fold = (calls) => x.completionFromChunks([...calls.map(ev), { choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }])
|
||||
.choices[0].message.tool_calls.map((c) => [c.id, c.function.name, c.function.arguments])
|
||||
const both = [["call_fixture_A", "fixture_alpha", '{"key":"A"}'], ["call_fixture_B", "fixture_beta", '{"key":"B"}']]
|
||||
assert.deepEqual(fold([A, B(0)]), both)
|
||||
assert.deepEqual(fold([A, B(1)]), both)
|
||||
assert.deepEqual(fold([
|
||||
{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"ke' } },
|
||||
{ index: 0, function: { arguments: 'y":' } },
|
||||
{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } },
|
||||
]), [["call_fixture_A", "fixture_alpha", '{"key":"A"}']])
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-codearts-auth",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"description": "Huawei Cloud in OpenCode and magpie: CodeArts (码道) and OfficeAce (AgentArts), each from its own Huawei Cloud OAuth sign-in — models, credit rates, credit usage and the daily check-in (unofficial)",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
@@ -162,6 +162,9 @@ 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.
|
||||
- Two calls sent the OpenAI way at one index, each with its own id, are
|
||||
two calls (since 0.2.65, #930). A piece with no id, or the open call's
|
||||
id, is more of the open call.
|
||||
- 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
|
||||
|
||||
@@ -2224,6 +2224,7 @@ 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
|
||||
const begun = [] // every native call, one an index has moved past too
|
||||
// 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) =>
|
||||
@@ -2281,9 +2282,14 @@ async function* events(body, tools = []) {
|
||||
const args = tc.function?.arguments ?? ""
|
||||
if (!tc.id && !name && !args) continue
|
||||
let call = native.get(i)
|
||||
if (!call) {
|
||||
// A new id at an index already in use is a new call: Qoder Ultimate
|
||||
// has sent two calls at index 0, and the second's arguments ran
|
||||
// into the first's as {"a"}{"b"} (plugins#930). No id, or the same
|
||||
// one, is the open call going on.
|
||||
if (!call || (tc.id && call.id && tc.id !== call.id)) {
|
||||
call = { id: "", args: "" }
|
||||
native.set(i, call)
|
||||
begun.push(call)
|
||||
}
|
||||
if (tc.id) call.id = tc.id
|
||||
if (call.index === undefined) {
|
||||
@@ -2331,7 +2337,7 @@ async function* events(body, tools = []) {
|
||||
// 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
|
||||
const nameless = begun.filter((call) => call.index === undefined).length
|
||||
if (nameless && !said) {
|
||||
yield { error: { status: 502, message: NAMELESS, nameless: true } }
|
||||
return
|
||||
|
||||
@@ -288,3 +288,68 @@ test("the streaming adapter emits only the named text call after a native placeh
|
||||
index: 0, type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' },
|
||||
})
|
||||
})
|
||||
|
||||
// plugins#930: pedh's wire, two calls with their own ids and names at
|
||||
// index 0, each with whole arguments
|
||||
const fixtureA = { index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":"A"}' } }
|
||||
const fixtureB = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":"B"}' } })
|
||||
|
||||
test("two calls with their own ids at one index are two calls (plugins#930)", async () => {
|
||||
const calls = callsFrom(await collect(
|
||||
chunk({ tool_calls: [fixtureA] }, null) + chunk({ tool_calls: [fixtureB(0)] }, null) + finish,
|
||||
))
|
||||
expect(calls).toEqual([
|
||||
{ index: 0, id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' },
|
||||
{ index: 1, id: "call_fixture_B", name: "fixture_beta", args: '{"key":"B"}' },
|
||||
])
|
||||
for (const call of calls) expect(() => JSON.parse(call.args)).not.toThrow()
|
||||
})
|
||||
|
||||
test("calls at their own indexes stay two calls (plugins#930 control)", async () => {
|
||||
const calls = callsFrom(await collect(
|
||||
chunk({ tool_calls: [fixtureA] }, null) + chunk({ tool_calls: [fixtureB(1)] }, null) + finish,
|
||||
))
|
||||
expect(calls).toEqual([
|
||||
{ index: 0, id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' },
|
||||
{ index: 1, id: "call_fixture_B", name: "fixture_beta", args: '{"key":"B"}' },
|
||||
])
|
||||
})
|
||||
|
||||
test("fragments with no id go on with the open call", async () => {
|
||||
const calls = callsFrom(await collect(
|
||||
chunk({ tool_calls: [{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"ke' } }] }, null)
|
||||
+ chunk({ tool_calls: [{ index: 0, function: { arguments: 'y":' } }] }, null)
|
||||
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '"A"}' } }] }, null)
|
||||
+ finish,
|
||||
))
|
||||
expect(calls).toEqual([{ index: 0, id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' }])
|
||||
})
|
||||
|
||||
test("fragments that repeat the open call's id go on with it", async () => {
|
||||
const calls = callsFrom(await collect(
|
||||
chunk({ tool_calls: [{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":' } }] }, null)
|
||||
+ chunk({ tool_calls: [{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } }] }, null)
|
||||
+ finish,
|
||||
))
|
||||
expect(calls).toEqual([{ index: 0, id: "call_fixture_A", name: "fixture_alpha", args: '{"key":"A"}' }])
|
||||
})
|
||||
|
||||
test("after a second id at one index, fragments with no id go to the second call", async () => {
|
||||
const calls = callsFrom(await collect(
|
||||
chunk({ tool_calls: [fixtureA] }, null)
|
||||
+ chunk({ tool_calls: [{ index: 0, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":' } }] }, null)
|
||||
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '"B"}' } }] }, null)
|
||||
+ finish,
|
||||
))
|
||||
expect(calls.map((c) => [c.id, c.args])).toEqual([["call_fixture_A", '{"key":"A"}'], ["call_fixture_B", '{"key":"B"}']])
|
||||
})
|
||||
|
||||
test("the streaming adapter sends two calls at one upstream index as two (plugins#930)", async () => {
|
||||
const response = await ask(chunk({ tool_calls: [fixtureA] }, null) + chunk({ tool_calls: [fixtureB(0)] }, null) + finish, true)
|
||||
expect(response.status).toBe(200)
|
||||
const tools = (await framesFrom(response)).flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])
|
||||
expect(tools.map((t) => [t.index, t.id, t.function.name, t.function.arguments])).toEqual([
|
||||
[0, "call_fixture_A", "fixture_alpha", '{"key":"A"}'],
|
||||
[1, "call_fixture_B", "fixture_beta", '{"key":"B"}'],
|
||||
])
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-qoder-auth",
|
||||
"version": "0.2.64",
|
||||
"version": "0.2.65",
|
||||
"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",
|
||||
|
||||
+12
-1
@@ -1123,6 +1123,7 @@ function responsesWhole(events) {
|
||||
function chatWhole(events) {
|
||||
let out = null
|
||||
const choices = []
|
||||
const open = new Map() // "choice:index" -> the call being written there
|
||||
for (const ev of events) {
|
||||
out ??= { id: ev.id, object: "chat.completion", created: ev.created, model: ev.model }
|
||||
if (ev.usage) out.usage = ev.usage
|
||||
@@ -1133,7 +1134,17 @@ function chatWhole(events) {
|
||||
if (d.reasoning_content) ch.message.reasoning_content = (ch.message.reasoning_content ?? "") + d.reasoning_content
|
||||
for (const t of d.tool_calls ?? []) {
|
||||
const calls = (ch.message.tool_calls ??= [])
|
||||
const tc = (calls[t.index ?? 0] ??= { id: "", type: "function", function: { name: "", arguments: "" } })
|
||||
// a new id at an index in use is a new call, not more of the open
|
||||
// one: two calls at one index ran together as {"a"}{"b"}
|
||||
// (plugins#930). No id, or the same one, goes on with it.
|
||||
const key = `${c.index ?? 0}:${t.index ?? 0}`
|
||||
let tc = open.get(key)
|
||||
if (!tc || (t.id && tc.id && t.id !== tc.id)) {
|
||||
tc = { id: "", type: "function", function: { name: "", arguments: "" } }
|
||||
if (calls[t.index ?? 0]) calls.push(tc)
|
||||
else calls[t.index ?? 0] = tc
|
||||
open.set(key, tc)
|
||||
}
|
||||
if (t.id) tc.id = t.id
|
||||
if (t.function?.name) tc.function.name += t.function.name
|
||||
if (t.function?.arguments) tc.function.arguments += t.function.arguments
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zed-auth",
|
||||
"version": "0.1.18",
|
||||
"version": "0.1.19",
|
||||
"description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// A streamed Chat Completions reply put together for a client that asked
|
||||
// for one whole: two calls that share an upstream index but have their own
|
||||
// ids are two calls, not one with {"a"}{"b"} arguments (plugins#930).
|
||||
// Fragments with no id, or the same id, go on with the open call.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
_internal.tokens.clear()
|
||||
})
|
||||
|
||||
const s = { userId: "4242", access: "plain-access", systemId: "", org: "org-me", plan: "zed_pro", who: "octo" }
|
||||
|
||||
async function whole(deltas) {
|
||||
const lines = [{ status: "started" }, ...deltas.map((delta) => ({ event: { id: "c1", object: "chat.completion.chunk", created: 1, model: "grok-4.7", choices: [{ index: 0, delta, finish_reason: null }] } })),
|
||||
{ event: { id: "c1", object: "chat.completion.chunk", created: 1, model: "grok-4.7", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] } }, { status: "stream_ended" }]
|
||||
globalThis.fetch = async (url) => {
|
||||
const path = new URL(String(url)).pathname
|
||||
if (path === "/client/llm_tokens") return Response.json({ token: "llm-token" })
|
||||
if (path === "/completions")
|
||||
return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } })
|
||||
return new Response("", { status: 404 })
|
||||
}
|
||||
const res = await _internal.complete(s, "https://cloud.zed.dev/v1/chat/completions", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "grok-4.7", stream: false, messages: [{ role: "user", content: "hi" }], max_tokens: 100 }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
return (await res.json()).choices[0].message.tool_calls.map((c) => [c.id, c.function.name, c.function.arguments])
|
||||
}
|
||||
|
||||
const A = { index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":"A"}' } }
|
||||
const B = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":"B"}' } })
|
||||
|
||||
test("two ids at one index are two calls", async () => {
|
||||
const calls = await whole([{ tool_calls: [A] }, { tool_calls: [B(0)] }])
|
||||
expect(calls).toEqual([["call_fixture_A", "fixture_alpha", '{"key":"A"}'], ["call_fixture_B", "fixture_beta", '{"key":"B"}']])
|
||||
for (const [, , args] of calls) expect(() => JSON.parse(args)).not.toThrow()
|
||||
})
|
||||
|
||||
test("calls at their own indexes stay two calls", async () => {
|
||||
expect(await whole([{ tool_calls: [A] }, { tool_calls: [B(1)] }])).toEqual([
|
||||
["call_fixture_A", "fixture_alpha", '{"key":"A"}'], ["call_fixture_B", "fixture_beta", '{"key":"B"}'],
|
||||
])
|
||||
})
|
||||
|
||||
test("fragments with no id, or the same id, go on with the open call", async () => {
|
||||
expect(await whole([
|
||||
{ tool_calls: [{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"ke' } }] },
|
||||
{ tool_calls: [{ index: 0, function: { arguments: 'y":' } }] },
|
||||
{ tool_calls: [{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } }] },
|
||||
])).toEqual([["call_fixture_A", "fixture_alpha", '{"key":"A"}']])
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zen-free-auth",
|
||||
"version": "0.1.26",
|
||||
"version": "0.1.27",
|
||||
"description": "OpenCode Zen free models through the public credential, with native streaming protocols",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
@@ -59,7 +59,7 @@ function chatAccumulator() {
|
||||
message: { role: "assistant", content: null },
|
||||
finish_reason: null,
|
||||
});
|
||||
tools.set(position, new Map());
|
||||
tools.set(position, { open: new Map(), all: [] });
|
||||
}
|
||||
const choice = choices.get(position);
|
||||
const message = choice.message;
|
||||
@@ -75,9 +75,15 @@ function chatAccumulator() {
|
||||
for (const fragment of delta.tool_calls ?? []) {
|
||||
const toolIndex = index(fragment.index);
|
||||
const calls = tools.get(position);
|
||||
if (!calls.has(toolIndex))
|
||||
calls.set(toolIndex, { type: "function", function: { name: "", arguments: "" } });
|
||||
const call = calls.get(toolIndex);
|
||||
// A new id at an index in use is a new call, not more of the open
|
||||
// one: two calls at one index ran together as {"a"}{"b"}
|
||||
// (plugins#930). No id, or the same one, goes on with it.
|
||||
let call = calls.open.get(toolIndex);
|
||||
if (!call || (fragment.id && call.id && fragment.id !== call.id)) {
|
||||
call = { type: "function", function: { name: "", arguments: "" } };
|
||||
calls.open.set(toolIndex, call);
|
||||
calls.all.push([toolIndex, call]);
|
||||
}
|
||||
for (const key of ["id", "type"]) {
|
||||
if (fragment[key] !== undefined) call[key] = fragment[key];
|
||||
}
|
||||
@@ -96,7 +102,9 @@ function chatAccumulator() {
|
||||
},
|
||||
finish() {
|
||||
for (const [position, choice] of choices) {
|
||||
if (tools.get(position).size) choice.message.tool_calls = sorted(tools.get(position));
|
||||
const calls = tools.get(position).all;
|
||||
// by index, and in the order they began within one (sort is stable)
|
||||
if (calls.length) choice.message.tool_calls = calls.sort(([a], [b]) => a - b).map(([, call]) => call);
|
||||
}
|
||||
body.choices = sorted(choices);
|
||||
return body;
|
||||
|
||||
@@ -691,3 +691,25 @@ test("read failures after a completion marker are not swallowed", async () => {
|
||||
);
|
||||
await assert.rejects(collapseResponse(response, "chat"), (error) => error === cause);
|
||||
});
|
||||
|
||||
// plugins#930: two calls with their own ids at one index are two calls, not
|
||||
// one with {"a"}{"b"} arguments; fragments with no id, or the same id, go on
|
||||
// with the open call.
|
||||
test("collapsing chat keeps two ids at one tool index as two calls", async () => {
|
||||
const A = { index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"key":"A"}' } };
|
||||
const B = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "fixture_beta", arguments: '{"key":"B"}' } });
|
||||
const fold = async (fragments) =>
|
||||
(await json(
|
||||
fragments.map((tc) => event({ id: "c1", choices: [{ index: 0, delta: { tool_calls: [tc] }, finish_reason: null }] })).join("")
|
||||
+ event({ id: "c1", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }) + event("[DONE]"),
|
||||
"chat",
|
||||
)).choices[0].message.tool_calls.map((c) => [c.id, c.function.name, c.function.arguments]);
|
||||
const both = [["call_fixture_A", "fixture_alpha", '{"key":"A"}'], ["call_fixture_B", "fixture_beta", '{"key":"B"}']];
|
||||
assert.deepEqual(await fold([A, B(0)]), both);
|
||||
assert.deepEqual(await fold([A, B(1)]), both);
|
||||
assert.deepEqual(await fold([
|
||||
{ index: 0, id: "call_fixture_A", type: "function", function: { name: "fixture_alpha", arguments: '{"ke' } },
|
||||
{ index: 0, function: { arguments: 'y":' } },
|
||||
{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } },
|
||||
]), [["call_fixture_A", "fixture_alpha", '{"key":"A"}']]);
|
||||
});
|
||||
|
||||
@@ -290,7 +290,8 @@ function chatBuffer(checkName) {
|
||||
]) {
|
||||
if (data[key] !== undefined) metadata[key] = data[key];
|
||||
}
|
||||
const state = { calls: new Map(), legacy: null, metadata, bytes: 0 };
|
||||
// calls: slot -> call; open: upstream index -> the slot being written
|
||||
const state = { calls: new Map(), open: new Map(), slots: 0, collided: false, legacy: null, metadata, bytes: 0 };
|
||||
pending.set(index, state);
|
||||
charge(state, metadata);
|
||||
}
|
||||
@@ -303,7 +304,10 @@ function chatBuffer(checkName) {
|
||||
function complete(state, index) {
|
||||
const delta = {};
|
||||
if (state.calls.size) {
|
||||
delta.tool_calls = [...state.calls].sort(([a], [b]) => a - b).map(([, value]) => value);
|
||||
// by index, and in the order they began within one (sort is stable)
|
||||
delta.tool_calls = [...state.calls.values()].sort((a, b) => a.index - b.index);
|
||||
// two calls that began at one index each get an index of their own
|
||||
if (state.collided) delta.tool_calls.forEach((call, i) => (call.index = i));
|
||||
}
|
||||
if (state.legacy) delta.function_call = state.legacy;
|
||||
const { notes } = checkChatMessage(delta, checkName);
|
||||
@@ -345,7 +349,24 @@ function chatBuffer(checkName) {
|
||||
}
|
||||
charge(state, fragment);
|
||||
const index = position(fragment.index);
|
||||
const previous = state.calls.get(index) ?? { index, function: {} };
|
||||
// A new id at an index in use is a new call, not more of the open
|
||||
// one: two calls at one index ran together as {"a"}{"b"}
|
||||
// (plugins#930). No id, or the same one, goes on with it.
|
||||
let slot = state.open.get(index);
|
||||
const open = slot === undefined ? undefined : state.calls.get(slot);
|
||||
if (
|
||||
slot === undefined ||
|
||||
(typeof fragment.id === "string" &&
|
||||
fragment.id &&
|
||||
typeof open?.id === "string" &&
|
||||
open.id &&
|
||||
fragment.id !== open.id)
|
||||
) {
|
||||
if (slot !== undefined) state.collided = true;
|
||||
slot = state.slots++;
|
||||
state.open.set(index, slot);
|
||||
}
|
||||
const previous = state.calls.get(slot) ?? { index, function: {} };
|
||||
const value = { ...previous, ...fragment, index, function: previous.function };
|
||||
// 空 ID 片段不应抹掉已缓存的有效 ID,同时允许首次 ID 后续到达。
|
||||
if (
|
||||
@@ -356,7 +377,7 @@ function chatBuffer(checkName) {
|
||||
value.id = previous.id;
|
||||
}
|
||||
if (fragment.function != null) appendFunction(value.function, fragment.function);
|
||||
state.calls.set(index, value);
|
||||
state.calls.set(slot, value);
|
||||
}
|
||||
if (delta.function_call != null) {
|
||||
charge(state, delta.function_call);
|
||||
|
||||
@@ -1636,3 +1636,32 @@ test("a declared name of separators only is never handed another call (#76 follo
|
||||
const exact = await guardToolResponse(Response.json(snapshot("chat", ["_"])), "chat", rules);
|
||||
assert.deepEqual(callsIn("chat", [await exact.json()]), ["_"]);
|
||||
});
|
||||
|
||||
// plugins#930: two calls with their own ids at one index are two calls, each
|
||||
// with an index of its own, not one with {"a"}{"b"} arguments; fragments
|
||||
// with no id, or the same id, go on with the open call.
|
||||
test("Chat streaming keeps two ids at one tool index as two calls", async () => {
|
||||
const A = { index: 0, id: "call_fixture_A", type: "function", function: { name: "Read", arguments: '{"key":"A"}' } };
|
||||
const B = (index) => ({ index, id: "call_fixture_B", type: "function", function: { name: "Bash", arguments: '{"key":"B"}' } });
|
||||
const guarded = async (fragments) => {
|
||||
const response = await guardToolResponse(
|
||||
sse(fragments.map((tc) => event(chat({ tool_calls: [tc] }))).join("") + event(chat({}, "tool_calls")) + terminal("chat")),
|
||||
"chat",
|
||||
policy,
|
||||
);
|
||||
assert.equal(response.status, 200);
|
||||
return parse(await response.text())
|
||||
.filter((frame) => frame.data && typeof frame.data === "object")
|
||||
.flatMap((frame) => frame.data.choices ?? [])
|
||||
.flatMap((choice) => choice.delta?.tool_calls ?? [])
|
||||
.map((c) => [c.index, c.id, c.function.name, c.function.arguments]);
|
||||
};
|
||||
const both = [[0, "call_fixture_A", "Read", '{"key":"A"}'], [1, "call_fixture_B", "Bash", '{"key":"B"}']];
|
||||
assert.deepEqual(await guarded([A, B(0)]), both);
|
||||
assert.deepEqual(await guarded([A, B(1)]), both);
|
||||
assert.deepEqual(await guarded([
|
||||
{ index: 0, id: "call_fixture_A", type: "function", function: { name: "Read", arguments: '{"ke' } },
|
||||
{ index: 0, function: { arguments: 'y":' } },
|
||||
{ index: 0, id: "call_fixture_A", function: { arguments: '"A"}' } },
|
||||
]), [[0, "call_fixture_A", "Read", '{"key":"A"}']]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user