Files
plugins/packages/workbuddy/index.mjs
T
tearsleeandtearslee 5d1beb37e0 workbuddy: one user send, one X-Conversation-Request-ID (#48)
WorkBuddy's backend counts a user send as one request by
X-Conversation-Request-ID. The China build was sent no conversation headers
at all, and the international build a new pair on every request, so one send
that takes several steps — a tool result sent back, a retry, another account
answering — was counted as a request of its own: one conversation showed up
in the usage detail as many requests.

The ids are now made as workbuddy2api's fix makes them: the turn's from the
body's last user message (its place and its signature, a tool result's part
left out), the conversation's from the session magpie or OpenCode names —
the chat.headers hook now carries it — else from the chat's first user
message; nothing is made up when neither names one. The message and request
ids stay each request's own, and both builds carry the ids now.

Co-authored-by: tearslee <16331052+tearslee@users.noreply.github.com>
2026-10-08 16:41:53 +08:00

974 lines
40 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// OpenCode provider plugins for WorkBuddy's plans, Tencent's two builds of
// WorkBuddy (CodeBuddy's desktop agent):
// - workbuddy: the China build, copilot.tencent.com
// - workbuddy-ai: the international build, www.workbuddy.ai
// A WorkBuddy account signs in in the browser (Tencent's page, polled for
// the token as WorkBuddy's desktop app does) or is taken from WorkBuddy
// desktop's own sign-in. Its chats are chat completions at <endpoint>/v2,
// streamed only, with WorkBuddy's headers: a request whose User-Agent isn't
// WorkBuddy/<version> is refused (error 10085).
import { createHash, randomBytes } from "node:crypto"
import { readFileSync } from "node:fs"
import { homedir } from "node:os"
import { join } from "node:path"
const APP_VERSION = "2.0.0" // the version WorkBuddy's sign-in page is opened with
const UA_VERSION = "5.5.6" // WorkBuddy/<this> is the User-Agent the API takes
const POLL_MS = 1000
const SIGN_IN_MS = 5 * 60 * 1000
const EARLY_MS = 60 * 1000 // a token this close to its end is refreshed before a request
const LEAD_MS = 5 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh)
const KEEP_RENEWED_MS = 60 * 1000 // how long a refresh's result answers for the old refresh token
// [id, name, context, efforts]
const CN_MODELS = [
["auto", "Auto", 168000],
["hy4-preview-f", "Hy4 preview", 1000000, ["high"]],
["hy3", "Hy3", 192000, ["low", "high"]],
["hy3-x", "Hy3-X", 192000, ["low", "high"]],
["deepseek-v4.1-flash", "Deepseek-V4.1-Flash", 1000000],
["glm-5.3", "GLM-5.3", 1000000, ["low", "high", "max"]],
["glm-5.3-flash", "GLM-5.3-Flash", 1000000, ["low", "high", "max"]],
["glm-5.2", "GLM-5.2", 1000000, ["high", "xhigh"]],
["glm-5.1", "GLM-5.1", 200000],
["glm-5v-turbo", "GLM-5v-Turbo", 200000],
["minimax-m3", "MiniMax-M3", 512000],
["kimi-k3-1", "Kimi-K3", 1000000, ["low", "high", "xhigh"]],
["kimi-k2.7", "Kimi-K2.7-Code", 256000],
["kimi-k2.6", "Kimi-K2.6", 256000],
["deepseek-v4-pro", "Deepseek-V4-Pro", 1000000, ["none", "high", "xhigh"]],
]
const AI_MODELS = [
["default-model", "Default", 176000],
["fast-model", "Fast", 200000],
["balanced-model", "Balanced", 256000],
["primary-model", "Primary", 272000],
["deep-model", "Deep", 176000],
["gpt-5.5", "GPT-5.5", 1000000],
["gpt-5.4", "GPT-5.4", 272000],
["gpt-5.3-codex", "GPT-5.3-Codex", 272000],
["gemini-3.1-pro", "Gemini-3.1-Pro", 400000],
["gemini-3.5-flash", "Gemini-3.5-Flash", 1000000],
["glm-5.3", "GLM-5.3", 1000000, ["low", "high", "max"]],
["glm-5.2", "GLM-5.2", 1000000, ["high", "xhigh"]],
["hy3", "Hy3", 192000, ["low", "high"]],
["kimi-k3", "Kimi-K3", 1000000],
["kimi-k2.6", "Kimi-K2.6", 256000],
["minimax-m3", "MiniMax-M3", 512000],
]
const SITES = {
workbuddy: {
id: "workbuddy",
name: "WorkBuddy",
endpoint: "https://copilot.tencent.com",
authID: "workbuddy-desktop",
platform: "workbuddy",
ai: false,
models: CN_MODELS,
},
"workbuddy-ai": {
id: "workbuddy-ai",
name: "WorkBuddy AI",
endpoint: "https://www.workbuddy.ai",
authID: "workbuddy-desktop-ai",
platform: "workbuddy-ai",
ai: true,
models: AI_MODELS,
},
}
const NPM = "@ai-sdk/openai-compatible"
const hex = () => randomBytes(16).toString("hex")
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const api = (site) => site.endpoint + "/v2"
// ---- WorkBuddy's API ------------------------------------------------------
class WBError extends Error {
constructor(message, code, status, said) {
super(message)
this.code = code
this.status = status
this.said = said // as magpie's built-in (wbCall) worded it
}
}
// call makes a request of WorkBuddy's plugin API, which answers
// {code, msg, data}; a code but 0 is an error.
async function call(site, method, path, headers = {}, body) {
const res = await fetch(site.endpoint + path, {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent": "WorkBuddy/" + UA_VERSION,
...headers,
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30000),
})
const text = await res.text()
let env = {}
try {
env = JSON.parse(text)
} catch {}
const code = Number.parseInt(env.code, 10) || 0
if (!res.ok) {
const why = env.msg || env.message || env.error?.message || text.slice(0, 200) || res.statusText
const said = code ? env.msg || `error ${code}` : env.msg || statusText(res.status)
throw new WBError(`${site.name}: ${why} (HTTP ${res.status}${env.code ? ", code " + env.code : ""})`, env.code, res.status, said)
}
if (env.code) throw new WBError(`${site.name}: ${env.msg || "error"} (${env.code})`, env.code, res.status, env.msg || `error ${code}`)
return env.data
}
function domainOf(site, a) {
return a.domain || new URL(api(site)).host
}
// merge takes a token WorkBuddy gave (sign-in or refresh) into the
// stored sign-in, times given as at-ms or in-seconds.
function merge(a, got) {
const now = Date.now()
const out = { ...a, access: got.accessToken }
if (got.refreshToken) out.refresh = got.refreshToken
if (got.domain) out.domain = got.domain
if (got.tokenType) out.tokenType = got.tokenType
if (got.expiresAt > 0) out.expires = got.expiresAt
else if (got.expiresIn > 0) out.expires = now + got.expiresIn * 1000
if (got.refreshExpiresAt > 0) out.refreshExpiresAt = got.refreshExpiresAt
else if (got.refreshExpiresIn > 0) out.refreshExpiresAt = now + got.refreshExpiresIn * 1000
return out
}
function stale(a) {
return !!a.expires && Date.now() >= a.expires - EARLY_MS
}
// renewing is each refresh under way, by site and the refresh token it
// spends; renewed is what each gave, kept a minute so one that read the
// old refresh token after it was spent (magpie's auth.refresh, a request)
// takes that rather than spending it again.
const renewing = new Map()
const renewed = new Map()
function refreshable(a) {
return !!a.refresh && !(a.refreshExpiresAt && Date.now() >= a.refreshExpiresAt)
}
// renew spends a's refresh token, once: those who come while it runs, or
// within KEEP_RENEWED_MS of it, get what it gave. save keeps the result.
function renew(site, a, save) {
const key = site.id + "\n" + a.refresh
const done = renewed.get(key)
if (done && Date.now() - done.at < KEEP_RENEWED_MS) return Promise.resolve(merged(a, done.next))
let r = renewing.get(key)
if (!r) {
r = (async () => {
const got = await call(site, "POST", "/v2/plugin/auth/token/refresh", {
"X-Refresh-Token": a.refresh,
"X-Auth-Refresh-Source": "plugin",
"X-Domain": domainOf(site, a),
}, {})
if (!got?.accessToken) throw Object.assign(new Error("WorkBuddy gave no refreshed token"), { bare: true })
const next = merge(a, got)
renewed.set(key, { next, at: Date.now() })
await save?.(next)
return next
})().finally(() => renewing.delete(key))
renewing.set(key, r)
}
return r.then((next) => merged(a, next))
}
// merged is a with the tokens another's refresh gave over it.
function merged(a, next) {
const out = { ...a }
for (const k of TOKEN_FIELDS) if (k in next) out[k] = next[k]
return out
}
const TOKEN_FIELDS = ["access", "refresh", "expires", "refreshExpiresAt", "domain", "tokenType"]
// fresh is the sign-in with an access token that isn't about to end:
// refreshed (and saved) when it is. A refresh that fails, or a refresh
// token that has ended, leaves the access token there is. Its failures
// are worded as the built-in's (wbFresh), "WorkBuddy" on both sites.
async function fresh(site, client, a) {
if (!stale(a)) return a
if (!refreshable(a)) {
if (a.access) return a
throw new Error("this WorkBuddy account is signed out; sign in again")
}
try {
return await renew(site, a, async (next) => {
try {
await client?.auth?.set?.({ path: { id: site.id }, body: next })
} catch {}
})
} catch (e) {
if (a.access) return a
if (e?.bare) throw e
throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`)
}
}
// refreshed is what magpie's auth.refresh gives for a browser sign-in:
// the fields a refresh changed, nothing when there's nothing to renew.
// magpie saves them itself.
async function refreshed(site, auth) {
if (auth?.type !== "oauth" || auth.source === "desktop" || !auth.access || !auth.refresh) return undefined
// a refresh token that has ended is said plainly, never as signIn
// "expired": the built-in never marked a WorkBuddy account
if (!refreshable(auth)) throw new Error("this WorkBuddy account is signed out; sign in again")
let next
try {
next = await renew(site, auth)
} catch (e) {
if (e?.bare) throw e
throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`)
}
const out = {}
for (const k of TOKEN_FIELDS) if (k in next && next[k] !== auth[k]) out[k] = next[k]
return Object.keys(out).length ? out : undefined
}
// sign sets on headers what WorkBuddy's desktop app sends with a chat: the
// account's own, the client's, and the attribution WorkBuddy's usage list
// shows as the client that asked (使用端). The chat's ids — the
// conversation's, the turn's, the message's — are attend's below.
//
// WorkBuddy's own client sends the whole of this on both builds
// (application-manifest.js: X-Agent-Purpose "conversation", X-IDE-Name/Type
// "WorkBuddy", X-IDE-Version, X-Product "SaaS"); a chat without them is
// counted under no client at all, which is the empty 使用端 a request shows
// when only some of the group is there. The gate below used to give the China
// build none of the client's headers, so every China-build request was
// attribution-less.
function sign(site, a, headers) {
headers.set("Authorization", "Bearer " + a.access)
headers.set("X-User-Id", a.uid ?? "")
headers.set("X-Domain", domainOf(site, a))
headers.set("X-Product", "SaaS")
headers.set("X-IDE-Type", "WorkBuddy")
headers.set("User-Agent", "WorkBuddy/" + UA_VERSION)
headers.set("X-Requested-With", "XMLHttpRequest")
headers.set("X-Agent-Intent", "craft")
headers.set("X-Agent-Purpose", "conversation")
headers.set("X-IDE-Name", "WorkBuddy")
headers.set("X-IDE-Version", UA_VERSION)
if (!site.ai) return
headers.set("X-Agent-Type", "main")
}
// WorkBuddy's own client names each chat to its gateway four ways: the
// conversation it belongs to, the user send (turn) it answers, the message
// itself, and the request that carried it. Its backend counts a user send as
// one request by X-Conversation-Request-ID: a chat carrying a new one every
// time is counted on its own, so one send that takes several steps — a tool
// call answered and sent again, a retry, another account answering — shows up
// in the usage detail as many requests. The ids below are made from what
// names the conversation and the turn, so every step of one send carries the
// same turn id and the user's next message carries another, as WorkBuddy's
// own client does.
// SESSION carries the conversation magpie (or OpenCode) names a request by,
// from the chat.headers hook to the loader's fetch. It goes no further.
const SESSION = "x-magpie-workbuddy-session"
// SALT is what the ids are derived with, so an id says nothing of the words
// it was made from. New in each process, as WorkBuddy's own ids are one
// conversation's own within a run.
const SALT = randomBytes(16).toString("hex")
// idFor is the 32 hex digits WorkBuddy's own ids are made of, made of a
// name of the thing the id is for (a turn, a conversation) and what names it.
function idFor(kind, key) {
return createHash("sha256").update(`${SALT}|${kind}|${key}`).digest("hex").slice(0, 32)
}
// signatureOf is a message content's signature: its text, and a digest of
// every part that isn't text (an image, a file), so a turn of images alone is
// a turn of its own too. A tool result's part — carried in a user message by
// clients of Anthropic's shape — is left out: it is not what the user said,
// and it changes with every step of the send.
function signatureOf(content) {
if (typeof content === "string") return content
if (!Array.isArray(content)) return ""
let out = ""
for (const part of content) {
const type = part?.type ?? ""
if (type === "" || type === "text") out += typeof part?.text === "string" ? part.text : ""
else if (type !== "tool_result" && type !== "tool-result") {
out += `[${type}:${createHash("sha256").update(JSON.stringify(part)).digest("hex").slice(0, 8)}]`
}
}
return out
}
// answeredBefore is whether msgs[i] answers the message before it — a tool's
// result, or an assistant's calls — rather than carrying the user's own
// 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.
function answeredBefore(msgs, i) {
const prev = msgs[i - 1]
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
}
// turnKey names the user send a chat answers: the body's last user message
// that is the user's own, by its place and its signature. Every step of one
// send repeats it; the user's next message changes it. "" for a chat whose
// last such message has nothing signable in it (an empty message) or which
// has none at all: the caller then makes a fresh id for that request, as
// before these were derived at all.
function turnKey(chat) {
const msgs = Array.isArray(chat?.messages) ? chat.messages : []
for (let i = msgs.length - 1; i >= 0; i--) {
if (msgs[i]?.role !== "user" || answeredBefore(msgs, i)) continue
const sig = signatureOf(msgs[i].content)
return sig ? `u${i}:${sig}` : ""
}
return ""
}
// conversationKey names the conversation a chat belongs to: the session
// magpie or OpenCode names (its chat.headers hook), else the chat's first
// user message, which every later turn of it repeats. "" when neither names
// one — a body that isn't a chat, or one with no user message in it — and no
// conversation id is sent then: a made-up one would be a conversation of the
// request's own, which is what fragments the usage detail in the first place.
function conversationKey(chat, session) {
if (session) return `session:${session}`
const msgs = Array.isArray(chat?.messages) ? chat.messages : []
for (const m of msgs) {
if (m?.role !== "user") continue
const sig = signatureOf(m.content)
if (sig) return `first:${sig}`
}
return ""
}
// 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) {
if (typeof body !== "string") return null
try {
const b = JSON.parse(body)
return b !== null && typeof b === "object" ? b : null
} catch {
return null
}
}
// sessionOf takes the session a chat.headers hook named off the headers,
// with the header: it goes no further than here. Its length is capped as
// magpie's own session ids are, the id below being derived from it anyway.
function sessionOf(headers) {
const s = String(headers.get(SESSION) ?? "").trim()
headers.delete(SESSION)
return s.slice(0, 128)
}
// attend sets a chat's ids on the headers its request goes to WorkBuddy
// with: the message's (each request its own, as the client makes them), the
// turn's (one user send, whatever it takes), and the conversation's. A header
// already there — the caller's own, or another plugin's — is kept, and the
// message and request ids are the same one, as WorkBuddy's client has them.
function attend(headers, body, session) {
const chat = chatOf(body)
const conv = conversationKey(chat, session)
const msg = hex()
headers.set("X-Conversation-Message-ID", msg)
headers.set("X-Request-ID", msg)
if (!headers.has("X-Conversation-Request-ID")) {
const turn = turnKey(chat)
// a turn is a conversation's own: two conversations whose user message
// reads the same are still two sends, not one
headers.set("X-Conversation-Request-ID", turn ? idFor("turn", `${conv}|${turn}`) : hex())
}
if (conv && !headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", idFor("conversation", conv))
}
// FLAGGED are the words WorkBuddy refuses a chat for, "Illegal API
// invocation from an unapproved channel" (magpie #182), each with words
// that say the same and pass: tried one by one against both builds with
// the requests Claude Code 2.1.280 and Codex 0.159.2 send. WorkBuddy reads
// every message, not only the system prompt (Claude Code puts its main
// branch in the first user message), and pays no mind to case. Claude
// Code's billing header means nothing to WorkBuddy's models and goes.
const FLAGGED = [
[/x-anthropic-billing-header:[^\n]*\n?/gi, ""],
[/You are Claude Code, Anthropic['’]s official CLI for Claude/gi, "You are Claude Code, Anthropic's CLI for Claude"],
[/Main branch \(you will usually use this for PRs\)/gi, "Main branch (usually the base for PRs)"],
[/(?<!the )Codex CLI is an open source project led by OpenAI\./gi, "The Codex CLI is an open source project led by OpenAI."],
]
function unflagged(text) {
for (const [re, to] of FLAGGED) text = text.replace(re, to)
return text
}
// unflag puts FLAGGED's words in place in every message of a chat, and
// leaves out a text that had nothing else (the billing header's system
// block). It says whether it changed anything.
function unflag(messages) {
let changed = false
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i]
if (typeof m?.content === "string") {
const t = unflagged(m.content)
if (t === m.content) continue
changed = true
if (t.trim() || m.role !== "system") m.content = t
else messages.splice(i, 1)
} else if (Array.isArray(m?.content)) {
const parts = []
let here = false
for (const p of m.content) {
const t = typeof p?.text === "string" ? unflagged(p.text) : null
if (t === null || t === p.text) {
parts.push(p)
continue
}
here = true
if (t.trim()) parts.push({ ...p, text: t })
}
if (!here) continue
changed = true
if (parts.length || m.role !== "system") m.content = parts
else messages.splice(i, 1)
}
}
return changed
}
// 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.
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)
if (typeof body !== "string") return body
try {
const b = JSON.parse(body)
if (!Array.isArray(b?.messages) || !b.messages.length) return body
let changed = unflag(b.messages)
if (b.messages[0]?.role !== "system") {
b.messages.unshift({ role: "system", content: "You are a helpful assistant." })
changed = true
}
return changed ? JSON.stringify(b) : body
} catch {
return body
}
}
// ---- signing in -------------------------------------------------------------
// poll asks path until WorkBuddy answers with data, retrying the codes
// that mean "not yet".
async function poll(site, path, headers, retry, deadline) {
for (;;) {
if (Date.now() > deadline) throw new Error(`${site.name} sign-in timed out`)
try {
const data = await call(site, "GET", path, headers)
if (data && Object.keys(data).length) return data
} catch (e) {
if (!(retry.includes(e.code) || e.status === 408 || e.status === 429)) throw e
}
await sleep(POLL_MS)
}
}
async function browserSignIn(site) {
const state = await call(site, "POST", `/v2/plugin/auth/state?platform=${encodeURIComponent(site.platform)}`, {
"X-No-Authorization": "true",
"X-No-User-Id": "true",
"X-No-Enterprise-Id": "true",
"X-No-Department-Info": "true",
}, {})
if (!state?.state || !state?.authUrl) throw new Error(`${site.name} gave no sign-in page`)
const url = new URL(state.authUrl)
if (url.protocol !== "https:") throw new Error(`${site.name}'s sign-in page isn't https`)
url.searchParams.set("version", APP_VERSION)
url.searchParams.set("loginSessionId", hex())
return {
url: url.toString(),
instructions: `Sign in to ${site.name} in the browser; this finishes by itself.`,
method: "auto",
async callback() {
try {
const deadline = Date.now() + SIGN_IN_MS
const q = encodeURIComponent(state.state)
const token = await poll(site, `/v2/plugin/auth/token?state=${q}`, {}, [11217], deadline)
if (!token.accessToken) return { type: "failed", error: `${site.name} sent back no token` }
let a = merge({}, token)
const who = await poll(site, `/v2/plugin/login/account?state=${q}`, {
Authorization: "Bearer " + a.access,
"X-Domain": domainOf(site, a),
"X-No-User-Id": "true",
"X-No-Enterprise-Id": "true",
}, [12151], deadline)
a.uid = who.uid ?? ""
return success(site, a, who.nickname || who.phoneNumber || who.uid)
} catch (e) {
return { type: "failed", error: e.message }
}
},
}
}
function success(site, a, name) {
return {
type: "success",
refresh: a.refresh ?? "",
access: a.access,
expires: a.expires ?? 0,
accountId: name || site.name,
uid: a.uid ?? "",
domain: a.domain ?? "",
...(a.refreshExpiresAt ? { refreshExpiresAt: a.refreshExpiresAt } : {}),
...(a.tokenType ? { tokenType: a.tokenType } : {}),
}
}
// desktopFile is where WorkBuddy's desktop app keeps its sign-in.
function desktopFile(site) {
const home = homedir()
const base =
process.platform === "darwin" ? join(home, "Library", "Application Support", "CodeBuddyExtension")
: process.platform === "win32" ? join(home, "AppData", "Local", "CodeBuddyExtension")
: join(home, ".local", "share", "CodeBuddyExtension")
return join(base, "Data", "Public", "auth", site.authID + ".info")
}
// readDesktop is WorkBuddy desktop's sign-in as the app keeps it now, null
// for none (or tokens the app keeps encrypted, which can't be read).
function readDesktop(site) {
try {
const f = JSON.parse(readFileSync(desktopFile(site), "utf8"))
const t = f?.auth ?? {}
if (typeof t.accessToken !== "string" || !t.accessToken || !f?.account?.uid) return null
const now = Date.now()
const acct = f.account
return {
access: t.accessToken,
refresh: typeof t.refreshToken === "string" ? t.refreshToken : "",
expires: t.expiresAt > 0 ? t.expiresAt : t.expiresIn > 0 ? now + t.expiresIn * 1000 : 0,
refreshExpiresAt: t.refreshExpiresAt > 0 ? t.refreshExpiresAt : t.refreshExpiresIn > 0 ? now + t.refreshExpiresIn * 1000 : 0,
domain: typeof t.domain === "string" ? t.domain : "",
tokenType: typeof t.tokenType === "string" ? t.tokenType : "",
uid: acct.uid,
name: acct.nickname || acct.phoneNumber || acct.uid,
}
} catch {
return null
}
}
// desktopSignIn uses the account WorkBuddy desktop is signed in to: nothing
// is copied (a copied refresh token would be the app's and the plugin's
// both, and the first to use it would sign the other out); its file is
// read each time, as the app keeps it.
function desktopSignIn(site) {
return {
url: "",
instructions: `Uses the account ${site.name} desktop is signed in to.`,
method: "auto",
async callback() {
const d = readDesktop(site)
if (!d) return { type: "failed", error: `${site.name} desktop isn't signed in` }
return { type: "success", refresh: "", access: "", expires: 0, source: "desktop", accountId: d.name || site.name, uid: d.uid }
},
}
}
// desktopHeld is what a desktop sign-in was renewed to here, by site and
// account: kept in memory only, never written where the app keeps it.
const desktopHeld = new Map()
// current is the sign-in a stored auth names, fresh: WorkBuddy desktop's,
// read where it keeps it, or one kept here.
async function current(site, client, auth) {
if (auth?.source !== "desktop") return fresh(site, client, auth)
const d = readDesktop(site)
if (!d) throw new Error(`${site.name} desktop isn't signed in`)
const k = site.id + "|" + d.uid
const h = desktopHeld.get(k)
const a = await fresh(site, null, h && h.expires >= d.expires ? h : d)
desktopHeld.set(k, a)
return a
}
// ---- allowance ----------------------------------------------------------------
// STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
// refused meter call with; a status Go has no words for is "HTTP <n>", so
// the card always has an error.
const STATUS_TEXT = {
100: "Continue", 101: "Switching Protocols", 102: "Processing", 103: "Early Hints",
200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content",
206: "Partial Content", 207: "Multi-Status", 208: "Already Reported", 226: "IM Used",
300: "Multiple Choices", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy",
307: "Temporary Redirect", 308: "Permanent Redirect",
400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone",
411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request URI Too Long",
415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 418: "I'm a teapot",
421: "Misdirected Request", 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", 425: "Too Early",
426: "Upgrade Required", 428: "Precondition Required", 429: "Too Many Requests", 431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout",
505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", 507: "Insufficient Storage", 508: "Loop Detected",
510: "Not Extended", 511: "Network Authentication Required",
}
const statusText = (n) => STATUS_TEXT[n] || `HTTP ${n}`
// meter asks the billing API as magpie's built-in did, its errors said
// the same: WorkBuddy's message, else its code, else the HTTP status.
async function meter(site, a, path) {
const res = await fetch(site.endpoint + path, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + UA_VERSION,
Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS",
"X-IDE-Type": "WorkBuddy" },
body: "{}",
signal: AbortSignal.timeout(20000),
})
let env = {}
try {
env = JSON.parse(await res.text()) ?? {}
} catch {}
const code = Number.parseInt(env.code, 10) || 0
if (!res.ok) {
if (code) throw new Error(env.msg || `error ${code}`)
if (env.msg) throw new Error(env.msg)
throw new Error(statusText(res.status))
}
if (code) throw new Error(env.msg || `error ${code}`)
return env.data ?? null
}
// capacity is a capacity the billing API sends, as a string ("438.88")
// or now and then a number; empty is 0.
function capacity(v) {
if (v == null || v === "") return 0
if (typeof v === "number") return v
const s = String(v)
const n = Number(s)
if (s.trim() !== s || Number.isNaN(n)) throw new Error(`strconv.ParseFloat: parsing ${JSON.stringify(s)}: invalid syntax`)
return n
}
// compact is a count as magpie says one: whole, else to two places.
const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""))
// usageOf is the account's credits, from its resource summary: the plan's
// credits used against what the cycle grants, as magpie's built-in said —
// the count itself too (amount of limit, in credits), for magpie to say it
// as used or left beside the share (magpie#659).
function usageOf(sum, plan) {
const out = { plan: plan || (sum?.IsPaidUser ? "Pro" : "Free"), windows: [] }
let total = 0, used = 0
for (const p of sum?.Packages ?? []) {
total += capacity(p?.CycleTotalCapacity)
used += capacity(p?.CycleUsedCapacity)
}
if (total > 0) out.windows.push({ name: "Credits", used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}`, amount: used, limit: total, unit: "credits" })
return out
}
// ---- models -----------------------------------------------------------------
// variants are the reasoning levels as OpenCode gives them to the AI SDK.
function variants(efforts) {
return Object.fromEntries((efforts ?? []).map((e) => [e, { reasoningEffort: e }]))
}
function configModels(site) {
return Object.fromEntries(site.models.map(([id, name, context, efforts]) => [id, {
name,
limit: { context, output: 0 },
tool_call: true,
...(efforts ? { reasoning: true, variants: variants(efforts) } : {}),
}]))
}
function modelOf(site, provider, m) {
return {
id: m.id,
providerID: provider.id,
name: m.name,
api: { id: m.id, url: api(site), npm: NPM },
status: "active",
headers: {},
options: {},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: m.context ?? 0, output: m.output ?? 0 },
capabilities: {
temperature: true,
reasoning: !!m.efforts?.length,
attachment: !!m.images,
toolcall: true,
input: { text: true, image: !!m.images, audio: false, video: false, pdf: false },
output: { text: true, image: false, audio: false, video: false, pdf: false },
interleaved: false,
},
release_date: "",
variants: variants(m.efforts),
// magpie's own: served at no cost to the plan's credits
free: !!m.free,
// magpie's own: the credits a request costs, as a multiple (0: none)
rate: m.rate ?? 0,
}
}
// liveModels asks WorkBuddy's product config for the plan's models: the
// "cli" agent's list, each with its details. The CLI User-Agent picks
// WorkBuddy's config (a bare WorkBuddy/<v> gets CodeBuddy IDE's, no cli).
// creditsOf reads a model's credits, the multiple WorkBuddy's picker shows
// by it: "x0.03", "0" or 0; "x0.00" is free. A rate it can't read (or
// none, or an infinite one) is undefined: the model is neither free nor
// rated. The same rule as magpie's built-in (wbCredits).
function creditsOf(c) {
if (c == null || c === "") return undefined
const s = String(c).trim().toLowerCase().replace(/^x/, "")
const n = Number(s)
return s !== "" && Number.isFinite(n) && n >= 0 ? n : undefined
}
// freeCredits says whether a model's credits are none: "x0.00", "0" or 0.
// A rate it can't read is not free.
function freeCredits(c) {
return creditsOf(c) === 0
}
async function liveModels(site, a) {
const headers = new Headers()
sign(site, a, headers)
headers.set("User-Agent", `CLI/${APP_VERSION} WorkBuddy/${UA_VERSION}`)
headers.set("X-Requested-With", "XMLHttpRequest")
headers.set("Accept", "application/json")
const res = await fetch(site.endpoint + "/v3/config", { headers, signal: AbortSignal.timeout(15000) })
const env = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(`${site.name}'s config: HTTP ${res.status}`)
if (env.code) throw new Error(`${site.name}'s config: ${env.msg} (${env.code})`)
const cfg = env.data ?? {}
const out = []
for (const agent of cfg.agents ?? []) {
if (agent.name !== "cli") continue
for (const id of agent.models ?? []) {
const d = (cfg.models ?? []).find((x) => x.id === id)
const m = { id, name: d?.name || id }
if (d) {
m.context = d.maxInputTokens
m.output = d.maxOutputTokens
m.images = d.supportsImages === true
const r = creditsOf(d.credits)
if (r !== undefined) {
m.free = r === 0
m.rate = r
}
const es = d.reasoning?.supportedEfforts ?? []
if (es.length) {
const canOff = d.reasoning?.canDisableThinking
m.efforts = [...(!d.onlyReasoning && (canOff == null || canOff) ? ["none"] : []), ...es]
}
}
out.push(m)
}
}
// tell apart models the config names alike: deepseek-v4.1-flash and
// deepseek-v4.1-flash-sg are both "Deepseek-V4.1-Flash"
const first = new Map()
for (const m of out) {
const id = first.get(m.name)
if (id === undefined) {
first.set(m.name, m.id)
continue
}
const rest = m.id.startsWith(id + "-") ? m.id.slice(id.length + 1) : ""
m.name = `${m.name} (${rest ? rest.toUpperCase() : m.id})`
}
return out
}
// ---- the plugins --------------------------------------------------------------
function makePlugin(site) {
return async ({ client }) => ({
config: async (config) => {
config.provider ??= {}
config.provider[site.id] ??= {}
const p = config.provider[site.id]
p.name ??= site.name
p.npm ??= NPM
p.api ??= api(site)
p.models = { ...configModels(site), ...(p.models ?? {}) }
},
// the conversation's id, which the chats below carry to WorkBuddy:
// magpie's (or OpenCode's) session for this request, when it names one
"chat.headers": async (input, output) => {
const id = input?.model?.providerID ?? input?.provider?.info?.id
if (id !== site.id || !input?.sessionID) return
output.headers[SESSION] = String(input.sessionID).slice(0, 128)
},
provider: {
id: site.id,
// the account's own list, when it's signed in and WorkBuddy answers;
// else the list above
async models(provider, { auth }) {
if (auth?.type !== "oauth" || !(auth.access || auth.source)) return provider.models
try {
const a = await current(site, client, auth)
const ms = await liveModels(site, a)
if (!ms.length) return provider.models
return Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m)]))
} catch {
return provider.models
}
},
},
auth: {
provider: site.id,
// magpie renews a browser sign-in LEAD_MS before its end (an hour's
// token), once for the account, before its requests, models and
// usage ask; the check before each request stays for OpenCode,
// which doesn't call this. Desktop's sign-in has no expiry stored
// and is renewed as before.
refreshLead: LEAD_MS,
refresh: (auth) => refreshed(site, auth),
async loader(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth") return {}
return {
baseURL: api(site),
apiKey: "",
async fetch(input, init) {
let a = await getAuth()
if (a?.type !== "oauth") throw new Error(`${site.name} isn't signed in`)
a = await current(site, client, a)
const req = input instanceof Request ? input : null
const headers = new Headers(init?.headers ?? req?.headers)
headers.delete("authorization")
headers.delete("x-api-key")
headers.delete("content-length")
const session = sessionOf(headers)
sign(site, a, headers)
let body = init?.body
if (body === undefined && req) body = await req.clone().text()
body = withSystem(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)
},
}
},
// the account's credits, as magpie's built-in showed them; each
// read keeps the sign-in (signIn), as the built-in's neither marked
// an account lapsed nor cleared it
async usage(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in", signIn: "kept" }
try {
const a = await current(site, client, auth)
// the meter has no /v2 prefix, on either site
return { ...usageOf(await meter(site, a, "/billing/meter/get-user-resource-summary"), auth.plan), signIn: "kept" }
} catch (e) {
return { error: e?.message ?? String(e), signIn: "kept" }
}
},
methods: [
{
type: "oauth",
label: `${site.name} account (browser)`,
authorize: () => browserSignIn(site),
},
{
type: "oauth",
label: `${site.name} desktop's sign-in`,
authorize: async () => desktopSignIn(site),
},
],
},
})
}
// REFUSED_HINT is what the user can do about WorkBuddy's "Illegal API
// invocation from an unapproved channel": both builds answer it to a chat
// holding words of Codex's or Claude Code's own (magpie #182), whatever the
// headers. FLAGGED rewrites the ones known; this is for one it doesn't know. It ends the error's message, as magpie's built-in
// put it (provider.WBRefusedHint), so magpie's routing page says it apart.
const REFUSED_HINT =
"WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group"
const REFUSED = /unapproved channel|illegal api invocation/i
// EXHAUSTED_HINT explains WorkBuddy's requirement of an active package
// even for 0-rate / free models. When an account has no packages or 0 credits,
// WorkBuddy returns code 14018 ("Credits exhausted...").
const EXHAUSTED_HINT =
"WorkBuddy requires an active credit package even for 0-rate free models; check your account package balance"
// The code is matched whole: a code that only begins with 14018 (140185) is
// another error, and insufficient_quota would rest the account as out of credit.
const EXHAUSTED_TEXT = /credits exhausted|额度已用尽|["']code["']\s*:\s*["']?14018(?![\d.])/i
// kept is an answer that went through, saying the sign-in is kept: the
// built-in never cleared a WorkBuddy account's mark, as it never set one.
function kept(res) {
const headers = new Headers(res.headers)
headers.set("X-Magpie-Sign-In", "kept")
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
}
// explained is res with REFUSED_HINT or EXHAUSTED_HINT added to that refusal's message.
// Each refusal says the sign-in is kept: the built-in passed WorkBuddy's
// 401 on and never marked a WorkBuddy account lapsed.
async function explained(res) {
const text = await res.text()
const again = (b) => {
const headers = new Headers(res.headers)
headers.delete("content-length")
headers.delete("content-encoding")
headers.set("X-Magpie-Sign-In", "kept")
return new Response(b, { status: res.status, statusText: res.statusText, headers })
}
let v
try {
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
const isRefused = REFUSED.test(text)
const isExhausted = code === 14018 || Number(code) === 14018 || EXHAUSTED_TEXT.test(text)
if (!isRefused && !isExhausted) return again(text)
let msg = text.trim()
if (at && typeof at.message === "string") msg = at.message
else if (typeof at?.data?.msg === "string") msg = at.data.msg
else if (typeof v?.error === "string") msg = v.error
else if (typeof v?.msg === "string" && v.msg) msg = v.msg // WorkBuddy's own {"code", "msg"}
else if (typeof v?.data?.msg === "string") msg = v.data.msg
const hint = isRefused ? REFUSED_HINT : EXHAUSTED_HINT
const type = isRefused ? "permission_error" : "insufficient_quota"
const errCode = isRefused ? null : 14018
msg = `${msg} — ${hint}`
const headers = new Headers(res.headers)
headers.set("content-type", "application/json")
headers.delete("content-length")
headers.delete("content-encoding")
headers.set("X-Magpie-Sign-In", "kept")
return new Response(JSON.stringify({ error: { message: msg, type, code: errCode } }), { status: res.status, statusText: res.statusText, headers })
}
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 }