// ZCode's GLM Coding Plan, as an OpenCode provider plugin. // // ZCode (zcode.z.ai) signs in to a Z.ai account, or a BigModel (智谱, // bigmodel.cn) one, through a flow zcode.z.ai opens and is polled for. With // the account's sign-in it finds or makes the coding plan key it uses (the // key named zcode-api-key in the account's default project) and sends the // models' requests, Anthropic's Messages, to the plan's endpoint: // api.z.ai/api/anthropic or open.bigmodel.cn/api/anthropic. // // An account with no plan of its own may have a seat on a team's plan (a // project of type 2, and its zcode-team-api-key), or ZCode's free Start // Plan, served by zcode.z.ai itself to ZCode's own session token (a JWT // that can't be refreshed: when it runs out, sign in again). // // The sign-in is kept as OpenCode keeps an OAuth one: `access` is the key, // `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 { arch, homedir, release, userInfo } from "node:os" import { isAbsolute, join } from "node:path" import PROMPT from "./prompt.mjs" const PROVIDER = "zcode" // FREE_FIRST is magpie's switch for free first in the provider's editor const FREE_FIRST = "free_first" const ZCODE = "https://zcode.z.ai" const ZAI_API = "https://api.z.ai" const BIGMODEL_API = "https://bigmodel.cn" // BigModel's business API, where ZCode asks it const ZAI_BASE = "https://api.z.ai/api/anthropic" const BIGMODEL_BASE = "https://open.bigmodel.cn/api/anthropic" const START_BASE = ZCODE + "/api/v1/zcode-plan/anthropic" // APP_VERSION is the ZCode this signs in and asks as, on every call. ZCode // gates by it: its marketing feed answers empty to an older one (#678), // and its Start Plan balance "judges capability by the real app_version" // (zaiStartPlanBilling.ts in zai-org/ZCode@a9fe401, 3.17.2). const APP_VERSION = "3.17.2" const UA = "ZCode/" + APP_VERSION // ZCode's models before its config is read; the Start Plan has all but GLM-5.3. const MODELS = [ { id: "GLM-5.3", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] }, { id: "GLM-5.3-Flash", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] }, { id: "GLM-5.2", context: 1_000_000, output: 128_000, efforts: ["none", "high", "max"] }, { id: "GLM-5-Turbo", context: 200_000, output: 64_000, efforts: ["none", "high"] }, ] const START_MODELS = MODELS.filter((m) => m.id !== "GLM-5.3") const SITES = { zai: { name: "Z.ai", api: ZAI_API, base: ZAI_BASE, subscribe: "z.ai/subscribe" }, bigmodel: { name: "BigModel", api: BIGMODEL_API, base: BIGMODEL_BASE, subscribe: "bigmodel.cn/glm-coding" }, } const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai") const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them const uuid = () => crypto.randomUUID() const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list) // uuidOf is a version 4 shaped UUID made from a seed: the same seed gives // the same UUID every time const uuidOf = (seed) => { const h = createHash("sha256").update(seed).digest("hex") return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}` } // keyDevice is a device id for an account known only by its key: the same // key gives the same id on every start, as a sign-in's saved device does const keyDevice = (key) => uuidOf("zcode-device\0" + key) const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? "" // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a // refusal with no message in. const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 408: "Request Timeout", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" } class ZError extends Error { constructor(message, status) { super(message) this.status = status } } // call asks one of Z.ai's JSON endpoints, which wrap what they say in // {code, msg, data}: a code of 0 or 200 is a success. zcode.z.ai is told // the machine's id (X-Device-Mid), as ZCode tells it. async function call(method, url, { auth, body, headers, device, signal } = {}) { const h = { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA } if (auth) h.Authorization = auth if (url.startsWith(ZCODE + "/")) h["X-Device-Mid"] = device || anyDevice Object.assign(h, headers ?? {}) const res = await fetch(url, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body), signal }) const text = await res.text() let env try { env = JSON.parse(text) } catch {} const code = env?.code == null ? "" : String(env.code) if (!res.ok) { const said = env?.msg ? (code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`) : (STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim()) const err = new ZError(said, res.status) err.code = Number(code) || 0 // 3002 and the like: so a caller can tell a rate limit from a failure err.retryAfterMs = retryAfterMs(res) // 0 unless the reply carried a Retry-After throw err } if (!env || typeof env !== "object") throw new ZError("not JSON", res.status) if (code && code !== "0" && code !== "200") throw new ZError(env.msg || `error ${code}`, res.status) return env.data ?? null } // ---- the account's plan ---------------------------------------------------------- const rootOf = (base) => { try { const u = new URL(base) return `${u.protocol}//${u.host}` } catch { return ZAI_API } } const isTeam = (s) => !!(s.org && s.project) // plan names the coding plan a key has, "" for none. async function plan(s) { const subs = (await call("GET", rootOf(s.base) + "/api/biz/subscription/list", { auth: s.key })) ?? [] return (Array.isArray(subs) ? subs : []).find((x) => String(x.status).toUpperCase() === "VALID")?.productName ?? "" } function jwtExpiry(jwt) { const p = String(jwt ?? "").split(".") if (p.length !== 3) return 0 try { const claims = JSON.parse(Buffer.from(p[1], "base64url").toString("utf8")) return Number(claims.exp) > 0 ? Number(claims.exp) * 1000 : 0 } catch { return 0 } } const jwtExpired = (jwt) => { const t = jwtExpiry(jwt) return t > 0 && Date.now() > t } // EXPIRED is the built-in's words (errZCodeExpired) for a Start Plan // sign-in past its end. const EXPIRED = "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" const num = (v) => { const n = typeof v === "string" ? parseFloat(v) : v return typeof n === "number" && Number.isFinite(n) ? n : undefined } // the alias is the catalog spelling of the model plus -trial, so the picker // reads GLM-5.3-Trial while the loader strips it back to the raw name const giftID = (m) => (MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m) + "-Trial" const uniqueModels = (names) => { const byName = new Map() for (const m of names) if (!byName.has(m.toLowerCase())) byName.set(m.toLowerCase(), m) return [...byName.values()] } const giftNames = (g) => g?.allModels ?? g?.models ?? [] // wireModel is a gift model as ZCode sends it: the buckets name it lowercased // ("glm-5.3-flash"), the app's request carries its registry id // ("GLM-5.3-Flash"; normalizeOfficialGlmModelId's spelling). Names ZCode // does not know go as the bucket wrote them. const wireModel = (m) => MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m const giftModel = (g, id) => giftNames(g).find((m) => giftID(m).toLowerCase() === id.toLowerCase()) const bucketModels = (x) => (Array.isArray(x.capabilities) ? x.capabilities : []) .map((c) => String(c ?? "").trim()).filter((c) => c.startsWith("model:") || !c.includes(":")) .map((c) => c.replace(/^model:/, "").trim()).filter(Boolean) // Both the card and the request route use the same test for a spent bucket. // Older balances may omit remaining_units but still tell used and total. const giftSpent = (x) => { const left = num(x.remaining_units) if (left !== undefined) return left <= 0 const total = num(x.total_units), used = num(x.used_units) return total !== undefined && used !== undefined && used >= total } // startPlan is the gift an account can spend now ({models}), as ZCode reads // its balance: several plans can be active at once, and a model routes to // the gift when any of them has a live bucket serving it — a bucket past // its plan's own end, or one whose remaining_units says none, is skipped // rather than asked and refused. models are those live buckets' names. // // coming (sign-in only) also takes a plan that has not started yet, as // ZCode's own check does (resolveStartPlanBalanceAvailability's "pending" // counts as entitled): {name, models: [], coming: true}. Requests and the // card never ask for it: a plan not started serves nothing yet. async function startPlan(jwt, device, coming = false) { if (!jwt) throw new Error("not signed in to ZCode") if (jwtExpired(jwt)) throw new Error(EXPIRED) const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + jwt, device })) ?? {} const now = num(b.server_time) > 0 ? num(b.server_time) : Date.now() / 1000 const same = (x, p) => (x.user_plan_id && p.user_plan_id ? x.user_plan_id === p.user_plan_id : String(x.plan_id ?? "") === String(p.plan_id ?? "")) const plans = Array.isArray(b.plans) ? b.plans : [] const balances = Array.isArray(b.balances) ? b.balances : [] const ms = new Set(), all = new Map() let ttl = 600_000 let any = false let name = "" for (const p of plans) { const st = String(p?.status ?? "").trim().toLowerCase() const end = num(p?.ends_at) if (st !== "active" || (end > 0 && end <= now) || notStarted(p, now)) continue any = true if (end > 0) ttl = Math.min(ttl, (end - now) * 1000) if (!name) name = String(p?.name ?? "").trim() for (const x of balances) { if (!same(x, p)) continue const exp = num(x.expires_at) if (exp > 0 && exp <= now) continue if (exp > 0) ttl = Math.min(ttl, (exp - now) * 1000) // Spent buckets still declare models; only live ones can spend now. for (const m of bucketModels(x)) { if (!all.has(m.toLowerCase())) all.set(m.toLowerCase(), m) if (!giftSpent(x)) ms.add(m) } } } if (any) return { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl } if (!coming) return null const next = plans.filter((p) => notStarted(p, now) && !(num(p?.ends_at) > 0 && num(p?.ends_at) <= now)) .sort((a, b) => startNum(a.starts_at) - startNum(b.starts_at))[0] return next ? { name: String(next.name ?? "").trim() || "Start Plan", models: [], allModels: [], ttl, coming: true } : null } // plansOf says where an account's requests go and what more it can spend: // {start, gift}. start is what onStart said: an account with no coding plan // sends every request to the gift and reads no balance to do it; a // sign-in with no ZCode token and a key whose plan-list read found // no gift stay on the coding plan. gift is what a coding account also holds: // the gift plans ({models}), and its requests spend the gift for a model it // serves, until it says it is spent (see blocked). Asked again after 10 // minutes (a minute when unsure — a plan-list read that failed is retried // sooner; a gift read that failed simply leaves gift null until the next // ask). const routes = new Map() async function plansOf(s) { if (!s.jwt) return { start: false, gift: null } if (!s.key && !isTeam(s)) return { start: true, gift: null } const id = s.key + "\0" + s.jwt const r = routes.get(id) if (r && Date.now() - r.at < r.ttl) return r let start = false let gift = null let sure = false try { // A team seat stays on its team even when its personal plan list is // empty. Its ZCode session still holds the person's gift plans. if (!isTeam(s) && !(await plan(s))) start = true else { // a gift read that failed is unknown, not "no gift": asked again in // a minute, so its trial entries come back with the next list (an // expired session is known: the card says to sign in again) let failed = false gift = await startPlan(s.jwt, s.device).catch(() => ((failed = !jwtExpired(s.jwt)), null)) sure = !failed } // a key whose plan list read no plan, where the last read found one, // is asked again in a minute rather than sent to the Start Plan for // ten: one list without the plan (a renewal's boundary, a hiccup) // turned a GLM Coding Plan account's every request into the Start // Plan's 405 until the route was read again (#369) if (start) sure = !(s.key && r && !r.start) } catch { // the plan list could not be read: a key account takes the dual route // (start stays false, the gift is kept, a minute's ttl), so a gift // refusal still replays to the coding plan rather than blacking out try { gift = await startPlan(s.jwt, s.device) sure = false } catch {} } const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) } routes.set(id, out) return out } // blocked remembers the models a gift said it has none left for: a key+jwt+ // model for a minute, so one turn that is refused does not ask again. const blocked = new Map() // sidelined remembers, the same way, the models whose gift turned free // first away for another reason (a 405/3012, a block page): free first // leaves them on the plan for the minute, but a -Trial entry, the user's // own pick of the gift, still asks ZCode and gets its real answer. Once // one rest served both, and a refusal under free first answered the // Trial entry locally as a quota "exhausted" it never was (Can4ry_ on X). const sidelined = new Map() const rest = (map, k) => { for (const [x, until] of map) if (Date.now() >= until) map.delete(x) map.set(k, Date.now() + 60_000) } // giftServes: the gift's buckets name their models lowercased ("glm-5.3- // flash"); what is asked for arrives as the plan lists it ("GLM-5.3-Flash"). const giftServes = (gift, m) => (gift.models ?? []).some((x) => x.toLowerCase() === m.toLowerCase()) const giftRested = (s, m) => Date.now() < (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0) const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) && Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0) const giftSidelined = (s, m) => Date.now() < (sidelined.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0) // spentUp is the gift saying it has nothing left to spend: its own no- // resource-package code 1113, its "exceed quota limit" 1005 — a spent gift // can answer a 200 with a JSON body carrying one of those codes. Every other // 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's // own in-flight cap (3008/3009) does not, since it is a turn not yet come. function spentUp(text, status) { if (busy(status, text)) return false if (status === 429) return true let b try { b = JSON.parse(text) } catch { return false } if (!b || typeof b !== "object") return false const code = (v) => String(v ?? "") const c1 = code(b.code), c2 = code(b.error?.code) return c1 === "1113" || c1 === "1005" || c2 === "1113" || c2 === "1005" } // spentSaid is an answer that carries spentUp's code inside a 200, as a // spent bucket's can, said as the 429 it is (plugins#817: a Start Plan // account's GLM-5.3 out for the day answered 200 "exceed quota limit", // which magpie took for a reply that did not stream and rested the whole // account, GLM-5.3-Flash's own bucket with it). Any other answer goes on // as it came; a stream's body is never read here. async function spentSaid(res) { if (res.status >= 400 || !(res.headers.get("content-type") ?? "").includes("application/json")) return res const text = await res.text() const status = spentUp(text, res.status) ? 429 : res.status return new Response(text, { status, statusText: status === 429 ? "Too Many Requests" : res.statusText, headers: res.headers }) } // ---- keys ------------------------------------------------------------------------ function teamHeaders(base, org, project) { return { "Bigmodel-Organization": org, "Bigmodel-Project": project, "Set-Language": base.includes("bigmodel.cn") ? "zh" : "en", "Accept-Language": "en-US,en", } } const keysURL = (root, org, project) => `${root}/api/biz/v1/organization/${encodeURIComponent(org)}/projects/${encodeURIComponent(project)}/api_keys` // projectKey finds the project's key named want.name (of want.keyType, when // given), makes it when it isn't there and reads its secret: `.`. async function projectKey(site, keys, auth, headers, want) { const name = SITES[site].name let list try { list = (await call("GET", keys, { auth, headers })) ?? [] } catch (e) { throw new Error(`${name} API keys: ${e.message}`) } const typed = "keyType" in want let id = "" for (const k of Array.isArray(list) ? list : []) { if (k.name === want.name && (!typed || String(k.keyType) === String(want.keyType)) && first(k.apiKey)) id = first(k.apiKey) } if (!id) { try { id = first((await call("POST", keys, { auth, headers, body: want }))?.apiKey) } catch (e) { throw new Error(`${name} API key: ${e.message}`) } } let secret = "" if (id) { try { secret = first((await call("GET", `${keys}/copy/${encodeURIComponent(id)}`, { auth, headers }))?.secretKey) } catch (e) { throw new Error(`${name} API key: ${e.message}`) } } if (id && !secret && typed) return id // a team's key with no secret goes as it is if (!id || !secret) throw new Error(`${name} gave no API key`) return `${id}.${secret}` } // teamKey is a team seat's key when the sign-in kept none. const teamKeys = new Map() async function teamKey(s) { if (s.key) return s.key const id = [s.token, s.org, s.project].join("\0") const got = teamKeys.get(id) if (got && (!got.err || Date.now() - got.at < 60_000)) { if (got.err) throw got.err return got.key } const site = s.base.includes("bigmodel.cn") ? "bigmodel" : "zai" try { const key = await projectKey(site, keysURL(SITES[site].api, s.org, s.project), s.token, teamHeaders(s.base, s.org, s.project), { name: "zcode-team-api-key", keyType: 2 }) teamKeys.set(id, { key, at: Date.now() }) return key } catch (e) { const err = new Error(`ZCode's team plan: ${e.message} — sign in to ZCode again`) teamKeys.set(id, { err, at: Date.now() }) throw err } } // ---- allowance --------------------------------------------------------------------- // As magpie's built-in told it (internal/provider zcode.go, zcode_start.go, // zcode_team.go): the Coding Plan's windows and term, the Start Plan's // buckets, or a team seat's windows and its plan's end. // bizRoot is the business API of the site a plan is served from. function bizRoot(base) { let h = "" try { h = new URL(base).host.toLowerCase() } catch {} return h === new URL(BIGMODEL_BASE).host || h.endsWith("bigmodel.cn") ? BIGMODEL_API : rootOf(base) } // spanOf reads a limit's window, in seconds: unit 3 counts hours, 6 weeks // (and 1, 4, 5 minutes, days and months by the same count). A team's five // hours come with no count. function spanOf(unit, n) { n = Math.trunc(Number(n) || 0) if (unit === 3 && n <= 0) n = 5 n = Math.max(n, 1) return { 1: 60, 3: 3600, 4: 86400, 5: 30 * 86400, 6: 7 * 86400 }[unit] * n || 0 } function windowName(span) { if (span === 0) return "Credits" if (span < 86400) return `${Math.trunc(span / 3600)} hours` if (span === 7 * 86400) return "Weekly" if (span >= 28 * 86400) return "Monthly" return `${Math.trunc(span / 86400)} days` } // 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(/\.$/, "")) const isNum = (v) => typeof v === "number" && Number.isFinite(v) // limitWindows are /api/monitor/usage/quota/limit's limits as windows: what // is used of the whole when both are told (the whole less what remains, or // the current value), else the percentage given. TIME_LIMIT is the month's // MCP tool calls, which ZCode shows but never stops the models on, so it is // set aside, as is a limit whose whole is told as 0: no cap (an older // plan's), which the vendor may still give as 100% used. A window whose // count is told carries it as amount of limit, so magpie's card says the // count as used or as left, as it says the share beside it (#659). function limitWindows(d) { const out = [] for (const x of d?.limits ?? []) { const span = spanOf(Math.trunc(Number(x?.unit) || 0), x?.number) const w = { name: windowName(span), used: 0 } if (String(x?.type ?? "").toUpperCase() === "TIME_LIMIT") (w.name = "MCP · Month"), (w.aside = true) if (isNum(x?.percentage)) w.used = x.percentage if (x?.usage === 0) (w.used = 0), (w.aside = true) if (isNum(x?.usage) && x.usage > 0) { const total = x.usage if (isNum(x.remaining)) { const used = total - x.remaining w.used = (100 * used) / total w.amount = used w.limit = total w.display = `${compact(used)} / ${compact(total)}` } else if (isNum(x.currentValue)) { if (!isNum(x.percentage)) w.used = (100 * x.currentValue) / total w.amount = x.currentValue w.limit = total w.display = `${compact(x.currentValue)} / ${compact(total)}` } } const reset = Math.trunc(Number(x?.nextResetTime) || 0) if (reset > 0) w.resetsAt = new Date(reset).toISOString() if (span) w.span = span out.push(w) } return out } // beijing reads the plan's times, "2026-10-18 12:00:00" in Beijing: ms, or 0. function beijing(s) { s = String(s ?? "").trim().replace(" ", "T") if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2})?$/.test(s)) return 0 const t = Date.parse(s + (s.length === 10 ? "T00:00:00" : "") + "+08:00") return Number.isFinite(t) ? t : 0 } // termOf is how long a GLM Coding plan is paid for: the valid // subscription's next renewal, a charge when it renews itself, else the // end of its time, the last date its "valid" span names. function termOf(subs) { for (const x of Array.isArray(subs) ? subs : []) { if (String(x?.status ?? "").toUpperCase() !== "VALID") continue const auto = x.autoRenew === true || x.autoRenew === 1 const t = beijing(typeof x.nextRenewTime === "string" ? x.nextRenewTime : "") if (t) return { until: new Date(t).toISOString(), renew: auto ? "auto" : "off" } const ds = String(typeof x.valid === "string" ? x.valid : "").match(/\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?/g) ?? [] if (ds.length && !auto) { const end = beijing(ds[ds.length - 1]) if (end) return { until: new Date(end).toISOString(), renew: "off" } } return {} } return {} } // codingUsage is a Coding Plan key's allowance: credits per five hours and // per week, the plan's level and its term. async function codingUsage(s) { const root = rootOf(s.base) const d = (await call("GET", root + "/api/monitor/usage/quota/limit", { auth: s.key })) ?? {} const out = {} const level = typeof d.level === "string" ? d.level : "" if (level) out.plan = "GLM Coding " + level[0].toUpperCase() + level.slice(1) out.windows = limitWindows(d) const resets = personalResets(root, s.key) let subs = null try { subs = await call("GET", root + "/api/biz/subscription/list", { auth: s.key }) Object.assign(out, termOf(subs)) } catch {} const r = await resets if (r) out.resets = r // a key whose account has no plan in force, read as such, says so // rather than showing an empty card: what a key can spend is a GLM // Coding Plan alone (a ZCode gift plan is never one, see NO_PLAN_KEY). // A list that couldn't be read, a level, a counted window or a plan // the sign-in saved keeps the card as it was. const valid = (Array.isArray(subs) ? subs : []).some((x) => String(x?.status ?? "").toUpperCase() === "VALID") if (subs !== null && !valid && !level && !s.plan && !out.windows.some((w) => !w.aside)) return { error: NO_PLAN_KEY } return out } // NO_PLAN_KEY is a key with no GLM Coding Plan behind it. ZCode's gift // plans (its Start Plan, ZCode 1024 Dev Day) are served by zcode.z.ai // to ZCode's own session token, which a sign-in with ZCode (the app's, // or Z.ai's or BigModel's in the browser) carries and a key never does: // with a key, a gift-only account has nothing to spend, and Z.ai answers // each request 1113 (rtbeilin on X, 10-24). const NO_PLAN_KEY = "this key's account has no GLM Coding Plan; ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day) are spent only with ZCode's sign-in, never with a key — add the account with \"ZCode app's sign-in\" or a ZCode sign-in in the browser" // noPlanKey is a coding plan's 1113 refusal (no plan, no resource // package) to a sign-in with no ZCode session, its message followed by // NO_PLAN_KEY; anything else goes on as it came. Read only once the // answer has failed. function noPlanKey(res, text) { let v try { v = JSON.parse(text) } catch { return null } // Z.ai names the code in error.code ("1113", as magpie's // zhipu_coding_test has it) or error.type (its 401's "1000"), BigModel's // envelope in code if (![v?.error?.code, v?.error?.type, v?.code].some((c) => String(c ?? "") === "1113")) return null const said = first(v?.error?.message, v?.msg, v?.message) const out = v?.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message: (said ? said + " — " : "") + NO_PLAN_KEY } } : { ...v, msg: (said ? said + " — " : "") + NO_PLAN_KEY } const h = new Headers(res.headers) h.set("content-type", "application/json") return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h }) } // startNum reads a number the balance gives as a number or a string. function startNum(v) { if (isNum(v)) return v if (typeof v === "string" && v.trim() !== "") { const n = Number(v.trim()) if (!Number.isNaN(n)) return n } return undefined } // notStarted is a plan whose starts_at is still to come (a Start Plan // that takes effect at 23:00 today, windy on Discord): it serves nothing // yet, so no request is routed to it and its buckets don't count, but the // card names it with its start. ZCode's balance gives every plan a // starts_at in Unix seconds; which status a plan not started yet carries // is not known, so any but "expired" is taken. function notStarted(p, now) { const at = startNum(p?.starts_at) return at > now && String(p?.status ?? "").trim().toLowerCase() !== "expired" } // PENDING is the card's line for a gift plan that has not started yet: a // fixed sentence, so magpie translates it; the plan's name and its start, // in this computer's time, are the display. Set aside: it stops nothing. const PENDING = "ZCode gift plan not started yet" const two = (n) => String(n).padStart(2, "0") const localTime = (sec) => { const d = new Date(Math.trunc(sec) * 1000) return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}` } const pendingLines = (g) => (g?.pending ?? []).map((p) => ({ name: PENDING, used: 0, aside: true, display: `${p.name} · ${localTime(p.start)}` })) // giftOf reads the balance and returns the gift's card fields: its plans and // windows. Several plans can be active at once, so every live plan's buckets // show, each keeping its own models and end; the plan and end put on the // card (for a gift-only account) are the soonest-ending live plan's. null // when there is no live plan to show. async function giftOf(s) { if (!s.jwt) throw new Error("not signed in to ZCode") if (jwtExpired(s.jwt)) throw new Error(EXPIRED) const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + s.jwt, device: s.device })) ?? {} const str = (v) => (typeof v === "string" ? v : "") const plans = (Array.isArray(b.plans) ? b.plans : []).map((p) => ({ ...p, status: str(p?.status), user_plan_id: str(p?.user_plan_id), plan_id: str(p?.plan_id) })) const now = startNum(b.server_time) > 0 ? startNum(b.server_time) : Math.trunc(Date.now() / 1000) const over = new Set() for (const p of plans) { const end = startNum(p.ends_at) if (end > 0 && end <= now && p.status.trim().toLowerCase() === "active") p.status = "expired" if (p.status.trim().toLowerCase() === "expired") over.add(p.user_plan_id + "\0" + p.plan_id) } const same = (x, p) => (x.user_plan_id && p.user_plan_id ? x.user_plan_id === p.user_plan_id : String(x.plan_id ?? "") === String(p.plan_id ?? "")) const balances = (Array.isArray(b.balances) ? b.balances : []) .map((x) => ({ ...x, user_plan_id: str(x?.user_plan_id), plan_id: str(x?.plan_id) })) .filter((x) => { let keep = true for (const p of plans) { if (!same(x, p)) continue keep = !over.has(p.user_plan_id + "\0" + p.plan_id) if (keep) break } return keep }) // a plan not started yet is named with its start, soonest first; its // buckets, if the balance lists any, wait for it const pending = plans.filter((p) => notStarted(p, now)) .map((p) => ({ name: first(str(p.name), "Start Plan"), start: startNum(p.starts_at) })) .sort((a, b) => a.start - b.start) // every live plan counts as the gift: no plan-name filter decides it, // the balance says what the session can spend let active = null for (const p of plans) { if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) continue const end = startNum(p.ends_at) if (end > 0 && end <= now) continue if (active && !(end > 0 && (!startNum(active.end) || end < startNum(active.end)))) continue active = { name: first(str(p.name), "Start Plan"), end, until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" } } if (!active && !pending.length) return null // with no live plan, the one starting soonest names the card const out = { plan: active?.name ?? pending[0].name, windows: [], live: !!active, pending } if (active?.until) Object.assign(out, { until: active.until, renew: "off" }) const live = plans.filter((p) => { if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) return false const end = startNum(p.ends_at) return !(end > 0 && end <= now) }) for (const x of balances) { const owner = live.find((p) => same(x, p)) if (!owner) continue const exp = startNum(x.expires_at) if (exp > 0 && exp <= now) continue // a bucket past its own end is over const total = startNum(x.total_units), left = startNum(x.remaining_units) let used = startNum(x.used_units) if (total === undefined && used === undefined && left === undefined) continue const models = bucketModels(x) const base = first(str(x.show_name), models.join(", "), "Credits") const w = { name: base, used: 0, _plan: str(owner.name), _spent: giftSpent(x) } if (used === undefined) used = total !== undefined && left !== undefined ? total - left : 0 if (total > 0) { // the bucket's count as amount of limit, as the Coding windows' is // (#659): magpie says it as used or as left, as it says the share w.used = (100 * used) / total w.amount = used w.limit = total w.display = `${compact(used)} / ${compact(total)}` } if (w._spent) w.used = Math.max(100, w.used) if (exp > 0) w.resetsAt = new Date(Math.trunc(exp) * 1000).toISOString() let span = 0 for (const p of plans) { if (!same(x, p)) continue for (const e of Array.isArray(p.entitlements) ? p.entitlements : []) { if (str(e?.entitlement_id) === str(x.entitlement_id)) span = periodOf(str(e?.period)) } } if (!span) { const a = startNum(x.period_start), z = startNum(x.period_end) if (a !== undefined && z !== undefined && z > a) span = Math.trunc(z - a) } if (span) w.span = span if (models.length) w.models = models out.windows.push(w) } return out } // CLAIM_HINT is the claim line's name: a fixed sentence, so magpie // translates it with the interface's own language (the plan's name and // the count are data, and go in the display, which is shown as it came). const CLAIM_HINT = "Gift plans to claim in the ZCode app" // claimHint is the card's line for gift plans ZCode is holding for the // account but has not put on it: the app's banners (marketing/touch) // list them (toClaim). The // card only names them: they are claimed in the ZCode app, or by the // daily claim (claimDaily) when the user turned it on; on 10-06 a claim // without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no // allowance: using it up stops nothing), so the card shows it and // routing, caps and the menu bar pass it over. The window's name is a // fixed sentence, so magpie can translate it (a display is shown as it // came); the count and the plan's own name go in the display. null when // there is nothing to claim, the preview failing or listing none among // it: a failed read is no line at all, never a card or a refusal of its // own. async function claimHint(s) { if (!s.jwt || jwtExpired(s.jwt)) return null const { plans } = await toClaim(s) if (!plans.length) return null const n = plans.length const plan = first(...plans.map((p) => p.name), "ZCode gift plan") return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` } } // ---- the daily claim --------------------------------------------------------------- // CLAIMED_ALREADY is /billing/claim's body code for a plan the account // has claimed before: HTTP 200 {"code":1003,"msg":"target already // exists"} (magpie-community/plugins#503, a real reply), the desktop // app's manualClaimPlan.claim.failure.alreadyClaimed. CAPTCHA is its // answer to a claim without the Aliyun captcha attestation the ZCode app's // renderer makes: HTTP 400 {"code":3007,"msg":"captcha verify failed"} // (seen 10-06, #30). const CLAIMED_ALREADY = 1003 const CAPTCHA = 3007 // NOT_ELIGIBLE is /billing/claim's body code for a plan the account is not // offered at that moment: HTTP 400 {"code":1004,…}. A stale APP_VERSION // answers it for every account at once (11-04: six accounts all answered // 1004 under 3.16.3's header, and four of them claimed with code 0 under // 3.17.2's, one night, with nothing else changed). const NOT_ELIGIBLE = 1004 // RATE_LIMITED is Z.ai's "请求过于频繁" body code, its answer (with HTTP // 429) to a client that asked too often. #503 (MiniFullC, 11-04) read 180 // "gift plans to claim: Too Many Requests" over four days at magpie's // 30-minute retry, so asking again the same half hour keeps the limit on. // magpie asks a failed again once retryAfter() has passed, whatever the // answer's `until` says (the contract reads `until` as when an answer // stops standing, not as the earliest time to ask again), so the account // is held here instead: while the wait lasts, claimDaily answers the same // failed again, `until` and all, and asks ZCode nothing. A Retry-After // ZCode sent is honored up to RATE_LIMIT_MAX_MS; without one the // account's own wait doubles from RECHECK_MS, and a read that comes // through forgets it. const RATE_LIMITED = 3002 const RATE_LIMIT_MAX_MS = 6 * 60 * 60_000 const rateWait = new Map() // s.key -> { ms, until, message }: the hold this account is under // resetRateWait is for tests: it forgets the holds, and with `expire` it // back-dates them, standing where the wait has passed. The plugin itself // forgets a hold by reading through or by waiting it out, never by calling // this. export function resetRateWait(expire = false) { if (!expire) { rateWait.clear() return } for (const [k, h] of rateWait) rateWait.set(k, { ...h, until: new Date(Date.now() - 1).toISOString() }) } // holdKey names the account a wait belongs to. stateOf gives key: "" to a // sign-in that has a jwt and no API key — the Start-Plan-only sign-ins // that claim gift plans, #503's case — so the key alone would put every // one of them under a single hold, and one account's 429 would answer for // all of them. The jwt tells them apart; a renewed token starting its own // wait is fine. const holdKey = (s) => s.key || s.jwt // retryAfterMs is a Retry-After header, in seconds or as an HTTP date, in // ms; 0 when there is none or it doesn't read. function retryAfterMs(res) { const v = first(res?.headers?.get?.("retry-after")) if (!v) return 0 const secs = Number(v) if (Number.isFinite(secs) && secs > 0) return secs * 1000 const at = Date.parse(v) return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0 } // noteRateLimit remembers the wait this account is under, with the failed // that wait answers with, and says when it ends: a Retry-After ZCode sent // is taken as it is, up to the cap; without one the wait doubles from // RECHECK_MS (and never falls below it), so a client ZCode keeps turning // away asks less and less. function noteRateLimit(key, saidMs, message) { const last = rateWait.get(key)?.ms ?? 0 const want = saidMs > 0 ? saidMs : Math.max(RECHECK_MS, last * 2) const ms = Math.min(RATE_LIMIT_MAX_MS, want) const until = new Date(Date.now() + ms).toISOString() rateWait.set(key, { ms, until, message }) return until } const CAPTCHA_WORDS = /captcha/i // claimNeedsCaptcha says whether ZCode's claims want its security check // now, from what client/configs says: its captcha (Aliyun's, which the // ZCode app passes before every claim, invisibly as a rule, and sends as // X-Aliyun-Captcha-Verify-Param, 3.17.2's requestVerificationClaimHeaders) // switched on. No captcha in the configs is no check, as the app reads it // (readRequestVerificationConfig gives null, and the claim goes without // the header); one that isn't an object is unknown, null. // skip_model_request is the same check for Start Plan requests, which it // spares (true on 11-07); it is not read here. function claimNeedsCaptcha(c) { const k = c?.configs?.captcha if (k == null) return false if (typeof k !== "object" || Array.isArray(k)) return null return k.enabled !== false } const CAPTCHA_CLAIM = "claim it in the ZCode app: ZCode asks its security check before a claim, which only the app passes, so the daily check-in leaves it to the app" // The marketing feed and the claim are gated on the client's version: // under an older version's header the feed answers empty (11-03, #678: // the day's banner showed for 3.17.2 and for no older one), so they go, // as every call does, as the current client (APP_VERSION) sends them. const marketingHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() }) // claimOne asks /billing/claim for one plan and says what its body says: // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the // claim wants the app's captcha), else "failed" with why. Only a body // that reads decides: an HTTP error without one, or text that isn't // JSON, is failed (unknown), never claimed. Only the code is read (#503 // has a real code 0 reply, "Plan claimed successfully."). async function claimOne(s, planID) { let res, text try { res = await fetch(`${ZCODE}/api/v1/zcode-plan/billing/claim`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...marketingHeaders() }, body: JSON.stringify({ plan_id: planID }), }) text = await res.text() } catch (e) { return { outcome: "failed", why: e?.message ?? String(e) } } let env try { env = JSON.parse(text) } catch {} const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN const msg = typeof env?.msg === "string" ? env.msg : "" // a rate limit is no claim: it is said as one, and carries how long to wait if (res.status === 429 || code === RATE_LIMITED) return { outcome: "failed", why: `${msg || STATUS_TEXT[429]} (HTTP ${res.status}${Number.isFinite(code) ? `, code ${code}` : ""})`, rate: retryAfterMs(res) } if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` } if (code === CLAIMED_ALREADY) return { outcome: "done" } if (code === NOT_ELIGIBLE) return { outcome: "ineligible", why: msg || `code ${code}` } if (code === 0 && res.ok) return { outcome: "claimed" } if (!Number.isFinite(code)) return { outcome: "failed", why: `HTTP ${res.status}, unreadable reply ${String(text ?? "").trim().slice(0, 120) || "(empty)"}` } return { outcome: "failed", why: `${msg || "error"} (HTTP ${res.status}, code ${code})` } } // TOUCH is ZCode's marketing feed: the ZCode app's claim banners come // from it. A banner plan ("ZCODE WEEKEND BUILD", 10-30) is served only // while the app shows its banner, and the app claims it through the same // /billing/claim (#503's capture of 10-30, kongbai01203: GET // /api/v1/marketing/touch?seq= with the session, // X-Device-Mid, X-Client-Language and X-ZCode-App-Version, answered // data.deliveries[].banner.buttons[].action = {"type":"claim_zcode_plan", // "args":{"plan_id":…}} and the plan's name in // banner.background.args.zcode_plan.name). The v3.17 client reads this // feed alone: the old preview polling is gone, and the rewards center's // gifts are the rewards website's, claimed in the client. const TOUCH = "/api/v1/marketing/touch" const CLAIM_ACTION = "claim_zcode_plan" // touchSeq is the feed's seq: ZCode's own count of its feed requests // since the process started, from 0, one GET per refresh. It is not a // page: "仅供服务端日志定位,不改变投放判断" (docs/marketing-touch-client.md, // marketingTouchService.ts's bootRequestSeq, zai-org/ZCode@a9fe401), so a // check-in asks once, never seq 0..8 in a row (plugins#676), and a banner // seen at one seq and not another is a delivery arriving later. let touchSeq = 0 // clientLanguage is the language ZCode names to marketing/touch: zh-CN or // en-US, its two UI languages, never another (marketingTouchService's // localeSchema), so a computer set to zh-Hans-CN or en-GB asks as ZCode does. const clientLanguage = () => { let l = "" try { l = Intl.DateTimeFormat().resolvedOptions().locale || "" } catch {} return /^zh\b/i.test(l) ? "zh-CN" : "en-US" } // touchPlans is the plans marketing/touch's deliveries offer to claim: // [{plan_id, name}], [] for a feed with no deliveries, null for one that // doesn't read. Each delivery is searched for its claim_zcode_plan // actions and its zcode_plan's name, wherever the banner keeps them, so // a button moved inside the banner is still found. function touchPlans(d) { if (d == null) return [] if (typeof d !== "object" || Array.isArray(d)) return null if (d.deliveries == null) return [] if (!Array.isArray(d.deliveries)) return null const out = [] for (const dv of d.deliveries) { const ids = [], names = [] const walk = (v, depth) => { if (!v || typeof v !== "object" || depth > 12) return if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1)) if (v.type === CLAIM_ACTION && typeof v.args?.plan_id === "string" && v.args.plan_id.trim()) ids.push(v.args.plan_id.trim()) if (v.zcode_plan && typeof v.zcode_plan === "object" && typeof v.zcode_plan.name === "string") names.push(v.zcode_plan.name) for (const k of Object.keys(v)) walk(v[k], depth + 1) } walk(dv, 0) for (const id of ids) out.push({ plan_id: id, name: first(names[0] ?? "", id) }) } return out } // toClaim is every gift plan the account can claim: what the app's // marketing feed offers (its banners). The v3.17 client replaced the old // preview polling with the feed alone (docs/marketing-touch-client.md in // zai-org/ZCode), so the preview is read no more; a rewards center's gift // lives on the rewards website, outside this API, and is claimed in the // client. unread names a feed that didn't read: its plans are unknown, // never none. async function toClaim(s) { const plans = [], unread = [] const add = (p) => { if (!plans.some((q) => q.plan_id === p.plan_id)) plans.push(p) } let d try { d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() }) } catch (e) { unread.push(`gift plans to claim: ${e?.message ?? String(e)}`) // rate is the ms ZCode asked to wait (0 when it sent no Retry-After), // null when this was not a rate limit at all return { plans, unread, rate: e?.status === 429 || e?.code === RATE_LIMITED ? (e.retryAfterMs || 0) : null } } const got = touchPlans(d) if (!got) unread.push("gift plans to claim: the plan list doesn't read") else got.forEach(add) return { plans, unread, rate: null } } // RECHECK is how long an "nothing to claim" stands before magpie's loop // asks again: ZCode drops gift plans into the feed during the day (a // weekend banner, say) on its own schedule, and the day's ask // may have run hours before, so an inactive settled for the day lets a // plan sit unclaimed past its short life (the weekend plan of // testdata/touch-1030-wk.json starts 19:00 Beijing). `until` wakes the // loop again in half an hour, and it asks again all day while neither // list names a plan — two GETs and no claim posted. The other settled // answers stand for the day: a claimed plan leaves the feed, so asking // a claimed account again half an hour later finds nothing and flips // its card from "Checked in today" to "No check-in event now"; a // captcha plan re-asked makes ZCode demand its captcha again each time, // and a done plan re-asked posts a claim it already answered 1003. The // same shape as Qoder's campaign that opens mid-day, asked again on // magpie's side there (yetone/magpie#2696). A failed needs no until: // magpie asks a failed again after 30 minutes of its own. const RECHECK_MS = 30 * 60_000 const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString() // claimDaily claims every gift plan ZCode offers the account (#503: // toClaim, the app's banners and its preview), as auth.checkin's answer: // inactive when neither lists one, claimed when one was claimed now, // done when each was claimed before, captcha when ZCode wants the app's // captcha for one (it is claimed in the ZCode app), ineligible when // ZCode is not offering one at that moment (code 1004, read again later // in the day), failed when a list // or a claim can't be read. A rate-limited read (HTTP 429, or code 3002) // is not asked again either: the account is held here until the wait ends // (a Retry-After ZCode sent, else the account's own wait doubling from // RECHECK_MS, out to RATE_LIMIT_MAX_MS — see RATE_LIMITED), and every ask // inside the wait answers the failed it already gave, without a request. // The hold belongs to one account (`s.key || s.jwt`) and lives in this // process's memory alone: a magpie restart forgets it. magpie from // v0.1.3165 honors a failed's `until` itself; older versions wait for // this hold, which is why it stays. // A failed one is asked again later in the // day, when a plan claimed now answers 1003. An inactive stands only // until RECHECK_MS from now, so a plan dropped into the feed later in // the day is still claimed; the other settled answers stand for the day // (see RECHECK). // Nothing here marks the account: a failed claim keeps its sign-in. async function claimDaily(s) { if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" } if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED } // a rate limit this account is still under: the same failed again, and // not one request (magpie asks a failed again after 30 minutes of its // own, so holding it is the plugin's job — see RATE_LIMITED) const held = rateWait.get(holdKey(s)) if (held && Date.now() < Date.parse(held.until)) return { outcome: "failed", message: held.message, until: held.until } const { plans, unread, rate = null } = await toClaim(s) // a rate-limited read: held here until the wait is over if (rate !== null) { const message = unread.join("; ") || "ZCode rate limited this account" return { outcome: "failed", message, until: noteRateLimit(holdKey(s), rate, message) } } // the feed answered and no claim is read: the wait is over. It is not // forgotten before the claims below, so a claim ZCode keeps limiting // waits longer each time (see noteRateLimit) if (!plans.length) { rateWait.delete(holdKey(s)) return unread.length ? { outcome: "failed", message: unread.join("; ") } : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() } } // a claim ZCode guards with its security check is not posted: the app // passes it before each claim and sends the proof in a header, which // this plugin can't make, and a claim without it only gets 3007 again // (young02036 on Discord, 11-07: asked every day, never claimed). The // plans are named, to claim in the ZCode app. A config that doesn't // read leaves it unknown: nothing is posted, and it is asked again. let guarded try { guarded = claimNeedsCaptcha(await clientConfigs()) } catch (e) { guarded = null unread.push(`ZCode's client config: ${e?.message ?? String(e)}`) } if (guarded !== false) { rateWait.delete(holdKey(s)) if (guarded === null) return { outcome: "failed", message: [...plans.map((p) => `${p.name}: not claimed, ZCode's security check for claims can't be read`), ...unread].join("; ") } return { outcome: "captcha", message: plans.map((p) => `${p.name}: ${CAPTCHA_CLAIM}`).join("; ") } } const got = [] for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) }) const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name) const claimed = named("claimed") const said = [ claimed.length ? `claimed ${claimed.join(", ")}` : "", ...got.filter((g) => g.outcome === "captcha").map((g) => `${g.name}: claim it in the ZCode app (${g.why})`), ...got.filter((g) => g.outcome === "ineligible").map((g) => `${g.name}: ${g.why}`), ...got.filter((g) => g.outcome === "failed").map((g) => `${g.name}: ${g.why}`), ...unread, ].filter(Boolean).join("; ") // a plan claimed now is used by the next request, not ten minutes on if (claimed.length) routes.delete(s.key + "\0" + s.jwt) // a claim ZCode rate limited: the plan may still be there, later const limitedClaim = got.find((g) => g.rate !== undefined) if (limitedClaim) return { outcome: "failed", message: said, until: noteRateLimit(holdKey(s), limitedClaim.rate, said) } rateWait.delete(holdKey(s)) // nothing in this check-in was rate limited: the wait is over // a list that didn't read may hold a plan not claimed: asked again if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said } if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said } if (claimed.length) return { outcome: "claimed", message: said } // a plan not offered now can be offered later in the day (11-04: an // account's GLOBAL BUILD banner showed 28 minutes after it signed in), // so an ineligible is read again half an hour out, as an inactive is if (got.some((g) => g.outcome === "ineligible")) return { outcome: "ineligible", message: said, until: recheck() } return { outcome: "done", message: `already claimed: ${named("done").join(", ")}` } } // GIFT_SIGN_IN is the card's line for an account whose gift plans can't // be read: ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day, ZCode // Trust Build) are served by zcode.z.ai to ZCode's own session alone, so // a GLM Coding Plan key, or a sign-in whose ZCode session has run out // (that token can't be renewed), lists no -Trial entries and // spends the coding plan alone. A fixed sentence, so magpie can // translate it; why goes in the display. Set aside: it stops nothing. const GIFT_SIGN_IN = "ZCode gift plans (-Trial models) need ZCode's sign-in" function giftSignIn(s, key) { if (!s.jwt) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: key ? "not read with an API key: add the account with a ZCode sign-in" : "this sign-in has no ZCode session: sign in again" } if (jwtExpired(s.jwt)) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "ZCode's sign-in has expired: sign in again" } return null } // startUsage is a gift-only account's card: its buckets, or the words // for having none to show. The card's header already names the plan, so // the windows of one plan keep their own names; with several plans each // bucket is named after its plan (see byPlan). const NO_START = "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" async function startUsage(s) { const g = await giftOf(s) if (!g) return { error: NO_START } const best = bestBuckets(g.windows) const label = byPlan(g.windows) g.windows = countedFirst(g.windows.map(({ _plan, _spent, ...w }, i) => { w.name = label(w.name, _plan) if (!w.models?.length) return w // a model two plans give (Trust Build's and the Start Plan's Flash) // counts on the bucket ZCode spends now; the other stays on the card // without holding the model up (ganlerk, Discord) const models = w.models.filter((m) => best.get(m.toLowerCase()) === i) if (!models.length) { delete w.models return { ...w, aside: true } } return { ...w, models: [...models, ...models.map(giftID)] } })) g.windows.push(...pendingLines(g)) delete g.live delete g.pending return g } // byPlan names a bucket after its plan ("GLM-5.3 · ZCode 1024 Dev Day") // when the gift's buckets come from more than one plan: two plans each // give a GLM-5.3, and named alike a spent one and a live one can't be // told apart (01huadalang, Discord: the new-user plan's spent GLM-5.3 // showed, the 1024 plan's own GLM-5.3 didn't). One plan's buckets keep // their own names, as the card's header names the plan. function byPlan(windows) { const several = new Set(windows.map((w) => w._plan || "")).size > 1 return (name, plan) => (several && plan ? name + " · " + plan : name) } // countedFirst puts the buckets a request spends before those set aside // (a spent bucket another plan's live one stands in for), each group in // the balance's order: magpie's account row shows a card's first two // windows and leaves the rest to its tooltip, so a spent plan listed first // hid the live plan's allowance for the same model. const countedFirst = (ws) => [...ws.filter((w) => !w.aside), ...ws.filter((w) => w.aside)] // bestBuckets is, for each model the gift's buckets serve, the index of // the one a request spends: a live one before a spent one, the least // used of those. The server picks among an account's buckets itself // (ZCode sends no plan with a request), so one spent bucket doesn't stop // a model another still has. function bestBuckets(windows) { const best = new Map() windows.forEach((w, i) => { for (const m of w.models ?? []) { const key = m.toLowerCase(), old = best.get(key), prev = windows[old] if (old === undefined || (prev._spent && !w._spent) || (prev._spent === w._spent && w.used < prev.used)) best.set(key, i) } }) return best } // giftReadable: ZCode's session can read the gift beside a coding plan, // so the card asks for it even when no gift is live for requests: a plan // that starts later is named on the card (windy, Discord), not left out // because nothing could be spent yet. const giftReadable = (s) => !!s.jwt && !jwtExpired(s.jwt) // dualUsage shows both pools but only the pool a request can use counts // for its model. Live gift models don't spend the Coding windows; spent // or blocked gift buckets stay visible without holding up the Coding Plan. // Fresh usage also updates the request cache, so a replenished or spent // gift takes effect before its ten-minute route cache expires. A failed // gift read leaves the working Coding Plan's card and route alone. async function dualUsage(s, out) { out ??= await codingUsage(s) const cached = routes.get(s.key + "\0" + s.jwt) try { const g = await giftOf(s) const gift = g?.live ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent) .flatMap((w) => w.models ?? []).map((m) => m.toLowerCase()))], allModels: uniqueModels(g.windows.flatMap((w) => w.models ?? [])) } : null if (cached) { cached.gift = gift // a plan that starts later is read again when it starts const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t)) .concat(g.pending.map((p) => p.start * 1000)).filter(Number.isFinite) : [] if (ends.length) cached.ttl = Math.min(cached.ttl, Math.max(0, Math.min(...ends) - cached.at)) } if (g?.live) { // the gift's models are its trial entries alone: a plain model stays // on the coding plan, and the user picks the gift by its entry const notModels = gift.allModels.map((m) => giftID(m).toLowerCase()) if (notModels.length) out.windows = out.windows.map((w) => w.aside ? w : { ...w, notModels }) // Several buckets may serve one model: one spent sibling cannot block it. const best = bestBuckets(g.windows) // beside the Coding Plan's windows every gift bucket is named after // its plan, one plan or several: "GLM-5.1-Trial · Start Plan" can't // be read as the Coding Plan's own (windy, Discord). The bucket's // own name (ZCode's show_name, as its "Today's balance" lists it) // comes first: magpie's ring and account row cut a long name short, // and "ZCODE GLOBAL BUI…" said neither the model nor the plan's // kind, so the Start Plan read as missing (Danbuth, plugins#504) const label = (name, plan) => name + " · " + first(plan, "Start Plan") out.windows.push(...countedFirst(g.windows.map(({ _plan: p, _spent, ...w }, i) => { const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i) const models = selected.map(giftID) const scoped = models.length ? { ...w, models } : { ...w, aside: true } // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial) let name = w.name for (const m of selected) { const at = name.toLowerCase().indexOf(m.toLowerCase()) if (at >= 0) name = name.slice(0, at) + giftID(m) + name.slice(at + m.length) } return { ...scoped, name: label(name, p) } }))) } if (g) out.windows.push(...pendingLines(g)) } catch { if (cached) { cached.gift = null cached.at = Date.now() cached.ttl = 60_000 // an uncertain gift is read again sooner } } return out } // periodOf reads an entitlement's period: "daily", "weekly", "monthly". function periodOf(p) { p = p.toLowerCase() if (p.includes("day") || p.includes("daily")) return 86400 if (p.includes("week")) return 7 * 86400 if (p.includes("month")) return 30 * 86400 return 0 } // when is a team plan's end: a time in Beijing, or a Unix time in seconds // or milliseconds; ms, or 0. function when(v) { if (typeof v === "string") { const t = beijing(v) if (t) return t } const n = startNum(v) if (n > 0) return n > 1e12 ? Math.trunc(n) : Math.trunc(n) * 1000 return 0 } // teamUsage is a team seat's allowance: the team plan's five hours and // week, and the plan's name and end. async function teamUsage(s, key) { const root = bizRoot(s.base) const headers = teamHeaders(s.base, s.org, s.project) const d = (await call("GET", root + "/api/monitor/usage/quota/limit?type=2", { auth: key, headers })) ?? {} const out = { windows: limitWindows(d) } if (!s.token) return out const resets = teamResets(root, s.token, headers) try { const t = (await call("GET", root + "/api/biz/team/subscribe/product/querySubscribeDetail", { auth: s.token, headers })) ?? {} const usable = (t.hasSubscription == null || t.hasSubscription === true) && String(t.status ?? "").toUpperCase() === "EFFECTIVE" && String(t.memberGrantStatus ?? "").toUpperCase() === "VALID" if (usable) { if (typeof t.productName === "string" && t.productName) out.plan = t.productName const end = when(t.subscribeEndTime) if (end) Object.assign(out, { until: new Date(end).toISOString(), renew: "off" }) } } catch {} const r = await resets if (r) out.resets = r return out } // teamResets is how many resets a team member may spend, of the five hours // and of the week, marked a team's (team: true), as the built-in's // zhipuTeamResets did. null when it can't be told or there are none. async function teamResets(root, auth, headers) { const r = await resetsOf(root + "/api/biz/customer-package-reset/list?targetType=TEAM", auth, headers) if (r) r.team = true return r } // personalResets is how many resets a GLM Coding Plan of a person's own // holds, as bigmodel.cn's usage page lists them, asked with the plan's // key (the built-in's zhipuPersonalResets). Only read: a reset is spent // on the vendor's own page, never from here. async function personalResets(root, key) { return resetsOf(root + "/api/biz/customer-package-reset/list?targetType=PERSONAL", key) } // resetsOf reads customer-package-reset/list: the resets of the five // hours and of the week, of which only those still available count (one // run out stays listed a week, available false), each with its own end // (each, soonest first, one with no end last) and the soonest as until. // null when the list can't be read, so no count is shown rather than 0, // and when it holds none. async function resetsOf(url, auth, headers) { let d try { d = (await call("GET", url, { auth, headers })) ?? {} } catch { return null } let until = 0 const each = [] const count = (rs, window) => { let n = 0 for (const x of Array.isArray(rs) ? rs : []) { if (x?.available !== true) continue n++ const t = when(x.expireTime) if (t && (!until || t < until)) until = t each.push(t ? { until: new Date(t).toISOString(), window } : { window }) } return n } const fiveHour = count(d.fiveHourResets, "fiveHour") const weekly = count(d.weekResets, "weekly") if (fiveHour + weekly === 0) return null const end = (c) => (c.until ? Date.parse(c.until) : Infinity) each.sort((a, b) => (end(a) === end(b) ? 0 : end(a) < end(b) ? -1 : 1)) const r = { count: fiveHour + weekly, byWindow: true, fiveHour, weekly } if (until) r.until = new Date(until).toISOString() r.each = each return r } // ---- signing in ------------------------------------------------------------------ // bizAuth is the Authorization a sign-in gives the business API: Z.ai's // token exchanged for a business one, as a Bearer; BigModel's goes bare. async function bizAuth(site, token) { if (site === "bigmodel") return token let biz try { biz = await call("POST", ZAI_API + "/api/auth/z/login", { body: { token } }) } catch (e) { throw new Error(`Z.ai sign-in: ${e.message}`) } if (!biz?.access_token) throw new Error("Z.ai sign-in: no token") return "Bearer " + biz.access_token } // mintKey is the account's own coding plan key, in its default project // ("默认机构" / "默认项目", else the first), and the plan it has. async function mintKey(site, root, auth, info) { let org = "" let proj = "" for (const o of info?.organizations ?? []) { const ps = (o.projects ?? []).filter((p) => p.projectId && String(p.projectType) !== "2") if (!o.organizationId || !ps.length) continue const def = (ps.find((p) => String(p.projectName ?? "").includes("默认项目")) ?? ps[0]).projectId const named = String(o.organizationName ?? "").includes("默认机构") if (!org || named) { org = o.organizationId proj = def if (named) break } } if (!org) throw new Error(`this ${SITES[site].name} account has no project for an API key`) const key = await projectKey(site, keysURL(root, org, proj), auth, undefined, { name: "zcode-api-key" }) const s = { key, base: SITES[site].base } try { return { s, plan: await plan(s) } } catch (e) { throw new Error(`GLM Coding Plan: ${e.message}`) } } // teamSignIn is the account's seat on a team's plan: the first team project // whose plan is in force and gives it a seat, and that project's key. async function teamSignIn(site, root, auth, info) { const base = SITES[site].base const ps = [] for (const o of info?.organizations ?? []) for (const p of o.projects ?? []) if (o.organizationId && p.projectId && String(p.projectType) === "2") ps.push({ org: o.organizationId, project: p.projectId }) if (!ps.length) return { err: "no team plan", none: true } let why = "" let last = "" for (const p of ps) { let d try { d = (await call("GET", root + "/api/biz/team/subscribe/product/querySubscribeDetail", { auth, headers: teamHeaders(base, p.org, p.project) })) ?? {} } catch (e) { last = e.message continue } const status = String(d.status ?? "").toUpperCase() const grant = String(d.memberGrantStatus ?? "").toUpperCase() if (!(d.hasSubscription !== false && status === "EFFECTIVE" && grant === "VALID")) { if (!why && status === "EFFECTIVE" && grant === "UNASSIGNED") why = `this ${SITES[site].name} account is in a team with a GLM Coding Plan but has no seat on it yet — ask the team's admin to give it one, then sign in again` if (!why && status === "EXPIRED") why = `the ${SITES[site].name} team's GLM Coding Plan this account is in has expired` continue } let key try { key = await projectKey(site, keysURL(root, p.org, p.project), auth, teamHeaders(base, p.org, p.project), { name: "zcode-team-api-key", keyType: 2 }) } catch (e) { return { err: `the team's GLM Coding Plan: ${e.message}`, why: `the team's GLM Coding Plan: ${e.message}` } } return { s: { key, base, token: auth, org: p.org, project: p.project }, plan: first(d.productName, "GLM Coding Team") } } if (why) return { err: why, why } const err = `the team's GLM Coding Plan: ${last || "no seat on it"}` return { err, why: err } } // signedIn is what a sign-in gives: the account's coding plan key and plan; // or, with none of its own, a seat on a team's plan; or else ZCode's token // for its Start Plan while the account has one. Asked for the team's plan // (onTeam), it is the team seat alone, as ZCode's plan picker gives a team // plan beside the account's own (a "team-coding-plan" selection): an // account with both is signed in to each as an account of its own (#285). async function signedIn(site, token, jwt, device, onTeam = false) { const name = SITES[site].name const root = SITES[site].api let s = null let err = null let team = "" if (onTeam) { const auth = await bizAuth(site, token) let info try { info = await call("GET", root + "/api/biz/customer/getCustomerInfo", { auth }) } catch (e) { throw new Error(`${name} account: ${e.message}`) } const t = await teamSignIn(site, root, auth, info) if (t.s) return { ...t.s, jwt, plan: t.plan } if (t.none) throw new Error(`this ${name} account has no seat on a team's GLM Coding Plan — sign in with "ZCode: ${name} GLM Coding Plan" for its own plan`) throw new Error(t.why ?? t.err) } try { const auth = await bizAuth(site, token) let info try { info = await call("GET", root + "/api/biz/customer/getCustomerInfo", { auth }) } catch (e) { throw new Error(`${name} account: ${e.message}`) } const own = await mintKey(site, root, auth, info).catch((e) => ({ e })) if (own.e) err = own.e else if (own.plan) return { ...own.s, jwt, plan: own.plan } else s = own.s const t = await teamSignIn(site, root, auth, info) if (t.s) return { ...t.s, jwt, plan: t.plan } team = t.why ?? "" } catch (e) { err = e } let berr = null if (jwt) { try { const sp = await startPlan(jwt, device, true) if (sp) return { ...(err || !s?.key ? { base: SITES[site].base } : s), jwt, plan: sp.name } } catch (e) { berr = e } } if (team && berr) throw new Error(`${team}; ZCode's Start Plan: ${berr.message}`) if (team) throw new Error(team) if (err && berr) throw new Error(`${err.message}; ZCode's Start Plan: ${berr.message}`) if (err) throw err if (berr) throw new Error(`this ${name} account has no GLM Coding Plan, of its own or a team's, and ZCode's Start Plan could not be read: ${berr.message}`) throw new Error( `this ${name} account has no GLM Coding Plan, of its own or a team's, and ZCode's Start Plan has ended or was never started — subscribe at ${SITES[site].subscribe}, then sign in again`, ) } // TEAM marks a team seat's account name beside the account's own. const TEAM = "team" const who = (u) => first(String(u?.email ?? "").replace(/@phone\.local$/, ""), u?.name, u?.user_id, "ZCode") // uidOf is the account's user id, kept beside its name: magpie tells two // accounts of one name apart by it, a name being no one's own (wakkana on // Discord, WorkBuddy's) const uidOf = (u) => (u?.user_id === undefined || u?.user_id === null ? "" : String(u.user_id).trim()) const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) // authorize opens ZCode's sign-in flow on site; its callback polls it. // onTeam signs in to the account's seat on a team's plan, named apart from // the account's own plan (the host keeps one entry per account name). async function authorize(site, log, onTeam = false) { const poll = "Bearer " + Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex") const device = uuid() let flow try { flow = await call("POST", ZCODE + "/api/v1/oauth/cli/init", { auth: poll, body: { provider: site }, device }) } catch (e) { throw new Error(`ZCode sign-in: ${e.message}`) } let u try { u = new URL(flow?.authorize_url) } catch {} if (!flow?.flow_id || u?.protocol !== "https:") throw new Error("ZCode gave no sign-in page") // where Z.ai or BigModel sends the browser back, as ZCode sets it (BigModel's page names it redirect) const back = `${ZCODE}/app/oauth/login?` + new URLSearchParams({ redirect: "zcode://oauth/callback", app_version: APP_VERSION }) u.searchParams.set(site === "bigmodel" ? "redirect" : "redirect_uri", back) const interval = Math.max(Number(flow.poll_interval_sec) || 0, 1) * 1000 const deadline = Number(flow.expires_at) > 0 ? Number(flow.expires_at) * 1000 : Date.now() + 5 * 60_000 return { url: u.toString(), instructions: `Sign in to ${SITES[site].name} in the browser; this finishes on its own.`, method: "auto", async callback() { const fail = (msg) => (log(msg), { type: "failed", error: msg }) for (;;) { await sleep(interval) if (Date.now() > deadline) return fail("the sign-in expired; start again") let got try { got = (await call("GET", `${ZCODE}/api/v1/oauth/cli/poll/${encodeURIComponent(flow.flow_id)}`, { auth: poll, device })) ?? {} } catch (e) { if (e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429) return fail("ZCode sign-in: " + e.message) continue // a hiccup: ask again } const token = site === "bigmodel" ? first(got.bigmodel?.access_token, got.bigmodel?.accessToken) : first(got.zai?.access_token) if (got.status === "pending" || !got.status) continue if (got.status === "failed") return fail(`the sign-in was declined on ${SITES[site].name}`) if (got.status !== "ready" || !token) return fail("ZCode sign-in: unexpected answer " + got.status) let s try { s = await signedIn(site, token, first(got.token), device, onTeam) } catch (e) { return fail(e.message) } const state = { site, device, ...s } return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", // the key doesn't run out; ZCode's token, when it is all there is, does expires: s.key || isTeam(s) ? 0 : jwtExpiry(s.jwt), accountId: onTeam ? `${who(got.user)} (${TEAM})` : who(got.user), ...(uidOf(got.user) ? { uid: uidOf(got.user) } : {}), } } }, } } // ---- ZCode's own sign-in ------------------------------------------------------------ // ZCode keeps its sign-in in ~/.zcode/v2/credentials.json, each value // encrypted (AES-256-GCM, "enc:v1:..") 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). // // ZCode 3.14 can move its data (数据存储路径, "data storage path"): it copies // ~/.zcode/v2 to /.zcode/v2, all but setting.json, and from its next // start reads credentials.json and runtime/provider from there. The choice // stays in the home folder's setting.json as dataBaseDir, which ZCode's main // process reads before anything else (readBootstrapDataBaseDirFromDisk); // setting.json itself, and the team plan it names, stay in the home folder. // settingDir is where ZCode keeps setting.json, moved or not. const settingDir = () => join(homedir(), ".zcode", "v2") // dataIn is the folder ZCode keeps its .zcode data in: the home folder, // unless dataBaseDir moved it. A value that isn't an absolute path is // ignored, as magpie's built-in does (internal/appdir ZCodeDataIn). function dataIn() { const d = readJSON(join(settingDir(), "setting.json"))?.dataBaseDir const t = typeof d === "string" ? d.trim() : "" return t && isAbsolute(t) ? t : homedir() } // zcodeDir is where ZCode keeps credentials.json and runtime/provider. const zcodeDir = () => join(dataIn(), ".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(settingDir(), "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 } // configKey is the coding plan key ZCode's config.json gives its built-in // coding plan provider, Z.ai's first, as ZCode lists them; ZCode reads it // as it is, and one written encrypted is read too. function configKey(key) { const providers = readJSON(join(zcodeDir(), "config.json"))?.provider if (!providers || typeof providers !== "object") return null for (const [ids, base] of [ [["builtin:zai-coding-plan", "account:zai-individual-coding-plan"], ZAI_BASE], [["builtin:bigmodel-coding-plan", "account:bigmodel-individual-coding-plan"], BIGMODEL_BASE], ]) { for (const id of ids) { let k = providers[id]?.options?.apiKey if (typeof k !== "string") continue k = k.trim() if (k.startsWith("enc:")) k = first(decrypt(key, k)) if (k.includes(".") && !/[\s{$]/.test(k)) return { key: k, base } } } return null } // ownLocation is where ZCode 3.16 finds the account's own coding plan key // when it keeps none: credentials.json's // project-key-location:v1:<[origin, family, accountId, team, 1, selection]>, // URI-encoded JSON, holds { organizationId, projectId, apiKeyId } (its // ProjectAccessTokenClient). ZCode trades that key for a short-lived // project token each time; here its secret is read (located), as a sign-in // here reads its own key's. The account's own (team null), of the family // ZCode is on first, else Z.ai's, as ZCode lists them; one of another // account the profile names is left alone (meraki7304, #410). const LOCATION = "project-key-location:v1:" function ownLocation(store, key) { const set = readJSON(join(settingDir(), "setting.json")) const fams = set?.providerFamilyDomain === "bigmodel" ? ["bigmodel", "zai"] : ["zai", "bigmodel"] const found = [] for (const [name, v] of Object.entries(store)) { if (!name.startsWith(LOCATION)) continue let at try { at = JSON.parse(decodeURIComponent(name.slice(LOCATION.length))) } catch { continue } if (!Array.isArray(at) || at[3] !== null || String(at[4]) !== "1" || !fams.includes(at[1])) continue let loc try { loc = JSON.parse(decrypt(key, v) ?? "") } catch {} const org = first(loc?.organizationId), project = first(loc?.projectId), apiKeyId = first(loc?.apiKeyId) if (!org || !project || !apiKeyId) continue found.push({ site: at[1], origin: typeof at[0] === "string" ? at[0] : "", account: String(at[2] ?? ""), org, project, apiKeyId }) } for (const site of fams) { const token = first(decrypt(key, store[`oauth:${site}:access_token`])) if (!token) continue let me = "" try { me = String(JSON.parse(decrypt(key, store[`oauth:${site}:user_info`]) ?? "{}")?.id ?? "") } catch {} const mine = found.filter((l) => l.site === site && (!me || l.account === me)) if (!mine.length) continue const l = mine[0] // the origin ZCode asked, when it is the site's own; else the site's API let origin = SITES[site].api try { const u = new URL(l.origin) const h = u.host.toLowerCase() if (u.protocol === "https:" && (site === "zai" ? h === "z.ai" || h.endsWith(".z.ai") : h === "bigmodel.cn" || h.endsWith(".bigmodel.cn"))) origin = u.origin } catch {} return { site, base: SITES[site].base, token, loc: { origin, org: l.org, project: l.project, apiKeyId: l.apiKeyId } } } return null } // located gives a sign-in that has only ZCode's key location (ownLocation) // its key: the secret of the key it names, read as ZCode lists the // project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is // made: a location whose key is gone (404) leaves the sign-in keyless, as // before; any other failure is said. A key read is kept for the token. const locatedKeys = new Map() async function located(s) { if (!s || s.key || !s.loc || !s.token) return s const l = s.loc const id = [s.token, l.origin, l.org, l.project, l.apiKeyId].join("\0") let got = locatedKeys.get(id) if (!got || (got.err && Date.now() - got.at >= 60_000)) { const auth = s.site === "zai" ? "Bearer " + s.token : s.token try { const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey) got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") } } catch (e) { got = e?.status === 404 ? { key: "" } : { err: e } } got.at = Date.now() locatedKeys.set(id, got) } if (got.err) throw new Error(`ZCode's ${SITES[s.site].name} coding plan key: ${got.err.message} — sign in to ZCode again`) if (got.key) s.key = got.key return s } // 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::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 } } // ZCode 3.15 keeps no plan key in its credentials; the one it uses sits // in config.json, the provider's options.apiKey (yetone/magpie#2130) if (!s.key) s = configKey(key) || s // ZCode 3.16 keeps neither: only where the key is (#410) if (!s.key) s = ownLocation(store, key) || s 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), uid: uidOf(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 while ZCode stays signed in to that account.", 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, uid, ...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, ...(uid ? { uid } : {}) } }, } } // stateOf is a stored sign-in as the requests need it. function stateOf(auth) { if (auth?.type === "oauth") { let s = {} try { s = JSON.parse(auth.refresh) } catch {} if (s.source === "zcode") { // ZCode's own, read now, while ZCode is signed in to this same // account. Signed out, or signed in to another account since, it is // what it was when this was signed in: another account's key would // send this account's requests as that one, and an expired session // says sign in again (EXPIRED) rather than borrowing another's. const own = ownSignIn() // (by user id where both have one: another account may share the name) if (own && own.user === String(auth.accountId ?? "") && (!own.uid || !auth.uid || own.uid === String(auth.uid))) { const { user, uid: _uid, ...now } = own s = { source: "zcode", device: s.device, plan: s.plan, ...now } } } const site = siteOf(s.site) const key = s.key ?? (s.jwt ? "" : auth.access) return { ...s, site, base: s.base || SITES[site].base, key, device: s.device || (key ? keyDevice(key) : anyDevice) } } if (auth?.type === "api") { const site = siteOf(auth.metadata?.site) const key = String(auth.key ?? "").trim() return { site, base: SITES[site].base, key, device: key ? keyDevice(key) : anyDevice } } return null } // ---- models ---------------------------------------------------------------------- // planID is ZCode's providerId for the plan served at base; a team's plan // has the individual one's models. const planID = (base) => base.includes("/zcode-plan/") ? "account:zai-start-plan" : base.includes("bigmodel.cn") ? "account:bigmodel-individual-coding-plan" : "account:zai-individual-coding-plan" const efforts = (vs) => [...new Set(vs.map((v) => (v === "disabled" ? "none" : v === "enabled" ? "high" : v)))] // modelsOf is a plan's models in ZCode's provider config. function modelsOf(cfg, plan) { const c = cfg?.config ?? {} const ids = [] const on = new Set() const add = (id) => { if (!on.has(id.toLowerCase())) on.add(id.toLowerCase()), ids.push(id) } for (const r of c.providerConfigRules?.providerRules ?? []) if (r.providerId === plan) (r.builtinModelIds ?? []).forEach(add) const off = new Set() for (const r of c.modelConfigRules?.builtinProviderModelRules ?? []) { if (r.providerId !== plan) continue if (r.config?.enabled === false) off.add(String(r.modelId).toLowerCase()) else add(r.modelId) } const out = [] for (const id of ids) { if (off.has(id.toLowerCase())) continue const m = { id, context: 0, output: 0, efforts: [] } for (const r of c.modelConfigRules?.modelRules ?? []) { let re try { re = new RegExp(`^(?:${r.modelMatch})$`, "i") } catch { continue } if (!re.test(id)) continue const x = r.config ?? {} if (x.properties?.contextWindow > 0) m.context = x.properties.contextWindow if (x.optionSpecs?.maxOutputTokens?.max > 0) m.output = x.optionSpecs.maxOutputTokens.max if (typeof x.properties?.inputFormat?.supportsImage === "boolean") m.image = x.properties.inputFormat.supportsImage if (x.optionSpecs?.reasoningLevel?.values?.length) m.efforts = efforts(x.optionSpecs.reasoningLevel.values) } out.push(m) } return out } // localConfig is the latest provider config an installed ZCode has. function localConfig() { const files = [] const rt = join(zcodeDir(), "runtime", "provider") const walk = (dir, depth) => { let es = [] try { es = readdirSync(dir, { withFileTypes: true }) } catch { return } for (const e of es) { if (depth < 3 && e.isDirectory()) walk(join(dir, e.name), depth + 1) else if (depth === 3 && e.name === "zcode-builtin.json") files.push(join(dir, e.name)) } } walk(rt, 0) if (process.platform === "darwin") files.push("/Applications/ZCode.app/Contents/Resources/config/provider/zcode-builtin.json") let best = null for (const f of files) { try { if (!existsSync(f)) continue const b = JSON.parse(readFileSync(f, "utf8")) if (!best || (b.revision ?? 0) > (best.revision ?? 0)) best = b } catch {} } return best } // remoteConfig is the release of ZCode's provider config zcode.z.ai names now. async function remoteConfig() { const signal = AbortSignal.timeout(8000) const c = await clientConfigs() const url = c?.configs?.builtin_provider_config_json if (!String(url ?? "").startsWith("https://")) throw new Error("ZCode's configs name no provider config") const res = await fetch(url, { headers: { "User-Agent": UA }, signal }) if (!res.ok) throw new Error(`ZCode's provider config: ${res.status}`) return res.json() } // clientConfigs is what zcode.z.ai tells this client version // (/api/v1/client/configs): the provider config's address, and the // captcha its claims and requests need (claimNeedsCaptcha). A read that // came through is kept for 10 minutes; a failed one is not kept, and // throws. let clientCache = null async function clientConfigs() { if (clientCache && Date.now() - clientCache.at < 600_000) return clientCache.c const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal: AbortSignal.timeout(8000) }) clientCache = { c, at: Date.now() } return c } // resetClientConfigs is for tests: the next read asks zcode.z.ai again. export function resetClientConfigs() { clientCache = null } // config is ZCode's provider config, the later of zcode.z.ai's and an // installed ZCode's, kept for 10 minutes. let cfgCache = null async function zcodeConfig() { if (cfgCache && Date.now() - cfgCache.at < 600_000) return cfgCache.cfg let cfg = null try { cfg = await remoteConfig() } catch {} const local = localConfig() if (local && (!cfg || (local.revision ?? 0) > (cfg.revision ?? 0))) cfg = local cfgCache = { cfg, at: Date.now() } return cfg } // variants are a model's reasoning efforts as @ai-sdk/anthropic options. const BUDGET = { minimal: 1024, low: 4096, medium: 8192, high: 16_000, max: 31_999 } function variants(es) { const out = {} for (const e of es) out[e] = e === "none" ? { thinking: { type: "disabled" } } : { thinking: { type: "enabled", budgetTokens: BUDGET[e] ?? 16_000 } } return out } // entry is a model as a config hook declares it. const entry = (m) => ({ id: m.id, name: m.id, reasoning: m.efforts.some((e) => e !== "none"), tool_call: true, attachment: !!m.image, modalities: { input: m.image ? ["text", "image"] : ["text"], output: ["text"] }, // what ZCode's config names, else 0 (unknown), as magpie's built-in limit: { context: m.context || 0, output: m.output || 0 }, cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 }, variants: variants(m.efforts), }) // model is a model as OpenCode's provider hands it to provider.models. // modelOf reads the model a Messages body asks for. function modelOf(text) { try { const m = JSON.parse(text)?.model return typeof m === "string" ? m : "" } catch { return "" } } // kept passes a response on as it came, the account kept: the built-in // never marked a ZCode account lapsed nor cleared one. function kept(res, text) { const h = new Headers(res.headers) h.delete("content-length") h.delete("content-encoding") h.set("X-Magpie-Sign-In", "kept") return new Response(text !== undefined ? text : res.body, { status: res.status, statusText: res.statusText, headers: h }) } // ---- the plan's concurrency ------------------------------------------------------ // ZCode serves one account a few requests at a time. Past that it answers 429 // with code 3008, "user concurrency limit exceeded", 3009, "model // concurrency limit exceeded", or 3010: the request's turn has not come — not // a plan spent (1113/1005) and not a rate limit (1302/1303). ZCode's own // client (3.17.2) reads the three as one ("当前系统繁忙"), asks again after 1s // and 2s, and then gives up; it sends one request per session at a time and // has no hold. magpie sends every agent's and every session's requests of // this computer through this one process, so the plugin does what that // client does: the Start Plan gets a few requests of an account in flight at // once (startGate), the rest wait their turn here instead of being sent to be // refused, and a refusal anyway is asked again twice (BUSY_WAITS). // // The coding plan keeps no gate of the plugin's: its cap depends on its tier // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher // off-peak (https://docs.z.ai/devpack/usage-policy), so a number written here // would hold a Max account to a Lite one's. magpie's own queue spaces it by // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in // package.json), which a user raises on the account. const DEFAULT_CONCURRENCY = 3 // DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends // requests to at the same time (maxAccounts, on the auth hook and in // package.json): the first in the user's list, the next taking over once // one runs out or fails. 01huadalang on Discord: three accounts used at // once from one address got the address refused with a 405, two didn't. A // user sets their own on the provider (Accounts at once), 0 for no limit. const DEFAULT_ACCOUNTS = 2 const BUSY_CODES = new Set(["3008", "3009", "3010"]) // BUSY_WAITS are the waits before each ask again: ZCode's own client's, // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie, // which takes the request to another account or rests this one as its 429 // says. Six asks over ten seconds, before 0.1.56, put two or three times the // requests a capped account could serve on the wire, and the agents' own // retries came on top. const BUSY_WAITS = [1000, 2000] // The hint names neither "plan" nor "limit": after the vendor's "…limit // exceeded" either would read to magpie as a plan used up. const BUSY_HINT = "ZCode serves one account a few requests at a time and was still busy when asked again after 1s and 2s; run fewer agents or subagents on ZCode at once, or try again in a moment" // startGate is the Start Plan's in-flight count per account. PR #395 measured // one Z.ai gift account at 3 of 12 parallel requests served in one run and 4 // of 12 in another, so three are in flight at once, what magpie's queue sends // by DEFAULT_CONCURRENCY too. The gate holds them there when that queue // doesn't: a user who raised the account's number for the coding plan, two // magpie providers signed in to one account, a host that doesn't read // maxConcurrency. A cap the server still says now and then (a slot it lets // go of late, the ZCode app on the same account) the 1s re-ask gets past. // A request past them waits here, first come first served, until one is // answered to the end, up to startGate.wait; an agent that gives up leaves // the queue. A wait that runs out is answered startQueueAnswer's 429, // nothing sent. The gate lives in this process's memory alone, by account // (gateKey). // // An account ZCode serves fewer than that (plugins#438: one account, one // agent, never more than two in flight, and refused at two) is narrowed: // a request refused again at its 1s re-ask while others of this computer // were in flight beside it (busyCap) tells the cap is below the gate, and // the account's gate goes down to one fewer than were in flight, at least // one, for NARROW_FOR. Such a cap is this computer asking too much at once, // which the narrowed gate now stops, so it counts toward no firewall hold. // narrow is kept apart from lanes, which go when idle; now is its clock, // injectable for tests. const NARROW_FOR = 5 * 60_000 const startGate = { inflight: 3, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() } // limitOf is how many of the account's Start Plan requests go at once: the // gate's number, or less while the account is narrowed. function limitOf(key) { const n = startGate.narrow.get(key) if (!n) return startGate.inflight if (startGate.now() >= n.until) { startGate.narrow.delete(key) return startGate.inflight } return Math.min(startGate.inflight, n.limit) } // narrowed lowers the account's gate below the requests that were in flight // when one was refused again (busy, its own included), and says whether it // did: a lone request refused again is not this computer's doing. function narrowed(key) { const busy = startGate.lanes.get(key)?.busy ?? 0 if (busy < 2) return false const limit = Math.max(1, Math.min(limitOf(key), busy - 1)) startGate.narrow.set(key, { limit, until: startGate.now() + NARROW_FOR }) return true } // startFull says the account's Start Plan slots are all taken, or others wait. const startFull = (key) => { const l = startGate.lanes.get(key) return !!l && (l.busy >= limitOf(key) || l.queue.length > 0) } // startSlot waits for one of the account's Start Plan slots: { release }, // null when startGate.wait ran out first, or the agent's abort thrown. function startSlot(key, signal) { const lanes = startGate.lanes let l = lanes.get(key) if (!l) lanes.set(key, (l = { busy: 0, queue: [] })) const next = () => { while (l.busy < limitOf(key) && l.queue.length) l.queue.shift()() if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key) } const take = () => { l.busy++ let gone = false return { release() { if (gone) return gone = true l.busy-- next() }, } } if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError")) if (l.busy < limitOf(key) && !l.queue.length) return Promise.resolve(take()) return new Promise((resolve, reject) => { const leave = () => { clearTimeout(timer) signal?.removeEventListener?.("abort", aborted) const i = l.queue.indexOf(go) if (i >= 0) l.queue.splice(i, 1) } const go = () => { leave() resolve(take()) } const aborted = () => { leave() next() reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError")) } const timer = setTimeout(() => { leave() next() resolve(null) }, startGate.wait) signal?.addEventListener?.("abort", aborted, { once: true }) l.queue.push(go) }) } // released hands res on and lets its slot go once ZCode's answer has come // to its end, failed, or been given up on (the agent's abort, the reader's // cancel) — the request is in flight at ZCode until then. The answer is read // as it comes, whether or not the agent reads it yet, so a reply read late, // or dropped unread, does not keep its slot past ZCode's own end of it. function released(res, slot, signal) { if (!slot) return res if (!res.body) { slot.release() return res } const reader = res.body.getReader() const stop = (why) => { slot.release() reader.cancel(why).catch(() => {}) } signal?.addEventListener?.("abort", () => slot.release(), { once: true }) const pump = async (c) => { try { for (;;) { const { done, value } = await reader.read() if (done) break c.enqueue(value) } slot.release() c.close() } catch (e) { slot.release() try { c.error(e) } catch {} } } // started, not awaited: the agent reads each chunk as it comes const body = new ReadableStream({ start: (c) => void pump(c), cancel: stop }) return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }) } // startQueueAnswer is a request that waited its whole turn behind the // account's others and was never sent: a 429 magpie reads as a rate limit, // so it tries the next account, and a short Retry-After. function startQueueAnswer(key) { const n = limitOf(key) const error = { type: "rate_limit_error", message: `ZCode's free Start Plan serves this account ${n} request${n === 1 ? "" : "s"} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`, } return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" }, }) } // busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15 // and 11-06 06:23–06:27) show the same shape: sustained ~18 requests/min on // the Start Plan, up to ~10 of them in flight against a cap of about three, // brings code-3008 caps in a run, and 3–7.5 minutes later the edge firewall // (errors.aliyun.com) refuses the whole IP with 405 for 1–2 hours. Re-asks // absorbed ~90% of those caps, so neither magpie nor the agent saw that the // address was saturated and nobody slowed the arrival rate down. startGate // now keeps this computer's own requests under the cap, so a cap is ZCode // busy or another client on the account; a request refused on its first ask // and again a second later (busyCap) is that, sustained, and BUSY_N of them // in one minute hold the Start Plan (zcode.z.ai only, process-wide, every // account) off BUSY_HOLD. A sustained cap of a request with others of the // same account in flight beside it counts for nothing either: it narrows the // account's gate (startGate), which then sends no more than ZCode serves // (plugins#438: an account served one at a time, two in flight from one // agent, held again and again at ~5 requests/min). #801's caps came with up // to ~10 in flight, which the gate now never sends, and an account whose // slots are taken elsewhere is narrowed to one within a few caps and then // refused alone, which counts as before. A cap the 1s re-ask got past counts for nothing: // on 0.1.55 every capped request counted, a lone late slot as much as a // saturated address, and busy afternoons held users for nothing. Replay of // both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared // 37–52 requests. A held request answers 429 with Retry-After, so magpie // still reads a rate limit, rests the account and fails over; it is not the // 405/BlockedHint of an IP already refused. The coding plan, on another // host, is never held. The hold lives in this process's memory alone: magpie // restarting forgets it. Only model requests are held — balance reads, the // usage card and check-in still reach zcode.z.ai during it (the check-in // holds its own reads per account on a 429). const BUSY_N = 5 const BUSY_WINDOW = 60_000 const BUSY_HOLD = 3 * 60_000 const busyHold = { hits: [], until: 0, now: () => Date.now() } // busyHold.now is the clock, injectable for tests: a hold's window, its // length and its expiry all read through it. const busyHeld = () => busyHold.now() < busyHold.until // busyCap records one sustained concurrency cap of a Start Plan request. // Only a run arms a hold; the window is cleared on arming, and a cap that // lands while the hold is on counts toward nothing — the hold's own 429s and // the first caps after it cannot keep re-arming it. function busyCap(key) { if (key != null && narrowed(key)) return if (busyHeld()) return const now = busyHold.now() busyHold.hits.push(now) while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift() if (busyHold.hits.length >= BUSY_N) { busyHold.until = now + BUSY_HOLD busyHold.hits.length = 0 } } // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the // hold stopped locally never reached ZCode, and it says nothing about the // gift's quota. The gift paths (a -Trial pick, free first) read the mark // before they judge the answer spent, so a hold's 429 passes through as the // rate limit it is and arms no minute's rest (11-08: the hold's answer // through a -Trial entry read as "over its quota" with half the free quota // left). const BUSY_HOLD_MARK = "x-magpie-busy-hold" function busyHeldAnswer() { const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000)) const error = { type: "rate_limit_error", message: `ZCode turned away ${BUSY_N} requests in the last minute as too many requests at once, each again when asked a second later. So that ZCode's firewall does not block this network, magpie sends no free Start Plan requests for the next ${wait}s. Wait, run fewer agents or subagents on ZCode at once, or use a GLM Coding Plan model`, } return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait), [BUSY_HOLD_MARK]: "1" }, }) } // busy says a 429 is that in-flight cap: its own code (3008, 3009, 3010), or its // own words when the envelope carries no code. function busy(status, text) { if (status !== 429) return false let b try { b = JSON.parse(text) } catch { return false } if (!b || typeof b !== "object") return false const say = (v) => (v == null || typeof v === "object" ? "" : String(v)) if (BUSY_CODES.has(say(b.code) || say(b.error?.code))) return true return /concurrency limit exceeded/i.test(say(b.msg) + " " + say(b.message) + " " + say(b.error?.message) + " " + say(b.error)) } // busyAnswer is the vendor's cap refusal as the agent reads it: its words, // then what they are and what to do, as noPlanKey says why a key has no plan. function busyAnswer(res, text) { const h = new Headers(res.headers) h.set("content-type", "application/json") let v try { v = JSON.parse(text) } catch {} if (v && typeof v === "object") { const said = first(v.msg, v.message, v.error?.message, typeof v.error === "string" ? v.error : "", `${res.status}`) const code = v.code ?? v.error?.code const head = code != null && !said.includes(String(code)) ? `${said} (${res.status}, code ${code})` : said const message = `${head} — ${BUSY_HINT}` const out = v.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message } } : { ...v, msg: message } return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h }) } return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText} — ${BUSY_HINT}`.trim() } }), { status: res.status, statusText: res.statusText, headers: h, }) } // askBusy asks once and, when the answer is the vendor's in-flight cap // (3008/3009/3010, or its own words), asks again after BUSY_WAITS's waits, // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained // cap, told to onCap once (the firewall hold's count); one the re-ask got // past is not. The plan path's patience, shared with free first's replay, // whose plan has a cap of its own. async function askBusy(u, o, hs, onCap) { let res = await fetch(u, { ...o, headers: hs }) let caps = 0 for (let i = 0; res.status === 429; i++) { const text = await res.text() const cap = busy(429, text) // one request's refusals are one saturation signal, not one per ask if (cap && ++caps === 2) onCap?.() // the hold armed: a request already in flight stops asking too. The // second check catches the asks that capped before the hold armed and // woke from their wait after it. Keying on onCap keeps the coding plan // and free first's replay (no onCap) as they are. if (cap && onCap && busyHeld()) { res = busyHeldAnswer(); break } if (!cap || i >= BUSY_WAITS.length) { res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) break } await sleep(BUSY_WAITS[i]) if (onCap && busyHeld()) { res = busyHeldAnswer(); break } res = await fetch(u, { ...o, headers: hs }) } return res } function model(m, url) { const e = entry(m) return { id: m.id, providerID: PROVIDER, name: m.id, api: { id: m.id, url, npm: "@ai-sdk/anthropic" }, status: "active", cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, limit: e.limit, options: {}, headers: {}, capabilities: { temperature: true, reasoning: e.reasoning, attachment: e.attachment, toolcall: true, input: { text: true, image: !!m.image, audio: false, video: false, pdf: false }, output: { text: true, image: false, audio: false, video: false, pdf: false }, interleaved: false, }, release_date: "", variants: e.variants, } } // ---- the Start Plan's requests ---------------------------------------------------- // zcode.z.ai answers 405 "request has been blocked due to unusual // activity" (code 3012) to a request that doesn't look like ZCode's own // (#343: the agent's system prompt as a fourth block), and to every // request of an account its risk control blocked, ZCode's own app's too // (plugins#348). A Start Plan request goes as the plugin // the plan serves (ARNO's "Freeflow", provider zcode-start) sends it: its // headers (startHeaders) and its body (dress). The texts are prompt.mjs. // START_RESTRICTED is what ZCode's 3012, "request has been blocked due to // unusual activity", means: ZCode's risk control blocked the account // (ZCode's support says so, and ZCode's own app gets the same 405 on such // an account, plugins#348), not that the request was sent wrong. Word for // word magpie's provider.ZCodeRestrictedHint: the gateway reads it as the // account restricted, rests it and asks the group's next member, and the // Routing page says it in the user's language. const START_RESTRICTED = "ZCode's risk control blocked this account for unusual activity (code 3012); it rests, and the group's other providers are used. If the ZCode app fails on this account too, only ZCode support can lift the block" // START_EDGE is what a block page from ZCode's edge firewall (Aliyun's) // means: this network's address, not the account. Word for word magpie's // provider.BlockedHint. const START_EDGE = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy" const EDGE_PAGE = /errors\.aliyun\.com| status >= 400 && (status === 405 || START_REFUSED.test(text)) // edge is the hold a block page puts on this computer's address: zcode.z.ai // (the Start Plan, a gift) is not asked again until edge.until, and its // requests are answered here with the same 405 and START_EDGE, so magpie // still reads them as the network's (provider.EdgeBlocked) and asks the // group's next provider. Every account of this process goes out from the // one address, so the hold is the process's, not an account's. Asking on // while the address is blocked, from every account and every session, only // knocks again on a firewall that is counting (plugins#649: two accounts, // three sessions and their subagents, and ZCode's own app blocked too; a // block in #369 lasted about seven minutes). EDGE_HOLD is short enough that // a user who switched network or proxy waits little for it. const EDGE_HOLD = 3 * 60_000 const edge = { until: 0 } const edgeHeld = () => Date.now() < edge.until function hhmm(t) { const d = new Date(t) return String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0") + ":" + String(d.getSeconds()).padStart(2, "0") } // edgeHeldAnswer is a held request's answer: the block page's status and // meaning, and until when this computer holds off. function edgeHeldAnswer() { const error = { type: "permission_error", message: `405 ${STATUS_TEXT[405]} — ${START_EDGE} (ZCode's Start Plan is not asked again from here until ${hhmm(edge.until)}, plugins#649)` } return new Response(JSON.stringify({ type: "error", error }), { status: 405, statusText: STATUS_TEXT[405], headers: { "content-type": "application/json" } }) } // startBlocked is the refusal's answer: what the vendor said (its status // for a block page), then what it means. A block page is the network's; // anything else, ZCode's JSON 3012 or a bare 405, the account's. function startBlocked(res, text) { const page = EDGE_PAGE.test(text) let said = "" if (!page) { try { const v = JSON.parse(text) said = first(v?.error?.message, typeof v?.error === "string" ? v.error : "", v?.message, v?.msg) const code = v?.code ?? v?.error?.code if (said && code != null && !String(said).includes(String(code))) said = `${said} (${res.status}, code ${code})` } catch {} } said ||= `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText}`.trim() const h = new Headers(res.headers) h.set("content-type", "application/json") const error = { type: "permission_error", message: `${said} — ${page ? START_EDGE : START_RESTRICTED}` } return new Response(JSON.stringify({ type: "error", error }), { status: res.status, statusText: res.statusText, headers: h }) } const osVersion = () => `${process.platform} ${release()} ${arch()}` const osCategory = () => (process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux") function intl() { try { return Intl.DateTimeFormat().resolvedOptions() } catch { return {} } } // startHeaders is a Start Plan request's headers, jwt its key: ZCode's // own (3.16.3's Frn and Vdt in glm/zcode.cjs) and the body's content-type, // and nothing else. The agent's headers never go on: Claude Code's // anthropic-beta, x-app, x-stainless-*, anthropic-dangerous-direct-browser- // access and x-claude-code-session-id reach the plugin through magpie's // gateway, and ZCode sends none of them (no anthropic-beta at all on the // Start Plan: its tool search beta is for coding plans only). Accept and // accept-encoding are left to the HTTP client, as ZCode leaves them to // Node's. function startHeaders(h, jwt) { const out = new Headers() out.set("content-type", h.get("content-type") || "application/json") out.set("Authorization", "Bearer " + jwt) out.set("anthropic-version", "2023-06-01") out.set("HTTP-Referer", ZCODE) out.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81") out.set("X-ZCode-App-Version", APP_VERSION) // the desktop app's agent names itself electron: 3.17.2's // zcode-protocol-entrypoint passes sourceTitle "electron", and a bare // run under app-server says the same (Mvc in glm/zcode.cjs); "cli" is // the zcode command line's alone, which sends no X-Device-Mid on the // app's calls and no desktop prompt texts, as this plugin does out.set("X-Title", "Z Code@electron") out.set("X-Release-Channel", "production") const o = intl() out.set("X-Client-Language", o.locale || "unknown") out.set("X-Client-Timezone", o.timeZone || "unknown") out.set("X-ZCode-Agent", "glm") out.set("X-Platform", platform()) out.set("X-Os-Category", osCategory()) // os.release() alone, as ZCode's buildZCodeSourceHeadersFromContext // has it; the prompt's OS line is osVersion() out.set("X-Os-Version", release()) out.set("x-request-id", uuid()) out.set("x-zcode-session-type", "main") out.set("x-zcode-trace-id", uuid()) // 3.16's createModelRequestAttributionHeaders: what asked the model out.set("x-zcode-query-source", "main_turn") return out } // queryOf is the request's x-query-id, as 3.17.2's // createModelRequestAttributionHeaders (zft in glm/zcode.cjs) sends it: // the user's query, "query_" + a UUID with the prefix cut, the same for // every request of one turn (the tool calls the model makes on the way) // and a new one for the next thing the user says. The agent's turns are // counted: a user message that carries text, not tool results alone, // starts a query. A body that doesn't read gives none, and none is sent. function queryOf(text, session) { let b try { b = JSON.parse(text) } catch { return "" } if (!Array.isArray(b?.messages)) return "" let n = 0 for (const m of b.messages) { if (m?.role !== "user") continue const c = m.content if (typeof c === "string" ? c.trim() : Array.isArray(c) && c.some((x) => x && x.type !== "tool_result")) n++ } return n ? uuidOf("zcode-query\0" + session + "\0" + n) : "" } // Claude Code's tool search, as ZCode's plans take it. Claude Code // (2.1.310) offers a tool named ToolSearch, names its deferred tools in a // system turn, and sends a deferred tool's schema with defer_loading only // once a search loaded it (a tool_reference in a ToolSearch result), with // a DeferredToolPlaceholder that keeps the search on. api.z.ai's // Anthropic endpoint, given a tool named exactly ToolSearch, shows the // model none of the other tools, Bash, Read and Write among them, but // those a tool_reference loaded: a subagent, which hasn't searched, // reports only the deferred tools, and the main turn has to search for // Bash before it can run it (小八 on Discord, 10-24; the beta header // changes nothing, the name alone does). ZCode itself sends no ToolSearch // and no defer_loading. So the search goes as SEARCH_ALIAS, in the tools // and in the turns that called it, the tools Claude Code sent with their // schemas go as ZCode's do, without defer_loading, and the placeholder is // left out; the model's calls to SEARCH_ALIAS come back as ToolSearch // (searchNamed). const SEARCH = "ToolSearch" const SEARCH_ALIAS = "ToolSearchTool" const PLACEHOLDER = "DeferredToolPlaceholder" // searchless is a Messages request body without Claude Code's ToolSearch // name, and whether it had the tool; anything else goes as it is. function searchless(text) { if (typeof text !== "string" || !text.includes(`"${SEARCH}"`)) return { text, renamed: false } let b try { b = JSON.parse(text) } catch { return { text, renamed: false } } if (!b || !Array.isArray(b.tools) || !b.tools.some((t) => t?.name === SEARCH)) return { text, renamed: false } // a tool of the alias's own name keeps it; the search can't then be renamed if (b.tools.some((t) => t?.name === SEARCH_ALIAS)) return { text, renamed: false } b.tools = b.tools .filter((t) => t?.name !== PLACEHOLDER) .map((t) => { if (!t || typeof t !== "object") return t const { defer_loading, ...rest } = t return t.name === SEARCH ? { ...rest, name: SEARCH_ALIAS } : rest }) if (Array.isArray(b.messages)) for (const m of b.messages) if (m?.role === "assistant" && Array.isArray(m.content)) for (const x of m.content) if (x?.type === "tool_use" && x.name === SEARCH) x.name = SEARCH_ALIAS if (b.tool_choice?.type === "tool" && b.tool_choice.name === SEARCH) b.tool_choice.name = SEARCH_ALIAS return { text: JSON.stringify(b), renamed: true } } // searchNamed is an answer to a request searchless renamed, the model's // calls to SEARCH_ALIAS named ToolSearch again, as Claude Code runs them: // a stream's content_block_start events, or a whole message's content. function searchNamed(res) { if (!res.body) return res const type = res.headers.get("content-type") ?? "" const named = (block) => { if (block?.type === "tool_use" && block.name === SEARCH_ALIAS) { block.name = SEARCH return true } return false } const line = (l) => { if (!l.startsWith("data:") || !l.includes(`"${SEARCH_ALIAS}"`)) return l try { const d = JSON.parse(l.slice(5)) return named(d?.content_block) ? "data: " + JSON.stringify(d) : l } catch { return l } } if (type.includes("text/event-stream")) { const dec = new TextDecoder() const enc = new TextEncoder() let held = "" const body = res.body.pipeThrough( new TransformStream({ transform(chunk, ctl) { held += dec.decode(chunk, { stream: true }) const i = held.lastIndexOf("\n") if (i < 0) return ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n"))) held = held.slice(i + 1) }, flush(ctl) { held += dec.decode() if (held) ctl.enqueue(enc.encode(line(held))) }, }), ) return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }) } if (!type.includes("json")) return res return res.text().then((text) => { let out = text if (text.includes(`"${SEARCH_ALIAS}"`)) { try { const v = JSON.parse(text) if (Array.isArray(v?.content) && v.content.map(named).some(Boolean)) out = JSON.stringify(v) } catch {} } return new Response(out, { status: res.status, statusText: res.statusText, headers: res.headers }) }) } // startURL is a Start Plan request's URL without the query the agent put // on it: Claude Code asks /v1/messages?beta=true, which magpie passes on, // and ZCode asks /v1/messages alone. function startURL(url) { const i = url.indexOf("?") return i < 0 ? url : url.slice(0, i) } // WORK_DIR and WORK_GIT are where magpie tells a plugin's fetch the agent // that asked works: the folder, percent-encoded, and "yes" or "no" for a // git repository, each left off when magpie doesn't know it (magpie's // provider.WorkDirHeader and WorkGitHeader). They are for the plugin, not // the vendor. const WORK_DIR = "x-magpie-work-dir" const WORK_GIT = "x-magpie-work-git" // workPlace takes WORK_DIR and WORK_GIT off h: {dir?, git?}, what magpie // said of where the agent works. function workPlace(h) { const place = {} const dir = h.get(WORK_DIR) if (dir) { try { place.dir = decodeURIComponent(dir) } catch {} } const git = h.get(WORK_GIT) if (place.dir && (git === "yes" || git === "no")) place.git = git h.delete(WORK_DIR) h.delete(WORK_GIT) return place } // environment is the prompt's environment section, as ZCode 3.17.2's // env-info.ts renders it, bullets one space in. The plugin runs in magpie, // not in the agent's folder: the working directory and whether it is a git // repository are the agent's, as magpie tells them (place), and each is // left out when it isn't told rather than said as magpie's own (#86). The // agent's shell isn't known here either, so it isn't said; the platform // and OS version are this computer's, as ZCode's X-Os-* headers say them. function environment(place = {}) { const e = PROMPT.environment const lines = [e.heading, e.invokedLine] if (place.dir) { lines.push(` - ${e.cwdLabel}: ${place.dir}`) if (place.git) lines.push(` - ${e.gitLabel}: ${place.git === "yes" ? e.gitYes : e.gitNo}`) } lines.push(` - ${e.platformLabel}: ${process.platform}`, ` - ${e.osVersionLabel}: ${osVersion()}`) lines.push(` - ${e.untrustedNote}`) return lines.join("\n") } // today is the local date, YYYY-MM-DD. function today(now = new Date()) { const p = (n) => String(n).padStart(2, "0") return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}` } // contextPrefix is the user turn ZCode puts before the agent's: the day in // a , the tags hugging the text, as 3.17.2's current-date // section says it alone. function contextPrefix() { const c = PROMPT.context return { role: "user", content: [{ type: "text", text: "" + c.currentDateLine.replace("{date}", today()) + "" }] } } // dress is a Messages request body as ZCode sends it: ZCode's three cached // system blocks and no more, the agent's own system text at the end of the // third (#343); the context // prefix as the first turn; no cache mark in the turns but on the last // block of the last; none on the tools; metadata.user_id naming the // sign-in's device. site names the powered-by line's provider, place where // the agent works (workPlace). A body that isn't a Messages request goes as // it is. function dress(text, site, device, place, session) { if (typeof text !== "string" || !text.includes("messages")) return text let b try { b = JSON.parse(text) } catch { return text } if (!b || typeof b !== "object" || !Array.isArray(b.messages)) return text const cached = (t) => ({ type: "text", text: t, cache_control: { type: "ephemeral" } }) const provider = site === "bigmodel" ? "bigmodel-api" : "zai-api" const model = typeof b.model === "string" ? b.model : "" // The agent's own system text joins the third block, as ZCode's // ContextBuilder (3.17.2, core/src/context/builder.ts // assembleSystemMessages) joins every dynamic system section, an added // one too, with "\n\n" into that one block: ZCode never sends more than // three. zcode.z.ai turns a fourth block away with 405/3012 (#343), and // the first two must stay byte for byte ZCode's. The third's own // sections are 3.17.2's dynamic ones — the unheaded behavior paragraphs, // the slash-skill guidance when the request has a Skill tool, the // environment and the model, then context management. const own = [] if (typeof b.system === "string") { if (b.system.trim()) own.push(b.system) } else if (Array.isArray(b.system)) { for (const x of b.system) if (x?.type === "text" && typeof x.text === "string" && x.text.trim()) own.push(x.text) } const skill = Array.isArray(b.tools) && b.tools.some((t) => t && typeof t === "object" && t.name === "Skill") const dynamic = [ PROMPT.dynamicBehavior, ...(skill ? [PROMPT.sessionGuidance] : []), environment(place), ...(model ? [PROMPT.poweredBy.replace("{provider}", provider).replace("{model}", model)] : []), PROMPT.contextManagement, ...own, ] b.system = [cached(PROMPT.cliPrefix), cached(PROMPT.stableSections.join("\n\n")), cached("\n\n" + dynamic.join("\n\n"))] b.messages = [contextPrefix(), ...b.messages] let last = null for (const m of b.messages) { if (!m || m.role === "system") continue last = m if (Array.isArray(m.content)) for (const x of m.content) if (x && typeof x === "object") delete x.cache_control } if (last && typeof last.content === "string") last.content = [cached(last.content)] else if (last && Array.isArray(last.content) && last.content.length) { const x = last.content[last.content.length - 1] if (x && typeof x === "object" && !x.cache_control) x.cache_control = { type: "ephemeral" } } if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {} b.metadata = { ...meta, user_id: userIdOf(device, session) } return JSON.stringify(b) } // userIdOf is metadata.user_id as ZCode's client (3.14.3, glm/zcode.cjs // MLs and vWr) puts it on every Anthropic-format request, a coding plan's // too: the machine's device id, no account uuid. The plan's endpoint keeps // a prompt cache on the machine it picks by it, so a request without it // lands anywhere and its cache is mostly missed (#387). Its session_id is // the request's x-session-id (sessionOf), as ZCode's is. const userIdOf = (device, session = "") => JSON.stringify({ device_id: device, account_uuid: "", session_id: session }) // marked is a coding plan's Messages request body with metadata.user_id // as ZCode sends it, when the agent sent none of its own. Anything else, // a body that isn't a Messages request among them, goes as it is. function marked(text, device, session) { if (typeof text !== "string" || !device || !text.includes("messages")) return text let b try { b = JSON.parse(text) } catch { return text } if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {} if (typeof meta.user_id === "string" && meta.user_id.trim()) return text b.metadata = { ...meta, user_id: userIdOf(device, session) } return JSON.stringify(b) } // sessionOf is the x-session-id a request goes with, as ZCode's client // (3.14.3, glm/zcode.cjs xst and Tst) sends it: a bare UUID, the same on // every turn of a conversation. BigModel keeps a prompt's cache for the // requests that name the same session and seldom for those that name none // (#387). The agent's session (chat.headers below) goes as it is when it is // a UUID, else as a UUID made from it, so the vendor sees only ZCode's // format, never magpie's or another agent's; with none, a UUID made from // the device. const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i function sessionOf(id, device) { const own = typeof id === "string" ? id.trim() : "" if (UUID.test(own)) return own.toLowerCase() return uuidOf(own ? "zcode-session\0" + own : "zcode-session-device\0" + (device ?? "")) } // ---- the plugin ------------------------------------------------------------------ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { const log = (message) => { try { client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } }) } catch {} } // freeFirst reads the option from the provider config's options first, // and from the plugin's own (magpie's Plugins › Options) when the // provider carries no freeFirst of its own. It is on unless one of them // says false: a gift ZCode hands out (each weekend, sgfvdsg86265 on X) // lapses unused behind an agent that asks the plain model, and every // failure of the gift is answered from the plan. magpie's switch in the // provider's editor (FREE_FIRST, auth.options below) turns it off too; // it is on by default, so a JSON freeFirst: false a user wrote before // the switch existed keeps it off. A key magpie doesn't report (an older // magpie, OpenCode) leaves it as the JSON says. const freeFirst = (providerOptions) => magpie?.options?.(PROVIDER)?.[FREE_FIRST] !== false && (providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst !== false : options?.freeFirst !== false) const oauth = (site) => ({ type: "oauth", label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`, authorize: () => authorize(site, log), }) return { // the agent's session, which magpie tells the plugins here and not // in the request, goes on as x-session-id (sessionOf) "chat.headers": async (input, output) => { const provider = input?.model?.providerID ?? input?.provider?.info?.id if (provider !== PROVIDER) return const id = input?.sessionID if (typeof id === "string" && id.trim()) output.headers["x-session-id"] = sessionOf(id) }, config: async (cfg) => { cfg.provider ??= {} const was = cfg.provider[PROVIDER] ?? {} cfg.provider[PROVIDER] = { name: "ZCode", npm: "@ai-sdk/anthropic", api: ZAI_BASE + "/v1", ...was, models: { ...Object.fromEntries(MODELS.map((m) => [m.id, entry(m)])), ...(was.models ?? {}) }, } }, provider: { id: PROVIDER, // the account's plan's models, as ZCode's config lists them now async models(provider, { auth } = {}) { // a ZCode 3.16 sign-in holds only where its key is: read the key // first, as a request does, or plansOf takes the keyless sign-in // for a Start Plan one and lists that plan's models (#439). A key // that can't be read throws, and magpie keeps the list it had. const s = await located(stateOf(auth)) if (!s) return provider.models const { start, gift: known } = await plansOf(s).catch(() => ({ start: false, gift: null })) const gift = start ? await startPlan(s.jwt, s.device).catch(() => null) : known const base = start ? START_BASE : s.base const cfg = await zcodeConfig().catch(() => null) let ms = modelsOf(cfg, planID(base)) // ZCode's config can't be had: its table stands in, and magpie keeps // the list it was told last, as the built-in keeps the one it fetched last const fell = !ms.length if (fell) ms = start ? START_MODELS : MODELS // a gift-only account serves what its balance names, as ZCode // offers it (resolveStartPlanBalanceAvailability): the Start // Plan's config models the balance lacks would only be refused // (young02036). A balance naming none leaves the config's list. if (start && giftNames(gift).length) ms = ms.filter((m) => giftNames(gift).some((x) => x.toLowerCase() === m.id.toLowerCase())) const url = s.base + "/v1" const out = Object.fromEntries(ms.map((m) => [m.id, model(m, url)])) const details = [...ms, ...modelsOf(cfg, planID(START_BASE)), ...modelsOf(cfg, planID(ZAI_BASE)), ...MODELS] const about = (raw) => details.find((m) => m.id.toLowerCase() === raw.toLowerCase()) ?? { efforts: [] } const has = new Set(Object.keys(out).map((id) => id.toLowerCase())) for (const raw of giftNames(gift)) { // a gift-only account's models are its gift's, by their own // names, as ZCode lists them (its Start Plan's GLM-5.3, which the // plan's config leaves out): every request of it goes to the gift // anyway, and the card counts them by that name too (#1261) if (start && !has.has(raw.toLowerCase())) { const plain = about(raw).id ?? raw has.add(raw.toLowerCase()) out[plain] = model({ ...about(raw), id: plain }, url) } const id = giftID(raw) if (out[id]) continue // a trial entry is the gift's, which costs nothing: marked free, // so magpie reads a GLM Coding Plan model's weekly or monthly // limit (1310) as that model's, and the account's trial entries, // spent from the gift's own buckets, are still asked (plugins#438) out[id] = { ...model({ ...about(raw), id }, url), free: true } } // a fallback tells magpie to keep the list it was told last, which // predates the gift read just made: an account whose gift lists // trial entries is told this list, so ZCode's config out of reach // (a remote box that can't get its CDN) never hides them if (fell && !giftNames(gift).length) out[Symbol.for("magpie.fellBack")] = true return out }, }, auth: { provider: PROVIDER, // a plan serves one account a few requests at a time: magpie's own // field, so its queue spaces what the agents ask for before the vendor // sees it. For the coding plan this is a default, not a cap the plugin // enforces — its cap follows its tier (Max > Pro > Lite) and the time // of day, and a user who knows theirs can raise this on the account. // The Start Plan has the plugin's own gate below it (startGate) maxConcurrency: DEFAULT_CONCURRENCY, // how many accounts take requests at once, the others in reserve // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all maxAccounts: DEFAULT_ACCOUNTS, // magpie's own switches (OpenCode never reads auth.options), read at // each request through input.magpie options: [ { key: FREE_FIRST, label: "Free quota first", description: "When on, the plain GLM models spend ZCode's free Start Plan quota (the -Trial entries' quota) before the GLM Coding Plan, and go to the plan when it is spent or refused. Off: only the -Trial entries use it. freeFirst: false in the options JSON turns it off too.", labels: { zh: "优先用免费额度", "zh-TW": "優先用免費額度", ja: "無料枠を優先", de: "Gratis-Kontingent zuerst" }, descriptions: { zh: "开启后,普通的 GLM 模型先用 ZCode 的免费 Start Plan 额度(即 -Trial 条目的额度),用完或被拒时再用 GLM Coding Plan。关闭后只有 -Trial 条目会用它。选项 JSON 里的 freeFirst: false 也会关闭它。", "zh-TW": "開啟後,一般的 GLM 模型先用 ZCode 的免費 Start Plan 額度(即 -Trial 項目的額度),用完或被拒時再用 GLM Coding Plan。關閉後只有 -Trial 項目會用它。選項 JSON 裡的 freeFirst: false 也會關閉它。", ja: "オンにすると、通常の GLM モデルは GLM Coding Plan より先に ZCode の無料 Start Plan 枠(-Trial 項目の枠)を使い、使い切るか拒否されるとプランに戻ります。オフでは -Trial 項目だけが使います。オプション JSON の freeFirst: false でもオフになります。", de: "Ist dies an, nutzen die normalen GLM-Modelle zuerst ZCodes freies Start-Plan-Kontingent (das der -Trial-Einträge) und erst danach den GLM Coding Plan. Aus: nur die -Trial-Einträge nutzen es. freeFirst: false im Optionen-JSON schaltet es auch aus.", }, default: true, }, ], async loader(getAuth, provider) { const s0 = stateOf(await getAuth()) if (!s0) return {} const id = provider?.id ?? PROVIDER return { baseURL: s0.base + "/v1", apiKey: s0.key || "zcode", // the fetch below puts the real one on async fetch(input, init) { // a Start Plan request holds one of its account's slots // (startSlot) until its answer has been read to the end const own = {} try { return released(await serve(input, init, own), own.slot, own.signal) } catch (e) { own.slot?.release() throw e } }, } async function serve(input, init, own) { const auth = await getAuth() const s = await located(stateOf(auth)) if (!s) throw new Error("not signed in to ZCode") // the account a Start Plan slot belongs to: its user id, which a // renewed session keeps, before the key or session itself const gateKey = String(auth?.uid || auth?.accountId || holdKey(s)) let url = input instanceof Request ? input.url : String(input) const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init } const { start: alone, gift: known } = await plansOf(s) let gift = known let key = s.key if (isTeam(s) && !key) { key = await teamKey(s) if (auth?.type === "oauth") { const next = { ...auth, refresh: JSON.stringify({ ...s, key }), access: key } await client?.auth?.set?.({ path: { id }, body: next }).catch?.(() => {}) } } // a dual account's body is read ahead of sending, so a gift that // says it is spent can spend nothing and replay what was asked for let start = alone let orig, forcedGift = false, freeGift = false let asked = "" let renamed = false const done = (res) => (renamed ? searchNamed(res) : res) if (opts.body != null) { orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text() delete opts.duplex // Claude Code's tool search goes under another name, or // ZCode's plans show the model no other tool (searchless) const plain = searchless(orig) if (plain.renamed) { orig = opts.body = plain.text renamed = true } let m = modelOf(orig) asked = m if (m.toLowerCase().endsWith("-trial")) { gift ??= await startPlan(s.jwt, s.device).catch(() => null) const raw = giftModel(gift, m) const available = raw && giftUsable(s, gift, raw) if (!available) { const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}` } return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } })) } orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) m = raw forcedGift = true } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) { // free first: the plain model spends the account's own live // gift before it spends the coding plan, under the name the // gift lists. The gift is the route's cache alone (a failed // read cached its why), so a gift that cannot be read keeps // the request on the plan with no read per request; a // gift-only account is already on the gift and is left as // it was. A refusal past this check is replayed on the plan // in the same request (replayOnPlan below). A busy hold (or // a block page) keeps the plain model off the gift: the // coding plan is never held, and free first must not move // the request onto a route the hold answers 429 without // asking. Nor onto a gift whose slots are all taken // (startFull): the plan serves it now, the gift only after // the others. const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase()) orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) m = raw freeGift = true } start = alone || forcedGift || freeGift } const swap = (base) => { for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) { if (url.startsWith(b)) { url = base + url.slice(b.length) break } } } let h = new Headers(opts.headers) const askedUrl = url const place = workPlace(h) const sid = sessionOf(h.get("x-session-id"), s.device) // restModel is free first's gift turning this model away: the // model rests a minute and the route is dropped, so the requests // behind it re-read the balance and go straight to the plan. A // quota answer rests it in blocked, which a -Trial entry obeys // too; any other refusal (spent false) in sidelined, which only // free first reads. const restModel = (spent) => { rest(spent ? blocked : sidelined, s.key + "\0" + s.jwt + "\0" + asked.toLowerCase()) routes.delete(s.key + "\0" + s.jwt) } // replayOnPlan is free first's answer to a gift that refused // what its own balance read had promised: the model as the // agent sent it, the plan's headers, the plan's own patience // (askBusy). const replayOnPlan = async () => { // the gift is done with: its slot goes to the next request own.slot?.release() let u = askedUrl for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) { if (u.startsWith(b)) { u = s.base + u.slice(b.length) break } } const h2 = new Headers(opts.headers) workPlace(h2) h2.set("x-session-id", sid) h2.delete("authorization") h2.set("x-api-key", key) h2.set("Authorization", "Bearer " + key) h2.delete("content-length") opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid) delete opts.duplex return askBusy(u, opts, h2) } // a block page held this computer off zcode.z.ai (edge): the // Start Plan and a picked gift are answered here; free first // already left the gift for the plan. Checked before the busy // hold: an IP the firewall already refused keeps that behavior // (the 405 magpie reads as the network's), hold or no hold. if (start && edgeHeld()) return kept(edgeHeldAnswer()) // a run of busy caps held this computer off zcode.z.ai before the // edge firewall could block the IP: a held request is answered // here, with a 429 magpie still reads as a rate limit if (start && busyHeld()) return kept(busyHeldAnswer()) // the account's Start Plan slots (startGate): a request past them // waits here for one rather than being sent to be refused if (start) { own.slot = await startSlot(gateKey, opts.signal) own.signal = opts.signal if (!own.slot) return kept(startQueueAnswer(gateKey)) // a hold may have armed while it waited if (edgeHeld()) return kept(edgeHeldAnswer()) if (busyHeld()) return kept(busyHeldAnswer()) } if (start) { if (jwtExpired(s.jwt)) throw new Error(EXPIRED) if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again") swap(START_BASE) // the Start Plan is served only to what looks like ZCode's own request url = startURL(url) h = startHeaders(h, s.jwt) h.set("x-session-id", sid) if (opts.body != null) { const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()) opts.body = dress(text, s.site, s.device, place, sid) const q = queryOf(text, sid) if (q) h.set("x-query-id", q) delete opts.duplex h.delete("content-length") } } else { if (!key) throw new Error("ZCode's sign-in has no key; sign in again") swap(s.base) // a Messages request names the device, as ZCode's does (#387); // count_tokens and other paths ZCode never sends go as they are if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) { const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text() const next = marked(text, s.device, sid) if (next !== text) h.delete("content-length") opts.body = next delete opts.duplex } if (renamed) h.delete("content-length") h.set("x-session-id", sid) h.delete("authorization") h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) } // a refusal that is the account's or the model's own in-flight // cap is asked again a moment later (see the plan's concurrency): // magpie sends every agent's and every session's requests of this // computer through this one process, and its queue spaces them by // the number declared above let res try { // Only Start Plan caps count toward the firewall hold: the // coding plan is served by another host and was never refused // with the IP's 405. res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined) } catch (e) { // free first moved the request onto the gift, so a gift that // cannot be asked at all — the network, the host — is answered // from the plan; the route read is dropped, so the next // request learns whether the host is back. A caller's abort // stays an abort. if (!freeGift || opts.signal?.aborted || e?.name === "AbortError") throw e routes.delete(s.key + "\0" + s.jwt) res = await replayOnPlan() } // the Start Plan turning the request away says what to do about // it: the account blocked, or the network if (start && res.status >= 400) { const text = await res.text() if (startRefused(res.status, text)) { // a key account sent to the Start Plan (its plan list read // none) reads its plans again on the next request, so a // coding plan that is there after all is used (#369) // a block page holds every request off zcode.z.ai a while if (EDGE_PAGE.test(text)) edge.until = Date.now() + EDGE_HOLD if (freeGift) { restModel(false) return done(kept(await spentSaid(await replayOnPlan()))) } if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt) return kept(startBlocked(res, text)) } res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) } // a key with no plan behind it: what Z.ai said, and why a // ZCode gift plan can't be had with a key (NO_PLAN_KEY) if (!start && !s.jwt && res.status >= 400) { const text = await res.text() const why = noPlanKey(res, text) if (why) return done(kept(why)) res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) } // a trial entry's gift answer that can't serve the request is // the agent's answer, not the coding plan's: the user picked the // gift, so a spent bucket says 429 (its quota error inside a 200 // among them) and anything else goes on as it came. A quota // answer keeps that model off the gift for a minute, so a rate // limit is not knocked twice. A stream's body is never read here. if (start && forcedGift) { const json = (res.headers.get("content-type") ?? "").includes("application/json") if (res.status >= 400 || json) { const text = await res.text() // the hold's own answer (BUSY_HOLD_MARK) is a rate limit the // gift never said: it passes through as it came and arms // no rest const held = res.headers.get(BUSY_HOLD_MARK) === "1" const spent = !held && spentUp(text, res.status) if (!spent && res.status < 400) return done(kept(res, text)) if (spent) rest(blocked, s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase()) return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text)) } } // free first's gift answer: the choice was the plugin's, so the // plan answers what the gift would fail — a spent bucket and a // refusal like any other 4xx or 5xx among them, the gift's own // waited-out busy cap included, since the plan's cap is its own. // A spent answer or a block page rests the model a minute and // drops the route read; a 401/403 drops the read alone, so the // next request learns whether the session is gone. Anything // else — a 200 carrying the answer — goes on as it came. A // stream's body is never read here. else if (start && freeGift) { const json = (res.headers.get("content-type") ?? "").includes("application/json") if (res.status >= 400 || json) { const text = await res.text() const cap = busy(res.status, text) // the hold's own answer is no spent answer either (see the // -Trial path above) const spent = !cap && res.headers.get(BUSY_HOLD_MARK) !== "1" && spentUp(text, res.status) if (spent) { restModel(true) return done(kept(await spentSaid(await replayOnPlan()))) } if (res.status >= 400) { if (!cap && (res.status === 401 || res.status === 403)) routes.delete(s.key + "\0" + s.jwt) return done(kept(await spentSaid(await replayOnPlan()))) } return done(kept(res, text)) } } // the plan's answer goes on as it came, the account kept: the // built-in never marked a ZCode account lapsed nor cleared one. // A spent bucket's 200 says 429 (spentSaid), as a trial // entry's does, so magpie rests the model, not the account return done(kept(await spentSaid(res))) } }, // the plan's allowance, as magpie's built-in showed it. Each read // keeps the sign-in (signIn): the built-in's marked no account lapsed, // its expired Start Plan sign-in among them, and cleared none async usage(getAuth, provider) { const auth = await getAuth() const s = stateOf(auth) if (!s) return { error: "not signed in", signIn: "kept" } try { await located(s) } catch (e) { return { error: e.message, signIn: "kept" } } // every card starts from the plan the sign-in saved, as magpie's // built-in did: a reply without a level, a team detail that // failed or an error keeps it const saved = (out) => { const plan = s.plan || auth?.plan if (plan && !out.plan) out.plan = plan // MCP reads as a footnote: its window goes last on the card if (Array.isArray(out.windows) && out.windows.some((w) => w.name === "MCP · Month")) out.windows = [...out.windows.filter((w) => w.name !== "MCP · Month"), ...out.windows.filter((w) => w.name === "MCP · Month")] out.signIn = "kept" return out } try { // a card read is a fresh read: the route is read again with it, // so a plan bought, a gift claimed or a plan lapsed reaches the // requests when the card shows it, not ten minutes later (#379) routes.delete(s.key + "\0" + s.jwt) const { start, gift } = await plansOf(s) let card if (isTeam(s)) { let key = s.key if (!key) { key = await teamKey(s) if (auth?.type === "oauth") { const next = { ...auth, refresh: JSON.stringify({ ...s, key }), access: key } await client?.auth?.set?.({ path: { id: provider?.id ?? PROVIDER }, body: next }).catch?.(() => {}) } } const team = await teamUsage(s, key) card = saved(gift || giftReadable(s) ? await dualUsage(s, team) : team) } else card = saved(start ? await startUsage(s) : gift || giftReadable(s) ? await dualUsage(s) : await codingUsage(s)) // a gift plan ZCode holds for the account but has not put on it: // named on the card, claimed in the ZCode app (its claim needs // the app's captcha attestation, see claimHint). A card that is // an error keeps its error and asks nothing if (!card.error) { const hint = await claimHint(s) if (hint) card.windows = [...(card.windows ?? []), hint] // a key, or a ZCode session that ran out: no gift read, so no // -Trial models, said on the card rather than left out unsaid const need = start ? null : giftSignIn(s, auth?.type === "api") if (need) card.windows = [...(card.windows ?? []), need] } return card } catch (e) { return saved({ error: e?.message ?? String(e) }) } }, // the daily claim of ZCode's gift plans (#503): magpie runs it once a // day per account while Settings' Daily check-in has ZCode on (off // until the user turns it on), and its Check in now button asks // right away. See claimDaily. async checkin(getAuth) { try { return await claimDaily(stateOf(await getAuth())) } catch (e) { return { outcome: "failed", message: e?.message ?? String(e) } } }, methods: [ oauth("zai"), oauth("bigmodel"), // a team's plan beside the account's own (#285): the sign-ins above // take the account's own plan when it has one { type: "oauth", label: "ZCode: a team's GLM Coding Plan", prompts: [ { type: "select", key: "site", message: "Where is the team's plan?", options: [ { label: "Z.ai", value: "zai", hint: "z.ai" }, { label: "BigModel (智谱)", value: "bigmodel", hint: "bigmodel.cn" }, ], }, ], authorize: (inputs) => authorize(inputs?.site === "bigmodel" ? "bigmodel" : "zai", log, true), }, { type: "oauth", label: "ZCode app's sign-in", authorize: async () => asZCode() }, { type: "api", label: "GLM Coding Plan API key", prompts: [ { type: "select", key: "site", message: "Where is the key from?", options: [ { label: "Z.ai", value: "zai", hint: "api.z.ai" }, { label: "BigModel (智谱)", value: "bigmodel", hint: "open.bigmodel.cn" }, ], }, ], }, ], }, } } // for tests // config sets what zcodeConfig has read, for tests: null is ZCode's config // out of reach, undefined forgets it const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() }) export const _internal = { edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }