workbuddy: the refusal of Codex's and Claude Code's prompt carries magpie's hint, and a model of no credits is marked free; zcode: sign in as the ZCode app, following its own sign-in and team switches

- workbuddy: 'Illegal API invocation from an unapproved channel' ends in the hint magpie's built-in added (provider.WBRefusedHint), where magpie's routing page finds it; models with credits x0.00 carry free: true
- zcode: a new sign-in, "ZCode app's sign-in", reads ~/.zcode/v2 (credentials decrypted as ZCode keeps them, setting.json's team plan) for every request, as magpie's built-in did; magpie moves ZCode's own account marked source: zcode
This commit is contained in:
yetone
2026-10-01 01:21:06 +08:00
parent c8f4d448df
commit 826d487839
4 changed files with 287 additions and 4 deletions
+49 -2
View File
@@ -439,12 +439,22 @@ function modelOf(site, provider, m) {
},
release_date: "",
variants: variants(m.efforts),
// magpie's own: served at no cost to the plan's credits
free: !!m.free,
}
}
// 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).
// 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) {
if (c == null || c === "") return false
const s = String(c).trim().toLowerCase().replace(/^x/, "")
return s !== "" && Number.isFinite(Number(s)) && Number(s) === 0
}
async function liveModels(site, a) {
const headers = new Headers()
sign(site, a, headers)
@@ -466,6 +476,7 @@ async function liveModels(site, a) {
m.context = d.maxInputTokens
m.output = d.maxOutputTokens
m.images = d.supportsImages === true
m.free = freeCredits(d.credits)
const es = d.reasoning?.supportedEfforts ?? []
if (es.length) {
const canOff = d.reasoning?.canDisableThinking
@@ -539,7 +550,8 @@ function makePlugin(site) {
sign(site, a, headers)
let body = init?.body
if (body === undefined && req) body = await req.clone().text()
return fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) })
const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) })
return res.status >= 400 ? explained(res) : res
},
}
},
@@ -571,8 +583,43 @@ function makePlugin(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
// whose system prompt is Codex's or Claude Code's own (magpie #182),
// whatever the headers. 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
// explained is res with REFUSED_HINT added to that refusal's message.
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")
return new Response(b, { status: res.status, statusText: res.statusText, headers })
}
if (!REFUSED.test(text)) return again(text)
let msg = text.trim()
let v
try {
v = JSON.parse(text)
} catch {}
const at = v?.error && typeof v.error === "object" ? v.error : v && typeof v === "object" ? v : null
if (at && typeof at.message === "string") msg = at.message
else if (typeof v?.error === "string") msg = v.error
msg = `${msg} — ${REFUSED_HINT}`
const headers = new Headers(res.headers)
headers.set("content-type", "application/json")
headers.delete("content-length")
headers.delete("content-encoding")
return new Response(JSON.stringify({ error: { message: msg, type: "permission_error", code: null } }), { 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 = { usageOf, desktopHeld }
export const _internal = { usageOf, desktopHeld, explained, REFUSED_HINT, freeCredits }
+25
View File
@@ -0,0 +1,25 @@
// WorkBuddy's refusal of Codex's and Claude Code's system prompt carries
// the hint magpie's built-in added (provider.WBRefusedHint), at the end of
// the message, where magpie's routing page looks for it.
import { expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const { explained, REFUSED_HINT } = _internal
test("the refusal ends in the hint", async () => {
const res = await explained(new Response(JSON.stringify({ error: { message: "Illegal API invocation from an unapproved channel", code: 11004 } }), { status: 403 }))
expect(res.status).toBe(403)
expect((await res.json()).error.message).toBe("Illegal API invocation from an unapproved channel — " + REFUSED_HINT)
})
test("other errors pass as they came", async () => {
const res = await explained(new Response('{"error":{"message":"rate limited"}}', { status: 429 }))
expect(res.status).toBe(429)
expect(await res.text()).toBe('{"error":{"message":"rate limited"}}')
})
test("a model of no credits is free, as magpie's built-in read them", () => {
const { freeCredits } = _internal
for (const c of ["x0.00", "0", 0, " X0 "]) expect(freeCredits(c)).toBe(true)
for (const c of ["x0.03", "", null, undefined, "free", 1]) expect(freeCredits(c)).toBe(false)
})
+143 -2
View File
@@ -16,8 +16,9 @@
// `refresh` the rest of it as JSON (site, base, key, jwt, team project,
// plan, device id), `accountId` the account's email.
import { createDecipheriv, createHash } from "node:crypto"
import { existsSync, readFileSync, readdirSync } from "node:fs"
import { homedir } from "node:os"
import { homedir, userInfo } from "node:os"
import { join } from "node:path"
const PROVIDER = "zcode"
@@ -696,6 +697,136 @@ async function authorize(site, log) {
}
}
// ---- ZCode's own sign-in ------------------------------------------------------------
// ZCode keeps its sign-in in ~/.zcode/v2/credentials.json, each value
// encrypted (AES-256-GCM, "enc:v1:<iv>.<tag>.<data>") with a key made from
// the machine's user; ~/.zcode/v2/setting.json says whether it is on a
// team's plan. An account signed in "as ZCode" reads them for every
// request, so it follows ZCode's own sign-in, its renewed session and its
// switches between plans, as magpie's built-in did (zcode.go zcodeOwn).
const zcodeDir = () => join(homedir(), ".zcode", "v2")
// secret is the key ZCode encrypts its credentials with.
function secret() {
let seed = process.env.ZCODE_CREDENTIAL_SECRET
if (!seed) {
let name = ""
try {
name = userInfo().username
} catch {}
name = name.slice(name.lastIndexOf("\\") + 1) // DOMAIN\user
seed = `zcode-credential-fallback:${process.platform}:${homedir()}:${name}`
}
return createHash("sha256").update(seed).digest()
}
function decrypt(key, v) {
if (typeof v !== "string" || !v.startsWith("enc:v1:")) return null
const parts = v.slice(7).split(".")
if (parts.length !== 3) return null
try {
const [iv, tag, data] = parts.map((p) => Buffer.from(p.replace(/=+$/, ""), "base64url"))
const d = createDecipheriv("aes-256-gcm", key, iv)
d.setAuthTag(tag)
return Buffer.concat([d.update(data), d.final()]).toString("utf8")
} catch {
return null
}
}
function readJSON(path) {
try {
return JSON.parse(readFileSync(path, "utf8"))
} catch {
return null
}
}
// ownTeam is the team plan ZCode switched to, when it did.
function ownTeam(store, key) {
const set = readJSON(join(zcodeDir(), "setting.json"))
if (!set) return null
const families = set.providerFamilyDomain === "zai" || set.providerFamilyDomain === "bigmodel" ? [set.providerFamilyDomain] : ["zai", "bigmodel"]
for (const fam of families) {
let org = ""
let project = ""
const sel = set.providerFamilyConnectionSelections?.[fam]
if (sel) {
if (sel.kind === "team-coding-plan") [org, project] = [first(sel.organizationId), first(sel.projectId)]
} else {
// before providerFamilyConnectionSelections
const legacy = first(set.modelProviderFamilySelectedKeys?.[fam])
const pre = `team-plan:builtin:${fam}-coding-plan:`
if (legacy.startsWith(pre)) {
const ps = legacy.slice(pre.length).split(":")
if (ps.length === 3) {
try {
;[org, project] = [decodeURIComponent(ps[1]), decodeURIComponent(ps[2])]
} catch {}
}
}
}
if (!org || !project) continue
const tok = first(decrypt(key, store[`oauth:${fam}:access_token`]))
if (!tok) continue
// a stale token ZCode won't use either
if (fam === "bigmodel" && first(decrypt(key, store.zcodejwttoken)) === tok) continue
return { site: fam, base: SITES[fam].base, key: "", token: tok, org, project }
}
return null
}
// ownSignIn is what ZCode is signed in to now: the account, its coding
// plan key, ZCode's session token (the Start Plan's key) and the team plan
// it is switched to; null when it has none of them.
function ownSignIn() {
const store = readJSON(join(zcodeDir(), "credentials.json"))
if (!store || typeof store !== "object") return null
const key = secret()
let s = { key: "", base: "" }
for (const [name, v] of Object.entries(store)) {
// account-provider:coding-plan:account:zai-individual-coding-plan:account:<uuid>:api-key
if (!name.includes(":coding-plan:") || !name.endsWith(":api-key")) continue
const k = decrypt(key, v)
if (!k || !k.includes(".")) continue
const base = name.includes(":bigmodel-") ? BIGMODEL_BASE : ZAI_BASE
// Z.ai's first, as ZCode lists it
if (!s.key || (base === ZAI_BASE && s.base !== ZAI_BASE)) s = { key: k, base }
}
const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
const team = ownTeam(store, key)
if (team) s = { ...team, jwt }
else s = { ...s, jwt, base: s.base || ZAI_BASE, site: s.base === BIGMODEL_BASE ? "bigmodel" : "zai" }
if (!s.key && !s.jwt && !isTeam(s)) return null
let info = {}
for (const name of ["oauth:zai:user_info", "oauth:bigmodel:user_info"]) {
const v = decrypt(key, store[name])
if (v && !first(info.email, info.name, info.user_id)) {
try {
info = JSON.parse(v)
} catch {}
}
}
return { ...s, user: who(info) }
}
// asZCode is the sign-in "as ZCode": what it reads is ZCode's own.
function asZCode() {
return {
url: "",
instructions: "Uses the account the ZCode app is signed in to, and follows it.",
method: "auto",
async callback() {
const own = ownSignIn()
if (!own) return { type: "failed", error: "ZCode isn't signed in on this computer; sign in to ZCode, or sign in to Z.ai or BigModel here" }
const { user, ...s } = own
const state = { source: "zcode", device: anyDevice, ...s }
return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user }
},
}
}
// stateOf is a stored sign-in as the requests need it.
function stateOf(auth) {
if (auth?.type === "oauth") {
@@ -703,6 +834,15 @@ function stateOf(auth) {
try {
s = JSON.parse(auth.refresh)
} catch {}
if (s.source === "zcode") {
// ZCode's own, read now: what it was when this was signed in, if
// ZCode has since signed out
const own = ownSignIn()
if (own) {
const { user, ...now } = own
s = { source: "zcode", device: s.device, plan: s.plan, ...now }
}
}
const site = siteOf(s.site)
return { ...s, site, base: s.base || SITES[site].base, key: s.key ?? (s.jwt ? "" : auth.access), device: s.device || anyDevice }
}
@@ -983,6 +1123,7 @@ export async function ZCodeAuthPlugin({ client }) {
methods: [
oauth("zai"),
oauth("bigmodel"),
{ type: "oauth", label: "ZCode app's sign-in", authorize: async () => asZCode() },
{
type: "api",
label: "GLM Coding Plan API key",
@@ -1004,4 +1145,4 @@ export async function ZCodeAuthPlugin({ client }) {
}
// for tests
export const _internal = { limitWindows, termOf, startUsage, routes, teamKeys }
export const _internal = { limitWindows, termOf, startUsage, routes, teamKeys, ownSignIn, stateOf }
+70
View File
@@ -0,0 +1,70 @@
// "ZCode app's sign-in" reads what ZCode keeps, as magpie's built-in did
// (internal/provider/zcode.go zcodeOwn, zcode_team.go zcodeOwnTeam), and
// follows it: a request made after ZCode switched to a team's plan, or
// signed in anew, uses what ZCode has now.
import { test, expect, beforeAll } from "bun:test"
import { homedir, tmpdir } from "node:os"
import { mkdirSync, realpathSync, writeFileSync } from "node:fs"
import { createCipheriv, createHash, randomBytes } from "node:crypto"
import { join } from "node:path"
let ZCodeAuthPlugin, _internal
beforeAll(async () => {
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
process.env.ZCODE_CREDENTIAL_SECRET = "test-seed"
;({ ZCodeAuthPlugin, _internal } = await import("./index.mjs"))
})
const dir = () => join(homedir(), ".zcode", "v2")
function enc(text) {
const key = createHash("sha256").update("test-seed").digest()
const iv = randomBytes(12)
const c = createCipheriv("aes-256-gcm", key, iv)
const data = Buffer.concat([c.update(text, "utf8"), c.final()])
return "enc:v1:" + [iv, c.getAuthTag(), data].map((b) => b.toString("base64url")).join(".")
}
function zcodeHas(store, setting = {}) {
mkdirSync(dir(), { recursive: true })
writeFileSync(join(dir(), "credentials.json"), JSON.stringify(Object.fromEntries(Object.entries(store).map(([k, v]) => [k, enc(v)]))))
writeFileSync(join(dir(), "setting.json"), JSON.stringify(setting))
}
const KEY = "account-provider:coding-plan:account:zai-individual-coding-plan:account:u1:api-key"
test("the sign-in takes ZCode's account and key, and follows ZCode after", async () => {
zcodeHas({ [KEY]: "id1.secret1", zcodejwttoken: "Bearer j1", "oauth:zai:user_info": JSON.stringify({ email: "ada@phone.local" }) })
const hooks = await ZCodeAuthPlugin({ client: {} })
const m = hooks.auth.methods.find((x) => x.label === "ZCode app's sign-in")
const got = await (await m.authorize()).callback()
expect(got.type).toBe("success")
expect(got.accountId).toBe("ada")
expect(got.access).toBe("id1.secret1")
expect(JSON.parse(got.refresh).source).toBe("zcode")
const auth = { ...got, type: "oauth" }
expect(_internal.stateOf(auth)).toMatchObject({ key: "id1.secret1", jwt: "j1", base: "https://api.z.ai/api/anthropic" })
// ZCode signs in again with a new key
zcodeHas({ [KEY]: "id2.secret2", zcodejwttoken: "j2" })
expect(_internal.stateOf(auth)).toMatchObject({ key: "id2.secret2", jwt: "j2" })
// and switches to a team's plan
zcodeHas(
{ [KEY]: "id2.secret2", zcodejwttoken: "j2", "oauth:zai:access_token": "tok-team" },
{ providerFamilyConnectionSelections: { zai: { kind: "team-coding-plan", organizationId: "org1", projectId: "p1" } } },
)
expect(_internal.stateOf(auth)).toMatchObject({ key: "", token: "tok-team", org: "org1", project: "p1", jwt: "j2" })
})
test("with ZCode signed out, the sign-in says so", async () => {
zcodeHas({})
const hooks = await ZCodeAuthPlugin({ client: {} })
const m = hooks.auth.methods.find((x) => x.label === "ZCode app's sign-in")
const got = await (await m.authorize()).callback()
expect(got.type).toBe("failed")
expect(got.error).toContain("ZCode isn't signed in")
})
test("a sign-in not ZCode's keeps its own key", () => {
zcodeHas({ [KEY]: "id9.secret9" })
const s = _internal.stateOf({ type: "oauth", access: "mine.k", refresh: JSON.stringify({ site: "zai", key: "mine.k" }) })
expect(s.key).toBe("mine.k")
})