diff --git a/packages/zcode/README.md b/packages/zcode/README.md index df29079..2ad27e6 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -128,9 +128,33 @@ coding plan; when the gift answers a trial entry with a quota error "exceed quota limit", which it can answer inside an HTTP 200) that too becomes a 429 and keeps the entry off for a minute. Any other gift answer (its 405, its 401, its 5xx) goes on as it came: the user picked -the gift, so the coding plan is not spent behind their back. Every 429 -counts as spent, Z.ai's 1302/1303 rate limits among them. A stream's -body is never read or buffered on the way. +the gift, so the coding plan is not spent behind their back. Every other +429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the +plan's own in-flight cap (3008/3009) does not: such a request is asked +again instead (see [A few at once](#a-few-at-once)). A stream's body is +never read or buffered on the way. + +## A few at once + +A plan serves one account a few requests at a time; past that, ZCode +answers 429 with code 3008 "user concurrency limit exceeded", or 3009 +"model concurrency limit exceeded". magpie funnels every agent's and every +session's requests of one computer through this one plugin process, so +magpie's own queue spaces an account's requests by the number this plugin +declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency` +in its `package.json`, both three. A request the vendor refuses anyway +waits a moment (a quarter of a second, then longer — about ten seconds of +waits in all) and asks again, the same request byte for byte. A cap that +outlasts the waits goes on as it came, ZCode's words followed by what it +is, so magpie can move that request along instead of resting the account. + +Three is a default, not a cap the plugin enforces. A plan's real cap +follows its tier — Z.ai serves a Max plan more at once than a Pro, and a +Lite fewer — and is higher off-peak +([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a +number written into the plugin would hold a Max account to a Lite one's +with no way to raise it. A user who knows their plan's cap sets it on the +account or the provider in magpie, and magpie's queue follows that. ## The usage card diff --git a/packages/zcode/concurrency.test.mjs b/packages/zcode/concurrency.test.mjs new file mode 100644 index 0000000..a0dd7e0 --- /dev/null +++ b/packages/zcode/concurrency.test.mjs @@ -0,0 +1,183 @@ +// ZCode serves one account a few requests at a time, and past that answers +// 429 code 3008 "user concurrency limit exceeded" or 3009 "model concurrency +// limit exceeded". magpie sends every agent's and every session's requests of +// this computer through this one plugin process and queues them by the number +// the plugin declares, so a request the vendor refuses anyway is asked again a +// moment later. The requests go to a local Bun.serve; nothing reaches z.ai or +// bigmodel. +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { readFileSync, realpathSync } from "node:fs" +import { ZCodeAuthPlugin, _internal } from "./index.mjs" + +const { busy, spentUp, BUSY_WAITS, DEFAULT_CONCURRENCY } = _internal +const WAITS = [...BUSY_WAITS] + +let server +const got = [] +let answer = null // what the fake answers, when set +beforeAll(() => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + server = Bun.serve({ + port: 0, + async fetch(req) { + got.push({ path: new URL(req.url).pathname, headers: Object.fromEntries(req.headers), body: await req.text() }) + if (answer) return answer() + return Response.json({ type: "message", content: [] }) + }, + }) +}) +afterAll(() => server?.stop(true)) + +// the plugin's requests to the plans go to the fake; anything else fails +const real = globalThis.fetch +const HOSTS = ["https://zcode.z.ai", "https://api.z.ai", "https://open.bigmodel.cn"] +function routeToFake() { + globalThis.fetch = (input, init) => { + const url = input instanceof Request ? input.url : String(input) + const host = HOSTS.find((h) => url.startsWith(h + "/")) + if (!host) throw new Error("no network in tests: " + url) + return real(`http://127.0.0.1:${server.port}/${new URL(host).host}${url.slice(host.length)}`, init) + } +} +beforeEach(() => { + routeToFake() + got.length = 0 + answer = null + // the plans read is this process's: each test starts from none, as the + // other suites do (dual.test.mjs) + _internal.routes.clear() + _internal.blocked.clear() +}) +afterEach(() => { + globalThis.fetch = real + answer = null + BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS) +}) + +const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const DEVICE = "11111111-2222-4333-8444-555555555555" +const auth = () => ({ type: "oauth", access: jwt, refresh: JSON.stringify({ site: "https://zcode.z.ai", device: DEVICE, jwt, plan: "Start Plan" }), expires: 0 }) +const BODY = JSON.stringify({ model: "GLM-5.3", max_tokens: 16, messages: [{ role: "user", content: "hi" }] }) + +// ask sends one request through the plugin and returns its answer unread +async function ask() { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth(), { id: "zcode" }) + const headers = { "content-type": "application/json", "x-api-key": "zcode", "anthropic-version": "2023-06-01", "user-agent": "ai-sdk/anthropic/3.0.81" } + return opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers, body: BODY }) +} + +// one is a whole request, read out, as an agent's client does +async function one() { + const res = await ask() + return { status: res.status, text: await res.text() } +} + +const CAP = { code: 3008, msg: "user concurrency limit exceeded" } + +test("a cap refusal is asked again and the answer served", async () => { + let n = 0 + answer = () => (++n === 1 ? Response.json(CAP, { status: 429 }) : Response.json({ type: "message", content: [] })) + const res = await one() + expect(res.status).toBe(200) + expect(JSON.parse(res.text)).toEqual({ type: "message", content: [] }) + // the same request, byte for byte, and no third ask + expect(got.length).toBe(2) + expect(got[1].path).toBe(got[0].path) + expect(got[1].body).toBe(got[0].body) + expect(got[1].headers["authorization"]).toBe(got[0].headers["authorization"]) + expect(got[1].headers["x-zcode-app-version"]).toBe(got[0].headers["x-zcode-app-version"]) +}) + +test("the cap's own codes are not a gift spent", () => { + expect(spentUp(JSON.stringify(CAP), 429)).toBe(false) + expect(spentUp('{"code":3009,"msg":"model concurrency limit exceeded"}', 429)).toBe(false) + expect(spentUp('{"error":{"code":"3008","message":"user concurrency limit exceeded"}}', 429)).toBe(false) + // a 429 that is a rate limit or a spent plan is as it was + expect(spentUp('{"code":1302,"msg":"rate limit reached"}', 429)).toBe(true) + expect(spentUp('{"error":{"code":"1113"}}', 429)).toBe(true) + expect(spentUp("", 429)).toBe(true) + expect(spentUp('{"code":1005}', 200)).toBe(true) +}) + +test("a rate limit is not asked again", async () => { + answer = () => Response.json({ code: 1302, msg: "rate limit reached" }, { status: 429 }) + const res = await one() + expect(res.status).toBe(429) + expect(got.length).toBe(1) + expect(res.text).toContain("rate limit reached") + expect(res.text).not.toContain("ZCode serves one account") +}) + +test("a cap that outlasts the waits is said plainly, still a 429", async () => { + BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1) + answer = () => Response.json(CAP, { status: 429 }) + const res = await one() + expect(res.status).toBe(429) + expect(got.length).toBe(3) + const said = JSON.parse(res.text).msg + expect(said).toContain("user concurrency limit exceeded (429, code 3008)") + expect(said).toContain("ZCode serves one account a few requests at a time") +}) + +// bodyThatFails is this plugin's fetch answered with a head and one chunk, +// then a body that fails while it is being read: a connection the vendor +// dropped mid-body, or the abort magpie sends when an agent's request goes +// away +function bodyThatFails(status) { + let sent = 0 + return new Response( + new ReadableStream({ + pull(c) { + if (sent++ === 0) return c.enqueue(new TextEncoder().encode('{"msg":"half a body')) + c.error(new Error("the connection dropped mid-body")) + }, + }), + { status, headers: { "content-type": "application/json" } }, + ) +} + +test("a body read that fails is the agent's error, and the account goes on", async () => { + // magpie aborts this fetch when the agent's request goes away, and the + // vendor's connection can drop mid-body: the failure goes back to the agent + // as the error it is, and the next request of the same account is served + const routed = globalThis.fetch + globalThis.fetch = async () => bodyThatFails(429) + expect(await ask().then(() => "served", () => "threw")).toBe("threw") + globalThis.fetch = routed + expect((await one()).status).toBe(200) +}) + +test("a failed read of the no-plan answer is the agent's error too", async () => { + // the other read a request takes: a key with no plan behind it reads what + // Z.ai said, and that read can fail the same way + const key = async () => { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => ({ type: "api", key: "sk-probe", metadata: { site: "zai" } }), { id: "zcode" }) + return opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: BODY }) + } + const routed = globalThis.fetch + globalThis.fetch = async () => bodyThatFails(400) + expect(await key().then(() => "served", () => "threw")).toBe("threw") + globalThis.fetch = routed + expect((await key()).status).toBe(200) +}) + +test("the cap is read by its words when the envelope carries no code", () => { + expect(busy(429, '{"error":{"type":"rate_limit_error","message":"model concurrency limit exceeded"}}')).toBe(true) + expect(busy(200, JSON.stringify(CAP))).toBe(false) + expect(busy(429, "blocked")).toBe(false) + expect(busy(429, '{"code":1302,"msg":"rate limit reached"}')).toBe(false) +}) + +test("the account's cap is declared, and declared as the same number twice", async () => { + // the field magpie reads off the auth hook, and the one its package.json + // declares for a host that reads nothing else: magpie's queue spaces the + // requests by it. It is a default, not a cap the plugin enforces — a plan's + // own cap follows its tier, so a user raises it on the account instead + const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + expect(hooks.auth.maxConcurrency).toBe(DEFAULT_CONCURRENCY) + expect(pkg.magpie.maxConcurrency).toBe(DEFAULT_CONCURRENCY) +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 965707b..6327d90 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -265,9 +265,11 @@ const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) && // spentUp is the gift saying it has nothing left to spend: its own no- // resource-package code 1113, its "exceed quota limit" 1005 — a spent gift -// can answer a 200 with a JSON body carrying one of those codes. Every 429 -// counts as spent, Z.ai's 1302/1303 rate limits among them. +// can answer a 200 with a JSON body carrying one of those codes. Every other +// 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's +// own in-flight cap (3008/3009) does not, since it is a turn not yet come. function spentUp(text, status) { + if (busy(status, text)) return false if (status === 429) return true let b try { b = JSON.parse(text) } catch { return false } @@ -1516,6 +1518,71 @@ function kept(res, text) { return new Response(text !== undefined ? text : res.body, { status: res.status, statusText: res.statusText, headers: h }) } +// ---- the plan's concurrency ------------------------------------------------------ +// ZCode serves one account a few requests at a time. Past that it answers 429 +// with code 3008, "user concurrency limit exceeded", or 3009, "model +// concurrency limit exceeded": the request's turn has not come — not a plan +// spent (1113/1005) and not a rate limit (1302/1303). magpie sends every +// agent's and every session's requests of this computer through this one +// process, and its own queue spaces an account's requests by the number +// declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json); +// a request the vendor refuses anyway waits a moment and asks again, the same +// bytes. A refusal is immediate while a turn's answer is not, so a redundant +// ask costs a round trip and no tokens. +// +// The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai +// serves Max more at once than Pro, and Lite fewer) and is higher off-peak +// (https://docs.z.ai/devpack/usage-policy), so a number written here would +// hold a Max account to a Lite one's, with no way for the user to raise it. +const DEFAULT_CONCURRENCY = 3 +const BUSY_CODES = new Set(["3008", "3009"]) +// BUSY_WAITS are the waits between asks, longest last: about ten seconds of +// them. Past that the account is saturated rather than busy, and magpie's +// routing takes the request (or rests the account, as its 429 says). +const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000] +const BUSY_HINT = + "ZCode serves one account a few requests at a time, and every agent and session of this computer asks through magpie; this request came behind the others, and the same request a moment later is served" + +// busy says a 429 is that in-flight cap: its own code (3008, 3009), or its +// own words when the envelope carries no code. +function busy(status, text) { + if (status !== 429) return false + let b + try { + b = JSON.parse(text) + } catch { + return false + } + if (!b || typeof b !== "object") return false + const say = (v) => (v == null || typeof v === "object" ? "" : String(v)) + if (BUSY_CODES.has(say(b.code) || say(b.error?.code))) return true + return /concurrency limit exceeded/i.test(say(b.msg) + " " + say(b.message) + " " + say(b.error?.message) + " " + say(b.error)) +} + +// busyAnswer is the vendor's cap refusal as the agent reads it: its words, +// then what they are and what to do, as noPlanKey says why a key has no plan. +function busyAnswer(res, text) { + const h = new Headers(res.headers) + h.set("content-type", "application/json") + let v + try { + v = JSON.parse(text) + } catch {} + if (v && typeof v === "object") { + const said = first(v.msg, v.message, v.error?.message, typeof v.error === "string" ? v.error : "", `${res.status}`) + const code = v.code ?? v.error?.code + const head = code != null && !said.includes(String(code)) ? `${said} (${res.status}, code ${code})` : said + const message = `${head} — ${BUSY_HINT}` + const out = v.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message } } : { ...v, msg: message } + return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h }) + } + return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText} — ${BUSY_HINT}`.trim() } }), { + status: res.status, + statusText: res.statusText, + headers: h, + }) +} + function model(m, url) { const e = entry(m) return { @@ -1979,6 +2046,12 @@ export async function ZCodeAuthPlugin({ client }) { }, auth: { provider: PROVIDER, + // a plan serves one account a few requests at a time: magpie's own + // field, so its queue spaces what the agents ask for before the vendor + // sees it. This is a default, not a cap the plugin enforces — a plan's + // own cap follows its tier (Max > Pro > Lite) and the time of day, and + // a user who knows theirs can raise this on the account + maxConcurrency: DEFAULT_CONCURRENCY, async loader(getAuth, provider) { const s0 = stateOf(await getAuth()) if (!s0) return {} @@ -2076,7 +2149,26 @@ export async function ZCodeAuthPlugin({ client }) { h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) } - let res = await fetch(url, { ...opts, headers: h }) + // a refusal that is the account's or the model's own in-flight + // cap is asked again a moment later (see the plan's concurrency): + // magpie sends every agent's and every session's requests of this + // computer through this one process, and its queue spaces them by + // the number declared above + const ask = () => fetch(url, { ...opts, headers: h }) + let res = await ask() + for (let i = 0; res.status === 429; i++) { + const text = await res.text() + const cap = busy(429, text) + if (!cap || i >= BUSY_WAITS.length) { + res = cap + ? busyAnswer(res, text) + : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) + break + } + const w = BUSY_WAITS[i] + await sleep(Math.round(w * (0.75 + Math.random() * 0.5))) + res = await ask() + } // the Start Plan turning the request away says what to do about // it: the account blocked, or the network if (start && res.status >= 400) { @@ -2229,4 +2321,4 @@ export async function ZCodeAuthPlugin({ client }) { // 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, located, dress, PROMPT, marked, keyDevice, sessionOf } +export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index d66add9..ac4fa06 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.31", + "version": "0.1.32", "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", @@ -12,5 +12,8 @@ "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/zcode" + }, + "magpie": { + "maxConcurrency": 3 } }