diff --git a/packages/autoclaw/README.en.md b/packages/autoclaw/README.en.md index 44706a6..6d7718c 100644 --- a/packages/autoclaw/README.en.md +++ b/packages/autoclaw/README.en.md @@ -123,6 +123,7 @@ A 406's upstream body is empty and magpie keeps only token counts — diagnosing - Phone-number accounts only ever use the CN host (managed gateway; 401/403 mark the sign-in expired); z.ai/Google accounts only the international host (401/403 retries the other side, both refusing marks it expired). - An exhausted quota is not a signed-out account: a `403` + `{"code":810000,"message":"GLM-5.3 免费额度已用完,…"}` answer (or a 403 body about quotas/balances) becomes a `429` carrying the upstream's own words, the sign-in is kept (`X-Magpie-Sign-In: kept`), and the international side stops host-hopping (plugins#274). - A banned account is not a signed-out account: a `403` + `{"code":410004,"message":"The account has been banned"}` answer (or code/message fields saying banned / 封禁 / 账号异常 / 账号被冻结) flows through on chat, refresh, credits and check-in with the upstream's own words; chat becomes a `403 permission_error`, the sign-in is kept, no host-hopping. Other 401/403s still mark the sign-in expired. +- A request too large is not a signed-out account (plugins#891): the CN gateway answers a ~200k-token request `401 AutoClaw 登录状态失效` while the same token's smaller requests seconds before and after get 200. A 401/403 for a body larger than the largest this process has seen answered has its sign-in checked on the credits route: a sign-in that holds turns it into `413 request_too_large` with the sign-in kept, so magpie tries another route or has the agent compact. A sign-in refused there too, a check that fails, or a body no larger than one answered is still the sign-in. No threshold is guessed; the comparison is with the largest request answered. - The upstream model whitelist changes with versions; a retired model returns `400 illegal model` (the error message passes through). - Refresh tokens are **mutually evicting** with the AutoClaw desktop app (both rotate) — do not stay signed in on desktop with the same account. - When the upstream changes protocols, `CLIENT_VERSION` / endpoint paths may need to follow the official client. diff --git a/packages/autoclaw/README.md b/packages/autoclaw/README.md index e52deda..b8b37e5 100644 --- a/packages/autoclaw/README.md +++ b/packages/autoclaw/README.md @@ -123,6 +123,7 @@ AutoClaw 对话网关对请求形状有硬性要求,缺任一条都回 `406 No - 手机号账号只认国内 host(走 managed gateway,401/403 标记登录失效);z.ai/Google 账号只认国际 host(401/403 自动换侧重试,均拒绝时标记失效)。 - 额度用完不算登录失效:上游以 `403` + `{"code":810000,"message":"GLM-5.3 免费额度已用完,…"}` 回答时(或 403 正文说额度/余额已用完),插件转成 `429`,原样带上游文案,登录保留(`X-Magpie-Sign-In: kept`),国际版也不再换 host 重试(plugins#274)。 - 账号被封不算登录失效:上游以 `403` + `{"code":410004,"message":"The account has been banned"}` 回答时(或 code/message 字段说 banned / 封禁 / 账号异常 / 账号被冻结等),对话、刷新、积分与签到都原样带上游文案,对话转成 `403 permission_error`,登录保留(`X-Magpie-Sign-In: kept`),不再换 host 重试。其他 401/403 仍按登录失效处理。 +- 请求过大不算登录失效(plugins#891):国内网关会对约 200k tokens 的请求回 `401 AutoClaw 登录状态失效`,而同一凭据前后几秒的小请求都是 200。请求体比本进程见过的最大成功请求还大时遇到 401/403,插件先用积分接口确认登录:登录有效就转成 `413 request_too_large`(登录保留),magpie 换一条路由或让 agent 压缩对话;登录也被拒、确认失败,或请求不比已成功的大,仍按登录失效处理。不猜阈值,只拿已成功的最大请求作比较。 - 上游模型白名单随版本变化,模型下线时上游返回 `400 非法模型`(原样透传错误消息)。 - refresh token 与 AutoClaw 桌面端**共用会互踢**(双方都轮换),插件账号请勿同时在桌面端登录。 - 上游偶发改协议时,`CLIENT_VERSION` / 端点路径可能需要随官方客户端更新。 diff --git a/packages/autoclaw/index.mjs b/packages/autoclaw/index.mjs index aad9393..350a1db 100644 --- a/packages/autoclaw/index.mjs +++ b/packages/autoclaw/index.mjs @@ -321,6 +321,70 @@ async function refusedNotSignIn(res) { return (await quotaRefusal(res)) ?? (await accountRefusal(res)); } +// A 401 is not always the sign-in either: the CN managed gateway answers a +// request of ~200k tokens 401 {"message":"AutoClaw 登录状态失效"}, while the +// same token is answered 200 seconds before and after (plugins#891, +// hj01857655: 401 at 207k and 218k tokens, every 200 that day at most +// 129k). Read as expired, magpie marked the account signed out and stopped +// there. The gateway's limit isn't known, so no threshold is guessed: a +// refusal of a body larger than the largest one this provider's gateway +// has answered has its sign-in checked on the wallets route, and a sign-in +// that holds there makes it a 413, the request too large, with the +// sign-in kept. magpie then asks another route, or tells the agent to +// compact. A body no larger than one answered, a sign-in refused there, +// or a check that fails is the sign-in as before. +const largestServed = new Map(); // providerId → bytes of the largest chat body the gateway answered + +function bodyBytes(body) { + if (body == null) return 0; + if (typeof body === "string") return Buffer.byteLength(body); + if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return body.byteLength; + return 0; +} + +function noteServed(providerId, bytes) { + if (bytes > (largestServed.get(providerId) ?? 0)) largestServed.set(providerId, bytes); +} + +/** signInHolds is true when a host's wallets route takes the token, false when every answer refused it, null when unknown. */ +async function signInHolds(accessToken, hosts) { + let refused = false; + for (const host of dedupe(hosts)) { + try { + const res = await fetch(host + WALLETS_PATH, { + method: "GET", + headers: bizHeaders(accessToken), + redirect: "error", + signal: AbortSignal.timeout(10_000), + }); + if (res.status === 401 || res.status === 403) { + refused = true; + try { res.body?.cancel?.(); } catch {} + continue; + } + if (!res.ok) { + try { res.body?.cancel?.(); } catch {} + continue; + } + const payload = await res.json().catch(() => null); + if (payload && payload.code === 0) return true; + } catch {} + } + return refused ? false : null; +} + +/** sizeRefusal is a 401/403 for a body larger than any answered, its sign-in holding, as a 413; or null. */ +async function sizeRefusal(providerId, bytes, status, accessToken, hosts) { + const most = largestServed.get(providerId) ?? 0; + if (!(most > 0) || bytes <= most) return null; + if ((await signInHolds(accessToken, hosts)) !== true) return null; + const message = `AutoClaw: the gateway answered a ${bytes}-byte request ${status}, but the sign-in holds; the largest request it has answered is ${most} bytes. The request is too large for AutoClaw, not signed out.`; + return new Response(JSON.stringify({ error: { message, type: "request_too_large", code: null } }), { + status: 413, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, + }); +} + // tidyBody puts right, in place, what an agent's history can hold that // AutoClaw's chat gateway can't read: it answers each with 500 {"message": // "parse response failed"} and nothing more (plugins#437, tmuer, who @@ -1332,8 +1396,12 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) const tryFetch = (host) => fetch(`${host}${CHAT_PATH}`, { ...init, headers, body: nextBody, signal: init?.signal }); + const sentBytes = bodyBytes(nextBody); const res1 = await tryFetch(hosts[0]); - if (res1.status !== 401 && res1.status !== 403) return explained(res1, nextBody, providerId, options); + if (res1.status !== 401 && res1.status !== 403) { + if (res1.ok) noteServed(providerId, sentBytes); + return explained(res1, nextBody, providerId, options); + } // a spent quota or a ban is the account's on every host: not asked again const spent1 = await refusedNotSignIn(res1); if (spent1) return spent1; @@ -1343,11 +1411,14 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) if (spent2) return spent2; if (res2.status === 401 || res2.status === 403) { try { res2.body?.cancel?.(); } catch {} + const tooBig = await sizeRefusal(providerId, sentBytes, res2.status, accessToken, hosts); + if (tooBig) return tooBig; return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效(两个 host 均拒绝该 token)", type: "invalid_request_error" } }), { status: 401, headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" }, }); } + if (res2.ok) noteServed(providerId, sentBytes); return explained(res2, nextBody, providerId, options); } @@ -1362,10 +1433,16 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod }) headers, body: sentBody, }); - if (res.status !== 401 && res.status !== 403) return explained(res, sentBody, providerId, options); + const sentBytes = bodyBytes(sentBody); + if (res.status !== 401 && res.status !== 403) { + if (res.ok) noteServed(providerId, sentBytes); + return explained(res, sentBody, providerId, options); + } const spent = await refusedNotSignIn(res); if (spent) return spent; try { res.body?.cancel?.(); } catch {} + const tooBig = await sizeRefusal(providerId, sentBytes, res.status, accessToken, hosts); + if (tooBig) return tooBig; return new Response(JSON.stringify({ error: { message: "AutoClaw 登录已失效", type: "invalid_request_error" } }), { status: 401, headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "expired" }, @@ -2087,6 +2164,7 @@ export const AutoclawCnAuthPlugin = makeAutoclawPlugin({ /** 测试辅助(magpie/OpenCode 不会把它当插件调用)。 */ export const _internal = { quotaRefusal, accountRefusal, bannedSaid, + signInHolds, clearLargestServed: () => largestServed.clear(), makePluginForTest: makeAutoclawPlugin, platformTm, setOfficialChatHeaders, conversationSessionId, stainlessOs, stainlessArch, md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId, dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens, diff --git a/packages/autoclaw/index.test.mjs b/packages/autoclaw/index.test.mjs index 5741fd3..88f36c3 100644 --- a/packages/autoclaw/index.test.mjs +++ b/packages/autoclaw/index.test.mjs @@ -2868,3 +2868,115 @@ test("0.2.18: a checkin whose task-complete answers 500 with success:true ends t campCleanup(realFetch) } }) + +// plugins#891 (hj01857655): the CN managed gateway answers a ~200k-token +// request 401 "AutoClaw 登录状态失效" while the same token is answered 200 +// seconds before and after. These are the reporter's bytes for the refusal. +const BIG_401 = '{"error":{"code":null,"message":"AutoClaw 登录状态失效","param":null,"type":"authentication_error"}}' +const WALLETS_OK = JSON.stringify({ code: 0, data: { total_balance: 100 } }) +const chatOf = (n) => JSON.stringify({ model: "zai_glm-5.3-flash", messages: [{ role: "user", content: "x".repeat(n) }] }) + +for (const [name, Plugin, chatHosts] of [ + ["CN", AutoclawCnAuthPlugin, 1], + ["overseas", AutoclawAuthPlugin, 2], +]) { + test(`${name} chat: a 401 for a body larger than any answered, its sign-in holding, is a 413 and the sign-in is kept (plugins#891)`, async () => { + _internal.clearLargestServed() + const realFetch = globalThis.fetch + const calls = [] + let wallets = () => new Response(WALLETS_OK) + globalThis.fetch = async (input, init) => { + const url = String(input) + if (url.includes("/wallets")) { calls.push("wallets"); return wallets() } + calls.push("chat") + return String(init?.body).length > 100_000 ? new Response(BIG_401, { status: 401 }) : new Response("ok") + } + try { + const hooks = await Plugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" })) + + // before anything was answered, a 401 is the sign-in, and no check is made + calls.length = 0 + let r = await loader.fetch("x", { method: "POST", body: chatOf(200_000) }) + expect(r.status).toBe(401) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect(calls.filter((c) => c === "wallets").length).toBe(0) + + expect((await loader.fetch("x", { method: "POST", body: chatOf(50_000) })).status).toBe(200) + + // larger than the largest answered, the sign-in holding: too large, not signed out + calls.length = 0 + r = await loader.fetch("x", { method: "POST", body: chatOf(200_000) }) + expect(r.status).toBe(413) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("kept") + const e = (await r.json()).error + expect(e.type).toBe("request_too_large") + expect(e.message).toContain("too large") + expect(e.message).not.toContain("登录") + expect(calls).toEqual([...Array(chatHosts).fill("chat"), "wallets"]) + + // the sign-in refused on the wallets route too: it is the sign-in + wallets = () => new Response('{"code":401,"message":"token invalid"}', { status: 401 }) + r = await loader.fetch("x", { method: "POST", body: chatOf(200_000) }) + expect(r.status).toBe(401) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("expired") + + // a check that can't be read is unknown, and the 401 stays the sign-in's + wallets = () => { throw new TypeError("fetch failed") } + r = await loader.fetch("x", { method: "POST", body: chatOf(200_000) }) + expect(r.status).toBe(401) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("expired") + wallets = () => new Response(JSON.stringify({ code: 500, message: "busy" })) + r = await loader.fetch("x", { method: "POST", body: chatOf(200_000) }) + expect(r.status).toBe(401) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("expired") + } finally { + globalThis.fetch = realFetch + _internal.clearLargestServed() + } + }) + + test(`${name} chat: a 401 for a body no larger than one answered is the sign-in, with no check made (plugins#891)`, async () => { + _internal.clearLargestServed() + const realFetch = globalThis.fetch + const calls = [] + let refuse = false + globalThis.fetch = async (input) => { + const url = String(input) + calls.push(url.includes("/wallets") ? "wallets" : "chat") + if (url.includes("/wallets")) return new Response(WALLETS_OK) + return refuse ? new Response(BIG_401, { status: 401 }) : new Response("ok") + } + try { + const hooks = await Plugin({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "a1" })) + expect((await loader.fetch("x", { method: "POST", body: chatOf(50_000) })).status).toBe(200) + refuse = true + calls.length = 0 + const r = await loader.fetch("x", { method: "POST", body: chatOf(50_000) }) + expect(r.status).toBe(401) + expect(r.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect(calls).toEqual(Array(chatHosts).fill("chat")) + } finally { + globalThis.fetch = realFetch + _internal.clearLargestServed() + } + }) +} + +test("signInHolds: taken on any host is true, refused everywhere false, otherwise unknown", async () => { + const realFetch = globalThis.fetch + let answers = [] + globalThis.fetch = async () => answers.shift()() + try { + const hosts = ["https://a.example", "https://b.example"] + answers = [() => new Response("{}", { status: 401 }), () => new Response(WALLETS_OK)] + expect(await _internal.signInHolds("t", hosts)).toBe(true) + answers = [() => new Response("{}", { status: 401 }), () => new Response("{}", { status: 403 })] + expect(await _internal.signInHolds("t", hosts)).toBe(false) + answers = [() => { throw new TypeError("fetch failed") }, () => new Response("", { status: 502 })] + expect(await _internal.signInHolds("t", hosts)).toBe(null) + } finally { + globalThis.fetch = realFetch + } +}) diff --git a/packages/autoclaw/package.json b/packages/autoclaw/package.json index ef73277..ddfd26d 100644 --- a/packages/autoclaw/package.json +++ b/packages/autoclaw/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-autoclaw-auth", - "version": "0.2.19", + "version": "0.2.20", "description": "OpenCode provider plugin for AutoClaw (Zhipu OpenClaw): oversea web sign-in (Google/z.ai) and CN phone SMS, multi-account pool, credit balance and daily check-in", "type": "module", "main": "./opencode.mjs",