diff --git a/packages/qoder/README.md b/packages/qoder/README.md index d522190..f6ad851 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -189,6 +189,7 @@ itself. |---|---| | A refused sign-in (no code, or code 105) | 401 | | A quota (codes 110, 112–119, 122) | 429 | +| A model the account's listing has off while its usage says no credits are left (since 0.2.64, #880) | 429 usage limit reached, with the credits used and the model; a model off with credits left, or whose usage can't be read, stays 400 `unknown or disabled model`, and an id Qoder never served is that 400 at once | | Busy or queued for the model (code 10605) | Since 0.2.28 the request waits in Qoder's queue as Qoder's client does (below), then is sent again; since 0.2.62 a streamed request is answered 200 at once and kept alive with SSE comments for up to an hour, its outcome in the stream; past the wait, 503 with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none). Since 0.2.40, when magpie has another candidate after this request (`x-magpie-fallback: 1`), the 503 comes at once, saying the queue and how many are ahead, and magpie asks the next. The sign-in is untouched | | A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words | | "Error in upstream response", the model's own vendor behind Qoder failing, which Qoder sends as a 400 (since 0.2.24) | 502, so magpie asks again or another account; the sign-in is untouched | @@ -484,7 +485,8 @@ the account's credentials. (`Qoder.app` on macOS, `%LOCALAPPDATA%\Programs\Qoder` or, since 0.2.26, `%ProgramFiles%\Qoder` on Windows, `/opt/Qoder` on Linux) or the runtime the CLI caches in `~/.qoder/.bin` (`runtime-info---*` on macOS and Linux, - `umid-win32-x64-*\runtime-info.exe` on Windows; `QODER_CONFIG_DIR`, + `umid-win32-x64-*\runtime-info.exe` or, as qodercli 1.21.2 caches it + since 0.2.64, `runtime-info-win32-x64-*.exe` on Windows; `QODER_CONFIG_DIR`, `QODER_CLI_HOME` and `QODER_CONFIG_DIR_NAME` move it as they move the CLI's folder). - For another installation location, set `QODER_RUNTIME_INFO` to the diff --git a/packages/qoder/checkin.test.mjs b/packages/qoder/checkin.test.mjs index 05b8d74..a9e0a7f 100644 --- a/packages/qoder/checkin.test.mjs +++ b/packages/qoder/checkin.test.mjs @@ -193,6 +193,34 @@ for (const [platform, arch] of [["win32", "x64"], ["darwin", "arm64"], ["darwin" }) } +// plugins#879 (ArmedHelicopter): qodercli 1.21.2 on Windows 11 caches the +// runtime as one file in .bin, beside sgsdk.dll, the reporter's names: +// C:\Users\\.qoder\.bin\runtime-info-win32-x64-faa59bbe39db0bd1.exe +// sgsdk.dll +// Its .tmp while being written, another arch's and an older folder from +// qodercli 1.1.66 are passed over for it. +test("plugins#879: Windows finds the runtime qodercli 1.21.2 cached as a single file", async () => { + const cache = join(sandbox, ".qoder", ".bin") + mkdirSync(cache, { recursive: true }) + writeFileSync(join(cache, "sgsdk.dll"), "fixture") + const file = join(cache, "runtime-info-win32-x64-faa59bbe39db0bd1.exe") + writeFileSync(file, "fixture") + utimesSync(file, new Date(2000), new Date(2000)) + for (const other of ["runtime-info-win32-arm64-1111111111111111.exe", "runtime-info-win32-x64-2222222222222222.exe.0a1b2c3d.tmp"]) { + writeFileSync(join(cache, other), "fixture") + utimesSync(join(cache, other), new Date(3000), new Date(3000)) + } + const old = join(cache, "umid-win32-x64-ffffffffffffffff") + mkdirSync(old) + writeFileSync(join(old, "runtime-info.exe"), "fixture") + utimesSync(join(old, "runtime-info.exe"), new Date(1000), new Date(1000)) + const env = { LOCALAPPDATA: join(sandbox, "Local"), ProgramFiles: join(sandbox, "Program Files") } + expect(await inSandbox(() => _internal.campaignRuntime({ home: sandbox, platform: "win32", arch: "x64", env }))).toBe(file) + // the 1.1.66 folder is still taken when it is the newer + utimesSync(join(old, "runtime-info.exe"), new Date(4000), new Date(4000)) + expect(await inSandbox(() => _internal.campaignRuntime({ home: sandbox, platform: "win32", arch: "x64", env }))).toBe(join(old, "runtime-info.exe")) +}) + test("finds the runtime under Qoder CLI's own config folder", async () => { const dir = cliCache(join(sandbox, "custom"), "linux", "x64") const named = cliCache(join(sandbox, "clihome", ".qoder-work"), "linux", "x64") diff --git a/packages/qoder/credits-off.test.mjs b/packages/qoder/credits-off.test.mjs new file mode 100644 index 0000000..5f92536 --- /dev/null +++ b/packages/qoder/credits-off.test.mjs @@ -0,0 +1,160 @@ +// plugins#880 (zane668): on an international personal_professional_trial +// account, once the 800 credits were used up the account's listing had +// dfmodel off, and the plugin answered every chat for it with its own +// `400 unknown or disabled model "dfmodel"`, which magpie reads as the +// request's fault: a routing group neither failed over nor rested the +// account (yetone/magpie#5726). Qoder had said `429 usage limit reached` +// at 16:11, the 400 followed from 17:14, and dfmodel answered 200 again +// once the daily credits came back. +// +// A model the live listing names and has off, on an account whose usage +// says no credits are left, is now that account's quota: 429 usage limit +// reached. A model off while credits are left, an id Qoder never served, +// and a usage that can't be read keep the 400. +// +// The issue gives the plan, the 800 credits, used 100%, and dfmodel off; it +// doesn't give the listing's or the usage's bytes, so their shape is the +// one the other tests here use (listing-renew, spare-free). Every fetch is +// a fake; nothing reaches the network. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { constants, createDecipheriv, generateKeyPairSync, privateDecrypt } from "node:crypto" +import { QoderAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +const site = _internal.SITES.qoder +const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }) +beforeEach(() => (site.rsaKey = publicKey.export({ type: "spki", format: "pem" }))) +afterEach(() => { + globalThis.fetch = real + delete site.rsaKey +}) + +const HOUR = 3_600_000 +const CHAT = "https://api3.qoder.sh/v1/chat/completions" +const MODELS = ["dfmodel", "qfmodel", "efficient"] +const TRIAL = (used) => ({ displayMode: "qoder", qoderUsage: { userType: "personal_professional_trial", userQuota: { total: 800, used, remaining: 800 - used, unit: "credits" } } }) + +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) +const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n` +const answered = () => + new Response(line({ choices: [{ delta: { content: "hello" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }) + `data:${JSON.stringify({ headers: {}, body: "[DONE]", statusCodeValue: 200 })}\n\n`, { + headers: { "Content-Type": "text/event-stream" }, + }) +const chat = (model) => ({ method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) }) + +function tokenOf(headers) { + const block = privateDecrypt({ key: privateKey, padding: constants.RSA_NO_PADDING }, Buffer.from(headers["Cosy-Key"], "base64")) + const key = block.subarray(block.indexOf(0, 2) + 1) + const [payload] = headers.Authorization.slice("Bearer COSY.".length).split(".") + const { info } = JSON.parse(Buffer.from(payload, "base64").toString()) + const d = createDecipheriv("aes-128-cbc", key, key) + return JSON.parse(Buffer.concat([d.update(Buffer.from(info, "base64")), d.final()]).toString()).security_oauth_token +} + +// qoder is the fake: state.off is the models the listing has off, +// state.usage the usage reply (a function, or the envelope) +function qoder(state) { + const pairs = new Map([["jrt-1", "jt-1"]]) + const honoured = new Set(["jt-1"]) + const calls = { refresh: [], usage: 0, chats: [] } + let n = 1 + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + if (u.pathname === "/sash/api/v2/me/usage") { + calls.usage++ + return typeof state.usage === "function" ? state.usage() : json(state.usage) + } + if (u.pathname === "/api/v1/jobToken/refresh") { + const rt = JSON.parse(init.body).refresh_token + calls.refresh.push(rt) + if (!pairs.has(rt)) return json({ message: "invalid refresh token" }, 401) + pairs.delete(rt) + n++ + honoured.add(`jt-${n}`) + pairs.set(`jrt-${n}`, `jt-${n}`) + return json({ token: `jt-${n}`, refresh_token: `jrt-${n}`, expires_in: 24 * HOUR }) + } + const t = tokenOf(init.headers) + if (u.pathname.endsWith("/model/list")) { + return json({ app: MODELS.map((key) => ({ key, display_name: key, enable: !state.off.includes(key) })), byok_teams: [], byok_enterprise: [] }) + } + calls.chats.push(t) + return answered() + } + return calls +} + +async function account() { + const box = { + stored: { type: "oauth", access: "jt-1", refresh: "jrt-1", expires: Date.now() + 24 * HOUR, accountId: "trial@example.com", uid: "u-trial", email: "trial@example.com", machineId: "m1", deviceToken: "dt-1", deviceRefresh: "drt-1" }, + } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (box.stored = { ...body }) } } }) + const l = await hooks.auth.loader(async () => box.stored) + return { fetch: l.fetch, box } +} + +test("plugins#880: dfmodel off with the 800 credits used up is the account's quota, a 429 usage limit, with no token spent", async () => { + const calls = qoder({ off: ["dfmodel"], usage: TRIAL(800) }) + const a = await account() + const res = await a.fetch(CHAT, chat("dfmodel")) + expect(res.status).toBe(429) + const message = (await res.json()).error.message + expect(message).toStartWith("usage limit reached: ") + expect(message).toContain("800 / 800 credits") + expect(message).toContain('"dfmodel"') + expect(message).not.toContain("unknown or disabled") + expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(calls.refresh).toEqual([]) + expect(calls.chats).toEqual([]) + // the models still on are served + expect((await a.fetch(CHAT, chat("qfmodel"))).status).toBe(200) +}) + +test("plugins#880: once the daily credits are back and the listing has dfmodel on again, it is served", async () => { + const state = { off: ["dfmodel"], usage: TRIAL(800) } + qoder(state) + const a = await account() + expect((await a.fetch(CHAT, chat("dfmodel"))).status).toBe(429) + state.off = [] + state.usage = TRIAL(0) + expect((await a.fetch(CHAT, chat("dfmodel"))).status).toBe(200) +}) + +test("a model off while credits are left is still said disabled", async () => { + const calls = qoder({ off: ["dfmodel"], usage: TRIAL(200) }) + const a = await account() + const res = await a.fetch(CHAT, chat("dfmodel")) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('unknown or disabled model "dfmodel"') + expect(calls.usage).toBe(1) +}) + +test("an id Qoder never served is said unknown with the credits used up, its usage not read", async () => { + const calls = qoder({ off: ["dfmodel"], usage: TRIAL(800) }) + const a = await account() + const res = await a.fetch(CHAT, chat("no-such-model")) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('unknown or disabled model "no-such-model"') + expect(calls.usage).toBe(0) + expect(calls.refresh).toEqual([]) +}) + +test("a usage that can't be read says nothing of the credits: the model off is said disabled", async () => { + qoder({ off: ["dfmodel"], usage: () => new Response("boom", { status: 500 }) }) + const a = await account() + const res = await a.fetch(CHAT, chat("dfmodel")) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('unknown or disabled model "dfmodel"') +}) + +test("spentOf: none left in every pool spent in turn, a free account's pools of 0 too; a pool with some left, or no pool, is not spent", () => { + const { spentOf } = _internal + expect(spentOf(TRIAL(800))).toBe("800 / 800 credits") + expect(spentOf(TRIAL(799))).toBe("") + expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 300, used: 300 }, addOnQuota: { total: 100, used: 40 } } })).toBe("") + expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 300, used: 300 }, add_on_quota: { total: 100, remaining: 0 } } })).toBe("400 / 400 credits") + expect(spentOf({ displayMode: "qoder", qoderUsage: { userType: "personal_standard", userQuota: { total: 0, used: 0, remaining: 0 } } })).toBe("0 / 0 credits") + expect(spentOf({ displayMode: "qoder", qoderUsage: { userType: "personal" } })).toBe("") + expect(spentOf({ displayMode: "enterprise" })).toBe("") + expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 800 } } })).toBe("") +}) diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index b9931af..5f7c2f0 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -2607,10 +2607,16 @@ async function campaignRuntime({ home = homedir(), platform = process.platform, const cache = join(config, ".bin") const entries = await readdir(cache, { withFileTypes: true }).catch(() => []) const found = [] + // qodercli 1.1.66 cached it on Windows as a folder umid-win32-- + // holding runtime-info.exe and sgsdk.dll; qodercli 1.21.2 caches the file + // itself, runtime-info-win32--.exe, beside sgsdk.dll in .bin, + // as elsewhere (plugins#879). Either is taken, the newest first. for (const d of entries) { let path - if (platform === "win32") { - if (d.isDirectory() && d.name.startsWith(`umid-win32-${arch}-`)) path = join(cache, d.name, name) + if (platform === "win32" && d.isDirectory()) { + if (d.name.startsWith(`umid-win32-${arch}-`)) path = join(cache, d.name, name) + } else if (platform === "win32") { + if (d.isFile() && d.name.startsWith(`runtime-info-win32-${arch}-`) && d.name.toLowerCase().endsWith(".exe")) path = join(cache, d.name) } else if (d.isFile() && d.name.startsWith(`runtime-info-${platform}-${arch}-`) && !d.name.endsWith(".tmp")) { path = join(cache, d.name) } @@ -2811,6 +2817,31 @@ function when(v) { // account used up (magpie-community/plugins#454). const SPENT_IN_TURN = new Set(["Credits", "Add-on credits", "Shared credits"]) +// spentOf is the credits a usage envelope says the account has used of +// what it has ("800 / 800 credits") when the pools spent in turn +// (SPENT_IN_TURN) have none left together, and "" when they have some, or +// when it says no pool at all. A free account's pools of 0 have none. +function spentOf(env) { + const u = env?.qoderUsage + if (env?.displayMode !== "qoder" || !u || typeof u !== "object" || Array.isArray(u)) return "" + let used = 0 + let total = 0 + let pools = 0 + for (const [a, b] of [["userQuota", "user_quota"], ["addOnQuota", "add_on_quota"], ["orgResourcePackage", "org_resource_package"]]) { + const p = u[a] !== undefined ? u[a] : u[b] + if (p === null || typeof p !== "object" || Array.isArray(p)) continue + const t = p.total ?? p.cap + if (typeof t !== "number" || !Number.isFinite(t) || t < 0) continue + const n = typeof p.used === "number" ? p.used : typeof p.remaining === "number" ? t - p.remaining : NaN + if (t > 0 && !Number.isFinite(n)) return "" + pools++ + total += t + used += t > 0 ? Math.min(Math.max(n, 0), t) : 0 + } + if (!pools || used < total) return "" + return `${gfmt(used)} / ${gfmt(total)} credits` +} + // parseUsage is the plan and each pool of credits the envelope tells. When // more than one of the pools spent in turn holds credits, "Total credits" // is what they hold together, the one routing counts, and each pool is @@ -3252,11 +3283,16 @@ const makePlugin = (site) => async ({ client }) => { if (!l || again) { const s = siteOf(site, cred) const listing = await fetchListing(s, cred) + const off = new Set() for (const m of s.modelScene ? (Array.isArray(listing?.[s.modelScene]) ? listing[s.modelScene] : []) : sceneModels(listing)) { const k = String(m?.key ?? "").trim() if (k) served.add(k) + if (k && !m.enable) off.add(k) } l = modelInfos(listing, s) + // the keys this listing names and has off (ask tells a model off for + // the credits apart by them) + l.off = off if (!s.modelScene) l.freeView = freeView(sceneModels(listing)) listings.set(key, l) } @@ -3350,19 +3386,40 @@ const makePlugin = (site) => async ({ client }) => { const env = await fetchUsage(siteOf(site, cred), cred.access) return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who } } - let env - try { - env = await fetchUsage(siteOf(site, cred), cred.deviceToken) - } catch (e) { - if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e - env = await fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken)) - } - return { ...(await spareFree(cred, parseUsage(env))), signIn, ...who } + return { ...(await spareFree(cred, parseUsage(await usageEnv(getAuth, cred)))), signIn, ...who } } catch (e) { return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn } } } + // usageEnv is the account's usage envelope on its device token, rotated + // once when refused, as usage reads it + const usageEnv = async (getAuth, cred) => { + try { + return await fetchUsage(siteOf(site, cred), cred.deviceToken) + } catch (e) { + if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e + return fetchUsage(siteOf(site, cred), await deviceToken(getAuth, cred.deviceToken)) + } + } + + // creditsSpent is the credits the account has used of what it has + // ("800 / 800 credits") when its usage says none are left (spentOf), and + // "" when some are, or when it can't be read. Qoder and Qoder CN only: + // QwenWork reads its usage elsewhere. A PAT account's is read on its job + // token, as usage reads it. + const creditsSpent = async (getAuth) => { + if (site.usagePath) return "" + try { + const cred = await fresh(getAuth) + if (cred.lingma) return "" + if (cred.patAuth && !cred.deviceToken) return spentOf(await fetchUsage(siteOf(site, cred), cred.access)) + return spentOf(await usageEnv(getAuth, cred)) + } catch { + return "" + } + } + // campaign is a campaigns page (the daily check-in) asked as the account: // a refused device token is rotated once, as usage does, and asked again const campaign = async (getAuth, input, url, init) => { @@ -3514,6 +3571,26 @@ const makePlugin = (site) => async ({ client }) => { // could be refused and renew it. An id Qoder has never served is said // unknown at once, with no renewal spent on it. if (!m && getAuth && knows(chat.model)) { + // Off because the credits are used up (plugins#880): on an + // international personal_professional_trial account Qoder's listing + // had dfmodel off once the 800 credits were spent, and on again + // when the daily credits came back. That is the account's quota, + // not the request's fault, so it is said as Qoder's own quota codes + // are (429 usage limit reached), which a routing group fails over + // on and rests the account for. Only a model the live listing names + // and has off, on an account whose usage read says no credits are + // left; a usage that can't be read says nothing, and the model goes + // on to the renewal and the 400 below as before. + if ((await models(cred)).off?.has(chat.model)) { + const spent = await creditsSpent(getAuth) + if (spent) { + return errorResponse({ + status: 429, + message: `usage limit reached: the account's credits are used up (${spent}), and Qoder lists "${chat.model}" off for it until they refresh`, + signIn: "", + }) + } + } relogged = true const next = await relogin(getAuth, cred.access) if (next) { @@ -3999,4 +4076,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) { export const protocol = { makePlugin, deviceSignIn, openapi, siteOf } // for tests -export const _internal = { OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState } +export const _internal = { spentOf, OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState } diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 133a63c..1239fd5 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.63", + "version": "0.2.64", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains", "type": "module", "main": "./opencode.mjs",