From 36dc4007fc8824e5e03f03b4714e17ca0005565c Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 17 Nov 2026 01:24:45 +0800 Subject: [PATCH] zcode 0.1.68: every account takes requests, the Start Plan held to six in flight from this address mathfournity on X: with several ZCode accounts in magpie, requests went to two of them only. 0.1.40 declared maxAccounts 2 after 01huadalang's address was refused with a 405 while three accounts took requests at once, so magpie kept the first two of the list taking requests and held every other account in reserve until one rested. A user with five gift accounts saw two used. What zcode.z.ai's edge firewall counts is the address's Start Plan requests in flight (busyHold's logs: ~10 in flight against a cap of three before the IP's 405), not how many accounts sent them. So the plugin no longer declares maxAccounts, and holds that instead: besides each account's three (startGate), every account's Start Plan requests share one address lane of six, what two accounts of three each sent while the two-account default stood. A request takes its account's slot first, then the address's, within the one 120s wait; a wait that runs out on the address's is answered here with a 429 that says so, nothing sent, and lets the account's slot go. Free first counts the address lane full as it does the account's. The coding plan, on api.z.ai, is held to none of it. A user's own Accounts at once is kept as they set it. Run: - HOME=$(mktemp -d) bun test in packages/zcode on the Linux box (wsl-run, Bun 1.4.2): 275 pass, 0 fail. - Broken by hand: the new tests against origin/main's index.mjs and package.json: 3 red (maxAccounts 2 declared; peak 12 in flight over four accounts where six are allowed; the address wait never runs out). - magpie's gateway with this plugin under bun and four accounts on a fake Z.ai (a throwaway test, not committed, on mote): 12 requests at once went 3/3/3/3 to the four accounts, where 0.1.67 sent 6/6 to two and none to the others; 1302, 1308, 3008 and 500 on one account each went to the next and rested the first, as before. - start.test's in-flight hold test parks twelve accounts' requests at once; it raises the address lane to twelve, since the hold's handling of such a run is what it tests. Not tried: a real ZCode account; whether zcode.z.ai refuses an address for the number of accounts as well as for requests in flight. --- packages/zcode/README.md | 27 +++++----- packages/zcode/concurrency.test.mjs | 15 +++--- packages/zcode/index.mjs | 77 ++++++++++++++++++++++------- packages/zcode/inflight.test.mjs | 56 +++++++++++++++++++++ packages/zcode/package.json | 5 +- packages/zcode/start.test.mjs | 5 ++ 6 files changed, 145 insertions(+), 40 deletions(-) diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 95df350..e717b63 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -295,18 +295,23 @@ which it is answered here with the queue's 429. A request refused alone, or free first's gift (which goes to the coding plan), is answered as before. -## Two accounts at once +## Every account, one address -Three ZCode accounts used at once from one address can get the address -refused with a 405, where two are served (01huadalang on Discord). So the -plugin declares `maxAccounts` two, on the auth hook and as -`magpie.maxAccounts` in its `package.json`: magpie sends requests to the -first two accounts of the user's list only, and holds the others in -reserve. One that runs out or fails rests, and the first in reserve takes -its place until it is back. A user changes the number on the provider in -magpie (Advanced → Accounts at once, or `magpie provider at-once zcode -`), 0 for every account at once. A magpie older than the one that -reads it uses every account, as before. +The plugin declares no `maxAccounts`, so magpie sends requests to every +ZCode account of the user's: the routing chosen spreads them, and one +that runs out or fails rests while the others go on. A user who wants +fewer sets the number on the provider in magpie (Advanced → Accounts at +once, or `magpie provider at-once zcode `). + +What zcode.z.ai's firewall refuses an address for (405, for an hour or +two) is too many Start Plan requests in flight from it at once, whichever +accounts they are for. So besides each account's three, the Start Plan +is sent at most six requests at a time from this computer over all its +accounts; the rest wait their turn in the plugin, as an account's own do. +Six is what two accounts sent when 0.1.40 to 0.1.67 declared +`maxAccounts` two after a 405 with three (01huadalang on Discord), which +held a user's other accounts in reserve. The coding plan, on another +host, is held to none of it. ## The usage card diff --git a/packages/zcode/concurrency.test.mjs b/packages/zcode/concurrency.test.mjs index af52ce7..ab8e408 100644 --- a/packages/zcode/concurrency.test.mjs +++ b/packages/zcode/concurrency.test.mjs @@ -10,7 +10,7 @@ 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, DEFAULT_ACCOUNTS } = _internal +const { busy, spentUp, BUSY_WAITS, DEFAULT_CONCURRENCY } = _internal const WAITS = [...BUSY_WAITS] let server @@ -186,13 +186,12 @@ test("the account's cap is declared, and declared as the same number twice", asy expect(pkg.magpie.maxConcurrency).toBe(DEFAULT_CONCURRENCY) }) -test("two accounts at once are declared, the same number twice", async () => { - // 01huadalang on Discord: three ZCode accounts used at once from one - // address got it refused with a 405, two didn't. magpie keeps the first - // two of the user's list taking requests and the others in reserve +test("no accounts at once are declared, so magpie uses every account", async () => { + // mathfournity on X: with maxAccounts two, a user's other gift accounts + // sat in reserve. The address's Start Plan requests in flight are held + // instead (inflight.test.mjs), over every account const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) - expect(DEFAULT_ACCOUNTS).toBe(2) - expect(hooks.auth.maxAccounts).toBe(DEFAULT_ACCOUNTS) - expect(pkg.magpie.maxAccounts).toBe(DEFAULT_ACCOUNTS) + expect(hooks.auth.maxAccounts).toBeUndefined() + expect(pkg.magpie.maxAccounts).toBeUndefined() }) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index e1f3ab1..50b41f5 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -2124,13 +2124,16 @@ function kept(res, text) { // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in // package.json), which a user raises on the account. const DEFAULT_CONCURRENCY = 3 -// DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends -// requests to at the same time (maxAccounts, on the auth hook and in -// package.json): the first in the user's list, the next taking over once -// one runs out or fails. 01huadalang on Discord: three accounts used at -// once from one address got the address refused with a 405, two didn't. A -// user sets their own on the provider (Accounts at once), 0 for no limit. -const DEFAULT_ACCOUNTS = 2 +// No maxAccounts is declared: magpie sends requests to every ZCode account +// of the user's, and a user still sets their own on the provider (Accounts +// at once). 0.1.40 to 0.1.67 declared two, after 01huadalang's address was +// refused with a 405 while three accounts took requests at once (Discord), +// and the others sat in reserve until one ran out: a user with five gift +// accounts saw two used (mathfournity on X). What the edge firewall counts +// is this address's Start Plan requests in flight, not its accounts (see +// busyHold), so that is what is held now, over every account (startGate's +// address): as many as two accounts had in flight before, while a coding +// plan account, on another host, is held to none of it. const BUSY_CODES = new Set(["3008", "3009", "3010"]) // BUSY_WAITS are the waits before each ask again: ZCode's own client's, // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie, @@ -2172,11 +2175,18 @@ const BUSY_HINT = // narrow is kept apart from lanes, which go when idle; now is its clock, // injectable for tests. const NARROW_FOR = 5 * 60_000 -const startGate = { inflight: 3, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() } +const startGate = { inflight: 3, address: 6, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() } +// ADDRESS is the lane every account's Start Plan requests share as well as +// their own: zcode.z.ai sees one address, and its firewall refused the whole +// of it with 405 once ~10 were in flight (busyHold). startGate.address is +// six, what two accounts of three each sent when the plugin declared +// maxAccounts two, which no 405 followed. It is never narrowed. +const ADDRESS = "\0address" // limitOf is how many of the account's Start Plan requests go at once: the // gate's number, or less while the account is narrowed. function limitOf(key) { + if (key === ADDRESS) return startGate.address const n = startGate.narrow.get(key) if (!n) return startGate.inflight if (startGate.now() >= n.until) { @@ -2256,6 +2266,34 @@ function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) { }) } +// startSlots waits for a slot of the account's, then one of the address's +// (ADDRESS), both within the one wait: { release } letting both go, or +// { key } naming the lane whose wait ran out, nothing held. Every request +// takes the account's first, so one holding the address's never waits for +// an account's. +async function startSlots(key, signal, { wait = startGate.wait, front = false } = {}) { + const until = Date.now() + wait + const mine = await startSlot(key, signal, { wait, front }) + if (!mine) return { key } + let all + try { + all = await startSlot(ADDRESS, signal, { wait: until - Date.now(), front }) + } catch (e) { + mine.release() + throw e + } + if (!all) { + mine.release() + return { key: ADDRESS } + } + return { + release() { + all.release() + mine.release() + }, + } +} + // released hands res on and lets its slot go once ZCode's answer has come // to its end, failed, or been given up on (the agent's abort, the reader's // cancel) — the request is in flight at ZCode until then. The answer is read @@ -2299,9 +2337,12 @@ function released(res, slot, signal) { // so it tries the next account, and a short Retry-After. function startQueueAnswer(key) { const n = limitOf(key) + const s = n === 1 ? "" : "s" const error = { type: "rate_limit_error", - message: `ZCode's free Start Plan serves this account ${n} request${n === 1 ? "" : "s"} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`, + message: key === ADDRESS + ? `ZCode's free Start Plan is sent ${n} request${s} at a time from this computer, over all its accounts, as more get the address refused; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again` + : `ZCode's free Start Plan serves this account ${n} request${s} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`, } return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" }, @@ -3090,9 +3131,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // of day, and a user who knows theirs can raise this on the account. // The Start Plan has the plugin's own gate below it (startGate) maxConcurrency: DEFAULT_CONCURRENCY, - // how many accounts take requests at once, the others in reserve - // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all - maxAccounts: DEFAULT_ACCOUNTS, // magpie's own switches (OpenCode never reads auth.options), read at // each request through input.magpie options: [ @@ -3194,7 +3232,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { m = raw forcedGift = true giftName = giftID(raw) - } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) { + } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && !startFull(ADDRESS) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) { // free first: the plain model spends the account's own live // gift before it spends the coding plan, under the name the // gift lists. The gift is the route's cache alone (a failed @@ -3308,9 +3346,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // the account's Start Plan slots (startGate): a request past them // waits here for one rather than being sent to be refused if (start) { - own.slot = await startSlot(gateKey, opts.signal) + const got = await startSlots(gateKey, opts.signal) own.signal = opts.signal - if (!own.slot) return kept(startQueueAnswer(gateKey)) + if (!got.release) return kept(startQueueAnswer(got.key)) + own.slot = got // a hold may have armed while it waited if (edgeHeld()) return kept(edgeHeldAnswer()) if (busyHeld()) return kept(busyHeldAnswer()) @@ -3373,8 +3412,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { const until = Date.now() + startGate.wait for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) { own.slot?.release() - own.slot = await startSlot(gateKey, opts.signal, { wait: until - Date.now(), front: true }) - if (!own.slot) return kept(startQueueAnswer(gateKey)) + own.slot = null + const got = await startSlots(gateKey, opts.signal, { wait: until - Date.now(), front: true }) + if (!got.release) return kept(startQueueAnswer(got.key)) + own.slot = got if (edgeHeld()) return kept(edgeHeldAnswer()) if (busyHeld()) return kept(busyHeldAnswer()) res = await askBusy(url, opts, h, () => busyCap(gateKey)) @@ -3588,4 +3629,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, aloneGift, aloneSeen, aloneNames, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, giftSignIn, 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, giftSignIn, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, ADDRESS, startSlots } diff --git a/packages/zcode/inflight.test.mjs b/packages/zcode/inflight.test.mjs index d58ed90..181e4a3 100644 --- a/packages/zcode/inflight.test.mjs +++ b/packages/zcode/inflight.test.mjs @@ -59,6 +59,7 @@ afterEach(() => { globalThis.fetch = real BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS) startGate.inflight = GATE.inflight + startGate.address = GATE.address startGate.wait = GATE.wait startGate.lanes.clear() startGate.narrow.clear() @@ -148,6 +149,61 @@ test("each account has slots of its own", async () => { expect([...now.peak.values()]).toEqual([3, 3]) }) +test("every account's Start Plan requests share the address's six slots", async () => { + // mathfournity on X: every gift account takes requests now (no + // maxAccounts), so what reaches zcode.z.ai from this address is held to + // what two accounts sent before, three each, over all of them + let flight = 0 + let peak = 0 + answer = async () => { + peak = Math.max(peak, ++flight) + await sleep(60) + flight-- + return OK() + } + const accounts = await Promise.all([1, 2, 3, 4].map((n) => loader(startAuth(n)))) + const rs = await Promise.all(accounts.flatMap((a) => Array.from({ length: 5 }, () => one(a)))) + expect(rs.every((r) => r.status === 200)).toBe(true) + expect(messages().length).toBe(20) + expect(peak).toBe(startGate.address) + expect(Math.max(...now.peak.values())).toBeLessThanOrEqual(3) + expect(now.peak.size).toBe(4) +}) + +test("a wait for the address's slots that runs out says so, nothing sent, and lets the account's slot go", async () => { + startGate.address = 1 + startGate.wait = 200 + let release + answer = () => new Promise((r) => (release = () => r(OK()))) + const [a, b] = await Promise.all([loader(startAuth(1)), loader(startAuth(2))]) + const first = one(a) + while (!release) await sleep(5) + const res = await one(b) + expect(res.status).toBe(429) + expect(JSON.parse(res.text).error.message).toContain("over all its accounts") + expect(messages().length).toBe(1) + release() + expect((await first).status).toBe(200) + // neither lane is left holding a slot + expect(startGate.lanes.size).toBe(0) +}) + +test("the coding plan is held to none of the address's slots", async () => { + startGate.address = 1 + let flight = 0 + let peak = 0 + answer = async () => { + peak = Math.max(peak, ++flight) + await sleep(60) + flight-- + return OK() + } + const opts = await loader(planAuth()) + const rs = await Promise.all(Array.from({ length: 4 }, () => one(opts))) + expect(rs.every((r) => r.status === 200)).toBe(true) + expect(peak).toBe(4) +}) + test("a slot is held across the re-asks, and let go when the answer has been read", async () => { BUSY_WAITS.splice(0, BUSY_WAITS.length, 50, 50) const opts = await loader(startAuth()) diff --git a/packages/zcode/package.json b/packages/zcode/package.json index bee7e2c..c2ffcc9 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.67", + "version": "0.1.68", "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", @@ -14,7 +14,6 @@ "directory": "packages/zcode" }, "magpie": { - "maxConcurrency": 3, - "maxAccounts": 2 + "maxConcurrency": 3 } } diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index 826e09f..337d3d4 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -43,6 +43,7 @@ function routeToFake() { return real(`http://127.0.0.1:${server.port}/${new URL(host).host}${url.slice(host.length)}`, init) } } +const ADDRESS_SLOTS = 6 // startGate.address afterEach(() => { globalThis.fetch = real got.length = 0 @@ -55,6 +56,7 @@ afterEach(() => { _internal.startGate.lanes.clear() _internal.startGate.narrow.clear() _internal.startGate.now = () => Date.now() + _internal.startGate.address = ADDRESS_SLOTS }) const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16) @@ -703,6 +705,9 @@ test("caps that land after the hold armed change neither hits nor until (request _internal.BUSY_WAITS.push(1) try { routeToFake() + // twelve in flight at once, more than the address's gate lets go + // (startGate.address): what the hold does with such a run is under test + _internal.startGate.address = 12 let clock = 1_000_000_000_000 _internal.busyHold.now = () => clock const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })