zcode 0.1.1: usage shows as magpie's built-in did — plan, period, windows and what they count, balance, team resets
This commit is contained in:
+297
-1
@@ -51,6 +51,12 @@ const uuid = () => crypto.randomUUID()
|
||||
const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list)
|
||||
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)
|
||||
@@ -75,7 +81,7 @@ async function call(method, url, { auth, body, headers, device, signal } = {}) {
|
||||
const code = env?.code == null ? "" : String(env.code)
|
||||
if (!res.ok) {
|
||||
if (env?.msg) throw new ZError(code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`, res.status)
|
||||
throw new ZError(`${res.status} ${res.statusText}`.trim(), res.status)
|
||||
throw new ZError(STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim(), res.status)
|
||||
}
|
||||
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)
|
||||
@@ -236,6 +242,270 @@ async function teamKey(s) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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.
|
||||
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 (isNum(x?.percentage)) w.used = x.percentage
|
||||
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.display = `${compact(used)} / ${compact(total)}`
|
||||
} else if (isNum(x.currentValue)) {
|
||||
if (!isNum(x.percentage)) w.used = (100 * x.currentValue) / 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)
|
||||
try {
|
||||
Object.assign(out, termOf(await call("GET", root + "/api/biz/subscription/list", { auth: s.key })))
|
||||
} catch {}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// startUsage is the Start Plan's allowance: a window for each of its
|
||||
// buckets, a model's tokens for the day or for the plan's time. A plan
|
||||
// still "active" past its end is over, and its buckets are left out.
|
||||
async function startUsage(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 : x.plan_id === 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
|
||||
})
|
||||
|
||||
let active = null
|
||||
for (const p of plans) {
|
||||
if (p.status.trim().toLowerCase() !== "active") continue
|
||||
const id = p.plan_id.trim().toLowerCase(), n = str(p.name).trim().toLowerCase()
|
||||
const isStart = (x) => x.includes("start-plan") || x.includes("start plan")
|
||||
if ((id || n) && !isStart(id) && !isStart(n)) continue
|
||||
const end = startNum(p.ends_at)
|
||||
active = { name: first(str(p.name), "Start Plan"), until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" }
|
||||
break
|
||||
}
|
||||
if (!active) return { error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" }
|
||||
const out = { plan: active.name, windows: [] }
|
||||
if (active.until) Object.assign(out, { until: active.until, renew: "off" })
|
||||
for (const x of balances) {
|
||||
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 = (Array.isArray(x.capabilities) ? x.capabilities : [])
|
||||
.map((c) => String(c ?? "").trim().replace(/^model:/, "").trim()).filter(Boolean)
|
||||
const w = { name: first(str(x.show_name), models.join(", "), "Credits"), used: 0 }
|
||||
if (used === undefined) used = total !== undefined && left !== undefined ? total - left : 0
|
||||
if (total > 0) {
|
||||
w.used = (100 * used) / total
|
||||
w.display = `${compact(used)} / ${compact(total)}`
|
||||
}
|
||||
const exp = startNum(x.expires_at)
|
||||
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
|
||||
}
|
||||
|
||||
// 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: those of customer-package-reset/list still available.
|
||||
// null when it can't be told or there are none.
|
||||
async function teamResets(root, auth, headers) {
|
||||
let d
|
||||
try {
|
||||
d = (await call("GET", root + "/api/biz/customer-package-reset/list?targetType=TEAM", { auth, headers })) ?? {}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
let until = 0
|
||||
const count = (rs) => {
|
||||
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
|
||||
}
|
||||
return n
|
||||
}
|
||||
const fiveHour = count(d.fiveHourResets)
|
||||
const weekly = count(d.weekResets)
|
||||
if (fiveHour + weekly === 0) return null
|
||||
const r = { count: fiveHour + weekly, byWindow: true, fiveHour, weekly }
|
||||
if (until) r.until = new Date(until).toISOString()
|
||||
return r
|
||||
}
|
||||
|
||||
// ---- signing in ------------------------------------------------------------------
|
||||
|
||||
// bizAuth is the Authorization a sign-in gives the business API: Z.ai's
|
||||
@@ -687,6 +957,29 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
},
|
||||
}
|
||||
},
|
||||
// the plan's allowance, as magpie's built-in showed it
|
||||
async usage(getAuth, provider) {
|
||||
const auth = await getAuth()
|
||||
const s = stateOf(auth)
|
||||
if (!s) return { error: "not signed in" }
|
||||
try {
|
||||
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?.(() => {})
|
||||
}
|
||||
}
|
||||
return await teamUsage(s, key)
|
||||
}
|
||||
if (await onStart(s)) return await startUsage(s)
|
||||
return await codingUsage(s)
|
||||
} catch (e) {
|
||||
return { error: e?.message ?? String(e) }
|
||||
}
|
||||
},
|
||||
methods: [
|
||||
oauth("zai"),
|
||||
oauth("bigmodel"),
|
||||
@@ -709,3 +1002,6 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { limitWindows, termOf, startUsage, routes, teamKeys }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zcode-auth",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
// auth.usage tells what magpie's built-in ZCode usage told for the same
|
||||
// answers (internal/provider/zcode_test.go TestZCodeAccounts,
|
||||
// zcode_start_test.go TestZCodeStartPlanOwnAccount, zcode_team_test.go).
|
||||
import { test, expect, beforeAll, beforeEach } from "bun:test"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { realpathSync } from "node:fs"
|
||||
|
||||
let ZCodeAuthPlugin, _internal
|
||||
beforeAll(async () => {
|
||||
// Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so
|
||||
// no real sign-in is ever read
|
||||
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
|
||||
;({ ZCodeAuthPlugin, _internal } = await import("./index.mjs"))
|
||||
})
|
||||
// nothing leaves the machine
|
||||
const offline = async () => { throw new Error("no network in tests") }
|
||||
beforeEach(() => {
|
||||
globalThis.fetch = offline
|
||||
_internal.routes.clear()
|
||||
_internal.teamKeys.clear()
|
||||
})
|
||||
|
||||
const ok = (data) => new Response(JSON.stringify({ code: 0, data }))
|
||||
function serve(route) {
|
||||
const calls = []
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
const u = new URL(String(url))
|
||||
const c = { url: u, method: init.method ?? "GET", headers: init.headers ?? {}, body: init.body }
|
||||
calls.push(c)
|
||||
return (await route(c)) ?? new Response("", { status: 404 })
|
||||
}
|
||||
return calls
|
||||
}
|
||||
const oauth = (state) => ({ type: "oauth", access: state.key ?? state.jwt ?? "", refresh: JSON.stringify(state), expires: 0 })
|
||||
async function usage(auth, sets = []) {
|
||||
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async (x) => sets.push(x) } } })
|
||||
return hooks.auth.usage(async () => auth, { id: "zcode" })
|
||||
}
|
||||
const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
|
||||
|
||||
test("a Coding Plan's five hours and week", async () => {
|
||||
const reset = Date.now() + 3600_000
|
||||
const calls = serve(({ url, headers }) => {
|
||||
if (headers.Authorization !== "two.secret2") return new Response("", { status: 401 })
|
||||
if (url.pathname === "/api/biz/subscription/list") return ok([{ productName: "GLM Coding Pro", status: "VALID" }])
|
||||
if (url.pathname === "/api/monitor/usage/quota/limit")
|
||||
return ok({ level: "pro", limits: [
|
||||
{ type: "CREDIT_LIMIT", unit: 3, number: 5, usage: 2000, remaining: 1500, percentage: 25, nextResetTime: reset },
|
||||
{ type: "CREDIT_LIMIT", unit: 6, number: 1, usage: 10000, remaining: 9000, percentage: 10, nextResetTime: reset },
|
||||
] })
|
||||
})
|
||||
expect(await usage(oauth({ site: "zai", key: "two.secret2" }))).toEqual({
|
||||
plan: "GLM Coding Pro",
|
||||
windows: [
|
||||
{ name: "5 hours", used: 25, display: "500 / 2000", resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
|
||||
{ name: "Weekly", used: 10, display: "1000 / 10000", resetsAt: new Date(reset).toISOString(), span: 7 * 86400 },
|
||||
],
|
||||
})
|
||||
expect(calls.every((c) => c.url.origin === "https://api.z.ai")).toBe(true)
|
||||
// an API key, BigModel's, is asked on its own site
|
||||
const bm = serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : ok([])))
|
||||
expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ windows: [] })
|
||||
expect(bm[0].url.origin).toBe("https://open.bigmodel.cn")
|
||||
})
|
||||
|
||||
test("windows, names and terms as Go reads them", () => {
|
||||
const ws = _internal.limitWindows({ limits: [
|
||||
{ unit: 3, usage: 1000, currentValue: 420, percentage: 42 }, // the percentage stands
|
||||
{ unit: 6, usage: 800, currentValue: 200 }, // none: from the current value
|
||||
{ unit: 1, number: 30, percentage: 7.5 },
|
||||
{ unit: 4, number: 3 },
|
||||
{ unit: 5, number: 1, usage: 0, remaining: 5 },
|
||||
{ unit: 0 },
|
||||
] })
|
||||
expect(ws).toEqual([
|
||||
{ name: "5 hours", used: 42, display: "420 / 1000", span: 18000 },
|
||||
{ name: "Weekly", used: 25, display: "200 / 800", span: 604800 },
|
||||
{ name: "0 hours", used: 7.5, span: 1800 },
|
||||
{ name: "3 days", used: 0, span: 3 * 86400 },
|
||||
{ name: "Monthly", used: 0, span: 30 * 86400 },
|
||||
{ name: "Credits", used: 0 },
|
||||
])
|
||||
// Beijing times: the next renewal, auto or not; else the valid span's end
|
||||
expect(_internal.termOf([{ status: "EXPIRED", nextRenewTime: "2026-01-01 00:00:00" },
|
||||
{ status: "VALID", autoRenew: 1, nextRenewTime: "2026-10-18 12:00:00" }]))
|
||||
.toEqual({ until: "2026-10-18T04:00:00.000Z", renew: "auto" })
|
||||
expect(_internal.termOf([{ status: "valid", autoRenew: false, valid: "2026-09-18 12:00:00-2026-10-18 12:00:00" }]))
|
||||
.toEqual({ until: "2026-10-18T04:00:00.000Z", renew: "off" })
|
||||
expect(_internal.termOf([{ status: "VALID", autoRenew: true, valid: "2026-09-18-2026-10-18" }])).toEqual({})
|
||||
expect(_internal.termOf([{ status: "VALID", valid: "2026-09-18 - 2026-10-18" }])).toEqual({ until: "2026-10-17T16:00:00.000Z", renew: "off" })
|
||||
})
|
||||
|
||||
// a Start Plan with one bucket, GLM-5.1's tokens for the day, a quarter used
|
||||
function startBalance(now, status) {
|
||||
return { server_time: now, plans: [{ plan_id: "zai-start-plan", user_plan_id: "up1", name: "Start Plan", status, ends_at: now + 7 * 86400,
|
||||
entitlements: [{ entitlement_id: "e1", period: "daily" }] }],
|
||||
balances: [{ plan_id: "zai-start-plan", user_plan_id: "up1", entitlement_id: "e1", show_name: "GLM-5.1", capabilities: ["model:GLM-5.1"],
|
||||
total_units: "1000000", used_units: 250000, remaining_units: 750000, expires_at: now + 3600 }] }
|
||||
}
|
||||
|
||||
test("ZCode's Start Plan: its buckets, each for its models", async () => {
|
||||
const now = Math.trunc(Date.now() / 1000)
|
||||
const token = jwt(now + 86400)
|
||||
let balance = startBalance(now, "active")
|
||||
const calls = serve(({ url, headers }) => {
|
||||
if (url.pathname !== "/api/v1/zcode-plan/billing/balance") return
|
||||
if (!headers["X-Device-Mid"]) return new Response(JSON.stringify({ code: 3001, msg: "parameter error" }), { status: 400 })
|
||||
if (headers.Authorization !== "Bearer " + token || !url.searchParams.get("app_version")) return new Response("", { status: 401 })
|
||||
return ok(balance)
|
||||
})
|
||||
const auth = oauth({ site: "bigmodel", jwt: token, device: "11111111-2222-4333-8444-555555555555" })
|
||||
expect(await usage(auth)).toEqual({
|
||||
plan: "Start Plan", until: new Date((now + 7 * 86400) * 1000).toISOString(), renew: "off",
|
||||
windows: [{ name: "GLM-5.1", used: 25, display: "250000 / 1000000", resetsAt: new Date((now + 3600) * 1000).toISOString(), span: 86400,
|
||||
models: ["GLM-5.1"] }],
|
||||
})
|
||||
expect(calls[0].url.origin).toBe("https://zcode.z.ai")
|
||||
expect(calls[0].headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555")
|
||||
|
||||
const over = { error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" }
|
||||
balance = startBalance(now, "expired")
|
||||
expect(await usage(auth)).toEqual(over)
|
||||
// still "active" past its end is over too, as ZCode reads it
|
||||
balance = { ...startBalance(now, "active"), server_time: now + 8 * 86400 }
|
||||
expect(await usage(auth)).toEqual(over)
|
||||
// a bucket counted by what remains, spanned by its period
|
||||
balance = startBalance(now, "active")
|
||||
balance.balances = [{ plan_id: "zai-start-plan", capabilities: [" model: GLM-5-Turbo ", "model:"], total_units: 200, remaining_units: "150",
|
||||
period_start: now, period_end: now + 7 * 86400 }]
|
||||
expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", span: 7 * 86400, models: ["GLM-5-Turbo"] }])
|
||||
|
||||
// its token run out
|
||||
expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ error: "ZCode's sign-in has expired; sign in again" })
|
||||
})
|
||||
|
||||
test("a team seat: the team plan's windows, name, end and resets, its key found and saved", async () => {
|
||||
const reset = Date.now() + 2 * 3600_000
|
||||
let made = null
|
||||
const TOKEN = "Bearer team-token"
|
||||
serve(({ url, method, headers, body }) => {
|
||||
const p = url.pathname, org = headers["Bigmodel-Organization"], proj = headers["Bigmodel-Project"]
|
||||
if (url.origin !== "https://bigmodel.cn") return
|
||||
if (p === "/api/biz/team/subscribe/product/querySubscribeDetail" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1")
|
||||
return ok({ hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID", productId: "prod-1", productName: "GLM Coding Team Pro",
|
||||
subscribeEndTime: "2026-12-31 23:59:59" })
|
||||
if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1") {
|
||||
if (method === "POST") {
|
||||
made = JSON.parse(body)
|
||||
return ok({ name: "zcode-team-api-key", apiKey: "tk", keyType: 2 })
|
||||
}
|
||||
return ok([{ name: "zcode-team-api-key", apiKey: "wrong-type", keyType: 1 }, ...(made ? [{ name: "zcode-team-api-key", apiKey: "tk", keyType: 2 }] : [])])
|
||||
}
|
||||
if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys/copy/tk") return ok({ secretKey: "ts" })
|
||||
if (p === "/api/biz/customer-package-reset/list" && headers.Authorization === TOKEN && org === "t1" && proj === "tp1" && url.searchParams.get("targetType") === "TEAM")
|
||||
return ok({
|
||||
fiveHourResets: [{ available: true, expireTime: "2026-11-30 23:59:59" }, { available: true, expireTime: 1790000000 }, { available: false, expireTime: 1 }],
|
||||
weekResets: [{ available: true, expireTime: "2026-12-31 23:59:59" }],
|
||||
})
|
||||
if (p === "/api/monitor/usage/quota/limit") {
|
||||
if (headers.Authorization !== "tk.ts" || url.searchParams.get("type") !== "2" || headers["Set-Language"] !== "zh") return ok({ limits: [] })
|
||||
return ok({ limits: [
|
||||
{ type: "CREDIT_LIMIT", unit: 3, percentage: 42, currentValue: 420, usage: 1000, nextResetTime: reset },
|
||||
{ type: "CREDIT_LIMIT", unit: 6, percentage: 10, currentValue: 1000, usage: 10000, nextResetTime: reset + 86400000 },
|
||||
] })
|
||||
}
|
||||
})
|
||||
const sets = []
|
||||
const state = { site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", token: TOKEN, org: "t1", project: "tp1", plan: "GLM Coding Team Pro" }
|
||||
expect(await usage(oauth(state), sets)).toEqual({
|
||||
plan: "GLM Coding Team Pro", until: "2026-12-31T15:59:59.000Z", renew: "off",
|
||||
resets: { count: 3, byWindow: true, fiveHour: 2, weekly: 1, until: new Date(1790000000 * 1000).toISOString() },
|
||||
windows: [
|
||||
{ name: "5 hours", used: 42, display: "420 / 1000", resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
|
||||
{ name: "Weekly", used: 10, display: "1000 / 10000", resetsAt: new Date(reset + 86400000).toISOString(), span: 7 * 86400 },
|
||||
],
|
||||
})
|
||||
expect(made).toEqual({ name: "zcode-team-api-key", keyType: 2 })
|
||||
expect(sets.length).toBe(1)
|
||||
expect(sets[0].path).toEqual({ id: "zcode" })
|
||||
expect(sets[0].body.access).toBe("tk.ts")
|
||||
expect(JSON.parse(sets[0].body.refresh)).toEqual({ ...state, key: "tk.ts", device: expect.any(String) })
|
||||
})
|
||||
|
||||
test("Z.ai's refusals are the card's error", async () => {
|
||||
serve(() => new Response("", { status: 401 }))
|
||||
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "Unauthorized" })
|
||||
serve(() => new Response(JSON.stringify({ code: 1001, msg: "Authorization Token非法" }), { status: 401 }))
|
||||
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "Authorization Token非法 (401, code 1001)" })
|
||||
serve(() => new Response(JSON.stringify({ code: 500, msg: "" })))
|
||||
expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "error 500" })
|
||||
expect(await usage(undefined)).toEqual({ error: "not signed in" })
|
||||
})
|
||||
Reference in New Issue
Block a user