workbuddy 0.1.15: normalize chat request fields (#96)

This commit is contained in:
YuCreate
2026-10-12 20:26:02 +08:00
committed by GitHub
parent 6f1605f01d
commit 80bd2d9241
4 changed files with 162 additions and 5 deletions
+5
View File
@@ -82,6 +82,11 @@ 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.
The loader also translates OpenAI-compatible request spellings WorkBuddy
doesn't take: `max_completion_tokens` becomes `max_tokens`, `developer`
messages become `system`, and an object `tool_choice` becomes WorkBuddy's
string form.
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:
+60 -4
View File
@@ -487,8 +487,11 @@ function unflag(messages) {
}
// withSystem gives a chat that doesn't open with a system message
// WorkBuddy's default one, as its app does, and takes FLAGGED's words out
// of it.
// WorkBuddy's default one, as its app does, takes FLAGGED's words out of it,
// and applies the request spellings WorkBuddy's chat endpoint accepts. The
// OpenAI-compatible client normally uses max_completion_tokens and may call a
// reasoning prompt developer; WorkBuddy's endpoint takes max_tokens and
// system instead.
function withSystem(body) {
// a body magpie or OpenCode hands over as bytes is read as the text it is
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) body = new TextDecoder().decode(body)
@@ -497,6 +500,16 @@ function withSystem(body) {
const b = JSON.parse(body)
if (!Array.isArray(b?.messages) || !b.messages.length) return body
let changed = unflag(b.messages)
if (b.max_completion_tokens !== undefined) {
if (b.max_tokens === undefined) b.max_tokens = b.max_completion_tokens
delete b.max_completion_tokens
changed = true
}
for (const m of b.messages) {
if (m?.role !== "developer") continue
m.role = "system"
changed = true
}
if (b.messages[0]?.role !== "system") {
b.messages.unshift({ role: "system", content: "You are a helpful assistant." })
changed = true
@@ -507,6 +520,49 @@ function withSystem(body) {
}
}
// normalizeToolChoice converts the object form emitted by OpenAI clients to
// WorkBuddy's string form. It runs after fitted(), so a named choice follows a
// tool name that was made safe for WorkBuddy.
function normalizeToolChoice(body) {
if (typeof body !== "string") return body
try {
const b = JSON.parse(body)
if (!b || typeof b !== "object" || Array.isArray(b) || !("tool_choice" in b)) return body
const choice = b.tool_choice
if (typeof choice === "string") {
if (choice.trim().toLowerCase() === "none") {
delete b.tool_choice
delete b.tools
delete b.functions
}
return JSON.stringify(b)
}
if (!choice || typeof choice !== "object" || Array.isArray(choice)) {
delete b.tool_choice
return JSON.stringify(b)
}
const type = typeof choice.type === "string" ? choice.type.trim().toLowerCase() : ""
if (type === "none") {
delete b.tool_choice
delete b.tools
delete b.functions
} else if (type === "auto" || type === "required") {
b.tool_choice = type
} else if (type === "function") {
const fn = choice.function && typeof choice.function === "object" && !Array.isArray(choice.function)
? choice.function
: undefined
const name = typeof fn?.name === "string" ? fn.name.trim() : ""
b.tool_choice = name || "auto"
} else {
delete b.tool_choice
}
return JSON.stringify(b)
} catch {
return body
}
}
// ---- tools WorkBuddy takes ----------------------------------------------------
// WorkBuddy AI answers 400 code 11133 "Invalid request parameters" (the
@@ -1220,7 +1276,7 @@ function makePlugin(site) {
if (body === undefined && req) body = await req.clone().text()
body = withSystem(body)
const fit = fitted(body)
body = fit.body
body = normalizeToolChoice(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(await renamed(res, fit.names))
@@ -1338,4 +1394,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
// for tests
export const _internal = { runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
export const _internal = { runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, 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.14",
"version": "0.1.15",
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
"type": "module",
"main": "./index.mjs",
+96
View File
@@ -0,0 +1,96 @@
// WorkBuddy's international chat endpoint uses a narrower OpenAI-compatible
// request shape than pi-ai's default Chat Completions payload.
import { expect, test } from "bun:test"
import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs"
const { withSystem, normalizeToolChoice, fitted } = _internal
test("normalizes pi-ai output limits and developer messages", () => {
const body = JSON.stringify({
model: "gpt-6.1-sol",
stream: true,
stream_options: { include_usage: true },
store: false,
max_completion_tokens: 128000,
reasoning_effort: "high",
messages: [
{ role: "developer", content: "You are a coding assistant." },
{ role: "user", content: "Reply with exactly OK." },
],
})
const out = JSON.parse(withSystem(body))
expect(out.max_tokens).toBe(128000)
expect(out.max_completion_tokens).toBeUndefined()
expect(out.messages[0]).toEqual({ role: "system", content: "You are a coding assistant." })
expect(out.messages[1]).toEqual({ role: "user", content: "Reply with exactly OK." })
})
test("flattens tool_choice after tool names are made safe", () => {
const body = JSON.stringify({
messages: [{ role: "user", content: "run it" }],
tools: [{
type: "function",
function: { name: "fs.read", description: "Read a file", parameters: { type: "object" } },
}],
tool_choice: { type: "function", function: { name: "fs.read" } },
})
const fit = fitted(body)
const out = JSON.parse(normalizeToolChoice(fit.body))
expect(out.tools[0].function.name).toBe("fs_read")
expect(out.tool_choice).toBe("fs_read")
})
test("removes tools when tool_choice is none", () => {
const body = JSON.stringify({
messages: [{ role: "user", content: "hello" }],
tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }],
tool_choice: { type: "none" },
})
const out = JSON.parse(normalizeToolChoice(body))
expect(out.tool_choice).toBeUndefined()
expect(out.tools).toBeUndefined()
})
test("loader sends the normalized body to WorkBuddy", async () => {
const realFetch = globalThis.fetch
let sent
globalThis.fetch = async (_url, init) => {
sent = JSON.parse(init.body)
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
}
try {
const hooks = await WorkBuddyAIAuthPlugin({ client: {} })
const loader = await hooks.auth.loader(async () => ({
type: "oauth",
access: "access",
uid: "uid",
expires: Date.now() + 3600_000,
}))
const response = await loader.fetch("https://www.workbuddy.ai/v2/chat/completions", {
method: "POST",
body: JSON.stringify({
model: "gpt-6.1-sol",
max_completion_tokens: 128000,
reasoning_effort: "high",
messages: [
{ role: "developer", content: "You are helpful." },
{ role: "user", content: "run it" },
],
tools: [{ type: "function", function: { name: "fs.read", parameters: { type: "object" } } }],
tool_choice: { type: "function", function: { name: "fs.read" } },
}),
})
expect(response.status).toBe(200)
expect(sent.max_tokens).toBe(128000)
expect(sent.max_completion_tokens).toBeUndefined()
expect(sent.messages[0].role).toBe("system")
expect(sent.tools[0].function.name).toBe("fs_read")
expect(sent.tool_choice).toBe("fs_read")
} finally {
globalThis.fetch = realFetch
}
})