diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 44e0205..d728d2d 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -92,6 +92,18 @@ 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. +**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 +app's own list of them (`GET /api/v1/zcode-plan/billing/preview`) with +the card and names them there — "1 to claim · claim it in the ZCode app" +— set aside, so the line stops nothing and routing, usage caps and the +menu bar pass it over. The plugin never claims one: the claim needs the +Aliyun captcha attestation only the app's renderer can make. A preview +that fails, or lists nothing, adds no line at all, and a card that is an +error keeps its error. Claim the plan in the ZCode app (open it once); +the next read shows it as an ordinary gift bucket. + ## Models The models are the ones ZCode offers for the account's plan. They come diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index e40be67..59548f3 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -531,6 +531,30 @@ async function giftOf(s) { return out } +// claimHint is the card's line for gift plans ZCode is holding for the +// account but has not put on it: GET /billing/preview lists them, and +// only the ZCode app claims one — its claim takes the Aliyun captcha +// attestation the app's own renderer makes, so the plugin reads the list +// and asks the user to claim it there. 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. 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 + let d + try { + d = await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/preview?app_version=${APP_VERSION}&platform=${platform()}`, { auth: "Bearer " + s.jwt, device: s.device }) + } catch { + return null + } + const plans = (Array.isArray(d?.plans) ? d.plans : []).filter((p) => typeof p?.plan_id === "string" && p.plan_id.trim()) + if (!plans.length) return null + const n = plans.length + const name = first(...plans.map((p) => (typeof p?.name === "string" ? p.name : "")), "ZCode gift plan") + return { name, used: 0, aside: true, display: `${n} to claim · claim ${n === 1 ? "it" : "them"} in the ZCode app` } +} + // 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 keep their own names. @@ -1523,9 +1547,16 @@ export async function ZCodeAuthPlugin({ client }) { return saved(await teamUsage(s, key)) } const { start, gift } = await plansOf(s) - if (start) return saved(await startUsage(s)) - if (gift) return saved(await dualUsage(s)) - return saved(await codingUsage(s)) + const card = saved(start ? await startUsage(s) : gift ? 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] + } + return card } catch (e) { return saved({ error: e?.message ?? String(e) }) } @@ -1555,4 +1586,4 @@ export async function ZCodeAuthPlugin({ client }) { } // for tests -export const _internal = { entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT } +export const _internal = { entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 76be46f..3853831 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.10", + "version": "0.1.11", "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/usage.test.mjs b/packages/zcode/usage.test.mjs index 59477d8..cb484ec 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -251,3 +251,118 @@ test("a model ZCode's config gives no limits has none made up", () => { expect(_internal.entry({ id: "GLM-9", context: 0, output: 0, efforts: [] }).limit).toEqual({ context: 0, output: 0 }) expect(_internal.entry({ id: "GLM-9", context: 300_000, output: 8_000, efforts: [] }).limit).toEqual({ context: 300_000, output: 8_000 }) }) + +// The ZCode app's own list of manual-claim gift plans: GET /billing/preview +// is read with the usage card, and a plan it lists that the balance does not +// hold is named on the card, to be claimed in the ZCode app (the claim needs +// the app's captcha attestation, see claimHint). Both fixtures are real +// responses: one account's preview while the day's ZCode Trust Build was +// still unclaimed, and one after it had claimed it. The plugin never asks +// the claim endpoint. +const PREVIEW_CLAIMABLE = { + server_time: 1791216750, + plans: [{ + user_plan_id: "upl_2107141892427358208", plan_id: "zcode-v3-start-plan-trust-1006", name: "ZCode Trust Build", + description: "ZCode Global Build", priority: 110, status: "active", starts_at: 1791216750, ends_at: 1791302400, + entitlements: [{ entitlement_id: "zcode-v3-start-plan-trust-1006", show_name: "GLM-5.3-Flash", meter: "model_usage", + unit_type: "token", capabilities: ["model:glm-5.3-flash"], grant_units: 100000000, period: "one_time", priority: 110, effective_at: 0 }], + }], +} +const PREVIEW_CLAIMED = { server_time: 1791276990, plans: [] } +const TRUST_BUILD = { name: "ZCode Trust Build", used: 0, aside: true, display: "1 to claim · claim it in the ZCode app" } + +// the Start Plan's own card, with the preview answering what preview says +async function startCard(now, token, preview) { + const calls = serve(({ url }) => { + if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(startBalance(now, "active")) + if (url.pathname === "/api/v1/zcode-plan/billing/preview") return preview(calls) + }) + const auth = oauth({ site: "zai", jwt: token, device: "11111111-2222-4333-8444-555555555555" }) + return { u: await usage(auth), calls } +} + +test("a gift plan ZCode holds but has not granted is named on the card, to claim in the app", async () => { + const now = Math.trunc(Date.now() / 1000) + const token = jwt(now + 86400) + const { u, calls } = await startCard(now, token, () => ok(PREVIEW_CLAIMABLE)) + expect(u.windows).toEqual([ + { name: "GLM-5.1", used: 25, display: "250000 / 1000000", resetsAt: new Date((now + 3600) * 1000).toISOString(), span: 86400, + models: ["GLM-5.1", "GLM-5.1-Trial"] }, + TRUST_BUILD, + ]) + // it is no allowance: set aside, so routing, caps and the menu bar pass it over + expect(u.windows.at(-1).aside).toBe(true) + // the preview went out as ZCode's own client asks it + const p = calls.find((c) => c.url.pathname.endsWith("/preview")) + expect(p.method).toBe("GET") + expect(p.url.searchParams.get("app_version")).toBe("3.14.3") + expect(p.url.searchParams.get("platform")).toBe(`${process.platform}-${process.arch}`) + expect(p.headers.Authorization).toBe("Bearer " + token) + expect(p.headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555") + // nothing claims it here + expect(calls.some((c) => c.url.pathname.endsWith("/claim"))).toBe(false) +}) + +test("a claimed account's card has no line at all", async () => { + const now = Math.trunc(Date.now() / 1000) + const { u } = await startCard(now, jwt(now + 86400), () => ok(PREVIEW_CLAIMED)) + expect(u.windows.map((w) => w.name)).toEqual(["GLM-5.1"]) + expect(u.error).toBeUndefined() +}) + +test("a preview that fails shows nothing and leaves the card as it was", async () => { + const now = Math.trunc(Date.now() / 1000) + const token = jwt(now + 86400) + const before = (await startCard(now, token, () => new Response("", { status: 404 }))).u + const refused = (await startCard(now, token, () => new Response(JSON.stringify({ code: 3007, msg: "captcha verify failed" }), { status: 400 }))).u + const thrown = (await startCard(now, token, () => { + throw new Error("no network in tests") + })).u + for (const u of [refused, thrown]) { + expect(u).toEqual(before) + expect(u.error).toBeUndefined() + expect(u.windows.some((w) => w.aside)).toBe(false) + } + // an expired sign-in is no preview request either + const calls = serve(() => undefined) + expect((await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).error).toContain("sign-in has expired") + expect(calls.some((c) => c.url.pathname.endsWith("/preview"))).toBe(false) +}) + +test("the card's error stays the error: no line is added over it", async () => { + const now = Math.trunc(Date.now() / 1000) + const { u } = await startCard(now, jwt(now + 86400), () => ok(PREVIEW_CLAIMABLE)) + expect(u.windows.at(-1)).toEqual(TRUST_BUILD) // a working card gets it + const calls = serve(({ url }) => { + if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(startBalance(now, "expired")) + if (url.pathname === "/api/v1/zcode-plan/billing/preview") return ok(PREVIEW_CLAIMABLE) + }) + const over = await usage(oauth({ site: "zai", jwt: jwt(now + 86400), device: "d" })) + expect(over).toEqual({ signIn: "kept", error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" }) + expect(calls.some((c) => c.url.pathname.endsWith("/preview"))).toBe(false) // nothing to put it on +}) + +test("several claimable plans are counted", async () => { + const now = Math.trunc(Date.now() / 1000) + const two = { ...PREVIEW_CLAIMABLE, plans: [PREVIEW_CLAIMABLE.plans[0], { plan_id: "zcode-v3-start-plan-trust-1007", name: "ZCode Trust Build", status: "active" }] } + const { u } = await startCard(now, jwt(now + 86400), () => ok(two)) + expect(u.windows.at(-1)).toEqual({ name: "ZCode Trust Build", used: 0, aside: true, display: "2 to claim · claim them in the ZCode app" }) +}) + +// a coding account with gift plans: the line goes last, after both allowances +test("a coding account's line goes after its coding and gift windows", async () => { + const now = Math.trunc(Date.now() / 1000) + const token = jwt(now + 86400) + const calls = serve(({ url }) => { + 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, percentage: 25 }] }) + if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(startBalance(now, "active")) + if (url.pathname === "/api/v1/zcode-plan/billing/preview") return ok(PREVIEW_CLAIMABLE) + }) + const auth = oauth({ site: "zai", key: "k", jwt: token, device: "d" }) + const u = await usage(auth) + expect(u.plan).toBe("GLM Coding Pro") + expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "GLM-5.1-Trial", "ZCode Trust Build"]) + expect(u.windows.at(-1)).toEqual(TRUST_BUILD) + expect(calls.filter((c) => c.url.pathname.endsWith("/preview"))).toHaveLength(1) +})