diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 0775a7a..df098ed 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -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 `` 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 diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 166e881..6488d69 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -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 diff --git a/packages/zcode/package.json b/packages/zcode/package.json index e6c228e..703fce8 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -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", diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index da63cfd..c3b7ced 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.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("Sorry, your request has been blocked due to unusual activity.", { 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") +}) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index d40d39e..79a3a50 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -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 },