diff --git a/packages/zcode/README.md b/packages/zcode/README.md index e26c37e..5afb263 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -239,7 +239,8 @@ names it in a line set aside, "ZCode gift plan not started yet", with the plan's name and its start in this computer's time as the display ("Start Plan · 2026-10-29 23:00"), soonest first. An account whose only gift plan starts later gets a card with that line, not "ended or never -started". The status ZCode gives such a plan has not been seen, so any +started", and signs in with it too, as ZCode counts such a plan as the +account's (its "pending" Start Plan). The status ZCode gives such a plan has not been seen, so any status but `expired` is taken; `starts_at` decides it. **Resets.** A GLM Coding Plan of the account's own, and a team seat, diff --git a/packages/zcode/checkin.test.mjs b/packages/zcode/checkin.test.mjs index ecfcb39..7b7601d 100644 --- a/packages/zcode/checkin.test.mjs +++ b/packages/zcode/checkin.test.mjs @@ -343,3 +343,20 @@ test("after the claim the feed has no delivery: nothing to claim, not a failure" expect(await checkin()).toEqual({ outcome: "inactive", message: "no ZCode gift plan to claim", until: expect.any(String) }) expect(claims(calls)).toEqual([]) }) + +// ZCode names only zh-CN or en-US to the feed (marketingTouchService's +// localeSchema in zai-org/ZCode@a9fe401); a computer set to another +// locale asked with it as it was +test("the feed is asked in zh-CN or en-US only, as the app asks it", async () => { + const realDTF = Intl.DateTimeFormat + try { + for (const [locale, want] of [["zh-Hans-CN", "zh-CN"], ["zh-TW", "zh-CN"], ["zh-CN", "zh-CN"], ["en-GB", "en-US"], ["ja-JP", "en-US"], ["", "en-US"]]) { + Intl.DateTimeFormat = function () { return { resolvedOptions: () => ({ locale }) } } + const calls = claimWith(() => json("", 404)) + await checkin() + expect([locale, calls.find((c) => c.url.pathname === TOUCH).headers["X-Client-Language"]]).toEqual([locale, want]) + } + } finally { + Intl.DateTimeFormat = realDTF + } +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index c926f32..4e518b2 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -29,7 +29,11 @@ const BIGMODEL_API = "https://bigmodel.cn" // BigModel's business API, where ZCo const ZAI_BASE = "https://api.z.ai/api/anthropic" const BIGMODEL_BASE = "https://open.bigmodel.cn/api/anthropic" const START_BASE = ZCODE + "/api/v1/zcode-plan/anthropic" -const APP_VERSION = "3.16.3" // the ZCode whose sign-in this makes +// APP_VERSION is the ZCode this signs in and asks as, on every call. ZCode +// gates by it: its marketing feed answers empty to an older one (#678), +// and its Start Plan balance "judges capability by the real app_version" +// (zaiStartPlanBilling.ts in zai-org/ZCode@a9fe401, 3.17.2). +const APP_VERSION = "3.17.2" const UA = "ZCode/" + APP_VERSION // ZCode's models before its config is read; the Start Plan has all but GLM-5.3. @@ -167,7 +171,12 @@ const giftSpent = (x) => { // the gift when any of them has a live bucket serving it — a bucket past // its plan's own end, or one whose remaining_units says none, is skipped // rather than asked and refused. models are those live buckets' names. -async function startPlan(jwt, device) { +// +// coming (sign-in only) also takes a plan that has not started yet, as +// ZCode's own check does (resolveStartPlanBalanceAvailability's "pending" +// counts as entitled): {name, models: [], coming: true}. Requests and the +// card never ask for it: a plan not started serves nothing yet. +async function startPlan(jwt, device, coming = false) { if (!jwt) throw new Error("not signed in to ZCode") if (jwtExpired(jwt)) throw new Error(EXPIRED) const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + jwt, device })) ?? {} @@ -198,7 +207,11 @@ async function startPlan(jwt, device) { } } } - return any ? { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl } : null + if (any) return { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl } + if (!coming) return null + const next = plans.filter((p) => notStarted(p, now) && !(num(p?.ends_at) > 0 && num(p?.ends_at) <= now)) + .sort((a, b) => startNum(a.starts_at) - startNum(b.starts_at))[0] + return next ? { name: String(next.name ?? "").trim() || "Start Plan", models: [], allModels: [], ttl, coming: true } : null } // plansOf says where an account's requests go and what more it can spend: @@ -679,11 +692,10 @@ const CAPTCHA = 3007 const CAPTCHA_WORDS = /captcha/i // The marketing feed and the claim are gated on the client's version: -// under an older version's header the feed answers empty (11-03: the -// day's banner showed for 3.17.2 and for no older one), so they go as -// the current client (3.17.2) sends them. -const MARKETING_VERSION = "3.17.2" -const marketingHeaders = () => ({ "X-ZCode-App-Version": MARKETING_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() }) +// under an older version's header the feed answers empty (11-03, #678: +// the day's banner showed for 3.17.2 and for no older one), so they go, +// as every call does, as the current client (APP_VERSION) sends them. +const marketingHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() }) // claimOne asks /billing/claim for one plan and says what its body says: // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the @@ -730,12 +742,15 @@ async function claimOne(s, planID) { const TOUCH = "/api/v1/marketing/touch" const CLAIM_ACTION = "claim_zcode_plan" let touchSeq = 0 +// clientLanguage is the language ZCode names to marketing/touch: zh-CN or +// en-US, its two UI languages, never another (marketingTouchService's +// localeSchema), so a computer set to zh-Hans-CN or en-GB asks as ZCode does. const clientLanguage = () => { + let l = "" try { - return Intl.DateTimeFormat().resolvedOptions().locale || "en-US" - } catch { - return "en-US" - } + l = Intl.DateTimeFormat().resolvedOptions().locale || "" + } catch {} + return /^zh\b/i.test(l) ? "zh-CN" : "en-US" } // touchPlans is the plans marketing/touch's deliveries offer to claim: @@ -1213,7 +1228,7 @@ async function signedIn(site, token, jwt, device, onTeam = false) { let berr = null if (jwt) { try { - const sp = await startPlan(jwt, device) + const sp = await startPlan(jwt, device, true) if (sp) return { ...(err || !s?.key ? { base: SITES[site].base } : s), jwt, plan: sp.name } } catch (e) { berr = e diff --git a/packages/zcode/package.json b/packages/zcode/package.json index d552e28..37a44cb 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.45", + "version": "0.1.46", "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, and claims its gift plans daily", "type": "module", "main": "./opencode.mjs", diff --git a/packages/zcode/pending.test.mjs b/packages/zcode/pending.test.mjs index b0a817a..75ca156 100644 --- a/packages/zcode/pending.test.mjs +++ b/packages/zcode/pending.test.mjs @@ -132,3 +132,54 @@ test("a plan whose start has come is live, not coming", async () => { const u = await usage(startAuth()) expect(u.windows.map((w) => w.name)).toEqual(["GLM-5.1"]) }) + +// sliyrainbow (Discord, 11-03): a BigModel sign-in with no GLM Coding Plan +// failed "ZCode's Start Plan has ended or was never started". ZCode itself +// counts a Start Plan that starts later as entitled +// (zaiStartPlanBilling.ts resolveStartPlanBalanceAvailability, "pending"), +// so the sign-in takes it, and the card names its start. +function bigmodel(plans) { + return serve(({ url }) => { + const p = url.pathname + if (p === "/api/v1/oauth/cli/init") return ok({ flow_id: "f1", authorize_url: "https://open.bigmodel.cn/login", poll_interval_sec: 0, expires_at: 0 }) + if (p === "/api/v1/oauth/cli/poll/f1") return ok({ status: "ready", bigmodel: { access_token: "bm-token" }, token: jwt(now + 86400), user: { email: "sly@example.com" } }) + if (p === "/api/biz/customer/getCustomerInfo") + return ok({ organizations: [{ organizationId: "o", organizationName: "默认机构", projects: [{ projectId: "p", projectName: "默认项目", projectType: 1 }] }] }) + if (p === "/api/biz/v1/organization/o/projects/p/api_keys") return ok([{ name: "zcode-api-key", apiKey: "own" }]) + if (p === "/api/biz/v1/organization/o/projects/p/api_keys/copy/own") return ok({ secretKey: "s" }) + if (p === "/api/biz/subscription/list") return ok([]) + if (p === "/api/v1/zcode-plan/billing/balance") return ok({ server_time: now, plans, balances: [] }) + }) +} +async function signIn() { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const m = hooks.auth.methods.find((x) => x.label === "ZCode: BigModel (智谱) GLM Coding Plan") + return (await m.authorize()).callback() +} + +for (const status of ["active", "pending_unknown_word"]) { + test(`a sign-in whose only Start Plan starts later is taken, not 'ended or never started' (status ${status})`, async () => { + const calls = bigmodel([next(status)]) + const r = await signIn() + expect(r.error).toBeUndefined() + // the balance is asked as ZCode 3.17.2 asks it: it judges by app_version + const b = calls.find((c) => c.url.pathname === "/api/v1/zcode-plan/billing/balance") + expect(b.url.searchParams.get("app_version")).toBe("3.17.2") + expect(r.type).toBe("success") + const s = JSON.parse(r.refresh) + expect(s).toMatchObject({ site: "bigmodel", plan: "Start Plan" }) + // and the card says when it starts + bigmodel([next(status)]) + const u = await usage(oauth(s)) + expect(u.windows).toEqual([{ name: PENDING, used: 0, aside: true, display: `Start Plan · ${local(later)}` }]) + }) +} + +test("a sign-in with no plan at all, or only an expired one, still says so", async () => { + for (const plans of [[], [{ ...next("expired") }], [{ ...live, ends_at: now - 60 }]]) { + bigmodel(plans) + const r = await signIn() + expect(r.type).toBe("failed") + expect(r.error).toContain("ZCode's Start Plan has ended or was never started") + } +}) diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index f2b96ef..9e293a8 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -203,8 +203,8 @@ test("a Start Plan request carries ZCode's headers, and only those", async () => "anthropic-version": "2023-06-01", "content-type": "application/json", "http-referer": "https://zcode.z.ai", - "user-agent": "ZCode/3.16.3 ai-sdk/anthropic/3.0.81", - "x-zcode-app-version": "3.16.3", + "user-agent": "ZCode/3.17.2 ai-sdk/anthropic/3.0.81", + "x-zcode-app-version": "3.17.2", "x-title": "Z Code@cli", "x-release-channel": "production", "x-client-language": o.locale,