workbuddy 0.1.32: a Claude model is served on Messages, where effort (max included) is honored (#346)
WorkBuddy's China build serves its Claude models on Anthropic's Messages API (<endpoint>/v1/messages). A Claude model there is now `@ai-sdk/anthropic` and goes to Messages, where `output_config.effort` (max included) is honored. Every other model, and every WorkBuddy AI model, stays on chat. A Messages body goes as sent, minus thinking blocks with no signature, and goes once more without thinking when WorkBuddy refuses a signature it didn't make (11159). count_tokens goes on the Messages route too. One Claude Code send keeps one turn id (#48). Reviewed at 9e0eb2b (rebased on main ba9801c; workbuddy unchanged from the 39f71a7 the author answered the last review with), by @waynesguan. Run at 9e0eb2b, sandbox HOME and TMPDIR: - packages/workbuddy `bun test`: 149 pass, 0 fail. Run again with HTTP(S)_PROXY pointing at a dead port: 149 pass, so no test reaches the network. - `bun scripts/check.mjs workbuddy`: ok. - Broken by hand: BAD_SIGNATURE that never matches turns "a signature WorkBuddy didn't make is refused once…" red; isMessages without count_tokens turns "count_tokens is a Messages request" red. - Read: magpie's provider/plugins.go takes `firstOf(o.BaseURL, m.URL, …)`, so the loader's empty baseURL falls back to each model's api.url (/v1 for Claude, /v2 for chat). - magpie origin/main 4dfd88206's plugin host, sandbox HOME (scripts/try.sh): the package adds, workbuddy lists 15 models and workbuddy-ai 16. Not tried against the real API here: the sandbox has no WorkBuddy account that can reach a Claude model. The author's replays with a real account (empty text block 200, signature binding table) are what the 11159 handling rests on.
This commit is contained in:
@@ -77,6 +77,42 @@ after a renewal takes a mark off (`renewed`).
|
||||
Chats are chat completions (`@ai-sdk/openai-compatible`) at `<API>/chat/completions`.
|
||||
They are streamed only; WorkBuddy refuses a chat that isn't.
|
||||
|
||||
**On WorkBuddy (China), the Claude models are served on Anthropic's Messages
|
||||
API** instead: `@ai-sdk/anthropic` at `<endpoint>/v1/messages` (streamed only
|
||||
as well). `claude-opus-5.5`, `claude-sonnet-5.5`, `claude-opus-5` and
|
||||
`claude-opus-4.8-1m` answered there when each model of `/v3/config`'s `cli`
|
||||
agent was asked on 2026-10-24; `glm-5.3` and `deepseek-v4.1-flash` answered
|
||||
500, `gpt-5.5` and `kimi-k3-1` 400, so every other model stays on chat.
|
||||
WorkBuddy AI has no such route (`/v1/messages` is `404 Route Not Found` there
|
||||
for every model), so all its models stay on chat, a Claude one too.
|
||||
|
||||
A Messages request goes as the agent sent it: no default system message, no
|
||||
`max_completion_tokens`/`developer` rewrites, no tool reshaping, and nothing
|
||||
moved for a refused system prompt — Claude Code's own prompt is taken as it
|
||||
is, billing line and all, where a chat answers 11128 to it. One thing is
|
||||
left out: a `thinking` block with no `signature`. A conversation that began
|
||||
on chat (or on another provider) carries such blocks, and once a signed one
|
||||
from this route sits beside them WorkBuddy refuses the whole request, 11159
|
||||
"Invalid `signature` in `thinking` block … bound to a different
|
||||
conversation", on every try. Signed blocks go back as they came. It carries
|
||||
WorkBuddy's headers as a chat does, the same conversation and turn ids
|
||||
included: a tool result in a `user` message of `tool_result` blocks answers
|
||||
the step before it, as a `role: "tool"` message does in a chat.
|
||||
|
||||
The point of the route is effort. A chat carries `reasoning_effort` alone,
|
||||
and WorkBuddy's chat endpoint answers at about the same length whatever it
|
||||
says: asked the same question four times each (2026-10-24,
|
||||
`claude-opus-5.5`), the median answer was 3884 output tokens at `low`, 5144
|
||||
at `max` and 5715 at a value that isn't a level at all. Messages carries
|
||||
`output_config.effort`, and `max` is honored there: a median of 30850
|
||||
against 5748 at `low`, same model and question, four runs each. A Claude
|
||||
model on Messages therefore lists `max` in its levels even where
|
||||
`/v3/config` stops at `xhigh`.
|
||||
|
||||
`/v1/messages/count_tokens` **is not served** (404). magpie treats a 404 on
|
||||
count_tokens as "no counter" (`unsupportedCount`) and answers with its own
|
||||
estimate.
|
||||
|
||||
Each chat carries WorkBuddy's headers:
|
||||
- `Authorization`, `X-User-Id`, `X-Domain`, `X-Product: SaaS`, `X-IDE-Type: WorkBuddy`;
|
||||
- `User-Agent: WorkBuddy/5.5.6`. Without it, WorkBuddy answers error 10085;
|
||||
|
||||
+226
-19
@@ -68,6 +68,9 @@ const SITES = {
|
||||
platform: "workbuddy",
|
||||
ai: false,
|
||||
models: CN_MODELS,
|
||||
// it serves the Claude models on Anthropic's Messages API too (see
|
||||
// nativeOf)
|
||||
messages: true,
|
||||
},
|
||||
"workbuddy-ai": {
|
||||
id: "workbuddy-ai",
|
||||
@@ -103,6 +106,33 @@ const hex = () => randomBytes(16).toString("hex")
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
const api = (site) => site.endpoint + "/v2"
|
||||
|
||||
// MESSAGES is the API SDK package for Anthropic's Messages shape, which
|
||||
// WorkBuddy serves the Claude models on, beside its chat completions:
|
||||
// <endpoint>/v1/messages. Those models are Anthropic's own, and their
|
||||
// thinking is asked for the way Anthropic asks it (thinking.type adaptive
|
||||
// with output_config.effort), which the chat endpoint has no field for: a
|
||||
// chat carries reasoning_effort alone, and WorkBuddy's chat endpoint gives
|
||||
// the same answer at every level, so an agent that picked max got no more
|
||||
// than one that picked low. See nativeOf.
|
||||
const NPM_MESSAGES = "@ai-sdk/anthropic"
|
||||
const apiMessages = (site) => site.endpoint + "/v1"
|
||||
|
||||
// nativeOf is whether site serves model on Messages rather than chat: a
|
||||
// Claude model, on a site that serves Messages at all (site.messages).
|
||||
// Measured 2026-10-24 on WorkBuddy's China build, each model of
|
||||
// /v3/config's cli agent asked on /v1/messages: claude-opus-5.5,
|
||||
// claude-sonnet-5.5, claude-opus-5 and claude-opus-4.8-1m answered in
|
||||
// Anthropic's stream; glm-5.3 and deepseek-v4.1-flash answered 500, gpt-5.5
|
||||
// and kimi-k3-1 400. An account may still be refused a Claude model it has
|
||||
// no entitlement for (11158), which is the account's, not the endpoint's.
|
||||
// WorkBuddy AI (www.workbuddy.ai) has no such route: /v1/messages,
|
||||
// /v2/messages and /v1/messages?beta=true are all "404 Route Not Found"
|
||||
// there, whatever the model, so its models stay on chat, a Claude one too
|
||||
// should it list one.
|
||||
function nativeOf(site, model) {
|
||||
return site?.messages === true && /^claude-/i.test(String(model ?? ""))
|
||||
}
|
||||
|
||||
// ---- WorkBuddy's API ------------------------------------------------------
|
||||
|
||||
class WBError extends Error {
|
||||
@@ -370,11 +400,32 @@ function signatureOf(content) {
|
||||
// words. A client that sends a tool result's images in a user message (pi's
|
||||
// "Attached image(s) from tool result:") puts that message right after the
|
||||
// result, and a turn keyed on it would be a turn of its own on every step.
|
||||
//
|
||||
// Anthropic's Messages shape says the same another way: a tool's result is a
|
||||
// tool_result block in a user message, after an assistant message of
|
||||
// tool_use blocks. Such a user message answers too, whatever text sits
|
||||
// beside the results (Claude Code puts a reminder there, a user's words typed
|
||||
// mid-task go there as well), and so does one right after it, as a chat's
|
||||
// does after role "tool". Messages that are neither the user's nor the
|
||||
// assistant's (Claude Code's role "system" ones, which carry a turn's
|
||||
// effort, its environment and its token count between the steps) stand
|
||||
// between them without changing which message answers.
|
||||
function answeredBefore(msgs, i) {
|
||||
const prev = msgs[i - 1]
|
||||
if (hasBlock(msgs[i], "tool_result")) return true
|
||||
let j = i - 1
|
||||
while (j >= 0 && msgs[j]?.role === "system") j--
|
||||
const prev = msgs[j]
|
||||
if (prev === null || typeof prev !== "object") return false
|
||||
if (prev.role === "tool") return true
|
||||
return prev.role === "assistant" && Array.isArray(prev.tool_calls) && prev.tool_calls.length > 0
|
||||
if (prev.role === "user" && hasBlock(prev, "tool_result")) return true
|
||||
if (prev.role !== "assistant") return false
|
||||
if (Array.isArray(prev.tool_calls) && prev.tool_calls.length > 0) return true
|
||||
return hasBlock(prev, "tool_use")
|
||||
}
|
||||
|
||||
// hasBlock is whether message m's content holds a block of type.
|
||||
function hasBlock(m, type) {
|
||||
return Array.isArray(m?.content) && m.content.some((p) => p?.type === type)
|
||||
}
|
||||
|
||||
// turnKey names the user send a chat answers: the body's last user message
|
||||
@@ -410,6 +461,100 @@ function conversationKey(chat, session) {
|
||||
return ""
|
||||
}
|
||||
|
||||
// isMessages says whether a request is an Anthropic Messages one, which
|
||||
// site serves the Claude models natively: its URL ends at /messages or at
|
||||
// the counting endpoint beside it (/v1/messages/count_tokens, which the
|
||||
// chat route's rewrites would otherwise turn into a chat), or (a body is
|
||||
// all there is to go on) its system is Anthropic's blocks rather than a
|
||||
// chat's string, and its tools carry input_schema where a chat's carry a
|
||||
// function's parameters. A chat's own tools can look either way, so the URL
|
||||
// decides when there is one.
|
||||
function isMessages(url, body) {
|
||||
const path = (() => {
|
||||
try {
|
||||
return new URL(String(url ?? "")).pathname
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
})()
|
||||
if (path) return /\/messages(\/count_tokens)?$/.test(path)
|
||||
const b = chatOf(body)
|
||||
if (!b) return false
|
||||
if (Array.isArray(b.system)) return true
|
||||
const tools = Array.isArray(b.tools) ? b.tools : []
|
||||
return tools.some((t) => t && typeof t === "object" && "input_schema" in t && !t.function)
|
||||
}
|
||||
|
||||
// withoutUnsigned is a Messages body without the thinking blocks that carry
|
||||
// no signature, or whose signature WorkBuddy doesn't take.
|
||||
//
|
||||
// A conversation that began elsewhere — on WorkBuddy's chat route, whose
|
||||
// thinking comes back unsigned, or on any other provider — and goes on here
|
||||
// carries such blocks in its history, and WorkBuddy refuses the whole request
|
||||
// for one of them when another assistant message holds a signed block:
|
||||
// 11159 "Invalid `signature` in `thinking` block. The block is bound to a
|
||||
// different conversation" (or the same wrapped in 11133). Seen 2026-10-24 in
|
||||
// real Claude Code sessions moved onto this route mid-way: every request of
|
||||
// two of them refused, each attempt alike, until the session ended. Replayed
|
||||
// the same day, with a real account (20+ runs each):
|
||||
//
|
||||
// unsigned thinking alone, no signed block anywhere ....... 200
|
||||
// one unsigned-only assistant message + a signed one ...... 11159
|
||||
// that message with the unsigned block taken out .......... 200
|
||||
// unsigned and signed blocks in the SAME message .......... 200
|
||||
// thinking.block_binding.prefix_mismatch_behavior=drop_block ... 11159
|
||||
//
|
||||
// So what binds a signed block is the history it sits in, and a message that
|
||||
// is thinking alone can't be part of it; whether that thinking is signed
|
||||
// makes no difference (a signed block alone is accepted too). The signature
|
||||
// itself isn't checked for where it came from: a block keeping a signature
|
||||
// of an unrelated turn, of another model (sonnet-5.5's on opus-5.5), or
|
||||
// another account's answers 200, while a truncated or altered one is 11159.
|
||||
// What WorkBuddy checks is that it reads as a signature.
|
||||
//
|
||||
// A block with no signature can't be verified by the model anyway, so
|
||||
// nothing it could use is lost. A message whose only block that was gets an
|
||||
// empty text block: measured the same day, that history still answers 200
|
||||
// with a signed turn after it (three runs), where the unsigned block itself
|
||||
// answers 11159 (three runs), and Anthropic's API refuses an empty text
|
||||
// block — 200 here means WorkBuddy takes it. The signed blocks, this
|
||||
// route's own, go back as they came, as Anthropic asks. A body without
|
||||
// unsigned thinking is body itself, byte for byte.
|
||||
function withoutUnsigned(body) {
|
||||
const b = chatOf(body)
|
||||
const msgs = b?.messages
|
||||
if (!Array.isArray(msgs)) return body
|
||||
let changed = false
|
||||
for (const m of msgs) {
|
||||
if (m?.role !== "assistant" || !Array.isArray(m.content)) continue
|
||||
const kept = m.content.filter((p) => !(p?.type === "thinking" && !p.signature))
|
||||
if (kept.length === m.content.length) continue
|
||||
changed = true
|
||||
m.content = kept.length ? kept : [{ type: "text", text: "" }]
|
||||
}
|
||||
return changed ? JSON.stringify(b) : body
|
||||
}
|
||||
|
||||
// withoutSignedThinking is a Messages body without any thinking block at
|
||||
// all, for a refusal saying a signature is not one WorkBuddy made (see the
|
||||
// retry in the loader). An assistant message left with nothing gets an
|
||||
// empty text block, as withoutUnsigned leaves it. null for a body with no
|
||||
// thinking block to drop: the retry would send the same request again.
|
||||
function withoutSignedThinking(body) {
|
||||
const b = chatOf(body)
|
||||
const msgs = b?.messages
|
||||
if (!Array.isArray(msgs)) return null
|
||||
let dropped = 0
|
||||
for (const m of msgs) {
|
||||
if (m?.role !== "assistant" || !Array.isArray(m.content)) continue
|
||||
const kept = m.content.filter((p) => p?.type !== "thinking")
|
||||
if (kept.length === m.content.length) continue
|
||||
dropped += m.content.length - kept.length
|
||||
m.content = kept.length ? kept : [{ type: "text", text: "" }]
|
||||
}
|
||||
return dropped ? JSON.stringify(b) : null
|
||||
}
|
||||
|
||||
// chatOf is a chat's body as the object it is, null for one that isn't: a
|
||||
// body that isn't text (bytes), or isn't JSON at all.
|
||||
function chatOf(body) {
|
||||
@@ -1543,11 +1688,16 @@ function variants(efforts) {
|
||||
return Object.fromEntries((efforts ?? []).map((e) => [e, { reasoningEffort: e }]))
|
||||
}
|
||||
|
||||
// configModels is the site's own list as a provider's models, each on the
|
||||
// API it is served on: a Claude model on Messages, the rest on chat.
|
||||
function configModels(site) {
|
||||
return Object.fromEntries(site.models.map(([id, name, context, efforts]) => [id, {
|
||||
name,
|
||||
limit: { context, output: 0 },
|
||||
tool_call: true,
|
||||
// OpenCode (and magpie's host) read a config model's package and URL
|
||||
// from provider: { npm, api }, not api
|
||||
...(nativeOf(site, id) ? { provider: { npm: NPM_MESSAGES, api: apiMessages(site) } } : {}),
|
||||
...(efforts ? { reasoning: true, variants: variants(efforts) } : {}),
|
||||
}]))
|
||||
}
|
||||
@@ -1557,7 +1707,7 @@ function modelOf(site, provider, m) {
|
||||
id: m.id,
|
||||
providerID: provider.id,
|
||||
name: m.name,
|
||||
api: { id: m.id, url: api(site), npm: NPM },
|
||||
api: { id: m.id, url: nativeOf(site, m.id) ? apiMessages(site) : api(site), npm: nativeOf(site, m.id) ? NPM_MESSAGES : NPM },
|
||||
status: "active",
|
||||
headers: {},
|
||||
options: {},
|
||||
@@ -1656,9 +1806,20 @@ function priceOf(d, promotions, now = Date.now()) {
|
||||
// and a default reasoning.effort. Those take low, high and max (each
|
||||
// reasoned under a real account, on four of them) and their own default.
|
||||
const EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"]
|
||||
function effortsOf(d) {
|
||||
function effortsOf(d, site, id) {
|
||||
const said = d.reasoning?.supportedEfforts
|
||||
if (Array.isArray(said) && said.length) return said
|
||||
if (Array.isArray(said) && said.length) {
|
||||
// A Claude model on Messages takes max though the config's list stops
|
||||
// at xhigh: measured 2026-10-24, output_config.effort "max" answered
|
||||
// 200 on each Claude model, and on claude-opus-5.5 with more thinking
|
||||
// than xhigh (11248 thinking tokens against 1999, one run each). How
|
||||
// much more a level gives varies by model and run; what matters here
|
||||
// is that a client picking max reaches the server as max, not xhigh.
|
||||
// On chat max means nothing more (see NPM_MESSAGES), so a model there
|
||||
// keeps what the config says.
|
||||
if (nativeOf(site, id) && !said.includes("max")) return [...said, "max"]
|
||||
return said
|
||||
}
|
||||
if (d.supportsReasoning !== true) return []
|
||||
const own = d.reasoning?.effort
|
||||
const set = new Set(["low", "high", "max", ...(typeof own === "string" && EFFORT_ORDER.includes(own) ? [own] : [])])
|
||||
@@ -1687,7 +1848,7 @@ async function liveModels(site, a) {
|
||||
m.output = d.maxOutputTokens
|
||||
m.images = d.supportsImages === true && !textOnly(site, id)
|
||||
Object.assign(m, priceOf(d, cfg.modelPromotions))
|
||||
const es = effortsOf(d)
|
||||
const es = effortsOf(d, site, id)
|
||||
if (es.length) {
|
||||
const canOff = d.reasoning?.canDisableThinking
|
||||
m.efforts = [...(!d.onlyReasoning && (canOff == null || canOff) ? ["none"] : []), ...es]
|
||||
@@ -1793,7 +1954,10 @@ function makePlugin(site) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "oauth") return {}
|
||||
return {
|
||||
baseURL: api(site),
|
||||
// no baseURL: a model's own api.url says where it is served —
|
||||
// <endpoint>/v2 for a chat, <endpoint>/v1 for a Claude model on
|
||||
// Messages. A provider-wide base would put /messages under /v2.
|
||||
baseURL: "",
|
||||
apiKey: "",
|
||||
async fetch(input, init) {
|
||||
const stored = await getAuth()
|
||||
@@ -1808,9 +1972,25 @@ function makePlugin(site) {
|
||||
sign(site, a, headers)
|
||||
let body = init?.body
|
||||
if (body === undefined && req) body = await req.clone().text()
|
||||
body = withSystem(body)
|
||||
const fit = fitted(body)
|
||||
body = normalizeToolChoice(fit.body)
|
||||
// An Anthropic request goes as the agent sent it: WorkBuddy
|
||||
// serves these models on Messages itself, and the rewrites
|
||||
// below (a default system message, the chat endpoint's
|
||||
// max_tokens spelling, tool shapes, the move of a refused
|
||||
// system prompt) exist for the chat endpoint alone. Claude
|
||||
// Code's own system prompt is taken there as it is — measured
|
||||
// 2026-10-24: the billing line, the "official CLI" line,
|
||||
// Codex's and DeepSeek Harness's openings all answer on
|
||||
// /v1/messages, where a chat is refused 11128.
|
||||
const native = isMessages(req ? req.url : String(input), body)
|
||||
let names = {}
|
||||
if (!native) {
|
||||
body = withSystem(body)
|
||||
const fit = fitted(body)
|
||||
body = normalizeToolChoice(fit.body)
|
||||
names = fit.names
|
||||
} else {
|
||||
body = withoutUnsigned(body)
|
||||
}
|
||||
attend(headers, body, session)
|
||||
const post = (b) =>
|
||||
fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }).catch((e) => unanswered(site, a, b, e, init?.signal))
|
||||
@@ -1855,12 +2035,27 @@ function makePlugin(site) {
|
||||
const model = chatOf(body)?.model
|
||||
// a system prompt WorkBuddy refused before goes as the user's
|
||||
// words at once (see systemAsUser)
|
||||
const sysKey = systemKey(body)
|
||||
const sysKey = native ? "" : systemKey(body)
|
||||
if (sysKey && refusedSystems.has(sysKey)) body = systemAsUser(body) ?? body
|
||||
const shaped = (b) => (endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b)
|
||||
const shaped = (b) => (!native && endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b)
|
||||
let res = await send(shaped(body))
|
||||
if (res.status === 400) {
|
||||
let text = await res.text()
|
||||
// a signature WorkBuddy's own signing didn't make — a session
|
||||
// moved here from another provider keeps its thinking blocks,
|
||||
// and a truncated or altered one reads the same way — is 11159
|
||||
// too, and none of them can be told apart from a good one
|
||||
// before sending. The request goes once more without them.
|
||||
// Measured 2026-10-24: another vendor's signature answers 11159
|
||||
// on its own, drop_block notwithstanding; without the block the
|
||||
// same history answers 200. Only when the history holds a
|
||||
// signature that isn't this route's own, so a session on this
|
||||
// route never sends twice.
|
||||
if (native && res.status >= 400) {
|
||||
const text = await res.text()
|
||||
const again = BAD_SIGNATURE.test(text) ? withoutSignedThinking(body) : null
|
||||
if (again) res = await send(again)
|
||||
else res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
|
||||
}
|
||||
if (res.status === 400 && !native) { let text = await res.text()
|
||||
const moved = REFUSED.test(text) && sysKey && !refusedSystems.has(sysKey) ? systemAsUser(body) : null
|
||||
if (moved) {
|
||||
refusedSystems.add(sysKey)
|
||||
@@ -1879,7 +2074,7 @@ function makePlugin(site) {
|
||||
}
|
||||
if (ours.has(res)) return res
|
||||
// renewed here: a mark the account had comes off
|
||||
return res.status >= 400 ? explained(res) : kept(await renamed(res, fit.names), renewed ? "renewed" : "kept")
|
||||
return res.status >= 400 ? explained(res) : kept(native ? res : await renamed(res, names), renewed ? "renewed" : "kept")
|
||||
},
|
||||
}
|
||||
},
|
||||
@@ -1969,6 +2164,13 @@ const REFUSED_HINT =
|
||||
"WorkBuddy refused words in this client's prompt (most often its system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group"
|
||||
const REFUSED = /unapproved channel|illegal api invocation/i
|
||||
|
||||
// BAD_SIGNATURE is WorkBuddy's refusal of a thinking block whose signature it
|
||||
// didn't make: internal code 11159, "Invalid `signature` in `thinking` block.
|
||||
// The block is bound to a different conversation", else 11133 wrapping
|
||||
// "thinking_signature_invalid: replay the original thinking block and
|
||||
// signature unchanged".
|
||||
const BAD_SIGNATURE = /thinking_signature_invalid|invalid\s+`?signature`?\s+in\s+`?thinking|block is bound to a different conversation|"internal_code"\s*:\s*"?11159/i
|
||||
|
||||
// RESTRICTED_HINT is what the user can do about WorkBuddy's 403 code 11140
|
||||
// "request illegal", whose displayMsg says "Your account has been restricted
|
||||
// due to unusual activity" (magpie #1849): the account is out until WorkBuddy
|
||||
@@ -2017,10 +2219,15 @@ async function explained(res) {
|
||||
v = JSON.parse(text)
|
||||
} catch {}
|
||||
const at = v?.error && typeof v.error === "object" ? v.error : v && typeof v === "object" ? v : null
|
||||
const code = at?.data?.code ?? at?.code ?? v?.code ?? v?.data?.code
|
||||
// the Messages route words its code two more ways (seen 2026-10-24):
|
||||
// {"error": {"code": "400001", "internal_code": "11159", …}}, and
|
||||
// {"code": 11102, "error": "11158:…"}, the code that says what happened
|
||||
// first in a string error, where the outer one only says it failed
|
||||
const inner = at?.internal_code ?? (typeof v?.error === "string" ? v.error.match(/^(\d{5}):/)?.[1] : undefined)
|
||||
const codes = [inner, at?.data?.code, at?.code, v?.code, v?.data?.code].filter((c) => c != null).map(Number)
|
||||
const isRefused = REFUSED.test(text)
|
||||
const isRestricted = !isRefused && (Number(code) === RESTRICTED_CODE || RESTRICTED_TEXT.test(text))
|
||||
const isExhausted = !isRestricted && (code === 14018 || Number(code) === 14018 || EXHAUSTED_TEXT.test(text))
|
||||
const isRestricted = !isRefused && (codes.includes(RESTRICTED_CODE) || RESTRICTED_TEXT.test(text))
|
||||
const isExhausted = !isRestricted && (codes.includes(14018) || EXHAUSTED_TEXT.test(text))
|
||||
if (!isRefused && !isRestricted && !isExhausted) return again(text)
|
||||
|
||||
let msg = text.trim()
|
||||
@@ -2046,4 +2253,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
|
||||
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
|
||||
|
||||
// for tests
|
||||
export const _internal = { systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf }
|
||||
export const _internal = { systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
// WorkBuddy's China build serves the Claude models on Anthropic's Messages
|
||||
// API at <endpoint>/v1/messages, beside chat completions at <endpoint>/v2.
|
||||
// On 2026-10-24, with a real account, /v3/config's cli agent models were
|
||||
// each asked on /v1/messages: claude-opus-5.5, claude-sonnet-5.5,
|
||||
// claude-opus-5 and claude-opus-4.8-1m answered in Anthropic's stream;
|
||||
// glm-5.3, deepseek-v4.1-flash, gpt-5.5 and kimi-k3-1 did not. WorkBuddy AI
|
||||
// (www.workbuddy.ai) has no such route: /v1/messages is "404 Route Not Found"
|
||||
// there for every model.
|
||||
//
|
||||
// The point of the route is effort: a chat carries reasoning_effort and
|
||||
// WorkBuddy's chat endpoint answers at about the same length whatever it is
|
||||
// (median output tokens over 4 runs: low 3884, max 5144, a nonsense value
|
||||
// 5715), while Messages carries output_config.effort and max is honored
|
||||
// there (median 30850 at max against 5748 at low, 4 runs each).
|
||||
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"
|
||||
import { realpathSync } from "node:fs"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
|
||||
let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal
|
||||
beforeAll(async () => {
|
||||
// the loader tests sign in: no real sign-in may be read
|
||||
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
|
||||
;({ WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } = await import("./index.mjs"))
|
||||
})
|
||||
const offline = async () => { throw new Error("no network in tests") }
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = offline
|
||||
afterAll(() => (globalThis.fetch = real))
|
||||
afterEach(() => {
|
||||
globalThis.fetch = offline
|
||||
_internal.renewing.clear()
|
||||
_internal.renewed.clear()
|
||||
})
|
||||
|
||||
const CN = () => _internal.SITES.workbuddy
|
||||
const AI = () => _internal.SITES["workbuddy-ai"]
|
||||
|
||||
test("the China build serves the Claude models on Messages, the rest on chat", () => {
|
||||
for (const m of ["claude-opus-5.5", "claude-sonnet-5.5", "claude-opus-5", "claude-opus-4.8-1m"])
|
||||
expect(_internal.nativeOf(CN(), m)).toBe(true)
|
||||
for (const m of ["glm-5.3", "glm-5.3-flash", "deepseek-v4.1-flash", "gpt-5.6-sol", "kimi-k3-1", "hy3", "minimax-m3"])
|
||||
expect(_internal.nativeOf(CN(), m)).toBe(false)
|
||||
})
|
||||
|
||||
test("WorkBuddy AI serves nothing on Messages, a Claude model neither", () => {
|
||||
// its /v1/messages is a 404 route: a Claude model it lists one day goes to
|
||||
// chat, as on 0.1.31, not to a 404
|
||||
for (const m of ["claude-opus-5.5", "claude-sonnet-5.5", "glm-5.3", "gpt-5.5"])
|
||||
expect(_internal.nativeOf(AI(), m)).toBe(false)
|
||||
const m = _internal.modelOf(AI(), { id: "workbuddy-ai" }, { id: "claude-opus-5.5", name: "Claude-Opus-5.5" })
|
||||
expect(m.api.npm).toBe("@ai-sdk/openai-compatible")
|
||||
expect(m.api.url).toBe("https://www.workbuddy.ai/v2")
|
||||
})
|
||||
|
||||
test("a listed model's api is Messages for a Claude model on the China build, chat otherwise", () => {
|
||||
const claude = _internal.modelOf(CN(), { id: "workbuddy" }, { id: "claude-opus-5.5", name: "Claude-Opus-5.5", context: 1000000 })
|
||||
expect(claude.api.npm).toBe("@ai-sdk/anthropic")
|
||||
expect(claude.api.url).toBe("https://copilot.tencent.com/v1")
|
||||
const glm = _internal.modelOf(CN(), { id: "workbuddy" }, { id: "glm-5.3", name: "GLM-5.3", context: 1000000 })
|
||||
expect(glm.api.npm).toBe("@ai-sdk/openai-compatible")
|
||||
expect(glm.api.url).toBe("https://copilot.tencent.com/v2")
|
||||
})
|
||||
|
||||
// hostResolves is how OpenCode, and magpie's host (internal/plugin/host.js
|
||||
// info()), make a config model's package and URL: provider.npm and
|
||||
// provider.api on the model, else the provider's own.
|
||||
function hostResolves(cfg, key) {
|
||||
const m = cfg.models[key]
|
||||
return { npm: m.provider?.npm ?? cfg.npm ?? "@ai-sdk/openai-compatible", url: m.provider?.api ?? cfg.api ?? "" }
|
||||
}
|
||||
|
||||
test("a config model is placed where a host reads it: provider.npm and provider.api", async () => {
|
||||
const site = { ...CN(), models: [["claude-opus-5.5", "Claude-Opus-5.5", 1000000, ["low", "max"]], ["glm-5.3", "GLM-5.3", 1000000, ["low", "high"]]] }
|
||||
const models = _internal.configModels(site)
|
||||
const cfg = { npm: "@ai-sdk/openai-compatible", api: "https://copilot.tencent.com/v2", models }
|
||||
expect(hostResolves(cfg, "claude-opus-5.5")).toEqual({ npm: "@ai-sdk/anthropic", url: "https://copilot.tencent.com/v1" })
|
||||
expect(hostResolves(cfg, "glm-5.3")).toEqual({ npm: "@ai-sdk/openai-compatible", url: "https://copilot.tencent.com/v2" })
|
||||
// and on WorkBuddy AI a Claude model stays on chat
|
||||
const ai = _internal.configModels({ ...AI(), models: [["claude-opus-5.5", "Claude-Opus-5.5", 1000000]] })
|
||||
expect(hostResolves({ npm: "@ai-sdk/openai-compatible", api: "https://www.workbuddy.ai/v2", models: ai }, "claude-opus-5.5"))
|
||||
.toEqual({ npm: "@ai-sdk/openai-compatible", url: "https://www.workbuddy.ai/v2" })
|
||||
})
|
||||
|
||||
test("the plugin's config hook keeps the provider on chat, its static list too", async () => {
|
||||
const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const config = {}
|
||||
await hooks.config(config)
|
||||
const p = config.provider.workbuddy
|
||||
expect(p.npm).toBe("@ai-sdk/openai-compatible")
|
||||
expect(p.api).toBe("https://copilot.tencent.com/v2")
|
||||
expect(hostResolves(p, "glm-5.3")).toEqual({ npm: "@ai-sdk/openai-compatible", url: "https://copilot.tencent.com/v2" })
|
||||
})
|
||||
|
||||
const configOf = (efforts) => JSON.stringify({
|
||||
data: {
|
||||
agents: [{ name: "cli", models: ["claude-opus-5.5", "glm-5.3"] }],
|
||||
models: [
|
||||
{ id: "claude-opus-5.5", name: "Claude-Opus-5.5", supportsReasoning: true, maxInputTokens: 1000000, reasoning: { supportedEfforts: efforts } },
|
||||
{ id: "glm-5.3", name: "GLM-5.3", supportsReasoning: true, maxInputTokens: 1000000, reasoning: { supportedEfforts: ["low", "high", "xhigh"] } },
|
||||
],
|
||||
},
|
||||
})
|
||||
async function listed(site, cfg) {
|
||||
globalThis.fetch = async () => new Response(cfg)
|
||||
const out = await _internal.liveModels(site, { access: "a", uid: "u" })
|
||||
return Object.fromEntries(out.map((m) => [m.id, m.efforts]))
|
||||
}
|
||||
|
||||
test("a Claude model on Messages lists max though the config stops at xhigh", async () => {
|
||||
const e = await listed(CN(), configOf(["low", "medium", "high", "xhigh"]))
|
||||
expect(e["claude-opus-5.5"]).toEqual(["none", "low", "medium", "high", "xhigh", "max"])
|
||||
// a model on chat keeps what the config says: max means nothing more there
|
||||
expect(e["glm-5.3"]).toEqual(["none", "low", "high", "xhigh"])
|
||||
})
|
||||
|
||||
test("on WorkBuddy AI a Claude model keeps the config's levels: it would go to chat", async () => {
|
||||
const e = await listed(AI(), configOf(["low", "medium", "high", "xhigh"]))
|
||||
expect(e["claude-opus-5.5"]).toEqual(["none", "low", "medium", "high", "xhigh"])
|
||||
})
|
||||
|
||||
test("isMessages goes by the URL, and by the body when there is none", () => {
|
||||
const { isMessages } = _internal
|
||||
expect(isMessages("https://copilot.tencent.com/v1/messages", "")).toBe(true)
|
||||
expect(isMessages("https://copilot.tencent.com/v2/chat/completions", "")).toBe(false)
|
||||
expect(isMessages(new URL("https://copilot.tencent.com/v1/messages?beta=true"), "")).toBe(true)
|
||||
expect(isMessages("", JSON.stringify({ system: [{ type: "text", text: "x" }], messages: [] }))).toBe(true)
|
||||
expect(isMessages("", JSON.stringify({ tools: [{ name: "Read", input_schema: { type: "object" } }], messages: [] }))).toBe(true)
|
||||
expect(isMessages("", JSON.stringify({ tools: [{ type: "function", function: { name: "Read", parameters: {} } }], messages: [] }))).toBe(false)
|
||||
expect(isMessages("", "not json")).toBe(false)
|
||||
})
|
||||
|
||||
// ---- one user send is one request (#48), in Anthropic's shape too ----------
|
||||
|
||||
// ccLoop is a Claude Code send as it reaches the route, step by step: the
|
||||
// user's words with a reminder beside them; a {role: "system"} message of
|
||||
// Claude Code's own between steps (its environment, its token count); each
|
||||
// step an assistant message of thinking and tool_use, answered by a user
|
||||
// message of tool_result blocks — one with a reminder beside its result, as
|
||||
// Claude Code puts one there. Taken from the bodies a Claude Code 2.1.307
|
||||
// session sent on 2026-10-24.
|
||||
function ccLoop() {
|
||||
const u0 = { role: "user", content: [{ type: "text", text: "<system-reminder>\nAttribution for git commits...\n</system-reminder>" }, { type: "text", text: "Read hello.py, fix the bug, then run it." }] }
|
||||
const env = { role: "system", content: "# Environment\nYou have been invoked in the following environment..." }
|
||||
const a1 = { role: "assistant", content: [{ type: "thinking", thinking: "Read it first.", signature: "CAQSa1" }, { type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "/w/hello.py" } }] }
|
||||
const r1 = { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "def greet(name):\n return 'hi ' + nam" }, { type: "text", text: "<system-reminder>The file is short.</system-reminder>" }] }
|
||||
const t1 = { role: "system", content: [{ type: "text", text: "<total_tokens>14982892 tokens left</total_tokens>" }] }
|
||||
const a2 = { role: "assistant", content: [{ type: "thinking", thinking: "Typo.", signature: "CAQSa2" }, { type: "tool_use", id: "toolu_2", name: "Edit", input: {} }, { type: "tool_use", id: "toolu_3", name: "Bash", input: {} }] }
|
||||
const r2 = { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_2", content: "ok" }, { type: "tool_result", tool_use_id: "toolu_3", content: "hi x" }] }
|
||||
const t2 = { role: "system", content: [{ type: "text", text: "<total_tokens>14982595 tokens left</total_tokens>" }] }
|
||||
const a3 = { role: "assistant", content: [{ type: "text", text: "Fixed." }] }
|
||||
const u1 = { role: "user", content: "Now add a docstring." }
|
||||
const a4 = { role: "assistant", content: [{ type: "tool_use", id: "toolu_4", name: "Edit", input: {} }] }
|
||||
const r4 = { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_4", content: "ok" }] }
|
||||
const steps = [
|
||||
[u0, env],
|
||||
[u0, env, a1, r1, t1],
|
||||
[u0, env, a1, r1, t1, a2, r2, t2],
|
||||
// the user's next message
|
||||
[u0, env, a1, r1, t1, a2, r2, t2, a3, u1],
|
||||
[u0, env, a1, r1, t1, a2, r2, t2, a3, u1, a4, r4],
|
||||
]
|
||||
return steps.map((messages) => JSON.stringify({ model: "claude-opus-5.5", stream: true, system: [{ type: "text", text: "You are Claude Code." }], messages }))
|
||||
}
|
||||
|
||||
function turnsOf(bodies, session) {
|
||||
return bodies.map((b) => {
|
||||
const h = new Headers()
|
||||
_internal.attend(h, b, session)
|
||||
return { turn: h.get("X-Conversation-Request-ID"), conv: h.get("X-Conversation-ID"), msg: h.get("X-Conversation-Message-ID") }
|
||||
})
|
||||
}
|
||||
|
||||
test("each step of one Claude Code send carries one turn id; the user's next message another", () => {
|
||||
const ids = turnsOf(ccLoop(), "sess-1")
|
||||
// the first send: three steps, one turn
|
||||
expect(new Set(ids.slice(0, 3).map((x) => x.turn)).size).toBe(1)
|
||||
// the next user message: a turn of its own, every step of it the same
|
||||
expect(ids[3].turn).not.toBe(ids[0].turn)
|
||||
expect(ids[4].turn).toBe(ids[3].turn)
|
||||
// one conversation, and a message id each
|
||||
expect(new Set(ids.map((x) => x.conv)).size).toBe(1)
|
||||
expect(new Set(ids.map((x) => x.msg)).size).toBe(ids.length)
|
||||
})
|
||||
|
||||
test("without a session the conversation is still known by its first user message", () => {
|
||||
const ids = turnsOf(ccLoop(), "")
|
||||
expect(new Set(ids.map((x) => x.conv)).size).toBe(1)
|
||||
expect(new Set(ids.slice(0, 3).map((x) => x.turn)).size).toBe(1)
|
||||
})
|
||||
|
||||
test("a tool result in Anthropic's shape answers, and so does a message right after it", () => {
|
||||
const { answeredBefore } = _internal
|
||||
const msgs = JSON.parse(ccLoop()[2]).messages
|
||||
expect(answeredBefore(msgs, 0)).toBe(false) // the user's own words
|
||||
expect(answeredBefore(msgs, 3)).toBe(true) // tool_result, reminder beside it
|
||||
expect(answeredBefore(msgs, 6)).toBe(true) // two tool_results
|
||||
// a user message right after a tool_result message, with a system one
|
||||
// between (pi's images of a tool's result go like this)
|
||||
const after = [msgs[2], msgs[3], { role: "system", content: "x" }, { role: "user", content: [{ type: "image", source: {} }] }]
|
||||
expect(answeredBefore(after, 3)).toBe(true)
|
||||
// a chat's own shapes still answer
|
||||
expect(answeredBefore([{ role: "assistant", tool_calls: [{ id: "c" }] }, { role: "user", content: "x" }], 1)).toBe(true)
|
||||
expect(answeredBefore([{ role: "tool", content: "r" }, { role: "user", content: "x" }], 1)).toBe(true)
|
||||
expect(answeredBefore([{ role: "assistant", content: "plain" }, { role: "user", content: "x" }], 1)).toBe(false)
|
||||
})
|
||||
|
||||
// ---- unsigned thinking --------------------------------------------------------
|
||||
|
||||
test("thinking without a signature is left out of a Messages body; signed thinking stays", () => {
|
||||
const body = JSON.stringify({
|
||||
model: "claude-opus-5.5",
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "from chat, unsigned" }, { type: "tool_use", id: "t1", name: "Read", input: {} }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x" }] },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "unsigned alone" }] },
|
||||
{ role: "user", content: "go on" },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "signed", signature: "CAQSz" }, { type: "text", text: "ok" }] },
|
||||
{ role: "user", content: "more" },
|
||||
],
|
||||
})
|
||||
const out = JSON.parse(_internal.withoutUnsigned(body))
|
||||
expect(out.messages[1].content).toEqual([{ type: "tool_use", id: "t1", name: "Read", input: {} }])
|
||||
expect(out.messages[3].content).toEqual([{ type: "text", text: "" }])
|
||||
expect(out.messages[5].content).toEqual([{ type: "thinking", thinking: "signed", signature: "CAQSz" }, { type: "text", text: "ok" }])
|
||||
// a body with none is passed on as it is, byte for byte
|
||||
const clean = JSON.stringify({ model: "claude-opus-5.5", messages: [{ role: "user", content: "hi" }, { role: "assistant", content: [{ type: "thinking", thinking: "t", signature: "s" }] }] })
|
||||
expect(_internal.withoutUnsigned(clean)).toBe(clean)
|
||||
expect(_internal.withoutUnsigned("not json")).toBe("not json")
|
||||
})
|
||||
|
||||
// ---- the loader's fetch on a Messages URL --------------------------------------
|
||||
|
||||
const MSGS = "https://copilot.tencent.com/v1/messages"
|
||||
const REFRESH = "/v2/plugin/auth/token/refresh"
|
||||
const later = () => Date.now() + 340 * 86400_000
|
||||
const signedIn = (over = {}) => ({ type: "oauth", access: "old", refresh: "r1", expires: later(), refreshExpiresAt: later(), uid: "u1", domain: "www.workbuddy.cn", enterpriseId: "ent1", ...over })
|
||||
const ok = (data) => new Response(JSON.stringify({ code: 0, msg: "OK", data }))
|
||||
const RENEWED = { accessToken: "new", refreshToken: "r2", expiresIn: 340 * 86400, refreshExpiresIn: 340 * 86400 }
|
||||
const SSE = 'event: message_start\ndata: {"type":"message_start","message":{"usage":{"input_tokens":1}}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n'
|
||||
const refusedToken = () =>
|
||||
new Response("<html>401</html>", { status: 401, headers: { "content-type": "text/html", "www-authenticate": 'Bearer realm="copilot", error="invalid_token"' } })
|
||||
|
||||
function serve({ good = ["old"] } = {}) {
|
||||
const calls = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
const u = new URL(String(url instanceof Request ? url.url : url))
|
||||
const headers = new Headers(init?.headers)
|
||||
calls.push({ url: u.href, path: u.pathname, headers, body: init?.body })
|
||||
if (u.pathname === REFRESH) return ok(RENEWED)
|
||||
const token = (headers.get("authorization") ?? "").replace(/^Bearer /, "")
|
||||
return good.includes(token) ? new Response(SSE, { headers: { "content-type": "text/event-stream" } }) : refusedToken()
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
async function send(body, { auth = signedIn(), headers = {} } = {}) {
|
||||
const sets = []
|
||||
const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async (x) => sets.push(x) } } })
|
||||
const opts = await hooks.auth.loader(async () => auth)
|
||||
const res = await opts.fetch(MSGS, { method: "POST", headers: { "content-type": "application/json", "x-api-key": "unused", ...headers }, body })
|
||||
return { res, opts, sets }
|
||||
}
|
||||
|
||||
// what Claude Code sends: its billing line and identity in system, a
|
||||
// developer-free shape, tools with input_schema whose names a chat would
|
||||
// rename, max_tokens as Anthropic spells it, effort as output_config
|
||||
const CC_BODY = JSON.stringify({
|
||||
model: "claude-opus-5.5",
|
||||
max_tokens: 64000,
|
||||
stream: true,
|
||||
system: [
|
||||
{ type: "text", text: "x-anthropic-billing-header: cc_version=2.1.307; cc_entrypoint=cli; cch=abc;" },
|
||||
{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude.", cache_control: { type: "ephemeral", ttl: "1h" } },
|
||||
],
|
||||
tools: [{ name: "mcp__srv__tool.name", description: "d", input_schema: { type: "object", properties: {} } }],
|
||||
thinking: { type: "adaptive" },
|
||||
output_config: { effort: "max" },
|
||||
messages: [{ role: "user", content: "Say ok." }],
|
||||
})
|
||||
|
||||
test("a Messages request goes to /v1/messages byte for byte as sent, with WorkBuddy's headers", async () => {
|
||||
const calls = serve()
|
||||
const { res, opts } = await send(CC_BODY)
|
||||
expect(opts.baseURL).toBe("")
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe(SSE)
|
||||
expect(calls.length).toBe(1)
|
||||
const c = calls[0]
|
||||
expect(c.url).toBe(MSGS)
|
||||
// nothing of the chat route's rewrites: no default system message, no
|
||||
// max_tokens respelling, no tool renaming, no rewording
|
||||
expect(c.body).toBe(CC_BODY)
|
||||
expect(c.headers.get("authorization")).toBe("Bearer old")
|
||||
expect(c.headers.get("x-api-key")).toBeNull()
|
||||
expect(c.headers.get("user-agent")).toMatch(/^WorkBuddy\//)
|
||||
expect(c.headers.get("x-ide-type")).toBe("WorkBuddy")
|
||||
expect(c.headers.get("x-enterprise-id")).toBe("ent1")
|
||||
expect(c.headers.get("x-conversation-request-id")).toMatch(/^[0-9a-f]{32}$/)
|
||||
expect(c.headers.get("x-conversation-id")).toMatch(/^[0-9a-f]{32}$/)
|
||||
})
|
||||
|
||||
test("a Messages body with unsigned thinking goes without it, the rest as sent", async () => {
|
||||
const calls = serve()
|
||||
const body = JSON.stringify({
|
||||
model: "claude-opus-5.5", stream: true,
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "from chat" }, { type: "text", text: "hello" }] },
|
||||
{ role: "user", content: "again" },
|
||||
],
|
||||
})
|
||||
await send(body)
|
||||
const sent = JSON.parse(calls[0].body)
|
||||
expect(sent.messages[1].content).toEqual([{ type: "text", text: "hello" }])
|
||||
expect(sent.messages[0]).toEqual({ role: "user", content: "hi" })
|
||||
})
|
||||
|
||||
test("a 401 on Messages is renewed once and sent again, the body as it was", async () => {
|
||||
const calls = serve({ good: ["new"] })
|
||||
const { res, sets } = await send(CC_BODY)
|
||||
expect(res.status).toBe(200)
|
||||
const asked = calls.filter((c) => c.path === "/v1/messages")
|
||||
expect(asked.length).toBe(2)
|
||||
expect(asked[0].headers.get("authorization")).toBe("Bearer old")
|
||||
expect(asked[1].headers.get("authorization")).toBe("Bearer new")
|
||||
expect(asked[1].body).toBe(CC_BODY)
|
||||
expect(calls.filter((c) => c.path === REFRESH).length).toBe(1)
|
||||
expect(sets.some((x) => x?.body?.access === "new")).toBe(true)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed")
|
||||
})
|
||||
|
||||
test("a 401 renewed and refused again is not sent a third time", async () => {
|
||||
const calls = serve({ good: [] })
|
||||
const { res } = await send(CC_BODY)
|
||||
expect(res.status).toBe(401)
|
||||
expect(calls.filter((c) => c.path === "/v1/messages").length).toBe(2)
|
||||
})
|
||||
|
||||
test("the steps of one Claude Code send through the loader carry one turn id", async () => {
|
||||
const calls = serve()
|
||||
for (const b of ccLoop()) await send(b, { headers: { [_internal.SESSION]: "sess-9" } })
|
||||
const turns = calls.map((c) => c.headers.get("x-conversation-request-id"))
|
||||
expect(new Set(turns.slice(0, 3)).size).toBe(1)
|
||||
expect(turns[3]).not.toBe(turns[0])
|
||||
expect(turns[4]).toBe(turns[3])
|
||||
expect(new Set(calls.map((c) => c.headers.get("x-conversation-id"))).size).toBe(1)
|
||||
// the session header goes no further than the plugin
|
||||
expect(calls.every((c) => !c.headers.has(_internal.SESSION))).toBe(true)
|
||||
})
|
||||
|
||||
test("a chat request still goes through the chat route's rewrites", async () => {
|
||||
const calls = serve()
|
||||
const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const body = JSON.stringify({ model: "glm-5.3", max_completion_tokens: 4096, stream: true, messages: [{ role: "user", content: "hi" }] })
|
||||
await opts.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body })
|
||||
const sent = JSON.parse(calls[0].body)
|
||||
expect(sent.max_tokens).toBe(4096)
|
||||
expect(sent.max_completion_tokens).toBeUndefined()
|
||||
expect(sent.messages[0].role).toBe("system")
|
||||
})
|
||||
|
||||
// ---- the Messages route's error envelopes ----------------------------------------
|
||||
|
||||
// The envelopes are as the route answered on 2026-10-24: an entitlement
|
||||
// refusal as {"code": 11102, "error": "11158:…"}, a refused signature as
|
||||
// {"error": {"code": "400001", "internal_code": "11159", …}}. 11140 and
|
||||
// 14018 weren't met there; they are put in the same two envelopes, as the
|
||||
// route words a code, to see them told.
|
||||
const explain = async (body, status = 400) => {
|
||||
const r = await _internal.explained(new Response(JSON.stringify(body), { status }))
|
||||
return { status: r.status, said: r.headers.get("X-Magpie-Sign-In"), body: await r.text() }
|
||||
}
|
||||
|
||||
test("a code inside the Messages route's envelope is read: restricted and credits used up", async () => {
|
||||
for (const env of [
|
||||
{ code: 11102, error: "11140:request illegal", type: "invalid_request_error" },
|
||||
{ error: { code: "400001", internal_code: "11140", message: "request illegal" }, type: "error" },
|
||||
]) {
|
||||
const r = await explain(env, 403)
|
||||
expect(JSON.parse(r.body).error.code).toBe(11140)
|
||||
expect(r.said).toBe("kept")
|
||||
}
|
||||
for (const env of [
|
||||
{ code: 11102, error: "14018:quota", type: "invalid_request_error" },
|
||||
{ error: { code: "400001", internal_code: "14018", message: "quota" }, type: "error" },
|
||||
]) {
|
||||
const r = await explain(env, 429)
|
||||
expect(JSON.parse(r.body).error.code).toBe(14018)
|
||||
}
|
||||
})
|
||||
|
||||
test("an entitlement refusal or a refused signature on Messages passes as it came", async () => {
|
||||
const entitlement = { code: 11102, error: "11158:model [claude-opus-4.7-1m] is not allowed for user type [internal_enterprise_user]", type: "invalid_request_error" }
|
||||
const r1 = await explain(entitlement)
|
||||
expect(JSON.parse(r1.body)).toEqual(entitlement)
|
||||
const sig = { error: { code: "400001", internal_code: "11159", message: "content.0: Invalid `signature` in `thinking` block." }, type: "error" }
|
||||
const r2 = await explain(sig, 500)
|
||||
expect(JSON.parse(r2.body)).toEqual(sig)
|
||||
expect(r2.status).toBe(500)
|
||||
})
|
||||
|
||||
// ---- the reviewer's open question: the emptied assistant turn ----------------
|
||||
|
||||
test("a history whose assistant turn was emptied of unsigned thinking answers, as an empty text block", () => {
|
||||
// Replayed against WorkBuddy on 2026-10-24, with a real account, three
|
||||
// runs each: the unsigned block itself + a signed turn after it -> 11159;
|
||||
// the same with [{type:"text",text:""}] in its place -> 200, twice over.
|
||||
// So the empty text block is what WorkBuddy takes, where Anthropic's own
|
||||
// API refuses one. The test pins the shape withoutUnsigned leaves.
|
||||
const body = JSON.stringify({
|
||||
model: "claude-opus-5.5",
|
||||
messages: [
|
||||
{ role: "user", content: "Earlier question." },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "unsigned" }] },
|
||||
{ role: "user", content: "Carry on." },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "signed", signature: "CAQSz" }, { type: "text", text: "ok" }] },
|
||||
{ role: "user", content: "Say OK." },
|
||||
],
|
||||
})
|
||||
const out = JSON.parse(_internal.withoutUnsigned(body))
|
||||
// not an empty content list: a message must keep a block, and the empty
|
||||
// text block is the one WorkBuddy takes
|
||||
expect(out.messages[1].content).toEqual([{ type: "text", text: "" }])
|
||||
expect(_internal.withoutSignedThinking(body) && JSON.parse(_internal.withoutSignedThinking(body)).messages[1].content)
|
||||
.toEqual([{ type: "text", text: "" }])
|
||||
// and the signed one is untouched
|
||||
expect(out.messages[3].content).toEqual([{ type: "thinking", thinking: "signed", signature: "CAQSz" }, { type: "text", text: "ok" }])
|
||||
})
|
||||
|
||||
// ---- a signature WorkBuddy didn't make -----------------------------------------
|
||||
|
||||
test("a signature WorkBuddy didn't make is refused once, then the request goes without thinking", async () => {
|
||||
// Measured 2026-10-24: another vendor's signature (valid base64, right
|
||||
// length) answers 11159, drop_block notwithstanding; the same history
|
||||
// without the block answers 200. A session moved here from another
|
||||
// provider keeps such blocks, and a truncated one reads the same way.
|
||||
const REFUSAL = JSON.stringify({
|
||||
error: { code: "400001", internal_code: "11159", message: "content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation." },
|
||||
type: "error",
|
||||
})
|
||||
let n = 0
|
||||
const seen = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
const u = new URL(String(url))
|
||||
if (u.pathname.endsWith("/token/refresh")) return ok(RENEWED)
|
||||
n++
|
||||
seen.push(JSON.parse(init.body))
|
||||
// the first try is refused, the retry (without thinking) answers
|
||||
return n === 1 ? new Response(REFUSAL, { status: 500 }) : new Response(SSE, { headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
const body = JSON.stringify({
|
||||
model: "claude-opus-5.5", stream: true,
|
||||
thinking: { type: "adaptive" },
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: [{ type: "thinking", thinking: "foreign", signature: "Zm9yZWlnbg==" }, { type: "text", text: "hello" }] },
|
||||
{ role: "user", content: "again" },
|
||||
],
|
||||
})
|
||||
const { res } = await send(body)
|
||||
expect(res.status).toBe(200)
|
||||
expect(n).toBe(2)
|
||||
// the retry dropped the thinking block, and only that
|
||||
expect(seen[1].messages[1].content).toEqual([{ type: "text", text: "hello" }])
|
||||
expect(seen[1].messages[0]).toEqual(seen[0].messages[0])
|
||||
expect(seen[1].thinking).toEqual({ type: "adaptive" })
|
||||
})
|
||||
|
||||
test("a body with no thinking block isn't sent twice for a 400", async () => {
|
||||
let n = 0
|
||||
globalThis.fetch = async (url) => {
|
||||
const u = new URL(String(url))
|
||||
if (u.pathname.endsWith("/token/refresh")) return ok(RENEWED)
|
||||
n++
|
||||
return new Response(JSON.stringify({ error: { internal_code: "11159", message: "Invalid `signature` in `thinking` block" } }), { status: 500 })
|
||||
}
|
||||
const { res } = await send(JSON.stringify({ model: "claude-opus-5.5", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(res.status).toBe(500)
|
||||
expect(n).toBe(1)
|
||||
})
|
||||
|
||||
test("a refusal that isn't about a signature isn't retried", async () => {
|
||||
let n = 0
|
||||
globalThis.fetch = async (url) => {
|
||||
const u = new URL(String(url))
|
||||
if (u.pathname.endsWith("/token/refresh")) return ok(RENEWED)
|
||||
n++
|
||||
return new Response(JSON.stringify({ code: 11102, error: "11158:model [claude-opus-4.7-1m] is not allowed for user type [internal_enterprise_user]", type: "invalid_request_error" }), { status: 400 })
|
||||
}
|
||||
const { res } = await send(JSON.stringify({
|
||||
model: "claude-opus-5.5", stream: true,
|
||||
messages: [{ role: "user", content: "hi" }, { role: "assistant", content: [{ type: "thinking", thinking: "t", signature: "s" }] }, { role: "user", content: "go" }],
|
||||
}))
|
||||
expect(res.status).toBe(400)
|
||||
expect(n).toBe(1)
|
||||
})
|
||||
|
||||
test("count_tokens is a Messages request, not a chat", () => {
|
||||
expect(_internal.isMessages("https://copilot.tencent.com/v1/messages/count_tokens", "")).toBe(true)
|
||||
expect(_internal.isMessages("https://copilot.tencent.com/v2/chat/completions", "")).toBe(false)
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-workbuddy-auth",
|
||||
"version": "0.1.31",
|
||||
"version": "0.1.32",
|
||||
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user