diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 0fab6f9..c6f79fc 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -44,6 +44,10 @@ over Anthropic's Messages API. Provider id: `zcode`. - It is kept as an account of its own, named ` (team)`, beside the account's own plan, so both can be used. - With no seat on a team's plan, it says so and signs in to nothing. + - The same ZCode session also reads the person's gift plans. Their + `-Trial` entries and gift buckets appear beside the team's + models and allowance. Plain models spend the team plan; trial entries + spend the personal gift, with no fallback to the team on refusal. - **ZCode app's sign-in** - Uses the account the ZCode app on this computer is signed in to. For every request it reads ZCode's own credentials (`~/.zcode/v2`), so it diff --git a/packages/zcode/docs/bdd/gift-models.md b/packages/zcode/docs/bdd/gift-models.md index 44082d5..0d08d3d 100644 --- a/packages/zcode/docs/bdd/gift-models.md +++ b/packages/zcode/docs/bdd/gift-models.md @@ -17,6 +17,15 @@ Magpie plugin contract. No new UI page or test framework is introduced. ## Scenarios +### Show a team member's personal gift plans (#359) + +- Given a team seat's ZCode session also holds personal gift plans. +- When the plugin lists models and reads usage, even before resolving the team's key. +- Then the trial entries and personal gift buckets appear beside the team plan. +- And plain models spend the team plan while trial entries spend the personal gift. +- And a missing or expired ZCode session explains why trial entries are absent. +- And a failed gift read leaves the team's allowance available and retries within a minute. + ### Add a real limited-quota model - Given a coding-plan account has an active grant for a model absent from its plan catalog. diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index ba32b14..0274bc0 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -194,8 +194,8 @@ async function startPlan(jwt, device) { // plansOf says where an account's requests go and what more it can spend: // {start, gift}. start is what onStart said: an account with no coding plan -// sends every request to the gift and reads no balance to do it; a team's -// seat, a sign-in with no ZCode token and a key whose plan-list read found +// sends every request to the gift and reads no balance to do it; a +// sign-in with no ZCode token and a key whose plan-list read found // no gift stay on the coding plan. gift is what a coding account also holds: // the gift plans ({models}), and its requests spend the gift for a model it // serves, until it says it is spent (see blocked). Asked again after 10 @@ -204,8 +204,8 @@ async function startPlan(jwt, device) { // ask). const routes = new Map() async function plansOf(s) { - if (isTeam(s) || !s.jwt) return { start: false, gift: null } - if (!s.key) return { start: true, gift: null } + if (!s.jwt) return { start: false, gift: null } + if (!s.key && !isTeam(s)) return { start: true, gift: null } const id = s.key + "\0" + s.jwt const r = routes.get(id) if (r && Date.now() - r.at < r.ttl) return r @@ -213,7 +213,9 @@ async function plansOf(s) { let gift = null let sure = false try { - if (!(await plan(s))) start = true + // A team seat stays on its team even when its personal plan list is + // empty. Its ZCode session still holds the person's gift plans. + if (!isTeam(s) && !(await plan(s))) start = 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 @@ -632,7 +634,6 @@ async function claimHint(s) { // 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 @@ -704,8 +705,8 @@ function bestBuckets(windows) { // Fresh usage also updates the request cache, so a replenished or spent // gift takes effect before its ten-minute route cache expires. A failed // gift read leaves the working Coding Plan's card and route alone. -async function dualUsage(s) { - const out = await codingUsage(s) +async function dualUsage(s, out) { + out ??= await codingUsage(s) const cached = routes.get(s.key + "\0" + s.jwt) try { const g = await giftOf(s) @@ -1971,6 +1972,8 @@ export async function ZCodeAuthPlugin({ client }) { return out } try { + const { start, gift } = await plansOf(s) + let card if (isTeam(s)) { let key = s.key if (!key) { @@ -1980,10 +1983,9 @@ export async function ZCodeAuthPlugin({ client }) { await client?.auth?.set?.({ path: { id: provider?.id ?? PROVIDER }, body: next }).catch?.(() => {}) } } - return saved(await teamUsage(s, key)) - } - const { start, gift } = await plansOf(s) - const card = saved(start ? await startUsage(s) : gift ? await dualUsage(s) : await codingUsage(s)) + const team = await teamUsage(s, key) + card = saved(gift ? await dualUsage(s, team) : team) + } else 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 diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index 91aa163..634ab73 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -59,7 +59,7 @@ const start = (site) => { // send makes a request as @ai-sdk/anthropic does, to the URL it was made for // place is what magpie tells the fetch of where the agent works, as its // headers: {dir, git} -async function send(auth, body, { url = "https://api.z.ai/api/anthropic/v1/messages", asRequest = false, place = {}, extra = {} } = {}) { +async function send(auth, body, { url = "https://api.z.ai/api/anthropic/v1/messages", asRequest = false, place = {}, extra = {}, requests = 1 } = {}) { routeToFake() const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) @@ -70,8 +70,10 @@ async function send(auth, body, { url = "https://api.z.ai/api/anthropic/v1/messa ? await opts.fetch(new Request(url, { method: "POST", headers, body })) : await opts.fetch(url, { method: "POST", headers, body }) expect(res.status).toBe(200) - expect(got.length).toBe(1) - return got[0] + expect(got.length).toBe(requests) + const messages = got.filter((r) => r.path.endsWith("/messages")) + expect(messages.length).toBe(1) + return messages[0] } // what the HTTP client adds on its own, whatever the plugin sets @@ -383,7 +385,12 @@ test("a GLM Coding Plan key's request goes as the agent sent it", async () => { test("a team seat's request goes as the agent sent it, ZCode's token or not", async () => { const s = { site: "zai", base: "https://api.z.ai/api/anthropic", key: "team.secret", token: "tok", org: "o1", project: "p1", jwt, device: DEVICE } 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") + sentAsIs(await send(auth, agentText, { requests: 2 }), "team.secret", "/api.z.ai/api/anthropic/v1/messages") + expect(got.filter((r) => r.path.endsWith("/billing/balance"))).toHaveLength(1) + expect(got.filter((r) => r.path.endsWith("/subscription/list"))).toHaveLength(0) + got.length = 0 + sentAsIs(await send({ ...auth, refresh: JSON.stringify({ ...s, jwt: "" }) }, agentText), "team.secret", "/api.z.ai/api/anthropic/v1/messages") + expect(got).toHaveLength(1) }) // magpie's provider.ZCodeRestrictedHint and provider.BlockedHint, word for word diff --git a/packages/zcode/team-gift.test.mjs b/packages/zcode/team-gift.test.mjs new file mode 100644 index 0000000..7aae37e --- /dev/null +++ b/packages/zcode/team-gift.test.mjs @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with an isolated HOME") +const { ZCodeAuthPlugin, _internal } = await import("./index.mjs") +const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const state = { site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "team.secret", token: "team-token", org: "org", project: "project", jwt, device: "test-device", plan: "Team Max" } +const auth = (s = state) => ({ type: "oauth", access: s.key, refresh: JSON.stringify(s), expires: 0 }) +const now = Math.floor(Date.now() / 1000) +const balance = { + plans: [{ plan_id: "dev-day", name: "ZCode 1024 Dev Day", status: "active", ends_at: now + 86400 }], + balances: [{ plan_id: "dev-day", show_name: "GLM-5.3", capabilities: ["model:glm-5.3"], total_units: 100, used_units: 25, remaining_units: 75 }], +} +const real = globalThis.fetch +let sent, failGift +const ok = (data) => Response.json({ code: 0, data }) +beforeEach(() => { + _internal.routes.clear() + _internal.blocked.clear() + sent = [] + failGift = false + globalThis.fetch = async (input, init = {}) => { + const url = new URL(String(input)) + const headers = new Headers(init.headers) + sent.push({ url, headers, body: init.body }) + switch (url.pathname) { + case "/api/v1/zcode-plan/billing/balance": return failGift ? new Response("", { status: 502 }) : ok(balance) + // A team's personal subscription list is empty; it must stay on its team. + case "/api/biz/subscription/list": return ok([]) + case "/api/monitor/usage/quota/limit": return ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 90 }] }) + case "/api/biz/team/subscribe/product/querySubscribeDetail": return ok({ hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID", productName: "Team Max" }) + case "/api/biz/customer-package-reset/list": return ok({}) + case "/api/v1/zcode-plan/billing/preview": return ok({ plans: [{ plan_id: "trust", name: "Trust Build" }] }) + case "/api/anthropic/v1/messages": + case "/api/v1/zcode-plan/anthropic/v1/messages": return ok({ type: "message", content: [] }) + default: return new Response("", { status: 404 }) + } + } +}) +afterEach(() => { globalThis.fetch = real }) +const hooks = () => ZCodeAuthPlugin({ client: {} }) + +test("a team seat lists personal gift trials even without a resolved team key", async () => { + const h = await hooks() + for (const key of [state.key, ""]) { + const models = await h.provider.models({ models: {} }, { auth: auth({ ...state, key }) }) + expect(models["GLM-5.3-Trial"]).toBeDefined() + expect(models["GLM-5.3"]).toBeDefined() + expect((await _internal.plansOf({ ...state, key })).start).toBe(false) + } + expect(sent.filter((x) => x.url.pathname === "/api/biz/subscription/list")).toHaveLength(0) +}) + +test("the team card includes gift buckets and hints, with separate model limits", async () => { + const h = await hooks() + const card = await h.auth.usage(async () => auth()) + expect(card.plan).toBe("Team Max") + expect(card.windows[0]).toMatchObject({ used: 90, notModels: ["glm-5.3-trial"] }) + expect(card.windows.find((w) => w.models?.includes("GLM-5.3-Trial"))).toMatchObject({ used: 25 }) + expect(card.windows.find((w) => w.name === "Gift plans to claim in the ZCode app")).toBeDefined() +}) + +test("a gift failure preserves the team card and retries within a minute", async () => { + failGift = true + const h = await hooks() + await h.provider.models({ models: {} }, { auth: auth() }) + const card = await h.auth.usage(async () => auth()) + expect(card.error).toBeUndefined() + expect(card.windows[0].used).toBe(90) + const route = await _internal.plansOf(state) + expect(route).toMatchObject({ start: false, gift: null }) + expect(route.ttl).toBeLessThanOrEqual(60000) +}) + +test("a team without a ZCode session explains the missing trials", async () => { + const h = await hooks() + const card = await h.auth.usage(async () => auth({ ...state, jwt: "" })) + expect(card.windows.find((w) => w.name === "ZCode gift plans (-Trial models) need ZCode's sign-in")).toBeDefined() + expect(sent.filter((x) => x.url.pathname.includes("/billing/"))).toHaveLength(0) +}) + +test("ordinary models spend the team; trials spend the personal gift without team credentials", async () => { + const h = await hooks() + const loader = await h.auth.loader(async () => auth(), { id: "zcode" }) + for (const model of ["GLM-5.3", "GLM-5.3-Trial"]) { + expect((await loader.fetch(state.base + "/v1/messages", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model, max_tokens: 1, messages: [{ role: "user", content: "hi" }] }) })).status).toBe(200) + } + const messages = sent.filter((x) => x.url.pathname.endsWith("/messages")) + expect(messages).toHaveLength(2) + expect(messages[0].url.origin).toBe("https://open.bigmodel.cn") + expect(messages[0].headers.get("x-api-key")).toBe(state.key) + expect(messages[1].url.origin).toBe("https://zcode.z.ai") + expect(messages[1].headers.get("authorization")).toBe("Bearer " + jwt) + expect(messages[1].headers.get("x-api-key")).toBeNull() + expect(messages[1].headers.get("Bigmodel-Organization")).toBeNull() + expect(JSON.parse(messages[1].body).model).toBe("glm-5.3") +}) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index 0f64601..763508b 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -308,6 +308,7 @@ test("a team seat: the team plan's windows, name, end and resets, its key found 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 }, + { name: "ZCode gift plans (-Trial models) need ZCode's sign-in", used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" }, ], }) expect(made).toEqual({ name: "zcode-team-api-key", keyType: 2 })