diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 869ac43..40a33a8 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -350,8 +350,12 @@ menu bar pass it over. The name is a fixed sentence magpie can translate; the count and the plan's own name are the display. Reading the card never claims one. 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), or let the daily claim below do it; -the next read shows it as an ordinary gift bucket. +plan in the ZCode app (open it once); while ZCode asks its security check +for a claim, as it does now, the daily claim below posts none. The next +read shows it as an ordinary gift bucket: its `-Trial` entry is listed and +free first spends it. Until then a `-Trial` pick that finds no gift is +refused with the held plan's name and "claim it in the ZCode app", not +only "no active limited quota" (heduian and bg5eau on X, 11-14). ## The daily claim diff --git a/packages/zcode/gift.test.mjs b/packages/zcode/gift.test.mjs index 75235b1..233115d 100644 --- a/packages/zcode/gift.test.mjs +++ b/packages/zcode/gift.test.mjs @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test" import { homedir, tmpdir } from "node:os" -import { realpathSync } from "node:fs" +import { readFileSync, realpathSync } from "node:fs" if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run in an isolated home") const { ZCodeAuthPlugin, _internal } = await import("./index.mjs") @@ -481,3 +481,66 @@ test("a gift-only account lists only the models its balance names (young02036)", _internal.config(undefined) } }) + +// heduian and bg5eau on X (11-14): on a weekend the GLM-5.3-Flash-Trial +// pick answered only "no active limited quota". The weekend plan +// (ZCODE WEEKEND BUILD, testdata/touch-1030-wk.json, the feed's real +// reply) is a gift ZCode holds until it is claimed, and its claim needs +// the ZCode app's captcha, which the plugin doesn't post. The refusal +// now names the held plan and where it is claimed; it still asks no +// model and posts no claim, and the feed is read once for a retry. +test("a -Trial pick with no gift names the weekend plan ZCode holds unclaimed", async () => { + const touch = readFileSync(new URL("./testdata/touch-1030-wk.json", import.meta.url), "utf8") + balance = { server_time: now, plans: [], balances: [] } + _internal.unclaimedSeen.clear() + const asked = [] + const base = globalThis.fetch + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.pathname === "/api/v1/marketing/touch") { + asked.push((init.method ?? "GET").toUpperCase()) + return new Response(touch, { headers: { "content-type": "application/json" } }) + } + if (url.pathname === "/api/v1/zcode-plan/billing/claim") throw new Error("a claim was posted") + return base(input, init) + } + for (let i = 0; i < 2; i++) { + const res = await send("GLM-5.3-Flash-Trial") + expect(res.status).toBe(400) + const { error } = await res.json() + expect(error.message).toStartWith("ZCode has no active limited quota for GLM-5.3-Flash-Trial. ") + expect(error.message).toContain("ZCODE WEEKEND BUILD") + expect(error.message).toContain("claim it in the ZCode app") + } + expect(asked).toEqual(["GET"]) + expect(sent).toHaveLength(0) +}) + +test("a -Trial pick with no gift and nothing held says only that there is none", async () => { + balance = { server_time: now, plans: [], balances: [] } + _internal.unclaimedSeen.clear() + const base = globalThis.fetch + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.pathname === "/api/v1/marketing/touch") return ok({ deliveries: [] }) + return base(input, init) + } + const res = await send("GLM-5.3-Flash-Trial") + expect(res.status).toBe(400) + expect((await res.json()).error.message).toBe("ZCode has no active limited quota for GLM-5.3-Flash-Trial") + expect(sent).toHaveLength(0) +}) + +test("a -Trial pick whose feed doesn't read says only that there is none, and asks the feed again", async () => { + balance = { server_time: now, plans: [], balances: [] } + _internal.unclaimedSeen.clear() + let reads = 0 + const base = globalThis.fetch + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.pathname === "/api/v1/marketing/touch") return reads++, new Response("bad gateway", { status: 502 }) + return base(input, init) + } + for (let i = 0; i < 2; i++) expect((await (await send("GLM-5.3-Flash-Trial")).json()).error.message).toBe("ZCode has no active limited quota for GLM-5.3-Flash-Trial") + expect(reads).toBe(2) +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index d63511a..83277f7 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -715,6 +715,28 @@ async function claimHint(s) { return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` } } +// unclaimed names the gift plans ZCode holds for the account but has not +// put on it (toClaim), for a -Trial pick that finds no gift: the weekend +// plan (ZCODE WEEKEND BUILD) comes only by a claim, and the claim needs +// the ZCode app's captcha (claimDaily posts none), so until it is +// claimed in the app the pick's quota does not exist yet (heduian and +// bg5eau on X, 11-14). The refusal says where the quota is rather than +// only that there is none. Kept ten minutes per session, so an agent +// retrying the pick doesn't read the feed each time; a read that fails +// names none and is not kept. +const unclaimedSeen = new Map() +async function unclaimed(s) { + if (!s.jwt || jwtExpired(s.jwt)) return [] + const k = s.jwt + const c = unclaimedSeen.get(k) + if (c && Date.now() - c.at < 600_000) return c.names + const got = await toClaim(s).catch(() => null) + if (!got || got.unread.length) return [] + const names = uniqueModels(got.plans.map((p) => first(p.name, p.plan_id)).filter(Boolean)) + unclaimedSeen.set(k, { at: Date.now(), names }) + return names +} + // ---- the daily claim --------------------------------------------------------------- // CLAIMED_ALREADY is /billing/claim's body code for a plan the account @@ -3119,7 +3141,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { const raw = giftModel(gift, m) const available = raw && giftUsable(s, gift, raw) if (!available) { - const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}` } + const held = raw ? [] : await unclaimed(s) + const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}${held.length ? `. ZCode holds ${held.join(", ")} for this account unclaimed: claim it in the ZCode app (its claim needs the app's security check), and ${m} spends it` : ""}` } return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } })) } orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) @@ -3501,4 +3524,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // 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 = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS } +export const _internal = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, unclaimed, unclaimedSeen, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index e0e80d8..4ab1c1a 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.64", + "version": "0.1.65", "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",