diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 5bbaabd..fa30682 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -57,7 +57,9 @@ over Anthropic's Messages API. Provider id: `zcode`. Start Plan, ZCode 1024 Dev Day) are served to ZCode's own session, which a key doesn't carry: for an account with only a gift plan, the card and each refused request (1113) say to sign in with ZCode - instead. + instead. For an account with a GLM Coding Plan, the card says the + gift plans' `-Trial` models need ZCode's sign-in, since a key lists + none of them. ## Where the sign-in is kept @@ -139,12 +141,21 @@ 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. +**No ZCode session.** A card read with a key, or with a sign-in whose +ZCode session has run out (it can't be renewed), sets aside a line named +"ZCode gift plans (-Trial models) need ZCode's sign-in", with why in its +display: such an account reads no gift and lists no `-Trial` entries. +Sign in again with ZCode to get them back. A gift read that fails +otherwise is asked again a minute later, not ten. + ## Models The models are the ones ZCode offers for the account's plan. They come from ZCode's provider config: the release zcode.z.ai names, or an installed ZCode's copy if that one is newer. The list is kept for 10 -minutes. When the config can't be read, the plugin falls back to this list: +minutes. When the config can't be read, the plugin falls back to this list +(and magpie keeps the list it was told last, unless the account's gift +plans add `-Trial` entries, which are told as read): | Model | Context | Output | Efforts | |---|---|---|---| diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index 296bb5f..248ee67 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -310,14 +310,16 @@ test("a ZCode sign-in that expired after the gift was cached goes to the coding expect(sent.at(-1).headers["x-api-key"]).toBe(KEY) }) -test("a gift read that fails at once still trusts the plan list for ten minutes", async () => { +// a failed gift read is unknown, not "no gift": a ten-minute "none" hid +// the account's -Trial models for ten minutes after one hiccup +test("a gift read that fails at once is asked again in a minute", async () => { answers["/api/biz/subscription/list"] = ok([{ productName: "GLM Coding Pro", status: "VALID" }]) answers["/api/v1/zcode-plan/billing/balance"] = new Response("", { status: 500 }) await sendTo(MSG, body("glm-5.3-flash")) const r = _internal.routes.get(KEY + "\0" + jwt) expect(r.start).toBe(false) // on the coding plan expect(r.gift).toBeNull() // the balance read failed: no gift known - expect(r.ttl).toBe(600_000) // the plan list read fine: 10 minutes + expect(r.ttl).toBe(60_000) // the gift is unknown: a minute }) test("a coding account with no gift keeps its 10-minute cache", async () => { diff --git a/packages/zcode/gift.test.mjs b/packages/zcode/gift.test.mjs index 919f3b2..e4f904b 100644 --- a/packages/zcode/gift.test.mjs +++ b/packages/zcode/gift.test.mjs @@ -295,3 +295,63 @@ test("a coding plan account's two gift plans' GLM-5.3 each show, named by plan", expect(gift[1]).toMatchObject({ used: 25, models: ["GLM-5.3-Trial"] }) expect(gift[2]).toMatchObject({ used: 100, aside: true }) }) + +// bigsteven (Discord, 10-24): GLM Coding Plan spent, no GLM-5.3-Trial in +// the list. ZCode's config out of reach marks the list a fallback, and +// magpie then keeps the list it was told last, from before the gift: the +// -Trial entries just read went with it. A list with trial entries is +// told as it is. +test("ZCode's config out of reach still tells a gift's -Trial entries, not a fallback", async () => { + _internal.config(null) + try { + balance.balances[0].capabilities = ["model:glm-5.3"] + const models = await (await hooks()).provider.models({ models: {} }, { auth }) + expect(models["GLM-5.3-Trial"]?.name).toBe("GLM-5.3-Trial") + expect(models[Symbol.for("magpie.fellBack")]).toBeUndefined() + // with no gift there is nothing new to tell: still a fallback + _internal.routes.clear() + balance.plans = [] + const none = await (await hooks()).provider.models({ models: {} }, { auth }) + expect(Object.keys(none).some((id) => id.endsWith("-Trial"))).toBe(false) + expect(none[Symbol.for("magpie.fellBack")]).toBe(true) + } finally { + _internal.config(undefined) + } +}) + +test("a gift read that failed lists its -Trial entries again a minute later", async () => { + balance.balances[0].capabilities = ["model:glm-5.3"] + const good = balance + balance = null + const was = globalThis.fetch + globalThis.fetch = async (input, init) => { + if (balance === null && new URL(String(input)).pathname === "/api/v1/zcode-plan/billing/balance") return new Response("", { status: 502 }) + return was(input, init) + } + const h = await hooks() + expect((await h.provider.models({ models: {} }, { auth }))["GLM-5.3-Trial"]).toBeUndefined() + balance = good + const r = _internal.routes.get(state.key + "\0" + jwt) + r.at -= 61_000 + expect((await h.provider.models({ models: {} }, { auth }))["GLM-5.3-Trial"]?.name).toBe("GLM-5.3-Trial") +}) + +// a key, or a sign-in whose ZCode session ran out, reads no gift: the card +// says why there are no -Trial entries instead of leaving them out unsaid +test("a coding plan with no live ZCode session says its gift plans need ZCode's sign-in", async () => { + const line = (u) => u.windows.find((w) => w.name === "ZCode gift plans (-Trial models) need ZCode's sign-in") + const h = await hooks() + const key = await h.auth.usage(async () => ({ type: "api", key: state.key }), { id: "zcode" }) + expect(line(key)).toEqual({ name: "ZCode gift plans (-Trial models) need ZCode's sign-in", used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" }) + expect(Object.keys(await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })).some((id) => id.endsWith("-Trial"))).toBe(false) + const dead = ["{}", JSON.stringify({ exp: now - 60 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".synthetic" + const aged = { ...auth, refresh: JSON.stringify({ ...state, jwt: dead }) } + const u = await h.auth.usage(async () => aged, { id: "zcode" }) + expect(u.error).toBeUndefined() + expect(line(u)?.display).toBe("ZCode's sign-in has expired: sign in again") + expect(Object.keys(await h.provider.models({ models: {} }, { auth: aged })).some((id) => id.endsWith("-Trial"))).toBe(false) + // a live session reads the gift: no such line, its -Trial entries listed + const live = await h.auth.usage(async () => auth, { id: "zcode" }) + expect(line(live)).toBeUndefined() + expect(live.windows.some((w) => w.name.includes("-Trial") || (w.models ?? []).some((m) => m.endsWith("-Trial")))).toBe(true) +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 95dbd10..bd9aa01 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -214,8 +214,15 @@ async function plansOf(s) { let sure = false try { if (!(await plan(s))) start = true - else gift = await startPlan(s.jwt, s.device).catch(() => null) - sure = 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 + } + if (start) sure = true } 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 @@ -616,6 +623,21 @@ async function claimHint(s) { return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` } } +// 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 (isTeam(s)) return null + 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 @@ -1781,7 +1803,11 @@ export async function ZCodeAuthPlugin({ client }) { if (out[id]) continue out[id] = model({ ...about(raw), id }, url) } - if (fell) out[Symbol.for("magpie.fellBack")] = 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 }, }, @@ -1953,6 +1979,10 @@ export async function ZCodeAuthPlugin({ client }) { 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) { @@ -2002,4 +2032,7 @@ export async function ZCodeAuthPlugin({ client }) { } // for tests -export const _internal = { entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT } +// 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 = { config, 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 0addd84..6ef0b54 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.25", + "version": "0.1.26", "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 37274c3..0f64601 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -41,6 +41,11 @@ async function usage(auth, sets = []) { return hooks.auth.usage(async () => auth, { id: "zcode" }) } const jwt = (exp) => ["{}", JSON.stringify({ exp })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +// a card read with no ZCode session says the gift plans need one: a key +// (or a sign-in with no ZCode token) reads no gift and lists no -Trial +const GIFT = "ZCode gift plans (-Trial models) need ZCode's sign-in" +const KEY_LINE = { name: GIFT, used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" } +const NO_SESSION = { name: GIFT, used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" } test("a Coding Plan's five hours and week", async () => { const reset = Date.now() + 3600_000 @@ -59,12 +64,13 @@ test("a Coding Plan's five hours and week", async () => { windows: [ { name: "5 hours", used: 25, display: "500 / 2000", amount: 500, limit: 2000, resetsAt: new Date(reset).toISOString(), span: 5 * 3600 }, { name: "Weekly", used: 10, display: "1000 / 10000", amount: 1000, limit: 10000, resetsAt: new Date(reset).toISOString(), span: 7 * 86400 }, + NO_SESSION, ], }) 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({ level: "lite", limits: [] }) : ok([{ productName: "GLM Coding Lite", status: "VALID" }]))) - expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ signIn: "kept", plan: "GLM Coding Lite", windows: [] }) + expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ signIn: "kept", plan: "GLM Coding Lite", windows: [KEY_LINE] }) expect(bm[0].url.origin).toBe("https://open.bigmodel.cn") }) @@ -82,7 +88,7 @@ test("a key with no GLM Coding Plan says a ZCode gift plan needs ZCode's sign-in } // a list that couldn't be read is not "no plan" serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : new Response("", { status: 500 }))) - expect(await usage({ type: "api", key: "k", metadata: { site: "zai" } })).toEqual({ signIn: "kept", windows: [] }) + expect(await usage({ type: "api", key: "k", metadata: { site: "zai" } })).toEqual({ signIn: "kept", windows: [KEY_LINE] }) // a counted window or a level is a plan, whatever the list says serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [{ unit: 3, number: 5, percentage: 3 }] }) : ok([]))) expect((await usage({ type: "api", key: "k", metadata: { site: "zai" } })).error).toBeUndefined() @@ -234,7 +240,7 @@ test("a Coding Plan of a person's own shows its resets, each with its end, as th expect(await usage(auth)).toEqual({ signIn: "kept", plan: "GLM Coding Pro", - windows: [], + windows: [NO_SESSION], 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" },