From 4ea39f0155f0536a4c9e8c2045af2b566dbdae78 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 14 Nov 2026 09:58:53 +0800 Subject: [PATCH] =?UTF-8?q?doubao-work=200.1.12:=20a=20bare=20{"tool=5Fcal?= =?UTF-8?q?ls":[=E2=80=A6]}=20reply=20is=20its=20calls=20(#1114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sibling of qoder's #1113 (0.2.68). A reply that writes its calls as one JSON object in OpenAI's own wire shape went out as the answer with "stop". A whole {"tool_calls":[…]} object on a line of its own, outside code, is now those calls (finish tool_calls), with arguments as an object or as a JSON string. While the reply streams, such a line, or a tail that could become one, is held and never shown as text. JSON in prose or in a fence, an empty list, a nameless entry and unreadable arguments stay text, as an unreadable block does in this package. Run: bun test in packages/doubao-work on WSL (magpie-desktop), HOME=$(mktemp -d): 62 pass, 0 fail (jsoncall.test.mjs new, with #1113's bytes). bun scripts/check.mjs doubao-work ok. Broken by hand: without the lift and the hold, both jsoncall tests that are about them go red (2 fail). Not tried: a real Doubao reply in this shape; none has been reported. --- packages/doubao-work/jsoncall.test.mjs | 68 +++++++++++++++++++++ packages/doubao-work/package.json | 2 +- packages/doubao-work/prompt.mjs | 81 +++++++++++++++++++++++++- 3 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 packages/doubao-work/jsoncall.test.mjs diff --git a/packages/doubao-work/jsoncall.test.mjs b/packages/doubao-work/jsoncall.test.mjs new file mode 100644 index 0000000..832b097 --- /dev/null +++ b/packages/doubao-work/jsoncall.test.mjs @@ -0,0 +1,68 @@ +// plugins#1114, the sibling of qoder's #1113: a reply that is one JSON +// object in OpenAI's own wire shape, {"tool_calls":[{"name","arguments"}]}, +// written as text, went out as the answer with "stop". The object is the +// issue's, byte for byte; it is now those calls, finished tool_calls, and +// it is never shown as text while the reply streams. JSON in prose or code, +// an empty list and one that can't be read stay text. +import { expect, test } from "bun:test" +import { heldFrom, parse } from "./prompt.mjs" +import { Streamer, completion } from "./openai.mjs" + +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" }]] +let n = 0 +const id = () => "call_" + ++n +const named = (calls) => calls.map((c) => [c.function.name, JSON.parse(c.function.arguments)]) + +test("a bare {\"tool_calls\":[…]} reply is its calls", () => { + const p = parse(BARE, id) + expect(named(p.calls)).toEqual(CALLS) + expect(p.text).toBe("") + // after a line of text, and with arguments as a JSON string (OpenAI's own) + const q = parse('I will read it.\n {"tool_calls": [{"type":"function","function":{"name":"read_file","arguments":"{\\"path\\":\\"a.go\\"}"}}]}\n', id) + expect(named(q.calls)).toEqual([CALLS[0]]) + expect(q.text).toBe("I will read it.") + const c = completion({ id: "x", model: "m", final: { text: BARE }, promptTokens: 1, newId: id }) + expect(c.choices[0].finish_reason).toBe("tool_calls") + expect(c.choices[0].message.content).toBeNull() + expect(named(c.choices[0].message.tool_calls)).toEqual(CALLS) +}) + +test("JSON that isn't such an object stays text", () => { + for (const t of [ + 'The API answers {"tool_calls":[{"name":"a","arguments":{}}]} here.', + '```json\n' + BARE + '\n```', + '{"tool_calls":[]}', + '{"tool_calls":[{"name":"","arguments":{}}]}', + '{"tool_calls":[{"name":"a","arguments":"not json"}]}', + '{"other":1}', + '{"tool_calls":[{"name":"a","arguments":{"x":1}}', + ]) { + const p = parse(t, id) + expect(p.calls).toEqual([]) + expect(p.text).toBe(t) + } +}) + +test("the object is held, never shown, while the reply streams", () => { + const st = new Streamer() + const full = "Reading.\n" + BARE + let shown = "" + for (let k = 1; k <= full.length; k++) shown += st.update({ text: full.slice(0, k) }).content ?? "" + expect(shown).toBe("Reading.\n") + const f = st.finish({ text: full }, id) + expect(f.content).toBe("") + expect(named(f.calls)).toEqual(CALLS) + // a line that only began like one is shown once it isn't + expect(heldFrom('{"tool')).toBe(0) + expect(heldFrom('a\n{"to')).toBe(2) + expect(heldFrom('{"total": 3}')).toBe(12) + const st2 = new Streamer() + let out = "" + const t = '{"total": 3}' + for (let k = 1; k <= t.length; k++) out += st2.update({ text: t.slice(0, k) }).content ?? "" + out += st2.finish({ text: t }, id).content + expect(out).toBe(t) + // in code it is text as it comes + expect(heldFrom("```\n" + BARE)).toBe(4 + BARE.length) +}) diff --git a/packages/doubao-work/package.json b/packages/doubao-work/package.json index 35c39de..7bf6b44 100644 --- a/packages/doubao-work/package.json +++ b/packages/doubao-work/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-doubao-work-auth", - "version": "0.1.11", + "version": "0.1.12", "type": "module", "main": "./opencode.mjs", "files": [ diff --git a/packages/doubao-work/prompt.mjs b/packages/doubao-work/prompt.mjs index 8a4a08f..60449ff 100644 --- a/packages/doubao-work/prompt.mjs +++ b/packages/doubao-work/prompt.mjs @@ -95,11 +95,78 @@ export function flatten(body) { return out.join("\n\n") } +// plugins#1114 (qoder's #1113): a reply may write its calls as one JSON +// object in OpenAI's own wire shape, {"tool_calls":[{"name","arguments"}]}. +// 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 = /(^|\n)[ \t]*\{\s*"tool_calls"\s*:/g + +// inCode says whether at is inside a ``` fence +const inCode = (text, at) => (text.slice(0, at).match(/```/g)?.length ?? 0) % 2 === 1 + +// jsonStarts are where each such object's "{" is, outside code +function jsonStarts(text) { + const out = [] + for (const m of text.matchAll(JSON_AT)) { + const at = text.indexOf("{", m.index) + if (!inCode(text, at)) out.push(at) + } + return out +} + +// jsonEnd is where the JSON value 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 as its calls, or +// null when it isn't one the plugin can read whole (it stays text) +function jsonCalls(v) { + let f + try { f = JSON.parse(v) } catch { return null } + 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 null } + } + const name = String(fn?.name ?? "").trim() + if (!name || !args || typeof args !== "object" || Array.isArray(args)) return null + calls.push({ name, arguments: JSON.stringify(args) }) + } + return calls +} + // heldFrom is where text stops being safe to show while it streams: the -// first , or a tail that could be the start of one. +// first or {"tool_calls" line, or a tail that could be the +// start of one. export function heldFrom(text) { - const at = text.indexOf(OPEN) + let at = text.indexOf(OPEN) + const j = jsonStarts(text)[0] + if (j !== undefined && (at < 0 || j < at)) at = text.lastIndexOf("\n", j) + 1 if (at >= 0) return at + const nl = text.lastIndexOf("\n") + const line = text.slice(nl + 1) + const bare = line.replace(/\s+/g, "") + if (bare && JSON_KEY.startsWith(bare) && !inCode(text, nl + 1)) return nl + 1 for (let n = Math.min(OPEN.length - 1, text.length); n > 0; n--) if (OPEN.startsWith(text.slice(-n))) return text.length - n return text.length } @@ -123,6 +190,7 @@ function parseCall(raw) { // lost. An unclosed last block is read to the end. export function parse(text, newId = () => "call_" + Math.random().toString(36).slice(2, 14)) { const calls = [] + const lifted = [] let rest = "" let i = 0 while (i < text.length) { @@ -136,6 +204,15 @@ export function parse(text, newId = () => "call_" + Math.random().toString(36).s else rest += text.slice(at, end < 0 ? text.length : end + CLOSE.length) i = end < 0 ? text.length : end + CLOSE.length } + // a whole {"tool_calls":[…]} object on a line of its own is its calls + for (const at of jsonStarts(rest).reverse()) { + const end = jsonEnd(rest.slice(at)) + const got = end < 0 ? null : jsonCalls(rest.slice(at, at + end)) + if (!got) continue + lifted.unshift(...got) + rest = rest.slice(0, at) + rest.slice(at + end) + } + for (const c of lifted) calls.push({ id: newId(), type: "function", function: c }) // fences left empty around a call (```xml … ```) are not text const cleaned = calls.length ? rest.replace(/```[a-z]*\s*```/gi, "") : rest return { text: calls.length ? cleaned.trim() : rest, calls, raw: rest }