zcode 0.1.19: a GLM Coding Plan's own resets show on the card, each with its end, a team's say so, and a Start Plan refusal says what to do, as the built-in did
What changed, for parity with magpie's built-in ZCode before it retires:
- Personal resets. The built-in's zcodeQuota read
/api/biz/customer-package-reset/list?targetType=PERSONAL with the plan's
key (zhipuPersonalResets, yetone/magpie#1191) and showed the count, by
window, and each reset's end. The plugin read only the team's list.
codingUsage now reads the personal list alongside the subscription list,
so a Coding Plan card (and a dual gift + Coding Plan card, built on it)
carries resets: {count, byWindow, fiveHour, weekly, until, each}.
- Team resets now carry team: true and each, as zhipuTeamResets set Team.
Both lists are read by one resetsOf: only available ones count, each
{until?, window} sorted soonest first with an endless one last
(sortResetCards), nothing on a failed read or none left.
- Start Plan refusal. A Start Plan answer that is a 405, the block page
("request has been blocked" / errors.aliyun.com) or code 3012 / "unusual
activity" now comes back, same status, as {type:"error", error:{message:
"<vendor's words, or the status for a block page> — <hint>"}}, the hint
word for word magpie's provider.ZCodeStartBlockedHint, as the built-in's
zcodeStartExplain / Provider.Explain put it. The block page's own words
are left out, so magpie's APIError no longer reads it as a network
firewall's (BlockedHint). Coding Plan and team answers are untouched.
- README: the resets and the Start Plan's hint.
What was run:
- usage.test.mjs: a new test with #1191's literal reset list (the
built-in's zhipuResetList) fails on 0.1.18 (no resets); the team test,
now expecting team and each, fails on 0.1.18 too.
- start.test.mjs: the new refusal test fails with the startBlocked line
disabled by hand (block page passed through), passes with it.
- Every packages/zcode test file under a scratch HOME: dual 25, gift 20,
models 1, moved 1, own 6, signin 3, start 11, usage 16 (83 pass).
- bun scripts/check.mjs zcode passes.
Not tried: a real account's reset list or a real Start Plan refusal.
`team` and `each` reach magpie's card from its next release; older magpie
ignores them.
This commit is contained in:
@@ -24,7 +24,12 @@ over Anthropic's Messages API. Provider id: `zcode`.
|
||||
ZCode's does: ZCode's headers, ZCode's system prompt ahead of the
|
||||
agent's, the day in a `<system-reminder>` turn before the agent's
|
||||
turns, and the sign-in's device id in `metadata.user_id`. GLM Coding
|
||||
Plan and team requests go as the agent sent them.
|
||||
Plan and team requests go as the agent sent them. One it still turns
|
||||
away (a 405, the block page or code 3012) comes back with what to do
|
||||
about it, as magpie's built-in said: "ZCode's Start Plan still turned
|
||||
this request away, though magpie sends it as the ZCode app does; …
|
||||
Use an account with a GLM Coding Plan, or add another provider to this
|
||||
group".
|
||||
- The Start Plan's token can't be refreshed. When it runs out, sign in
|
||||
again.
|
||||
- **ZCode app's sign-in**
|
||||
@@ -96,6 +101,15 @@ behind an error, so a gift hiccup must not black out a working Coding
|
||||
Plan. A gift that goes out of date while requests use it simply stops
|
||||
showing.
|
||||
|
||||
**Resets.** A GLM Coding Plan of the account's own, and a team seat,
|
||||
show the resets the vendor's usage page lists
|
||||
(`/api/biz/customer-package-reset/list`, `targetType=PERSONAL` with the
|
||||
plan's key, `TEAM` with the team's sign-in): how many of the five hours
|
||||
and of the week are still available, and when each runs out, soonest
|
||||
first. A team's are marked a team's. They are only read; a reset is
|
||||
spent on the vendor's own page. A list that can't be read, or has none
|
||||
left, shows no count.
|
||||
|
||||
**Gift plans ZCode holds but has not granted.** ZCode hands out one-off
|
||||
trust-build / gift plans (a day's ZCode Trust Build, say) that are not
|
||||
on the account until the ZCode app claims them. The plugin reads the
|
||||
|
||||
@@ -436,9 +436,12 @@ async function codingUsage(s) {
|
||||
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)
|
||||
try {
|
||||
Object.assign(out, termOf(await call("GET", root + "/api/biz/subscription/list", { auth: s.key })))
|
||||
} catch {}
|
||||
const r = await resets
|
||||
if (r) out.resets = r
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -708,31 +711,56 @@ async function teamUsage(s, key) {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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", root + "/api/biz/customer-package-reset/list?targetType=TEAM", { auth, headers })) ?? {}
|
||||
d = (await call("GET", url, { auth, headers })) ?? {}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
let until = 0
|
||||
const count = (rs) => {
|
||||
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)
|
||||
const weekly = count(d.weekResets)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1311,6 +1339,36 @@ function model(m, url) {
|
||||
// the plan serves (ARNO's "Freeflow", provider zcode-start) sends it: its
|
||||
// headers (startHeaders) and its body (dress). The texts are prompt.mjs.
|
||||
|
||||
// START_BLOCKED is what the Start Plan still turning a request away means,
|
||||
// word for word magpie's provider.ZCodeStartBlockedHint (#425), which
|
||||
// magpie's Routing page knows and says in the user's language. It is put
|
||||
// in place of the block page, whose words magpie would otherwise read as a
|
||||
// network firewall's (provider.BlockedHint).
|
||||
const START_BLOCKED = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group"
|
||||
const EDGE_BLOCKED = /request has been blocked|errors\.aliyun\.com/i
|
||||
const START_REFUSED = /unusual activity|"code"\s*:\s*"?3012\b/i
|
||||
|
||||
// startRefused says a Start Plan answer is that refusal, as the built-in's
|
||||
// zcodeStartExplain read it: a 405, a block page or code 3012.
|
||||
const startRefused = (status, text) => status >= 400 && (status === 405 || EDGE_BLOCKED.test(text) || START_REFUSED.test(text))
|
||||
|
||||
// startBlocked is the refusal's answer as the built-in passed it on: what
|
||||
// the vendor said (its status for a block page), then START_BLOCKED.
|
||||
function startBlocked(res, text) {
|
||||
let said = ""
|
||||
if (!EDGE_BLOCKED.test(text)) {
|
||||
try {
|
||||
const v = JSON.parse(text)
|
||||
said = first(v?.error?.message, typeof v?.error === "string" ? v.error : "", v?.message, v?.msg)
|
||||
} 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} — ${START_BLOCKED}` }
|
||||
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")
|
||||
|
||||
@@ -1594,6 +1652,13 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
h.set("Authorization", "Bearer " + key)
|
||||
}
|
||||
let res = await fetch(url, { ...opts, headers: h })
|
||||
// the Start Plan turning the request away says what to do about
|
||||
// it, as the built-in's zcodeStartExplain did
|
||||
if (start && res.status >= 400) {
|
||||
const text = await res.text()
|
||||
if (startRefused(res.status, text)) return kept(startBlocked(res, text))
|
||||
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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zcode-auth",
|
||||
"version": "0.1.18",
|
||||
"version": "0.1.19",
|
||||
"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",
|
||||
|
||||
@@ -14,6 +14,7 @@ import { realpathSync } from "node:fs"
|
||||
let ZCodeAuthPlugin, PROMPT
|
||||
let server
|
||||
const got = []
|
||||
let answer = null // what the fake answers instead, when set
|
||||
beforeAll(async () => {
|
||||
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
|
||||
;({ ZCodeAuthPlugin } = await import("./index.mjs"))
|
||||
@@ -22,6 +23,7 @@ beforeAll(async () => {
|
||||
port: 0,
|
||||
async fetch(req) {
|
||||
got.push({ method: req.method, path: new URL(req.url).pathname, headers: Object.fromEntries(req.headers), body: await req.text() })
|
||||
if (answer) return answer()
|
||||
return Response.json({ type: "message", content: [] })
|
||||
},
|
||||
})
|
||||
@@ -42,6 +44,7 @@ function routeToFake() {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
got.length = 0
|
||||
answer = null
|
||||
})
|
||||
|
||||
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16)
|
||||
@@ -310,3 +313,39 @@ test("a team seat's request goes as the agent sent it, ZCode's token or not", as
|
||||
const auth = { type: "oauth", access: s.key, refresh: JSON.stringify(s), expires: 0 }
|
||||
sentAsIs(await send(auth, agentText), "team.secret", "/api.z.ai/api/anthropic/v1/messages")
|
||||
})
|
||||
|
||||
// magpie's provider.ZCodeStartBlockedHint, word for word
|
||||
const START_BLOCKED = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group"
|
||||
|
||||
test("the Start Plan turning a request away says what to do about it, as the built-in's zcodeStartExplain did (#425)", async () => {
|
||||
const ask = async (auth, url = "https://api.z.ai/api/anthropic/v1/messages") => {
|
||||
routeToFake()
|
||||
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const opts = await hooks.auth.loader(async () => auth, { id: "zcode" })
|
||||
const res = await opts.fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText })
|
||||
return { status: res.status, text: await res.text(), signIn: res.headers.get("x-magpie-sign-in") }
|
||||
}
|
||||
// the block page zcode.z.ai serves: its status, then the hint, and none
|
||||
// of the page's words, which magpie would read as a firewall's
|
||||
answer = () => new Response("<html>Sorry, your request has been blocked due to unusual activity.</html>", { status: 405, headers: { "content-type": "text/html" } })
|
||||
let r = await ask(start("zai"))
|
||||
expect(r.status).toBe(405)
|
||||
expect(JSON.parse(r.text)).toEqual({ type: "error", error: { type: "permission_error", message: "405 Method Not Allowed — " + START_BLOCKED } })
|
||||
expect(r.text).not.toMatch(/request has been blocked/)
|
||||
expect(r.signIn).toBe("kept")
|
||||
// code 3012 in JSON: the vendor's own words, then the hint
|
||||
answer = () => Response.json({ code: 3012, msg: "method not allowed" }, { status: 403 })
|
||||
r = await ask(start("zai"))
|
||||
expect(r.status).toBe(403)
|
||||
expect(JSON.parse(r.text).error.message).toBe("method not allowed — " + START_BLOCKED)
|
||||
// any other refusal of the Start Plan goes on as it came
|
||||
answer = () => Response.json({ type: "error", error: { type: "overloaded_error", message: "busy" } }, { status: 529 })
|
||||
r = await ask(start("zai"))
|
||||
expect(r.status).toBe(529)
|
||||
expect(JSON.parse(r.text).error.message).toBe("busy")
|
||||
// a GLM Coding Plan's 405 is not the Start Plan's, and says nothing of it
|
||||
answer = () => new Response("request has been blocked", { status: 405 })
|
||||
r = await ask({ type: "api", key: "one.secret", metadata: { site: "zai" } })
|
||||
expect(r.status).toBe(405)
|
||||
expect(r.text).toBe("request has been blocked")
|
||||
})
|
||||
|
||||
@@ -183,6 +183,57 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => {
|
||||
expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ signIn: "kept", error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" })
|
||||
})
|
||||
|
||||
// customer-package-reset/list?targetType=PERSONAL as the reporter of
|
||||
// yetone/magpie#1191 captured it on bigmodel.cn (the built-in's
|
||||
// zhipu_resets_test.go zhipuResetList): one run out stays listed.
|
||||
const PERSONAL_RESETS = {
|
||||
code: 200, msg: "操作成功", success: true,
|
||||
data: {
|
||||
customerId: 0, targetType: "PERSONAL", organizationId: null, projectId: null,
|
||||
lastFiveHourResetTime: "2026-10-06 21:14:03", lastWeekResetTime: null,
|
||||
fiveHourResets: [{ recordId: 0, grantType: "DIRECT", expireTime: "2026-11-02 23:59:59", available: true }],
|
||||
weekResets: [
|
||||
{ recordId: 0, grantType: "DIRECT", expireTime: "2026-10-30 23:59:59", available: true },
|
||||
{ recordId: 0, grantType: "DIRECT", expireTime: "2026-10-04 23:59:59", available: false },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
test("a Coding Plan of a person's own shows its resets, each with its end, as the built-in's zhipuPersonalResets did", async () => {
|
||||
let list = PERSONAL_RESETS
|
||||
const calls = serve(({ url, headers }) => {
|
||||
if (headers.Authorization !== "glm-key") return new Response("", { status: 401 })
|
||||
if (url.pathname === "/api/biz/subscription/list") return ok([])
|
||||
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ level: "pro", limits: [] })
|
||||
if (url.pathname === "/api/biz/customer-package-reset/list" && url.searchParams.get("targetType") === "PERSONAL")
|
||||
return typeof list === "number" ? new Response("", { status: list }) : new Response(JSON.stringify(list))
|
||||
})
|
||||
const auth = oauth({ site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "glm-key" })
|
||||
expect(await usage(auth)).toEqual({
|
||||
signIn: "kept",
|
||||
plan: "GLM Coding Pro",
|
||||
windows: [],
|
||||
resets: { count: 2, byWindow: true, fiveHour: 1, weekly: 1, until: "2026-10-30T15:59:59.000Z", each: [
|
||||
{ until: "2026-10-30T15:59:59.000Z", window: "weekly" },
|
||||
{ until: "2026-11-02T15:59:59.000Z", window: "fiveHour" },
|
||||
] },
|
||||
})
|
||||
const asked = calls.find((c) => c.url.pathname === "/api/biz/customer-package-reset/list")
|
||||
expect(asked.url.origin).toBe("https://open.bigmodel.cn")
|
||||
expect(asked.method).toBe("GET")
|
||||
// a list that can't be read shows no count, never 0; nor does one with none left
|
||||
list = 500
|
||||
expect((await usage(auth)).resets).toBeUndefined()
|
||||
list = { code: 200, data: { fiveHourResets: [], weekResets: [{ available: false, expireTime: "2026-10-04 23:59:59" }] } }
|
||||
expect((await usage(auth)).resets).toBeUndefined()
|
||||
// one with no end is listed last, with none
|
||||
list = { code: 200, data: { fiveHourResets: [{ available: true }], weekResets: [{ available: true, expireTime: "2026-10-30 23:59:59" }] } }
|
||||
expect((await usage(auth)).resets).toEqual({ count: 2, byWindow: true, fiveHour: 1, weekly: 1, until: "2026-10-30T15:59:59.000Z", each: [
|
||||
{ until: "2026-10-30T15:59:59.000Z", window: "weekly" },
|
||||
{ window: "fiveHour" },
|
||||
] })
|
||||
})
|
||||
|
||||
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
|
||||
@@ -219,7 +270,13 @@ test("a team seat: the team plan's windows, name, end and resets, its key found
|
||||
expect(await usage(oauth(state), sets)).toEqual({
|
||||
signIn: "kept",
|
||||
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() },
|
||||
// a team's resets say so, and each its own end, soonest first, as the
|
||||
// built-in's zhipuTeamResets did
|
||||
resets: { count: 3, byWindow: true, fiveHour: 2, weekly: 1, until: new Date(1790000000 * 1000).toISOString(), team: true, each: [
|
||||
{ until: new Date(1790000000 * 1000).toISOString(), window: "fiveHour" },
|
||||
{ until: "2026-11-30T15:59:59.000Z", window: "fiveHour" },
|
||||
{ until: "2026-12-31T15:59:59.000Z", window: "weekly" },
|
||||
] },
|
||||
windows: [
|
||||
{ name: "5 hours", used: 42, display: "420 / 1000", amount: 420, limit: 1000, resetsAt: new Date(reset).toISOString(), span: 5 * 3600 },
|
||||
{ name: "Weekly", used: 10, display: "1000 / 10000", amount: 1000, limit: 10000, resetsAt: new Date(reset + 86400000).toISOString(), span: 7 * 86400 },
|
||||
|
||||
Reference in New Issue
Block a user