zcode 0.1.66: a gift-only account's model the gift doesn't name is not sent to be billed, and a failed plan read keeps it on the gift (bg5eau on X)
bg5eau on X (11-14): through magpie ZCode's gift quota stopped going down while the account's pay-as-you-go balance was charged. Two routes in the plugin let a key with no GLM Coding Plan spend money while its free Start Plan quota sat unspent: - A gift-only account sends every request to the Start Plan, whatever the model. ZCode's app offers such an account only the models its balance names (resolveStartPlanBalanceAvailability in 3.18.2); an agent left on another model (GLM-5.2 while the gift serves only GLM-5.3-Flash) spent none of the gift. Such a request is now answered 400 with the models the balance names and is not sent. The balance is the one the model list already reads (aloneSeen, ten minutes); only a model it doesn't name has it read again, so a gift claimed since is sent, and a request whose model it names reads nothing. A balance not read yet, one that fails, or one naming none leaves the request as it was (unknown is not a refusal). - plansOf's catch path: a plan-list read that failed sent every key account down the dual route, to api.z.ai / open.bigmodel.cn's /api/anthropic with its key, which bills a key with no plan pay-as-you-go. An account whose last read found no plan now stays on the Start Plan for the minute. A key with no earlier read still takes the dual route, as before. Not known: which of the two was bg5eau's (no request log from them). No 503 is made by the plugin (skykiahhub's 503 on X is the vendor's or one of magpie's own, each of which says why). Run (mote, load ~130-180, mica's disk was full; HOME=$(mktemp -d)): bun test packages/zcode 271 pass 0 fail; bun scripts/check.mjs zcode ok. Broken by hand: the guard off, "a gift-only account's model its balance doesn't name is not sent" fails; the catch-path change off, "a gift-only account stays on the Start Plan when its plan list stops reading" fails (it sent GLM-5.2 to api.z.ai). Not tried: a real gift-only account (the owner's has a coding plan and no gift), a real pay-as-you-go charge, Windows and Linux.
This commit is contained in:
@@ -117,7 +117,14 @@ the plans again on the next request:
|
||||
(`/api/biz/subscription/list`), its requests go to that plan. A model
|
||||
the account's gift plans also serve is listed again as
|
||||
`<model>-Trial`; asking that entry spends the gift (see below).
|
||||
- Otherwise they go to the gift plans.
|
||||
- Otherwise they go to the gift plans. A model the gift plans' balance
|
||||
doesn't name (an agent left on GLM-5.2 while the gift serves only
|
||||
GLM-5.3-Flash) would spend none of the free quota, so it is answered
|
||||
with the models the balance names and not sent. The balance is the one
|
||||
the model list read; a model it doesn't name has it read again first.
|
||||
When the plan list can't be read, an account whose last read found no
|
||||
plan stays on the gift plans rather than sending its key to the coding
|
||||
plan's host, which bills a key with no plan pay-as-you-go.
|
||||
|
||||
Every request carries the key as both `x-api-key` and
|
||||
`Authorization: Bearer`.
|
||||
|
||||
@@ -19,6 +19,7 @@ let balance, paid, giftReply, planReply
|
||||
beforeEach(() => {
|
||||
_internal.routes.clear()
|
||||
_internal.blocked.clear()
|
||||
_internal.aloneSeen.clear()
|
||||
sent.length = 0
|
||||
paid = 100
|
||||
planReply = null
|
||||
@@ -544,3 +545,98 @@ test("a -Trial pick whose feed doesn't read says only that there is none, and as
|
||||
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)
|
||||
})
|
||||
|
||||
// bg5eau on X (11-14): "the gift isn't spent, pay-as-you-go is charged".
|
||||
// A key with no coding plan sends every request to the Start Plan, which
|
||||
// serves the models its balance names; ZCode's app offers only those
|
||||
// (resolveStartPlanBalanceAvailability). Another model the agent was left
|
||||
// on spent none of the gift. It is now answered here, and a plan-list read
|
||||
// that fails no longer moves such an account onto the coding plan's host,
|
||||
// where its key is billed pay-as-you-go.
|
||||
const giftOnly = (subs) => {
|
||||
balance.plans = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", name: "ZCode Start Plan", status: "active", ends_at: now + 7 * 86400 }]
|
||||
balance.balances = [{ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.3-Flash", capabilities: ["model:glm-5.3-flash"], total_units: 5_000_000, used_units: 0, remaining_units: 5_000_000 }]
|
||||
const base = globalThis.fetch
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input))
|
||||
if (url.pathname === "/api/biz/subscription/list") return subs()
|
||||
return base(input, init)
|
||||
}
|
||||
}
|
||||
const noPlan = { type: "oauth", access: state.key, refresh: JSON.stringify({ ...state, plan: undefined }), expires: 0 }
|
||||
|
||||
const listed = async (credentials = noPlan) => (await hooks()).provider.models({ models: {} }, { auth: credentials })
|
||||
|
||||
test("a gift-only account's model its balance doesn't name is not sent (bg5eau)", async () => {
|
||||
giftOnly(() => ok([]))
|
||||
expect(Object.keys(await listed())).toContain("GLM-5.3-Flash")
|
||||
const res = await send("GLM-5.2", noPlan)
|
||||
expect(res.status).toBe(400)
|
||||
const { error } = await res.json()
|
||||
expect(error.message).toContain("serves GLM-5.3-Flash;")
|
||||
expect(error.message).toContain("GLM-5.2 is not among them")
|
||||
expect(sent).toHaveLength(0)
|
||||
expect((await send("GLM-5.3-Flash", noPlan)).status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: "GLM-5.3-Flash" } })
|
||||
})
|
||||
|
||||
test("a gift-only account reads no balance for a request whose model the list's balance names", async () => {
|
||||
giftOnly(() => ok([]))
|
||||
await listed()
|
||||
let reads = 0
|
||||
const base = globalThis.fetch
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
if (new URL(input instanceof Request ? input.url : String(input)).pathname === "/api/v1/zcode-plan/billing/balance") reads++
|
||||
return base(input, init)
|
||||
}
|
||||
for (let i = 0; i < 3; i++) expect((await send("GLM-5.3-Flash", noPlan)).status).toBe(200)
|
||||
expect(reads).toBe(0)
|
||||
})
|
||||
|
||||
test("a gift claimed since the list was read is sent, not refused", async () => {
|
||||
giftOnly(() => ok([]))
|
||||
await listed()
|
||||
balance.balances.push({ plan_id: "zcode-v3-start-plan", user_plan_id: "s1", show_name: "GLM-5.2", capabilities: ["model:glm-5.2"], total_units: 100, used_units: 0, remaining_units: 100 })
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
||||
})
|
||||
|
||||
test("a gift-only account whose balance doesn't read again sends the request as before", async () => {
|
||||
giftOnly(() => ok([]))
|
||||
await listed()
|
||||
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/zcode-plan/billing/balance") return new Response("bad gateway", { status: 502 })
|
||||
return base(input, init)
|
||||
}
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
||||
})
|
||||
|
||||
test("a gift-only account stays on the Start Plan when its plan list stops reading (bg5eau)", async () => {
|
||||
let down = false
|
||||
giftOnly(() => (down ? new Response("bad gateway", { status: 502 }) : ok([])))
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
// GLM-5.2, which the gift doesn't serve: free first would take a
|
||||
// gift model to the gift on either route
|
||||
// the route's ten minutes pass, and the next plan-list read fails
|
||||
for (const r of _internal.routes.values()) r.at = 0
|
||||
down = true
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
expect(sent.map((x) => x.origin)).toEqual(["https://zcode.z.ai", "https://zcode.z.ai"])
|
||||
})
|
||||
|
||||
test("a coding plan account whose plan list stops reading still takes the plan", async () => {
|
||||
let down = false
|
||||
giftOnly(() => (down ? new Response("bad gateway", { status: 502 }) : ok([{ productName: "GLM Coding Pro", status: "VALID" }])))
|
||||
balance.balances = []
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
for (const r of _internal.routes.values()) r.at = 0
|
||||
down = true
|
||||
expect((await send("GLM-5.2", noPlan)).status).toBe(200)
|
||||
expect(sent.map((x) => x.origin)).toEqual(["https://api.z.ai", "https://api.z.ai"])
|
||||
})
|
||||
|
||||
@@ -263,13 +263,20 @@ async function plansOf(s) {
|
||||
// Plan's 405 until the route was read again (#369)
|
||||
if (start) sure = !(s.key && r && !r.start)
|
||||
} 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
|
||||
// refusal still replays to the coding plan rather than blacking out
|
||||
try {
|
||||
gift = await startPlan(s.jwt, s.device)
|
||||
sure = false
|
||||
} catch {}
|
||||
// the plan list could not be read. An account the last read found with
|
||||
// no coding plan stays on the Start Plan for the minute: the dual route
|
||||
// would send its key to the coding plan's host, which bills a key with
|
||||
// no plan pay-as-you-go while the free quota sits unspent (bg5eau on
|
||||
// X). Any other key account takes the dual route (start stays false,
|
||||
// the gift is kept, a minute's ttl), so a gift refusal still replays to
|
||||
// the coding plan rather than blacking out
|
||||
if (r?.start) start = true
|
||||
else {
|
||||
try {
|
||||
gift = await startPlan(s.jwt, s.device)
|
||||
} catch {}
|
||||
}
|
||||
sure = false
|
||||
}
|
||||
const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) }
|
||||
routes.set(id, out)
|
||||
@@ -724,6 +731,26 @@ async function claimHint(s) {
|
||||
// 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.
|
||||
// aloneSeen is a gift-only account's balance as last read (the model list
|
||||
// reads it), kept ten minutes. A request reads no balance on its own: only
|
||||
// a model the kept balance doesn't name has it read again (aloneGift), so
|
||||
// a gift claimed since is not refused. A read that fails is not kept.
|
||||
const aloneSeen = new Map()
|
||||
const aloneNames = (s) => {
|
||||
const c = aloneSeen.get(s.jwt)
|
||||
return c && Date.now() - c.at < 600_000 ? giftNames(c.gift) : []
|
||||
}
|
||||
async function aloneGift(s) {
|
||||
let gift
|
||||
try {
|
||||
gift = await startPlan(s.jwt, s.device)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
aloneSeen.set(s.jwt, { at: Date.now(), gift })
|
||||
return gift
|
||||
}
|
||||
|
||||
const unclaimedSeen = new Map()
|
||||
async function unclaimed(s) {
|
||||
if (!s.jwt || jwtExpired(s.jwt)) return []
|
||||
@@ -2992,7 +3019,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
||||
const s = await located(stateOf(auth))
|
||||
if (!s) return provider.models
|
||||
const { start, gift: known } = await plansOf(s).catch(() => ({ start: false, gift: null }))
|
||||
const gift = start ? await startPlan(s.jwt, s.device).catch(() => null) : known
|
||||
const gift = start ? await aloneGift(s) : known
|
||||
const base = start ? START_BASE : s.base
|
||||
const cfg = await zcodeConfig().catch(() => null)
|
||||
let ms = modelsOf(cfg, planID(base))
|
||||
@@ -3169,6 +3196,25 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
||||
m = raw
|
||||
freeGift = true
|
||||
giftName = giftID(raw)
|
||||
} else if (alone && /\/v1\/messages$/.test(new URL(url).pathname)) {
|
||||
// a gift-only account's Start Plan serves the models its
|
||||
// balance names, and ZCode's app offers only those
|
||||
// (resolveStartPlanBalanceAvailability). Any other model
|
||||
// spends none of the free quota, so it is not sent: an
|
||||
// agent left on another model would be billed while the
|
||||
// gift stayed unspent (bg5eau on X). The balance is the
|
||||
// one the model list read (aloneSeen); a model it doesn't
|
||||
// name has it read again before the refusal. One not read
|
||||
// yet, one that fails, or one naming none leaves the
|
||||
// request as it was.
|
||||
const named = (ns) => ns.some((x) => x.toLowerCase() === m.toLowerCase())
|
||||
const kept0 = aloneNames(s)
|
||||
const names = kept0.length && !named(kept0) ? giftNames(await aloneGift(s)) : []
|
||||
if (names.length && !named(names)) {
|
||||
const shown = uniqueModels(names.map(wireModel))
|
||||
const error = { type: "invalid_request_error", message: `ZCode's Start Plan on this account serves ${shown.join(", ")}; ${m} is not among them and would spend none of its free quota, so it was not sent. Pick ${shown.length > 1 ? "one of those" : shown[0]} for this account` }
|
||||
return kept(new Response(JSON.stringify({ type: "error", error }), { status: 400, headers: { "content-type": "application/json" } }))
|
||||
}
|
||||
}
|
||||
start = alone || forcedGift || freeGift
|
||||
}
|
||||
@@ -3524,4 +3570,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, unclaimed, unclaimedSeen, 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, aloneGift, aloneSeen, aloneNames, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zcode-auth",
|
||||
"version": "0.1.65",
|
||||
"version": "0.1.66",
|
||||
"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",
|
||||
|
||||
Reference in New Issue
Block a user