workbuddy 0.1.12: a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord)

WorkBuddy AI answers 11133 "Invalid request parameters" (the model
provider rejected them) when a tool's parameters or name are of a shape
its model turns away. Tried on the owner's account through magpie:
deepseek-v4.1-flash and -sg refuse each of a pattern's \0, a root anyOf,
parameters with no type, empty parameters, a tuple's items, and a name
holding . : / a space or CJK; Kimi, GPT, Gemini and GLM refuse some;
MiniMax none. Every client protocol reached the same error, so it is the
tools, not the protocol.

fitTools now gives each the shape that passes: an object root (unions
merged as magpie's provider.ObjectRoot does), \0 as \u0000, a tuple's
items as one anyOf, and a safe name, with the model's calls named back in
JSON and streamed answers and the history's calls named as sent. A clean
chat goes as the same bytes.

Run: HOME=$(mktemp -d) bun test packages/workbuddy (54 pass), bun
scripts/check.mjs workbuddy; through a sandbox magpie gateway with this
package, deepseek-v4.1-flash, -sg, glm-5.3, gpt-5.4, gemini-3.5-flash and
kimi-k3 answer 200 to every shape above (400 before), and an Anthropic
Messages call of a tool named fs.read, streamed and not, comes back as
fs.read. wyh's own ZCode/DeepSeek Harness tool set was not seen.
This commit is contained in:
yetone
2026-10-08 17:39:00 +08:00
parent f35c18981c
commit 17e75329b1
4 changed files with 379 additions and 3 deletions
+11
View File
@@ -74,6 +74,17 @@ Each chat carries WorkBuddy's headers:
A chat that doesn't open with a system message is given WorkBuddy's
default one, as the app does.
A chat's tools are given shapes WorkBuddy's models take. Without them
WorkBuddy AI answers 400 "Invalid request parameters" (11133), DeepSeek's
models to each shape below and Kimi's, GPT's, Gemini's and GLM's to some:
- a tool's parameters with no `type`, empty, or a union (`anyOf`, `oneOf`,
`allOf`) at the root are an object, the union's fields merged;
- a `pattern`'s `\0` is `\u0000`, which matches the same;
- a tuple's `items` (a list) is one schema any of them fits;
- a tool's name with a character other than letters, digits, `_` and `-`
(`.`, `:`, `/`, a space, CJK) is sent with `_` there, and the model's
calls come back under the tool's own name.
## Models
When you are signed in, the models are the ones WorkBuddy's product config
+248 -2
View File
@@ -468,6 +468,250 @@ function withSystem(body) {
}
}
// ---- tools WorkBuddy takes ----------------------------------------------------
// WorkBuddy AI answers 400 code 11133 "Invalid request parameters" (the
// model provider rejected them) to a chat whose tools it can't pass on to
// the model (wyh on magpie's Discord: ZCode and DeepSeek Harness on
// deepseek-v4.1-flash). Tried on the owner's account, 2026-10-08: DeepSeek
// turns away each of the shapes below, and Kimi, GPT, Gemini and GLM some
// of them; MiniMax none. fitTools gives each a shape every model takes.
// A tool's name may hold letters, digits, _ and -; another character
// (". : / space", CJK) is refused.
const NAME_OK = /^[A-Za-z0-9_-]+$/
// safeName is name with each character WorkBuddy refuses as _, kept apart
// from the names in taken.
function safeName(name, taken) {
const base = String(name).replace(/[^A-Za-z0-9_-]/g, "_") || "tool"
let n = base
for (let i = 2; taken.has(n); i++) n = `${base}_${i}`
taken.add(n)
return n
}
// NUL_ESCAPE finds a regex's \0 (the NUL character), stepping over each \\
// (a backslash) so that a \\0 is left; \01 is an octal escape, also left.
const NUL_ESCAPE = /\\\\|\\0(?![0-9])/g
// fitSchema mends a schema in place, at every depth: a pattern's \0, which
// DeepSeek's validator says is "not a 'regex'", is \u0000, which matches
// the same (magpie's gateway does this for DeepSeek's own API,
// deepseekToolPatterns); a tuple's items (a list) become one schema any of
// them fits. It reports whether it changed anything.
function fitSchema(s, depth = 0) {
if (!s || typeof s !== "object" || depth > 64) return false
let changed = false
if (Array.isArray(s)) {
for (const v of s) if (fitSchema(v, depth + 1)) changed = true
return changed
}
if (typeof s.pattern === "string" && s.pattern.includes("\\0")) {
const p = s.pattern.replace(NUL_ESCAPE, (m) => (m === "\\\\" ? m : "\\u0000"))
if (p !== s.pattern) {
s.pattern = p
changed = true
}
}
if (Array.isArray(s.items)) {
const list = s.items.filter((v) => v && typeof v === "object")
s.items = list.length === 0 ? {} : list.length === 1 ? list[0] : { anyOf: list }
delete s.additionalItems
changed = true
}
for (const v of Object.values(s)) if (fitSchema(v, depth + 1)) changed = true
return changed
}
// localRef is the schema a local $ref in root names ("#/$defs/x",
// "#/definitions/x"), or s itself.
function localRef(root, s) {
const ref = s?.$ref
if (typeof ref !== "string" || !ref.startsWith("#/")) return s
let at = root
for (const k of ref.slice(2).split("/")) at = at?.[k.replaceAll("~1", "/").replaceAll("~0", "~")]
return at && typeof at === "object" ? at : s
}
// objectRoot makes a tool's parameters an object at the root, as magpie's
// gateway does for xAI (provider.ObjectRoot): allOf's branches are merged
// whole; of anyOf's and oneOf's object branches the properties are merged
// and a field each requires stays required. A root with no type, or an
// empty one, is an object. It reports whether it changed anything.
function objectRoot(ps, root = ps, depth = 0) {
const unions = ["allOf", "anyOf", "oneOf"].filter((k) => Array.isArray(ps[k]))
if (ps.type === "object" && !unions.length) return false
const props = ps.properties && typeof ps.properties === "object" ? ps.properties : {}
const required = Array.isArray(ps.required) ? [...ps.required] : []
for (const b0 of ps.allOf ?? []) {
let b = localRef(root, b0)
if (!b || typeof b !== "object") continue
if (depth < 8 && ["allOf", "anyOf", "oneOf"].some((k) => Array.isArray(b[k]))) objectRoot((b = structuredClone(b)), root, depth + 1)
for (const [k, v] of Object.entries(b.properties ?? {})) if (!(k in props)) props[k] = v
if (Array.isArray(b.required)) required.push(...b.required)
}
const branches = []
for (const key of ["anyOf", "oneOf"]) {
for (const b0 of ps[key] ?? []) {
let b = localRef(root, b0)
if (!b || typeof b !== "object") continue
if (depth < 8 && ["allOf", "anyOf", "oneOf"].some((k) => Array.isArray(b[k]))) objectRoot((b = structuredClone(b)), root, depth + 1)
if (b.type !== "object" && !b.properties) continue
branches.push(b)
}
}
const from = new Map()
for (const b of branches) {
for (const [k, v] of Object.entries(b.properties ?? {})) {
if (k in props) continue
const seen = from.get(k) ?? []
if (!seen.some((x) => JSON.stringify(x) === JSON.stringify(v))) seen.push(v)
from.set(k, seen)
}
}
for (const [k, list] of from) props[k] = list.length === 1 ? list[0] : { anyOf: list }
if (branches.length) {
for (const k of Object.keys(branches[0].properties ?? {})) {
if (branches.every((b) => Array.isArray(b.required) && b.required.includes(k))) required.push(k)
}
}
for (const k of unions) delete ps[k]
ps.type = "object"
ps.properties = props
const req = [...new Set(required)].filter((k) => typeof k === "string" && k in props)
if (req.length) ps.required = req
else delete ps.required
return true
}
// fitTools mends b's function tools in place: their parameters (fitSchema,
// objectRoot) and names. It reports whether it changed anything, and the
// names it gave, each to the name the client knows (ours), so that the
// model's calls are named back. A call in the chat's history is named as
// its tool now is.
function fitTools(b) {
const names = new Map()
if (!Array.isArray(b?.tools) || !b.tools.length) return { changed: false, names }
let changed = false
const taken = new Set()
for (const t of b.tools) {
const n = t?.function?.name
if (typeof n === "string" && NAME_OK.test(n)) taken.add(n)
}
const theirs = new Map()
for (const t of b.tools) {
const fn = t?.type === "function" || t?.function ? t.function : null
if (!fn || typeof fn !== "object") continue
if (typeof fn.name === "string" && !NAME_OK.test(fn.name)) {
const safe = safeName(fn.name, taken)
names.set(safe, fn.name)
theirs.set(fn.name, safe)
fn.name = safe
changed = true
}
if (fn.parameters === undefined) continue
if (!fn.parameters || typeof fn.parameters !== "object" || Array.isArray(fn.parameters)) {
fn.parameters = { type: "object", properties: {} }
changed = true
continue
}
if (fitSchema(fn.parameters)) changed = true
if (objectRoot(fn.parameters)) changed = true
}
if (theirs.size && Array.isArray(b.messages)) {
for (const m of b.messages) {
for (const c of Array.isArray(m?.tool_calls) ? m.tool_calls : []) {
const safe = theirs.get(c?.function?.name)
if (safe) c.function.name = safe
}
if (m?.role === "tool" && theirs.has(m.name)) m.name = theirs.get(m.name)
}
}
const choice = b.tool_choice?.function
if (choice && theirs.has(choice.name)) choice.name = theirs.get(choice.name)
return { changed, names }
}
// fitted is a chat body with its tools mended (fitTools), and the names
// given its tools, each to the client's own; a body that isn't a chat is
// as it was.
function fitted(body) {
if (typeof body !== "string") return { body, names: new Map() }
try {
const b = JSON.parse(body)
const { changed, names } = fitTools(b)
return { body: changed ? JSON.stringify(b) : body, names }
} catch {
return { body, names: new Map() }
}
}
// namedBack gives the model's calls in a chat answer (one JSON body, or an
// SSE stream's chunks) the names the client gave its tools.
function namedBack(v, names) {
let changed = false
for (const c of Array.isArray(v?.choices) ? v.choices : []) {
for (const at of [c?.message, c?.delta]) {
for (const tc of Array.isArray(at?.tool_calls) ? at.tool_calls : []) {
const ours = names.get(tc?.function?.name)
if (ours) {
tc.function.name = ours
changed = true
}
}
}
}
return changed
}
// renamed is res with namedBack on its body, read as it comes.
function renamed(res, names) {
if (!names.size || !res.body) return res
const headers = new Headers(res.headers)
headers.delete("content-length")
headers.delete("content-encoding")
const json = /json/i.test(res.headers.get("content-type") ?? "")
if (json) {
const out = res.text().then((text) => {
try {
const v = JSON.parse(text)
return namedBack(v, names) ? JSON.stringify(v) : text
} catch {
return text
}
})
return out.then((text) => new Response(text, { status: res.status, statusText: res.statusText, headers }))
}
const dec = new TextDecoder()
const enc = new TextEncoder()
let rest = ""
const line = (l) => {
const m = /^data:\s?(.*)$/.exec(l)
if (!m || m[1] === "[DONE]") return l
try {
const v = JSON.parse(m[1])
return namedBack(v, names) ? `data: ${JSON.stringify(v)}` : l
} catch {
return l
}
}
const body = res.body.pipeThrough(
new TransformStream({
transform(chunk, ctl) {
rest += dec.decode(chunk, { stream: true })
const lines = rest.split("\n")
rest = lines.pop()
if (lines.length) ctl.enqueue(enc.encode(lines.map(line).join("\n") + "\n"))
},
flush(ctl) {
rest += dec.decode()
if (rest) ctl.enqueue(enc.encode(line(rest)))
},
}),
)
return new Response(body, { status: res.status, statusText: res.statusText, headers })
}
// ---- signing in -------------------------------------------------------------
// poll asks path until WorkBuddy answers with data, retrying the codes
@@ -863,9 +1107,11 @@ function makePlugin(site) {
let body = init?.body
if (body === undefined && req) body = await req.clone().text()
body = withSystem(body)
const fit = fitted(body)
body = fit.body
attend(headers, body, session)
const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body })
return res.status >= 400 ? explained(res) : kept(res)
return res.status >= 400 ? explained(res) : kept(await renamed(res, fit.names))
},
}
},
@@ -970,4 +1216,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
// for tests
export const _internal = { withSystem, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
export const _internal = { withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-workbuddy-auth",
"version": "0.1.11",
"version": "0.1.12",
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
"type": "module",
"main": "./index.mjs",
+119
View File
@@ -0,0 +1,119 @@
// WorkBuddy AI answers 400 "Invalid request parameters" (11133) to a chat
// whose tools its model turns away: wyh's ZCode and DeepSeek Harness on
// deepseek-v4.1-flash. Each shape below was refused on the owner's account
// (2026-10-08) and passed once mended as here.
import { expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const { fitted, fitTools, renamed } = _internal
const tool = (name, parameters) => ({ type: "function", function: { name, description: "d", parameters } })
const chat = (tools, extra = {}) => JSON.stringify({ model: "deepseek-v4.1-flash", messages: [{ role: "user", content: "hi" }], tools, ...extra })
test("a pattern's \\0 is sent as \\u0000, at any depth; \\\\0 and \\01 are left", () => {
const body = chat([tool("t", { type: "object", properties: {
a: { type: "string", pattern: "^[^\\0]*$" },
b: { type: "array", items: { type: "string", pattern: "x\\0" } },
c: { type: "string", pattern: "\\\\0|\\01" },
} })])
const b = JSON.parse(fitted(body).body)
const ps = b.tools[0].function.parameters
expect(ps.properties.a.pattern).toBe("^[^\\u0000]*$")
expect(ps.properties.b.items.pattern).toBe("x\\u0000")
expect(ps.properties.c.pattern).toBe("\\\\0|\\01")
expect(new RegExp(ps.properties.a.pattern).test("a\u0000b")).toBe(false)
expect(new RegExp(ps.properties.a.pattern).test("ab")).toBe(true)
})
test("a root anyOf of objects becomes one object; a field each branch requires stays required", () => {
const body = chat([tool("t", { anyOf: [
{ type: "object", properties: { kind: { const: "a" }, x: { type: "string" } }, required: ["kind", "x"] },
{ type: "object", properties: { kind: { const: "b" }, y: { type: "number" } }, required: ["kind"] },
] })])
const ps = JSON.parse(fitted(body).body).tools[0].function.parameters
expect(ps.anyOf).toBeUndefined()
expect(ps.type).toBe("object")
expect(Object.keys(ps.properties).sort()).toEqual(["kind", "x", "y"])
expect(ps.properties.kind).toEqual({ anyOf: [{ const: "a" }, { const: "b" }] })
expect(ps.required).toEqual(["kind"])
})
test("root allOf and $ref branches are merged", () => {
const body = chat([tool("t", { $defs: { A: { type: "object", properties: { a: { type: "string" } }, required: ["a"] } }, allOf: [{ $ref: "#/$defs/A" }, { type: "object", properties: { b: { type: "string" } } }] })])
const ps = JSON.parse(fitted(body).body).tools[0].function.parameters
expect(ps.allOf).toBeUndefined()
expect(Object.keys(ps.properties).sort()).toEqual(["a", "b"])
expect(ps.required).toEqual(["a"])
})
test("parameters with no type, or empty, are an object", () => {
const body = chat([tool("a", { properties: { x: { type: "string" } } }), tool("b", {}), tool("c", null)])
const tools = JSON.parse(fitted(body).body).tools
expect(tools[0].function.parameters).toEqual({ type: "object", properties: { x: { type: "string" } } })
expect(tools[1].function.parameters).toEqual({ type: "object", properties: {} })
expect(tools[2].function.parameters).toEqual({ type: "object", properties: {} })
})
test("a tuple's items become one schema", () => {
const body = chat([tool("t", { type: "object", properties: { p: { type: "array", items: [{ type: "number" }, { type: "string" }], additionalItems: false }, q: { type: "array", items: [{ type: "number" }] } } })])
const ps = JSON.parse(fitted(body).body).tools[0].function.parameters
expect(ps.properties.p).toEqual({ type: "array", items: { anyOf: [{ type: "number" }, { type: "string" }] } })
expect(ps.properties.q.items).toEqual({ type: "number" })
})
test("a clean chat is the same bytes", () => {
const body = chat([tool("mcp__node_repl__js", { type: "object", properties: { code: { type: "string", pattern: "^x" } }, required: ["code"] })])
const out = fitted(body)
expect(out.body).toBe(body)
expect(out.names.size).toBe(0)
const plain = JSON.stringify({ messages: [{ role: "user", content: "hi" }] })
expect(fitted(plain).body).toBe(plain)
})
test("a name WorkBuddy refuses is sent safe, in the tools and the history, and kept apart", () => {
const b = {
messages: [
{ role: "user", content: "hi" },
{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "fs.read", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "c1", content: "ok" },
],
tools: [tool("fs.read", { type: "object", properties: {} }), tool("fs_read", { type: "object", properties: {} }), tool("搜索", { type: "object", properties: {} }), tool("a/b c:d", { type: "object", properties: {} })],
}
const { changed, names } = fitTools(b)
expect(changed).toBe(true)
const sent = b.tools.map((t) => t.function.name)
for (const n of sent) expect(n).toMatch(/^[A-Za-z0-9_-]+$/)
expect(new Set(sent).size).toBe(4)
expect(sent[1]).toBe("fs_read")
expect(names.get(sent[0])).toBe("fs.read")
expect(names.get(sent[2])).toBe("搜索")
expect(names.get(sent[3])).toBe("a/b c:d")
expect(b.messages[1].tool_calls[0].function.name).toBe(sent[0])
})
test("the model's calls come back under the client's names, streamed or not", async () => {
const names = new Map([["fs_read_2", "fs.read"]])
const one = new Response(JSON.stringify({ choices: [{ message: { tool_calls: [{ id: "c", function: { name: "fs_read_2", arguments: "{}" } }] } }] }), { headers: { "content-type": "application/json" } })
const v = await (await renamed(one, names)).json()
expect(v.choices[0].message.tool_calls[0].function.name).toBe("fs.read")
const sse = [
`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ index: 0, id: "c", function: { name: "fs_read_2", arguments: "" } }] } }] })}\n\n`,
`data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: "{}" } }] } }] })}\n\ndata: [DONE]\n\n`,
].join("")
// split mid-line, as the network does
const enc = new TextEncoder()
const cut = 37
const stream = new ReadableStream({
start(c) {
c.enqueue(enc.encode(sse.slice(0, cut)))
c.enqueue(enc.encode(sse.slice(cut)))
c.close()
},
})
const text = await (await renamed(new Response(stream, { headers: { "content-type": "text/event-stream" } }), names)).text()
expect(text).toContain('"name":"fs.read"')
expect(text).not.toContain("fs_read_2")
expect(text).toContain("data: [DONE]")
expect(text.split("data:").length).toBe(sse.split("data:").length)
})