From 01aee5da288bb75317a1e92f70e3bbe87a229bc2 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 1 Oct 2026 04:53:29 +0800 Subject: [PATCH] =?UTF-8?q?all:=20a=20usage=20read=20says=20what=20it=20me?= =?UTF-8?q?ans=20for=20the=20sign-in,=20and=20a=20renewal=20clears=20the?= =?UTF-8?q?=20mark=20whatever=20follows,=20as=20the=20built-ins=20did=20(?= =?UTF-8?q?=E8=A6=81=E4=BF=9D=E8=AF=81=E6=8F=92=E4=BB=B6=E8=B7=9F=E5=86=85?= =?UTF-8?q?=E7=BD=AE=E7=9A=84=E6=89=80=E6=9C=89=E9=80=BB=E8=BE=91=E9=83=BD?= =?UTF-8?q?=E8=A6=81=E4=B8=80=E6=A8=A1=E4=B8=80=E6=A0=B7)=20=E2=80=94=20au?= =?UTF-8?q?th.usage=20returns=20signIn=20on=20every=20path:=20expired=20wh?= =?UTF-8?q?ere=20the=20built-in's=20quota=20read=20marked=20the=20account?= =?UTF-8?q?=20(Zed's=20/users/me=20401,=20Factory's=20and=20MiMo's=20refus?= =?UTF-8?q?ed=20renewals,=20Qoder's=20refused=20job=20refresh),=20renewed?= =?UTF-8?q?=20after=20a=20renewal,=20which=20took=20the=20mark=20off,=20ke?= =?UTF-8?q?pt=20everywhere=20else,=20so=20magpie=20no=20longer=20guesses?= =?UTF-8?q?=20from=20the=20words=20'sign=20in=20again'=20(Kiro's,=20Devin'?= =?UTF-8?q?s=20and=20ZCode's=20usage=20errors=20marked=20accounts=20their?= =?UTF-8?q?=20built-ins=20never=20did)=20nor=20clears=20on=20a=20clean=20r?= =?UTF-8?q?ead.=20A=20request=20after=20a=20renewal=20says=20renewed=20on?= =?UTF-8?q?=20any=20status;=20one=20without=20says=20kept,=20as=20the=20bu?= =?UTF-8?q?ilt-ins=20cleared=20only=20on=20renewal.=20Kiro,=20Cursor,=20De?= =?UTF-8?q?vin,=20Command=20Code,=20WorkBuddy,=20Grok=20and=20ZCode,=20who?= =?UTF-8?q?se=20built-ins=20never=20marked=20an=20account,=20say=20kept=20?= =?UTF-8?q?on=20every=20answer.=20New=20tests=20fail=20against=2085d7dd0's?= =?UTF-8?q?=20index.mjs.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/commandcode/errors.test.mjs | 9 +++- packages/commandcode/index.mjs | 14 ++--- packages/commandcode/usage.test.mjs | 20 +++---- packages/cursor/errors.test.mjs | 33 ++++++++---- packages/cursor/index.mjs | 41 ++++++++------ packages/cursor/usage.test.mjs | 30 ++++++----- packages/devin/errors.test.mjs | 9 ++++ packages/devin/index.mjs | 14 ++--- packages/devin/usage.test.mjs | 19 ++++--- packages/factory/index.mjs | 25 +++++---- packages/factory/lapsed.test.mjs | 9 +++- packages/factory/usage.test.mjs | 35 ++++++++++-- packages/grok/index.mjs | 16 +++--- packages/grok/signin.test.mjs | 6 ++- packages/grok/usage.test.mjs | 18 ++++--- packages/kiro/errors.test.mjs | 32 ++++++++--- packages/kiro/index.mjs | 42 +++++++++------ packages/kiro/usage.test.mjs | 25 ++++++--- packages/mimo/index.mjs | 32 +++++++---- packages/mimo/usage.test.mjs | 56 +++++++++++++++---- packages/qoder/index.mjs | 81 ++++++++++++++++++---------- packages/qoder/usage.test.mjs | 68 +++++++++++++++++++++-- packages/workbuddy/index.mjs | 20 +++++-- packages/workbuddy/signin.test.mjs | 6 ++- packages/workbuddy/usage.test.mjs | 18 ++++--- packages/zcode/index.mjs | 12 +++-- packages/zcode/signin.test.mjs | 6 ++- packages/zcode/usage.test.mjs | 19 ++++--- packages/zed/errors.test.mjs | 9 ++++ packages/zed/index.mjs | 20 ++++--- packages/zed/usage.test.mjs | 26 ++++++--- 31 files changed, 541 insertions(+), 229 deletions(-) diff --git a/packages/commandcode/errors.test.mjs b/packages/commandcode/errors.test.mjs index fbb955e..0243991 100644 --- a/packages/commandcode/errors.test.mjs +++ b/packages/commandcode/errors.test.mjs @@ -74,5 +74,12 @@ test("an error line saying 401 keeps the account too", async () => { test("the Provider API's 401 goes on as it came, the account kept", async () => { expect(await signIn(() => Response.json({ error: { message: "Invalid API key" } }, { status: 401 }), "Pro", "/provider/v1/chat/completions")) .toEqual({ status: 401, signIn: "kept" }) - expect(await signIn(() => Response.json({}), "Pro", "/provider/v1/chat/completions")).toEqual({ status: 200, signIn: null }) +}) + +// nor cleared one: an answer that went through leaves the mark as it is +test("an answer that goes through keeps the account's mark, Go's and the Provider API's", async () => { + expect(await signIn(() => Response.json({}), "Pro", "/provider/v1/chat/completions")).toEqual({ status: 200, signIn: "kept" }) + expect(await signIn(() => Response.json({}, { status: 404 }), "Pro", "/provider/v1/chat/completions")).toEqual({ status: 404, signIn: "kept" }) + const line = JSON.stringify({ type: "text-delta", text: "hi" }) + "\n" + JSON.stringify({ type: "finish", finishReason: "stop" }) + "\n" + expect(await signIn(() => new Response(line))).toEqual({ status: 200, signIn: "kept" }) }) diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index 6662964..3b9c05b 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -917,11 +917,11 @@ export async function CommandCodePlugin({ client } = {}) { } catch { return errorResponse({ status: 400, message: "a request that isn't JSON" }) } - return generate(key, chat, init.signal) + return kept(await generate(key, chat, init.signal)) } - // the Provider API's 401 went on as it came, the account kept - const res = await fetch(input, { ...init, headers }) - return res.status === 401 ? kept(res) : res + // the Provider API's answer goes on as it came, the account + // kept: the built-in neither marked one lapsed nor cleared it + return kept(await fetch(input, { ...init, headers })) }, } }, @@ -933,7 +933,9 @@ export async function CommandCodePlugin({ client } = {}) { // magpie's: the plan and how much of it is used async usage(getAuth) { const auth = await getAuth() - if (auth?.type !== "api" || !auth.key) return { error: "not signed in" } + // signIn kept on each: the built-in's usage read never marked the + // account lapsed nor cleared it + if (auth?.type !== "api" || !auth.key) return { error: "not signed in", signIn: "kept" } const md = auth.metadata ?? {} const { out, read } = await usage(await liveKey(auth), md.plan ? { id: md.planId ?? "", plan: md.plan } : undefined) // the plan read is saved with the key, so a start doesn't wait on @@ -943,7 +945,7 @@ export async function CommandCodePlugin({ client } = {}) { await client.auth.set({ path: { id: ID }, body: { ...auth, metadata: { ...md, plan: read.plan, planId: read.id } } }) } catch {} } - return out + return { ...out, signIn: "kept" } }, }, async config(config) { diff --git a/packages/commandcode/usage.test.mjs b/packages/commandcode/usage.test.mjs index e6f4664..e8ab0e5 100644 --- a/packages/commandcode/usage.test.mjs +++ b/packages/commandcode/usage.test.mjs @@ -36,6 +36,7 @@ test("a Max account: its 5 hours, its week and its credits, and its period", asy }, }) expect(u).toEqual({ + signIn: "kept", plan: "Max", until: "2026-10-28T00:00:00.000Z", renew: "off", @@ -53,7 +54,7 @@ test("no plan: the credits bought are a balance", async () => { "/alpha/billing/subscriptions": { success: true, data: null }, "/alpha/billing/credits": { credits: { monthlyCredits: 0, purchasedCredits: 7.25, freeCredits: 0 } }, }) - expect(u).toEqual({ plan: "No plan", balance: "$7.25", windows: [] }) + expect(u).toEqual({ signIn: "kept", plan: "No plan", balance: "$7.25", windows: [] }) }) test("Go: the month's $10 is the pool", async () => { @@ -61,7 +62,7 @@ test("Go: the month's $10 is the pool", async () => { "/alpha/billing/subscriptions": { data: { planId: "individual-go", status: "active" } }, "/alpha/billing/credits": { credits: { monthlyCredits: 4 } }, }) - expect(u).toEqual({ plan: "Go", windows: [{ name: "Credits", used: 60, display: "$6.00 / $10.00" }] }) + expect(u).toEqual({ signIn: "kept", plan: "Go", windows: [{ name: "Credits", used: 60, display: "$6.00 / $10.00" }] }) }) test("credits that can't be read keep the plan and say why", async () => { @@ -69,15 +70,15 @@ test("credits that can't be read keep the plan and say why", async () => { "/alpha/billing/subscriptions": { data: { planId: "individual-pro-monthly", status: "active", cancelAtPeriodEnd: false } }, "/alpha/billing/credits": 503, }) - expect(u).toEqual({ plan: "Pro", renew: "auto", error: "Service Unavailable", windows: [] }) + expect(u).toEqual({ signIn: "kept", plan: "Pro", renew: "auto", error: "Service Unavailable", windows: [] }) }) test("a canceled subscription is No plan; an unread one leaves the plan unsaid", async () => { let { u } = await run(api, { "/alpha/billing/subscriptions": { data: { planId: "individual-pro", status: "canceled" } }, "/alpha/billing/credits": 413 }) - expect(u).toEqual({ plan: "No plan", error: "Request Entity Too Large", windows: [] }) + expect(u).toEqual({ signIn: "kept", plan: "No plan", error: "Request Entity Too Large", windows: [] }) _internal.subsSeen.clear() // a plan read is kept ten minutes ;({ u } = await run(api, { "/alpha/billing/subscriptions": 401, "/alpha/billing/credits": 401 })) - expect(u).toEqual({ error: "Unauthorized", windows: [] }) + expect(u).toEqual({ signIn: "kept", error: "Unauthorized", windows: [] }) }) test("seconds and string amounts read as magpie reads them; a half cent goes to the even one", async () => { @@ -86,6 +87,7 @@ test("seconds and string amounts read as magpie reads them; a half cent goes to "/alpha/billing/credits": { credits: { monthlyCredits: "29.875" }, windowLimits: { fiveHour: { used: "5", cap: 0 }, weekly: { used: 150, cap: "100", resetAt: 0 } } }, }) expect(u).toEqual({ + signIn: "kept", plan: "Pro", until: new Date(1790000000 * 1000).toISOString(), windows: [{ name: "Weekly", used: 100, span: 604800 }, { name: "Credits", used: 0.4166666666666667, display: "$0.12 / $30.00" }], @@ -93,7 +95,7 @@ test("seconds and string amounts read as magpie reads them; a half cent goes to }) test("a sign-in that isn't a key is no account", async () => { - expect((await run({ type: "oauth" }, {})).u).toEqual({ error: "not signed in" }) + expect((await run({ type: "oauth" }, {})).u).toEqual({ signIn: "kept", error: "not signed in" }) }) test("a slow subscription: the windows go without it, and the next card has it", async () => { @@ -111,11 +113,11 @@ test("a slow subscription: the windows go without it, and the next card has it", } const hooks = await CommandCodePlugin() const first = await hooks.auth.usage(async () => api) - expect(first).toEqual({ windows: [{ name: "5 hours", used: 1, span: 18000 }] }) + expect(first).toEqual({ signIn: "kept", windows: [{ name: "5 hours", used: 1, span: 18000 }] }) answer() await new Promise((r) => setTimeout(r, 20)) const next = await hooks.auth.usage(async () => api) - expect(next).toEqual({ plan: "GOAT", renew: "off", windows: [{ name: "5 hours", used: 1, span: 18000 }, { name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) + expect(next).toEqual({ signIn: "kept", plan: "GOAT", renew: "off", windows: [{ name: "5 hours", used: 1, span: 18000 }, { name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) }) test("a plan read is saved with the key, once", async () => { @@ -148,7 +150,7 @@ test("a plan saved stands in for a subscription slow to read: waited for a momen const t = Date.now() const u = await hooks.auth.usage(async () => ({ ...api, metadata: { plan: "GOAT", planId: "individual-goat" } })) expect(Date.now() - t).toBeLessThan(3_000) - expect(u).toEqual({ plan: "GOAT", windows: [{ name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) + expect(u).toEqual({ signIn: "kept", plan: "GOAT", windows: [{ name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) answer() }) diff --git a/packages/cursor/errors.test.mjs b/packages/cursor/errors.test.mjs index 7de05c7..e148ee6 100644 --- a/packages/cursor/errors.test.mjs +++ b/packages/cursor/errors.test.mjs @@ -2,7 +2,7 @@ // built-in Cursor (internal/gateway/cursor.go, cursorFailure) gave it, so the // gateway moves on to the next account or member as it did. import { expect, test } from "bun:test" -import { _internal } from "./index.mjs" +import { CursorAuthPlugin, _internal } from "./index.mjs" const { failure, errorResponse } = _internal @@ -25,21 +25,34 @@ test("the codes and words map as the built-in's cursorStatus", () => { expect(failure(200, end("unauthenticated", "Error"))).toEqual({ status: 401, message: "unauthenticated — sign in to Cursor again in magpie" }) }) -// The built-in answered any "expired" with a 401 and marked nothing; here a -// token or session run out marks the account (a plain 401), anything else -// run out — a trial, a plan — is the same 401 with X-Magpie-Sign-In: kept. -test("any expired is the built-in's 401; only a sign-in run out marks the account", () => { +// The built-in answered any "expired" with a 401 and marked nothing, a +// session's as a trial's; nor did a success clear a mark. +test("any expired is the built-in's 401", () => { const end = (code, message) => JSON.stringify({ error: { code, message } }) expect(failure(200, end("failed_precondition", "Your free trial has expired"))).toEqual({ - status: 401, message: "Your free trial has expired — sign in to Cursor again in magpie", signIn: "kept" }) + status: 401, message: "Your free trial has expired — sign in to Cursor again in magpie" }) expect(failure(400, end("", "Your session has expired"))).toEqual({ status: 401, message: "Your session has expired — sign in to Cursor again in magpie" }) - expect(failure(401, "")).not.toHaveProperty("signIn") + expect(failure(401, "")).toEqual({ status: 401, message: "Unauthorized — sign in to Cursor again in magpie" }) }) -test("the answer carries what it means for the sign-in", async () => { - const res = errorResponse({ status: 401, message: "Your plan has expired", signIn: "kept" }) +test("every answer, failed or not, says the account is kept", async () => { + for (const status of [401, 403, 429, 502]) { + const res = errorResponse({ status, message: "x" }) + expect(res.status).toBe(status) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + } + const ok = _internal.kept(new Response("data: [DONE]\n\n", { status: 200, headers: { "Content-Type": "text/event-stream" } })) + expect(ok.status).toBe(200) + expect(ok.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(ok.headers.get("Content-Type")).toBe("text/event-stream") + expect(await ok.text()).toBe("data: [DONE]\n\n") +}) + +test("a sign-in that can't give a token is a 401, the account kept", async () => { + const hooks = await CursorAuthPlugin() + const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "", refresh: "", expires: 0, accountId: "a@b.c" })) + const res = await l.fetch("https://cursor.invalid/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "auto", messages: [] }) }) expect(res.status).toBe(401) expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") - expect(errorResponse({ status: 401, message: "x" }).headers.get("X-Magpie-Sign-In")).toBeNull() }) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 73c368a..d480836 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -848,22 +848,17 @@ function failure(status, text) { return statusOf(status, f.code ?? "", msg) } -// signInExpired is a message of a token or session run out. The built-in -// answered any "expired" with a 401, but a trial, a plan or a link run out -// is no lapsed sign-in: that 401 says "kept" (X-Magpie-Sign-In). -const signInExpired = (low) => low.includes("expired") && /token|session|sign[- ]?in|log[- ]?in|auth|credential/.test(low) - // statusOf is the status and words for Cursor's error of this code and // message. A region the team isn't served in says so, not to sign in. function statusOf(status, code, msg) { msg ||= statusText(status) const low = msg.toLowerCase() // magpie names the provider before the message itself - const out = (status, message, signIn) => ({ status, message, ...(signIn ? { signIn } : {}) }) + const out = (status, message) => ({ status, message }) if (regional(msg)) return out(403, msg + " — Cursor serves your team only in some regions and turned this request away; signing in again won't change that") if (code === "permission_denied") return out(403, msg) if (code === "unauthenticated" || status === 401 || low.includes("expired")) - return out(401, msg + " — sign in to Cursor again in magpie", code === "unauthenticated" || status === 401 || signInExpired(low) ? undefined : "kept") + return out(401, msg + " — sign in to Cursor again in magpie") if (code === "resource_exhausted" || low.includes("quota") || low.includes("rate limit") || low.includes("usage limit")) return out(429, "usage limit reached: " + msg) if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens")) @@ -1359,17 +1354,28 @@ function exec(msg, tools, send, closeExec) { // ---- chat completions ------------------------------------------------------------------ -// signIn, the X-Magpie-Sign-In header, says what the answer means for the -// account whatever its status: "kept" leaves it unmarked. -const errorResponse = ({ status, message, signIn }) => +// Every answer says X-Magpie-Sign-In: kept. The built-in marked no Cursor +// account lapsed, not for a 401 nor for any "expired" (a token, a session, +// a trial), and cleared none on a success or a renewed token. +const errorResponse = ({ status, message }) => new Response(JSON.stringify({ error: { message, type: "cursor_error", code: status } }), { status, - headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) }, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, }) -// answer runs a chat completion on Cursor and answers it as one, streamed +function kept(res) { + if (res.headers.has("X-Magpie-Sign-In")) return res + const headers = new Headers(res.headers) + headers.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + +// answer runs a chat completion on Cursor, the account kept (errorResponse). +const answer = async (auth, chat, signal) => kept(await answerOf(auth, chat, signal)) + +// answerOf runs a chat completion on Cursor and answers it as one, streamed // or not. -async function answer(auth, chat, signal) { +async function answerOf(auth, chat, signal) { let tok try { tok = await tokenOf(auth) @@ -1484,16 +1490,17 @@ export async function CursorAuthPlugin() { { type: "api", label: "Cursor API key (cursor.com/dashboard → Integrations)" }, ], // magpie's: how much of the plan's included usage is gone (the plan - // is the one the sign-in read) + // is the one the sign-in read). The built-in's read, clean or not, + // neither marked the account nor cleared it. async usage(getAuth, provider) { let tok try { tok = await tokenOf(await getAuth()) } catch (e) { - return { error: e.message, windows: [] } + return { error: e.message, windows: [], signIn: "kept" } } const [u, plan] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {})), planOf(tok)]) - return plan ? { ...u, plan } : u + return { ...u, ...(plan ? { plan } : {}), signIn: "kept" } }, }, async config(config) { @@ -1526,4 +1533,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { errorResponse, poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { errorResponse, kept, poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/usage.test.mjs b/packages/cursor/usage.test.mjs index 31e91b9..10894d6 100644 --- a/packages/cursor/usage.test.mjs +++ b/packages/cursor/usage.test.mjs @@ -100,31 +100,35 @@ for (const bucket of [["default", "composer-2.5", "cursor-grok-4.5-high", "futur } test("an enterprise plan's spend is no window", async () => { - expect((await run(fresh(), () => Response.json({ spendLimitUsage: {} }))).u).toEqual({ windows: [] }) + expect((await run(fresh(), () => Response.json({ spendLimitUsage: {} }))).u).toEqual({ windows: [], signIn: "kept" }) }) test("a refused token is the status magpie says", async () => { - expect((await run(fresh(), () => new Response("no", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [] }) + expect((await run(fresh(), () => new Response("no", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [], signIn: "kept" }) }) test("a run-out sign-in says so, and asks nothing", async () => { const { u, seen } = await run({ ...auth, access: jwt(1) }, () => Response.json({})) - expect(u).toEqual({ error: "Cursor's sign-in has run out; sign in to Cursor again", windows: [] }) + expect(u).toEqual({ error: "Cursor's sign-in has run out; sign in to Cursor again", windows: [], signIn: "kept" }) expect(seen).toEqual([]) }) -// magpie marks a plugin's account lapsed on any 401, so only a sign-in -// that is gone says 401 -// the built-in's 401 for any "expired"; X-Magpie-Sign-In keeps the account -// when what ran out was no sign-in -test("an expired token is a lapsed sign-in; an expired trial is not", () => { +// the built-in's 401 for any "expired", a token's or a trial's, which marked +// no account (errorResponse says kept) +test("anything expired is the built-in's 401", () => { const { failure } = _internal const says = (msg) => failure(400, JSON.stringify({ code: "failed_precondition", message: msg })) - expect(says("Your access token has expired")).toMatchObject({ status: 401 }) - expect(says("Your access token has expired")).not.toHaveProperty("signIn") - expect(says("Session expired, please log in again")).not.toHaveProperty("signIn") - expect(says("Your free trial has expired")).toMatchObject({ status: 401, signIn: "kept" }) - expect(says("This link has expired")).toMatchObject({ status: 401, signIn: "kept" }) + for (const m of ["Your access token has expired", "Session expired, please log in again", "Your free trial has expired", "This link has expired"]) + expect(says(m)).toEqual({ status: 401, message: m + " — sign in to Cursor again in magpie" }) +}) + +// The built-in's usage read neither marked nor cleared the account, so each +// read says kept, a clean one too. +test("a usage read keeps the account, clean or not", async () => { + const PERIOD_OK = () => Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 1, apiPercentUsed: 2, totalPercentUsed: 3 } }) + expect((await run(fresh(), PERIOD_OK)).u.signIn).toBe("kept") + expect((await run(fresh(), () => new Response("no", { status: 401 }))).u.signIn).toBe("kept") + expect((await run({ ...auth, access: jwt(1) }, PERIOD_OK)).u.signIn).toBe("kept") }) // the gateway names the provider before a plugin's error diff --git a/packages/devin/errors.test.mjs b/packages/devin/errors.test.mjs index 0904b30..d858fea 100644 --- a/packages/devin/errors.test.mjs +++ b/packages/devin/errors.test.mjs @@ -91,3 +91,12 @@ test("an error after a frame with nothing in it is streamed in the built-in's wo const ev = r.body.split("\n\n").map((l) => l.replace(/^data: /, "")).find((l) => l.includes('"error"')) expect(JSON.parse(ev).error.message).toBe("usage limit reached: rate limit") }) + +// a success cleared no mark the built-in's account could have had +test("an answer says the account is kept, streamed or not", async () => { + for (const stream of [false, true]) { + const r = await ask(() => new Response(join(new Uint8Array(5), end({}))), stream) + expect(r.status).toBe(200) + expect(r.signIn).toBe("kept") + } +}) diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index 1416a95..63b75b3 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1008,7 +1008,7 @@ async function* events(it) { // errorResponse is a failure as the built-in answered it. None marks the // account lapsed: the built-in's 401s (a key Devin turned away, none to // send) were answered without touching the account, so each says -// X-Magpie-Sign-In: kept. +// X-Magpie-Sign-In: kept — as a success does, which cleared nothing either. const errorResponse = ({ status, message }) => new Response(JSON.stringify({ error: { message, type: "devin_error", code: status } }), { status, @@ -1077,7 +1077,7 @@ async function complete({ key, server, families }, chat, signal) { } if (reasoning) msg.reasoning_content = reasoning if (calls.length) msg.tool_calls = calls - return Response.json({ id, object: "chat.completion", created, model: chat.model, choices: [{ index: 0, message: msg, finish_reason: stop }], usage }) + return Response.json({ id, object: "chat.completion", created, model: chat.model, choices: [{ index: 0, message: msg, finish_reason: stop }], usage }, { headers: { "X-Magpie-Sign-In": "kept" } }) } const chunk = (delta, finish_reason = null, extra = {}) => @@ -1109,7 +1109,7 @@ async function complete({ key, server, families }, chat, signal) { it.return?.() }, }) - return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } }) + return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Magpie-Sign-In": "kept" } }) } // ---- the plugin --------------------------------------------------------------------- @@ -1214,12 +1214,14 @@ export async function DevinAuthPlugin() { { type: "oauth", label: "Devin (browser)", authorize: browserSignIn }, { type: "oauth", label: "Devin CLI's sign-in", authorize: cliSignIn }, ], - // magpie's: the plan and how much of its quota is gone + // magpie's: the plan and how much of its quota is gone. The built-in + // read none, so no read marks the account or clears it, not even a + // key Devin turned away. async usage(getAuth) { const auth = await getAuth() - if (auth?.type !== "api" || !auth.key) return { error: "Devin isn't signed in" } + if (auth?.type !== "api" || !auth.key) return { error: "Devin isn't signed in", signIn: "kept" } const { key, server } = await live(auth) - return usage(key, server) + return { ...(await usage(key, server)), signIn: "kept" } }, }, async config(config) { diff --git a/packages/devin/usage.test.mjs b/packages/devin/usage.test.mjs index e224f33..beed05f 100644 --- a/packages/devin/usage.test.mjs +++ b/packages/devin/usage.test.mjs @@ -49,6 +49,7 @@ test("a Teams plan: its end, its day and week, the extra usage balance", async ( { name: "1 day", used: 0, span: 86400, resetsAt: 1790841600 }, { name: "7 days", used: 1, span: 604800, resetsAt: 1791100800 }, ], + signIn: "kept", }) expect(seen[0].url).toBe("https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetUserStatus") expect(seen[0].headers).toEqual({ "Content-Type": "application/json", "Connect-Protocol-Version": "1" }) @@ -62,28 +63,30 @@ test("a quota Devin says nothing left of isn't taken for used up; a hidden one i expect(u).toEqual({ until: "2026-10-26T21:45:55Z", windows: [{ name: "ACUs", used: 25, display: "12.5 / 50 ACUs", resetsAt: "2026-10-26T21:45:55Z", aside: true }], + signIn: "kept", }) }) test("a plan billed otherwise, with resets and no share given, has no quota windows", async () => { const s = status({ dailyQuotaRemainingPercent: undefined, weeklyQuotaRemainingPercent: undefined, overageBalanceMicros: undefined }) s.userStatus.planStatus.planInfo.billingStrategy = "BILLING_STRATEGY_CREDITS" - expect((await run(auth, () => Response.json(s))).u).toEqual({ until: "2026-10-26T21:45:55Z", windows: [] }) + expect((await run(auth, () => Response.json(s))).u).toEqual({ until: "2026-10-26T21:45:55Z", windows: [], signIn: "kept" }) }) test("a plan without quotas has no windows, and leaves the row's plan be", async () => { const s = { userStatus: { planStatus: { planInfo: { planName: "Free" } } } } - expect((await run(auth, () => Response.json(s))).u).toEqual({ windows: [] }) + expect((await run(auth, () => Response.json(s))).u).toEqual({ windows: [], signIn: "kept" }) }) -test("a refused key says to sign in again", async () => { +// the built-in read no usage, so none marked the account: a refused key +// says to sign in again, and says the account is kept +test("a refused key says to sign in again, the account kept", async () => { const { u } = await run(auth, () => Response.json({ code: "unauthenticated", message: "invalid api key" }, { status: 401 })) - // worded so magpie's /sign-in has expired/ marks the account - expect(u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [] }) - expect(u.error).toMatch(/sign-in has expired/) + expect(u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "kept" }) const bare = await run(auth, () => new Response("", { status: 401 })) - expect(bare.u.error).toBe("Devin's sign-in has expired — sign in again") - expect((await run({ type: "oauth" }, () => Response.json({}))).u).toEqual({ error: "Devin isn't signed in" }) + expect(bare.u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "kept" }) + expect((await run(auth, () => new Response("", { status: 500 }))).u.signIn).toBe("kept") + expect((await run({ type: "oauth" }, () => Response.json({}))).u).toEqual({ error: "Devin isn't signed in", signIn: "kept" }) }) // the built-in sends none and minimal as asked (devinVariantIn): the diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 725a612..b32d3eb 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -578,10 +578,15 @@ export const FactoryAuthPlugin = async ({ client }) => { }) // usage is the account's limits, asked once more when Factory refused - // an org that was put right + // an org that was put right. signIn is what the read did to the + // built-in's lapse mark: a renewal took it off whatever came after, a + // refused one put it on, a read that renewed nothing left it be (a + // clean read too) const usage = async () => { + let signIn = "kept" + const onRenew = () => (signIn = "renewed") const limits = async () => { - const c = await fresh() + const c = await fresh(onRenew) const h = new Headers({ Accept: "application/json" }) factoryHeaders(h, c) const res = await fetch(base(c) + "/api/billing/limits", { headers: h, signal: AbortSignal.timeout(15_000) }) @@ -594,13 +599,14 @@ export const FactoryAuthPlugin = async ({ client }) => { try { l = await limits() } catch (e) { - if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body).catch(() => false)))) throw e + if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body, onRenew).catch(() => false)))) throw e l = await limits() } - if (!l?.limits?.standard) return { error: "Factory: the account reported no limits" } - return { windows: limitWindows(l) } + if (!l?.limits?.standard) return { error: "Factory: the account reported no limits", signIn } + return { windows: limitWindows(l), signIn } } catch (e) { - return { error: e?.message ?? String(e) } + if (e?.lapsed) signIn = "expired" + return { error: e?.message ?? String(e), signIn } } } @@ -670,11 +676,12 @@ export const FactoryAuthPlugin = async ({ client }) => { if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer()) const url = input instanceof Request ? input.url : String(input) // the built-in takes an account's lapse off when it renews the - // token, and never for an answer: a 401 of Factory's leaves it - // be, and so does a success with no renewal on the way + // token, whatever the request then meets, and never for an + // answer: a 401 of Factory's leaves it be, and so does a success + // with no renewal on the way let renewed = false const onRenew = () => (renewed = true) - const answer = (res) => (renewed && res.status >= 200 && res.status < 300 ? res : said(res, "kept")) + const answer = (res) => said(res, renewed ? "renewed" : "kept") let res try { res = await send(input, init, body, onRenew) diff --git a/packages/factory/lapsed.test.mjs b/packages/factory/lapsed.test.mjs index 751c212..c9a2b33 100644 --- a/packages/factory/lapsed.test.mjs +++ b/packages/factory/lapsed.test.mjs @@ -96,7 +96,14 @@ test("a success takes the mark off only after a renewal", async () => { l = await live((path) => (path.endsWith("/authenticate") ? new Response(JSON.stringify({ access_token: "tok-new" })) : new Response("{}", { status: 200 })), { ...expired }) res = await ask(l) expect(res.status).toBe(200) - expect(res.headers.get("X-Magpie-Sign-In")).toBe(null) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") +}) + +test("a failure after a renewal still takes the mark off, as factoryFresh did before the request", async () => { + const l = await live((path) => (path.endsWith("/authenticate") ? new Response(JSON.stringify({ access_token: "tok-new" })) : new Response(JSON.stringify({ error: { message: "bad token" } }), { status: 401 })), { ...expired }) + const res = await ask(l) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") }) test("a renewal WorkOS fails without refusing it is magpie's 502 for the throw, in Go's words, the account unmarked", async () => { diff --git a/packages/factory/usage.test.mjs b/packages/factory/usage.test.mjs index 13f83c4..b9ee192 100644 --- a/packages/factory/usage.test.mjs +++ b/packages/factory/usage.test.mjs @@ -63,6 +63,7 @@ test("standard's windows, Droid Core's, and the extra usage", async () => { { name: "Droid Core · 5 hours", used: 100, span: 18000, resetsAt: "2026-10-01T05:00:00.000Z", aside: true, models: CORE }, { name: "Extra usage", used: 0, display: "$12.50", aside: true }, ], + signIn: "kept", }) // an EU org's usage is asked of the EU API, with its org expect(p.seen).toEqual(["api.eu.factory.ai/api/billing/limits fac_A"]) @@ -82,7 +83,7 @@ test("with no extra usage allowed a window used up stops the account; a half cen test("no standard limits is an error", async () => { const p = await plugin(account(), () => json({ limits: { core: {} } })) - expect(await p.usage()).toEqual({ error: "Factory: the account reported no limits" }) + expect(await p.usage()).toEqual({ error: "Factory: the account reported no limits", signIn: "kept" }) }) test("an org Factory refuses is put right and the limits asked once more", async () => { @@ -93,22 +94,46 @@ test("an org Factory refuses is put right and the limits asked once more", async return h.get("X-Factory-Org-Id") === "fac_A" ? json({ limits: { standard: { fiveHour: { usedPercent: 7 } } } }) : json(refused, 403) return new Response("", { status: 404 }) }) - expect(await p.usage()).toEqual({ windows: [{ name: "5 hours", used: 7, span: 18000, notModels: CORE }] }) + expect(await p.usage()).toEqual({ windows: [{ name: "5 hours", used: 7, span: 18000, notModels: CORE }], signIn: "kept" }) expect(p.seen).toEqual(["api.factory.ai/api/billing/limits fac_gone", "api.factory.ai/api/cli/whoami ", "api.factory.ai/api/billing/limits fac_A"]) expect(p.auth().activeOrganizationId).toBe("fac_A") }) test("another refusal is Factory's message, not retried", async () => { const p = await plugin(account(), () => json({ error: { message: "model not allowed" } }, 403)) - expect(await p.usage()).toEqual({ error: "Factory: model not allowed" }) + expect(await p.usage()).toEqual({ error: "Factory: model not allowed", signIn: "kept" }) expect(p.seen.length).toBe(1) const q = await plugin(account(), () => new Response("upstream went\naway", { status: 502 })) - expect(await q.usage()).toEqual({ error: "Factory: 502 Bad Gateway: upstream went away" }) + expect(await q.usage()).toEqual({ error: "Factory: 502 Bad Gateway: upstream went away", signIn: "kept" }) }) test("a refresh token WorkOS refuses lapses the account", async () => { const p = await plugin(account({ expires: Date.now() - 1000 }), (path) => path === "/user_management/authenticate" ? json({ error: "invalid_grant", error_description: "gone" }, 400) : new Response("", { status: 404 }), ) - expect(await p.usage()).toEqual({ error: "ada's Factory sign-in has expired — sign in again (Factory: invalid_grant gone)" }) + expect(await p.usage()).toEqual({ error: "ada's Factory sign-in has expired — sign in again (Factory: invalid_grant gone)", signIn: "expired" }) +}) + +// the built-in's factoryFresh took the lapse mark off when it renewed the +// token, whatever the limits read then met; a read with no renewal, clean or +// not, left the mark be +test("a read that renewed the token says so, whatever the limits then answer", async () => { + const renewing = (limits) => (path) => + path === "/user_management/authenticate" ? json({ access_token: "tok-new", refresh_token: "r-new" }) : path === "/api/billing/limits" ? limits() : json({}, 404) + const p = await plugin(account({ expires: Date.now() - 1000 }), renewing(() => json({ limits: { standard: { fiveHour: { usedPercent: 7 } } } }))) + expect(await p.usage()).toEqual({ windows: [{ name: "5 hours", used: 7, span: 18000, notModels: CORE }], signIn: "renewed" }) + const q = await plugin(account({ expires: Date.now() - 1000 }), renewing(() => json({ error: { message: "busy" } }, 503))) + expect(await q.usage()).toEqual({ error: "Factory: busy", signIn: "renewed" }) +}) + +test("a token put in an org on the way renews it, as the built-in's factoryMendOrg took the mark off", async () => { + const refused = { error: { message: "Requested active organization is not accessible by this user" } } + const p = await plugin(account({ activeOrganizationId: "", region: "" }), (path, h, init) => { + if (path === "/api/cli/org") return json({ workosOrgIds: ["org_W"] }) + if (path === "/user_management/authenticate") return json({ access_token: "tok-org" }) + if (path === "/api/billing/limits") + return h.get("Authorization") === "Bearer tok-org" ? json({ limits: { standard: { fiveHour: { usedPercent: 1 } } } }) : json(refused, 403) + return json({}, 404) + }) + expect((await p.usage()).signIn).toBe("renewed") }) diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 8145efc..3df4f2c 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -477,10 +477,10 @@ export const GrokAuthPlugin = async ({ client }) => { if (typeof parsed.model === "string" && parsed.model) headers.set("x-grok-model-override", parsed.model) if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key) headers.delete("content-length") - // sent once, as the built-in sent it: Grok's 401 goes on as it - // came, and the built-in never marked a Grok account lapsed - const res = await fetch(req.url, { ...init, method: req.method, headers, body }) - return res.status === 401 ? kept(res) : res + // sent once, as the built-in sent it: Grok's answer goes on as + // it came, the account kept, as the built-in never marked a Grok + // account lapsed nor cleared one + return kept(await fetch(req.url, { ...init, method: req.method, headers, body })) }, } }, @@ -496,7 +496,9 @@ export const GrokAuthPlugin = async ({ client }) => { authorize: current, }, ], - // magpie's: how much of the subscription's allowance is gone + // magpie's: how much of the subscription's allowance is gone; each + // read keeps the sign-in (signIn), as the built-in's marked no + // account lapsed nor cleared one async usage(getAuth) { const auth = await getAuth() let c @@ -504,10 +506,10 @@ export const GrokAuthPlugin = async ({ client }) => { if (!auth || auth.type !== "oauth" || !auth.refresh) throw new Error("Grok is not signed in; run `grok login`") c = await token(auth.refresh, false) } catch (e) { - return { error: e.message, windows: [] } + return { error: e.message, windows: [], signIn: "kept" } } await remember(auth, c) - return usage(c.key) + return { ...(await usage(c.key)), signIn: "kept" } }, }, diff --git a/packages/grok/signin.test.mjs b/packages/grok/signin.test.mjs index 57770bb..86701b0 100644 --- a/packages/grok/signin.test.mjs +++ b/packages/grok/signin.test.mjs @@ -37,11 +37,13 @@ test("Grok's 401 is passed on once, the account kept", async () => { expect(await res.json()).toEqual({ error: "token revoked" }) }) -test("other answers go as they came", async () => { +// nor cleared one: an answer that went through leaves the mark as it is +test("other answers go as they came, the account kept", async () => { for (const status of [200, 403, 429]) { const { res, sent } = await chat(() => new Response("x", { status })) expect(sent).toBe(1) expect(res.status).toBe(status) - expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.text()).toBe("x") } }) diff --git a/packages/grok/usage.test.mjs b/packages/grok/usage.test.mjs index 3a93018..ceec253 100644 --- a/packages/grok/usage.test.mjs +++ b/packages/grok/usage.test.mjs @@ -42,6 +42,7 @@ test("SuperGrok's week and its on-demand spending; the CLI's newer token is kept }), ) expect(u).toEqual({ + signIn: "kept", windows: [ { name: "7 days", used: 42.5, span: 604800, resetsAt: "2026-09-28T02:17:59.504011+00:00" }, { name: "On-demand", used: 25, resetsAt: "2026-09-28T02:17:59.504011+00:00", aside: true }, @@ -55,21 +56,21 @@ test("a month with no on-demand cap is one window", async () => { const { u, saved } = await run({ ...auth, access: "tok-2", expires: Date.parse(expires) }, () => Response.json({ config: { currentPeriod: { type: "USAGE_PERIOD_TYPE_MONTHLY", end: "2026-10-01T00:00:00+00:00" }, onDemandCap: { val: 0 } } }), ) - expect(u).toEqual({ windows: [{ name: "Month", used: 0, span: 2592000, resetsAt: "2026-10-01T00:00:00+00:00" }] }) + expect(u).toEqual({ signIn: "kept", windows: [{ name: "Month", used: 0, span: 2592000, resetsAt: "2026-10-01T00:00:00+00:00" }] }) expect(saved).toEqual([]) }) test("no current period: the billing period's Allowance; an unknown one has no span", async () => { let { u } = await run(auth, () => Response.json({ config: { creditUsagePercent: 7, billingPeriodEnd: "2026-10-05T00:00:00Z" } })) - expect(u).toEqual({ windows: [{ name: "Allowance", used: 7, resetsAt: "2026-10-05T00:00:00Z" }] }) + expect(u).toEqual({ signIn: "kept", windows: [{ name: "Allowance", used: 7, resetsAt: "2026-10-05T00:00:00Z" }] }) ;({ u } = await run(auth, () => Response.json({ config: { currentPeriod: { type: "USAGE_PERIOD_TYPE_HOURLY", end: "soon" } } }))) - expect(u).toEqual({ windows: [{ name: "Allowance", used: 0 }] }) + expect(u).toEqual({ signIn: "kept", windows: [{ name: "Allowance", used: 0 }] }) }) test("a refused token is the status magpie says; no sign-in says to sign in", async () => { - expect((await run(auth, () => new Response("", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [] }) + expect((await run(auth, () => new Response("", { status: 401 }))).u).toEqual({ signIn: "kept", error: "Unauthorized", windows: [] }) const { u, seen } = await run({ ...auth, refresh: join(home, "none") }, () => Response.json({})) - expect(u).toEqual({ error: "Grok is not signed in; run `grok login`", windows: [] }) + expect(u).toEqual({ signIn: "kept", error: "Grok is not signed in; run `grok login`", windows: [] }) expect(seen).toEqual([]) }) @@ -88,6 +89,7 @@ test("a fetch that fails is the card's error, worded for magpie's keepLast", asy for (const [e, said] of cases) { const { u } = await run(auth, fail(e)) expect(u.windows).toEqual([]) + expect(u.signIn).toBe("kept") expect(u.error.startsWith(`Get "${url}": `)).toBe(true) expect(u.error).toMatch(/no such host|connection refused|timeout|EOF|Service Unavailable/) expect(u.error).toContain(said) @@ -95,12 +97,12 @@ test("a fetch that fails is the card's error, worded for magpie's keepLast", asy }) test("a reply that isn't JSON is the card's error, as Go's encoding/json says it", async () => { - expect((await run(auth, () => new Response("oops"))).u).toEqual({ error: "invalid character '<' looking for beginning of value", windows: [] }) - expect((await run(auth, () => new Response(""))).u).toEqual({ error: "unexpected end of JSON input", windows: [] }) + expect((await run(auth, () => new Response("oops"))).u).toEqual({ signIn: "kept", error: "invalid character '<' looking for beginning of value", windows: [] }) + expect((await run(auth, () => new Response(""))).u).toEqual({ signIn: "kept", error: "unexpected end of JSON input", windows: [] }) }) test("a status Go has no words for still says something", async () => { - expect((await run(auth, () => new Response("", { status: 509 }))).u).toEqual({ error: "HTTP 509", windows: [] }) + expect((await run(auth, () => new Response("", { status: 509 }))).u).toEqual({ signIn: "kept", error: "HTTP 509", windows: [] }) }) test("a model list Grok couldn't give fails, not falls back to the configured few", async () => { diff --git a/packages/kiro/errors.test.mjs b/packages/kiro/errors.test.mjs index df57b29..4f74412 100644 --- a/packages/kiro/errors.test.mjs +++ b/packages/kiro/errors.test.mjs @@ -86,20 +86,20 @@ test("unstreamed, what was said before an exception is the answer", async () => }) // Failing before any of the answer, a request is answered with the built-in's -// status (internal/gateway/kiro.go askKiro), and X-Magpie-Sign-In says when -// that is no lapsed sign-in: only one Kiro refused marks the account. +// status (internal/gateway/kiro.go askKiro), and X-Magpie-Sign-In: kept, +// as the built-in marked no Kiro account lapsed, even one Kiro refused. const { generate, refresh, failure } = _internal const msgReq = { model: "claude-sonnet-4.5", messages: [{ role: "user", content: "hi" }] } const gone = (msg) => Object.assign(new Error(msg), { gone: true }) -test("credentials that can't be had are a 401; the account is kept unless the sign-in is gone", async () => { +test("credentials that can't be had are a 401, the account kept even when the sign-in is gone", async () => { let res = await generate(async () => { throw new Error("refreshing Kiro's sign-in: fetch failed") }, {}, msgReq) expect(res.status).toBe(401) expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") expect((await res.json()).error.message).toBe("refreshing Kiro's sign-in: fetch failed") res = await generate(async () => { throw gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE") }, {}, msgReq) expect(res.status).toBe(401) - expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") }) const withFetch = async (answer, fn) => { @@ -119,14 +119,14 @@ const creds = (fail) => { } } -test("a refresh failing after Kiro's 403 is a 502, marked only when Kiro refused it", async () => { +test("a refresh failing after Kiro's 403 is a 502, the account kept even when Kiro refused it", async () => { await withFetch(() => new Response("{}", { status: 403 }), async () => { let res = await generate(creds(new Error("refreshing Kiro's sign-in: 503 Service Unavailable")), {}, msgReq) expect(res.status).toBe(502) - expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") res = await generate(creds(gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE")), {}, msgReq) expect(res.status).toBe(502) - expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") }) }) @@ -154,3 +154,21 @@ test("a refresh is worded as the built-in's", async () => { await expect(refresh({ ...c, refresh: "" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" }) await expect(refresh({ ...c, method: "odd" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired" }) }) + +// a success, even after a renewal, never cleared the built-in's account +test("an answer says the account is kept, streamed or not, renewed or not", async () => { + const ok = () => new Response(stream(text("Hello")), { status: 200 }) + for (const s of [true, false]) { + await withFetch(ok, async () => { + const res = await generate(creds(), {}, { ...msgReq, stream: s }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + }) + let n = 0 + await withFetch(() => (n++ ? ok() : new Response("{}", { status: 403 })), async () => { + const res = await generate(creds(), {}, { ...msgReq, stream: s }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + }) + } +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 097355e..ea86f94 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -194,8 +194,8 @@ const EXPIRED = "Kiro's sign-in has expired; sign in again" const EXPIRED_CLI = EXPIRED + " with `kiro-cli login` or the Kiro IDE" // gone is an error saying the sign-in itself is gone — refused, or never -// there — which alone marks the account lapsed; a refresh that timed out -// or met a 5xx fails the request as the built-in did, the account kept. +// there. The built-in marked no Kiro account lapsed, not even then, nor +// cleared one: every answer and usage read says the account is kept. const gone = (msg) => Object.assign(new Error(msg), { gone: true }) const fresh = (c) => c.method === "apikey" || !c.expires || c.expires - Date.now() > 2 * 60 * 1000 @@ -726,14 +726,23 @@ function failure(status, body) { const ERROR_TYPES = { 400: "invalid_request_error", 401: "authentication_error", 402: "billing_error", 403: "permission_error", 404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded_error", 529: "overloaded_error" } const errorType = (status) => ERROR_TYPES[status] ?? "api_error" -// signIn, the X-Magpie-Sign-In header, says what the answer means for the -// account whatever its status: "expired" marks it lapsed, "kept" leaves it. -const errorResponse = (status, message, signIn) => +// Each failure says X-Magpie-Sign-In: kept, as the built-in never marked +// an account lapsed (see gone). +const errorResponse = (status, message) => new Response(JSON.stringify({ type: "error", error: { type: errorType(status), message } }), { status, - headers: { "Content-Type": "application/json", ...(signIn ? { "X-Magpie-Sign-In": signIn } : {}) }, + headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" }, }) +// kept is res saying the account is kept: a success too, which the +// built-in never took for a sign-in come back. +function kept(res) { + if (res.headers.has("X-Magpie-Sign-In")) return res + const headers = new Headers(res.headers) + headers.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + // ---- the reply: an AWS event stream → Messages --------------------------------------- // frames reads an AWS event stream: each message its length, its headers' @@ -1093,8 +1102,8 @@ async function reply(it, model, stream) { // generate answers a Messages request through Kiro's API: once more, // refreshed, when Kiro turns the token down (403). As the built-in: no -// credentials is a 401, a failed refresh after the 403 a 502; only a -// sign-in that is gone marks the account. +// credentials is a 401, a failed refresh after the 403 a 502; none marks +// the account. async function generate(creds, auth, req, signal) { const model = String(req.model ?? "auto") const budget = thinking(req, model) @@ -1102,7 +1111,7 @@ async function generate(creds, auth, req, signal) { try { a = await creds(auth) } catch (e) { - return errorResponse(401, e.message, e?.gone ? undefined : "kept") + return errorResponse(401, e.message) } let res try { @@ -1116,7 +1125,7 @@ async function generate(creds, auth, req, signal) { try { a = await creds(auth, true) } catch (e) { - return errorResponse(502, e.message, e?.gone ? "expired" : undefined) + return errorResponse(502, e.message) } try { res = await sendKiro(a, buildKiro(req, model, a.profile, budget), signal) @@ -1128,9 +1137,9 @@ async function generate(creds, auth, req, signal) { if (!res.ok) { // Kiro's own 401 is passed on, as the built-in did, the sign-in kept const f = failure(res.status, (await res.text()).slice(0, 1 << 20)) - return errorResponse(f.status, f.message, f.status === 401 ? "kept" : undefined) + return errorResponse(f.status, f.message) } - return reply(events(res.body, model, budget), model, req.stream === true) + return kept(await reply(events(res.body, model, budget), model, req.stream === true)) } // ---- signing in ---------------------------------------------------------------------- @@ -1337,14 +1346,15 @@ export async function KiroAuthPlugin({ client } = {}) { }, } }, - // the account's credits, as magpie's built-in showed them + // the account's credits, as magpie's built-in showed them; a read, + // clean or failed, marked the built-in's account nothing async usage(getAuth) { const auth = await getAuth() - if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in" } + if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in", signIn: "kept" } try { - return usageOf(await usageLimits(await creds(auth), true)) + return { ...usageOf(await usageLimits(await creds(auth), true)), signIn: "kept" } } catch (e) { - return { error: e.message } + return { error: e.message, signIn: "kept" } } }, methods: [ diff --git a/packages/kiro/usage.test.mjs b/packages/kiro/usage.test.mjs index 4b44cf7..8ec3ced 100644 --- a/packages/kiro/usage.test.mjs +++ b/packages/kiro/usage.test.mjs @@ -43,6 +43,7 @@ test("a free account's credits and trial", async () => { { name: "Free trial", used: 20, resetsAt: new Date(1791000000_000).toISOString(), display: "100 / 500" }, { name: "Credits", used: 25, resetsAt: new Date(1790000000_000).toISOString(), display: "12.5 / 50", span: 30 * 24 * 3600 }, ], + signIn: "kept", }) const u = new URL(calls[0].url) expect(u.pathname).toEndWith("/Get-Usage-Limits") @@ -68,14 +69,14 @@ test("names, resets and counts as Go says them", () => { test("Kiro's refusal is the card's error", async () => { answer(403, { message: "The bearer token included in the request is invalid." }) - expect(await usage()).toEqual({ error: "Kiro: The bearer token included in the request is invalid. (403)" }) + expect(await usage()).toEqual({ error: "Kiro: The bearer token included in the request is invalid. (403)", signIn: "kept" }) answer(500, "") - expect(await usage()).toEqual({ error: "Kiro: Internal Server Error" }) + expect(await usage()).toEqual({ error: "Kiro: Internal Server Error", signIn: "kept" }) }) test("no account, no usage", async () => { const calls = answer(200, FREE) - expect(await usage(null)).toEqual({ error: "not signed in" }) + expect(await usage(null)).toEqual({ error: "not signed in", signIn: "kept" }) expect(calls).toEqual([]) }) @@ -92,19 +93,27 @@ async function ask(a) { const stale = { ...auth, expires: Date.now() - 60_000 } // the built-in answered any credentials it couldn't get with a 401 and -// marked nothing; only a refresh Kiro refused marks the account here -test("a refresh that failed for a while is the built-in's 401, the account kept; one Kiro refused marks it", async () => { +// marked nothing, not even for a refresh Kiro refused +test("a refresh that failed, or that Kiro refused, is the built-in's 401, the account kept", async () => { answer(500, "") expect(await ask(stale)).toEqual({ status: 401, message: "refreshing Kiro's sign-in: 500 Internal Server Error", signIn: "kept" }) globalThis.fetch = async () => { throw new Error("getaddrinfo ENOTFOUND") } expect(await ask(stale)).toEqual({ status: 401, message: "refreshing Kiro's sign-in: getaddrinfo ENOTFOUND", signIn: "kept" }) answer(401, { error: "invalid_grant" }) const refused = "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" - expect(await ask(stale)).toEqual({ status: 401, message: refused }) - expect(await ask({ ...stale, refresh: "" })).toEqual({ status: 401, message: refused }) + expect(await ask(stale)).toEqual({ status: 401, message: refused, signIn: "kept" }) + expect(await ask({ ...stale, refresh: "" })).toEqual({ status: 401, message: refused, signIn: "kept" }) }) test("errors don't name Kiro, which magpie adds", async () => { answer(500, { message: "boom" }) - expect(await ask(auth)).toEqual({ status: 500, message: "boom" }) + expect(await ask(auth)).toEqual({ status: 500, message: "boom", signIn: "kept" }) +}) + +// The built-in's usage read neither marked nor cleared the account: a +// refusal that says to sign in again is kept too, not read by magpie's words. +test("a usage read that finds the sign-in refused keeps the account", async () => { + answer(401, { error: "invalid_grant" }) + expect(await usage({ ...auth, expires: Date.now() - 60_000 })).toEqual({ + error: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE", signIn: "kept" }) }) diff --git a/packages/mimo/index.mjs b/packages/mimo/index.mjs index 5586b2c..97ffaf8 100644 --- a/packages/mimo/index.mjs +++ b/packages/mimo/index.mjs @@ -378,16 +378,22 @@ export const MimoAuthPlugin = async ({ client }) => { } // page asks the MiMo server for one of the account's pages, signing on - // again once when it is turned away, and gives its data. - const page = async (getAuth, path) => { + // again once when it is turned away, and gives its data. read.signIn is + // what that did to the built-in's lapse mark: signed on again took it + // off, a sign-in Xiaomi no longer takes (mimoLapse) put it on. + const page = async (getAuth, path, read) => { for (let t = 0; ; t++) { let s try { s = await fresh(getAuth, t > 0) } catch (e) { - if (e instanceof Lapsed) throw new SignInGone(`${fromAuth(await getAuth())?.creds.userId}: the Xiaomi MiMo sign-in has expired — sign in again`) + if (e instanceof Lapsed) { + read.signIn = "expired" + throw new SignInGone(`${fromAuth(await getAuth())?.creds.userId}: the Xiaomi MiMo sign-in has expired — sign in again`) + } throw e } + if (s.renewed) read.signIn = "renewed" const res = await fetch(s.creds.base.replace(/\/+$/, "") + path, { headers: { Cookie: cookieHeader(s.cookies), ...appHeaders() }, signal: AbortSignal.timeout(20_000), @@ -401,6 +407,7 @@ export const MimoAuthPlugin = async ({ client }) => { if (res.status === 401 || (res.status === 200 && bad)) { // a session gone stale, or a redirect to Xiaomi's sign-in if (t === 0) continue + read.signIn = "expired" throw new SignInGone(`${s.creds.userId}: the Xiaomi MiMo sign-in has expired — sign in again`) } if (res.status !== 200 || bad) throw new Error(`Xiaomi MiMo ${path}: ${vendorError(text, statusLine(res.status))}`) @@ -409,13 +416,16 @@ export const MimoAuthPlugin = async ({ client }) => { } } - // usage is the plan and the week's allowance, magpie's own hook + // usage is the plan and the week's allowance, magpie's own hook; signIn + // is the lapse mark as the built-in's reads left it, a clean read with + // no signing on again leaving it be const usage = async (getAuth) => { + const read = { signIn: "kept" } let self try { - self = await page(getAuth, "/user/xiaomi/subscription/self") + self = await page(getAuth, "/user/xiaomi/subscription/self", read) } catch (e) { - return { error: e?.message ?? String(e) } + return { error: e?.message ?? String(e), signIn: read.signIn } } const c = self?.current const out = { plan: "Free" } @@ -429,12 +439,13 @@ export const MimoAuthPlugin = async ({ client }) => { } let use try { - use = await page(getAuth, "/user/usage") + use = await page(getAuth, "/user/usage", read) } catch (e) { if (e instanceof SignInGone) out.error = e.message // the plan alone, when the week's allowance can't be read - return out + return { ...out, signIn: read.signIn } } + out.signIn = read.signIn const percent = use?.percent const reset = use?.resetDate // no plan: the free offer shows no allowance @@ -500,9 +511,10 @@ export const MimoAuthPlugin = async ({ client }) => { headers.set("User-Agent", UA) headers.set("X-Client-Version", APP_VERSION) // the server's answer goes through as it is, a 401 too, as the - // built-in's did: it took the lapse off only when it signed on again + // built-in's did: it took the lapse off only when it signed on + // again, whatever the server then answered const res = await fetch(url, { ...init, method: init.method ?? req?.method ?? "POST", headers, body }) - return s.renewed && res.status >= 200 && res.status < 300 ? res : said(res, "kept") + return said(res, s.renewed ? "renewed" : "kept") }, } }, diff --git a/packages/mimo/usage.test.mjs b/packages/mimo/usage.test.mjs index bc2b6ab..0a55fb9 100644 --- a/packages/mimo/usage.test.mjs +++ b/packages/mimo/usage.test.mjs @@ -44,13 +44,14 @@ test("the plan, its end and renewal, and the week's allowance", async () => { until: "2026-10-31T16:00:00.000Z", // 2026-11-01 00:00 in UTC+8 renew: "auto", windows: [{ name: "7 days", used: 30, span: 604800, resetsAt: "2026-10-04T16:00:00.000Z" }], + signIn: "kept", }) expect(p.seen).toEqual(["/api/user/xiaomi/subscription/self", "/api/user/usage"]) }) test("no plan is the free offer, with no allowance shown", async () => { const p = await plugin(account(), (path) => (path === "/api/user/usage" ? json({ code: 0, data: { percent: 100, resetDate: null } }) : json({ code: 0, data: { current: null } }))) - expect(await p.usage()).toEqual({ plan: "Free" }) + expect(await p.usage()).toEqual({ plan: "Free", signIn: "kept" }) }) test("a plan named by its tier, else its code; a one-time plan doesn't renew", async () => { @@ -58,14 +59,14 @@ test("a plan named by its tier, else its code; a one-time plan doesn't renew", a const p = await plugin(account(), (path) => (path === "/api/user/usage" ? json({ code: 0, data: {} }) : json({ code: 0, data: { current } }))) return p.usage() } - expect(await sub({ title: " ", planTier: 4, renewalMode: "ONE_TIME", endTime: "2026-11-01 08:30:00" })()).toEqual({ plan: "Ultra", until: "2026-11-01T00:30:00.000Z", renew: "off" }) - expect(await sub({ planTier: 9, planCode: "mimo_x" })()).toEqual({ plan: "mimo_x" }) - expect(await sub({})()).toEqual({ plan: "MiMo" }) + expect(await sub({ title: " ", planTier: 4, renewalMode: "ONE_TIME", endTime: "2026-11-01 08:30:00" })()).toEqual({ plan: "Ultra", until: "2026-11-01T00:30:00.000Z", renew: "off", signIn: "kept" }) + expect(await sub({ planTier: 9, planCode: "mimo_x" })()).toEqual({ plan: "mimo_x", signIn: "kept" }) + expect(await sub({})()).toEqual({ plan: "MiMo", signIn: "kept" }) }) test("the allowance unread leaves the plan alone; a refused sign-in says so", async () => { let p = await plugin(account(), (path) => (path === "/api/user/usage" ? json({ code: 500, msg: "busy" }) : json(SELF))) - expect(await p.usage()).toEqual({ plan: "MiMo 高阶", until: "2026-10-31T16:00:00.000Z", renew: "auto" }) + expect(await p.usage()).toEqual({ plan: "MiMo 高阶", until: "2026-10-31T16:00:00.000Z", renew: "auto", signIn: "kept" }) // the session turned away, and the passToken no longer signs it on p = await plugin(account(), (path) => { @@ -73,7 +74,7 @@ test("the allowance unread leaves the plan alone; a refused sign-in says so", as if (path === "/api/user/xiaomi/me") return new Response("sign in", { status: 200 }) return new Response("", { status: 404 }) }) - expect(await p.usage()).toEqual({ error: "42: the Xiaomi MiMo sign-in has expired — sign in again" }) + expect(await p.usage()).toEqual({ error: "42: the Xiaomi MiMo sign-in has expired — sign in again", signIn: "expired" }) }) test("two accounts signing on at once each keep their own session", async () => { @@ -106,9 +107,9 @@ test("two accounts signing on at once each keep their own session", async () => test("a failure is the page's and the server's word", async () => { let p = await plugin(account(), () => json({ code: 10001, msg: "no such user" })) - expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: code 10001 no such user" }) + expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: code 10001 no such user", signIn: "kept" }) p = await plugin(account(), () => json({ message: "down" }, 503)) - expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: down" }) + expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: down", signIn: "kept" }) }) test("the server's times", () => { @@ -175,7 +176,16 @@ test("a success takes the mark off only when the account was signed on again", a ) res = await p.fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" }) expect(res.status).toBe(200) - expect(res.headers.get("X-Magpie-Sign-In")).toBe(null) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") +}) + +test("a failure after signing on again still takes the mark off, as mimoFresh did before the request", async () => { + const p = await loaderFetch(account(0), (path) => + path === "/api/user/xiaomi/me" ? new Response(JSON.stringify({ code: 0, data: { userId: "42" } }), { headers: { "set-cookie": "serviceToken=st-2; Path=/" } }) : json({ error: { message: "stale" } }, 401), + ) + const res = await p.fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" }) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") }) test("a sign-on that can't reach the server is a thrown fetch (magpie's 502) in the built-in's words, the account unmarked", async () => { @@ -185,3 +195,31 @@ test("a sign-on that can't reach the server is a thrown fetch (magpie's 502) in }) await expect(fetch(BASE + "/route/chat/completions", { method: "POST", body: "{}" })).rejects.toThrow(/^Xiaomi MiMo sign-in: connection refused$/) }) + +// the built-in's mimoFresh took the lapse mark off when it signed the +// account on again, and mimoLapse put it on; whichever came last stands +const signOn = () => new Response(JSON.stringify({ code: 0, data: { userId: "42" } }), { headers: { "set-cookie": "serviceToken=st-2; Path=/" } }) + +test("a read that signed the account on again says so, whatever the pages then answer", async () => { + let p = await plugin(account(0), (path) => (path === "/api/user/xiaomi/me" ? signOn() : path === "/api/user/usage" ? json(USAGE) : json(SELF))) + expect((await p.usage()).signIn).toBe("renewed") + p = await plugin(account(0), (path) => (path === "/api/user/xiaomi/me" ? signOn() : json({ message: "down" }, 503))) + expect(await p.usage()).toEqual({ error: "Xiaomi MiMo /user/xiaomi/subscription/self: down", signIn: "renewed" }) + // a stale session turned away, signed on again, then the allowance unread + let n = 0 + p = await plugin(account(), (path) => { + if (path === "/api/user/xiaomi/me") return signOn() + if (path === "/api/user/xiaomi/subscription/self") return n++ ? json(SELF) : new Response("", { status: 401 }) + return json({ code: 500, msg: "busy" }) + }) + expect(await p.usage()).toEqual({ plan: "MiMo 高阶", until: "2026-10-31T16:00:00.000Z", renew: "auto", signIn: "renewed" }) +}) + +test("the allowance's page refused after the plan's read marks the account", async () => { + const p = await plugin(account(), (path) => { + if (path === "/api/user/xiaomi/me") return new Response("sign in", { status: 200 }) + if (path === "/api/user/usage") return new Response("", { status: 401 }) + return json(SELF) + }) + expect(await p.usage()).toEqual({ plan: "MiMo 高阶", until: "2026-10-31T16:00:00.000Z", renew: "auto", error: "42: the Xiaomi MiMo sign-in has expired — sign in again", signIn: "expired" }) +}) diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 7321c67..d7d1163 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -759,6 +759,17 @@ async function bodyText(input, init) { return typeof b === "string" ? b : new TextDecoder().decode(b) } +// signed is res saying what it means for the sign-in, as the built-in's +// answer did: a renewed job token cleared the mark whatever came of the +// request; without one, a success left the mark as it was. +function signed(res, renewed) { + const said = renewed ? "renewed" : res.ok ? "kept" : null + if (!said) return res + const headers = new Headers(res.headers) + headers.set("X-Magpie-Sign-In", said) + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + // ---- usage -------------------------------------------------------------------- // // The account's allowance as magpie's built-in Qoder account shows it @@ -880,6 +891,9 @@ export async function QoderAuthPlugin({ client }) { } // each account's listing, the model configs a request carries const listings = new Map() + // the accounts fresh renewed: the built-in took the lapse mark off on a + // renewed job token (qoderPersist), whatever the request then met + const renewals = new WeakSet() // fresh is the account with a live job token, refreshed and saved near // its end. @@ -891,6 +905,7 @@ export async function QoderAuthPlugin({ client }) { const jt = await refreshJob(a.refresh, a.accountId || a.email || a.uid) const next = { ...a, access: jt.token, refresh: jt.refresh_token, expires: expiresAt(jt) } await client.auth.set({ path: { id: ID }, body: next }) + renewals.add(next) return next }) @@ -914,10 +929,15 @@ export async function QoderAuthPlugin({ client }) { return dt.token }) - // usage is the account's allowance, magpie's own hook + // usage is the account's allowance, magpie's own hook. signIn is what the read means for the sign-in, as the built-in's did: + // a refused job refresh marks it, a renewed one clears it, and nothing + // else does — not a clean read, nor a refused device token, which serves + // only the account pages const usage = async (getAuth) => { + let signIn = "kept" try { const cred = await fresh(getAuth) + if (renewals.has(cred)) signIn = "renewed" let env try { env = await fetchUsage(cred.deviceToken) @@ -925,9 +945,9 @@ export async function QoderAuthPlugin({ client }) { if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e env = await fetchUsage(await deviceToken(getAuth, cred.deviceToken)) } - return parseUsage(env) + return { ...parseUsage(env), signIn } } catch (e) { - return { error: e?.message ?? String(e) } + return { error: e?.message ?? String(e), signIn: e?.expired ? "expired" : signIn } } } @@ -938,6 +958,35 @@ export async function QoderAuthPlugin({ client }) { signIn: e?.expired ? "expired" : undefined, }) + // ask is the answer to a chat completion on the live account cred. + const ask = async (chat, cred, init) => { + let m + try { + m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model) + } catch (e) { + // the built-in answered any failure to read the list 400 + // (QoderModelOf), a refused one included, marking nothing + return errorResponse({ status: 400, message: e.message }) + } + if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` }) + const wire = encodeBody(JSON.stringify(qoderBody(chat, m))) + const headers = { + ...cosyHeaders(CHAT_URL, cred, wire), + Accept: "text/event-stream", + "Cache-Control": "no-cache", + "X-Model-Key": m.key, + "X-Model-Source": m.source, + } + let res + try { + res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal }) + } catch (e) { + return errorResponse({ status: 502, message: e.message }) + } + if (!res.ok) return errorResponse(failure(res.status, (await res.text()).slice(0, 1 << 20))) + return answer(res, chat) + } + return { auth: { provider: ID, @@ -964,31 +1013,7 @@ export async function QoderAuthPlugin({ client }) { } catch (e) { return signedInError(e) } - let m - try { - m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model) - } catch (e) { - // the built-in answered any failure to read the list 400 - // (QoderModelOf), a refused one included, marking nothing - return errorResponse({ status: 400, message: e.message }) - } - if (!m) return errorResponse({ status: 400, message: `unknown or disabled model "${chat.model}"` }) - const wire = encodeBody(JSON.stringify(qoderBody(chat, m))) - const headers = { - ...cosyHeaders(CHAT_URL, cred, wire), - Accept: "text/event-stream", - "Cache-Control": "no-cache", - "X-Model-Key": m.key, - "X-Model-Source": m.source, - } - let res - try { - res = await fetch(CHAT_URL, { method: "POST", headers, body: wire, signal: init.signal }) - } catch (e) { - return errorResponse({ status: 502, message: e.message }) - } - if (!res.ok) return errorResponse(failure(res.status, (await res.text()).slice(0, 1 << 20))) - return answer(res, chat) + return signed(await ask(chat, cred, init), renewals.has(cred)) }, } }, diff --git a/packages/qoder/usage.test.mjs b/packages/qoder/usage.test.mjs index 261c62b..ee88bcc 100644 --- a/packages/qoder/usage.test.mjs +++ b/packages/qoder/usage.test.mjs @@ -65,6 +65,7 @@ test("a refused device token is rotated, saved, and the usage read with it", asy { name: "Shared credits", used: 50, display: "10 / 20 credits" }, { name: "Team", used: 20, display: "2 / 10 credits" }, ], + signIn: "kept", }) expect(p.seen).toEqual(["/sash/api/v2/me/usage", "/api/v1/deviceToken/refresh", "/sash/api/v2/me/usage"]) expect(p.auth()).toMatchObject({ deviceToken: "dt-new", deviceRefresh: "drt-new", access: "jt-one", refresh: "rt-one" }) @@ -75,25 +76,26 @@ test("a refused device refresh says usage is unavailable, chat still working", a expect(await p.usage()).toEqual({ error: "Qoder usage is unavailable: Qoder refused the account-page sign-in (chat still works) — sign in again to see usage (qoder device token refresh: upstream HTTP 403)", + signIn: "kept", }) expect(p.auth().deviceToken).toBe("dt-old") }) test("another failure is Qoder's status", async () => { const p = await plugin(() => new Response("", { status: 500 })) - expect(await p.usage()).toEqual({ error: "qoder usage: upstream HTTP 500" }) + expect(await p.usage()).toEqual({ error: "qoder usage: upstream HTTP 500", signIn: "kept" }) }) test("an enterprise account has a plan and no windows", async () => { const p = await plugin(() => json({ displayMode: "enterprise" })) - expect(await p.usage()).toEqual({ plan: "Enterprise" }) + expect(await p.usage()).toEqual({ plan: "Enterprise", signIn: "kept" }) }) test("an unknown display mode, or no quota, is an error", async () => { let p = await plugin(() => json({ displayMode: "team" })) - expect(await p.usage()).toEqual({ error: "qoder usage: unknown display mode" }) + expect(await p.usage()).toEqual({ error: "qoder usage: unknown display mode", signIn: "kept" }) p = await plugin(() => json({ displayMode: "qoder", qoderUsage: null })) - expect(await p.usage()).toEqual({ error: "qoder usage: missing quota data" }) + expect(await p.usage()).toEqual({ error: "qoder usage: missing quota data", signIn: "kept" }) }) test("snake_case fields, an expiry, units, and pools too thin to show", () => { @@ -230,3 +232,61 @@ test("a model Qoder lists free (is_free, or a price_factor of 0) is marked free" expect(Object.fromEntries(Object.entries(ms).map(([k, m]) => [k, m.free]))).toEqual({ qmodel: false, fmodel: true, pmodel: true, cmodel: false }) expect(_internal.modelInfo({ key: "x", isFree: true }).free).toBe(true) }) + +// a usage read on an account whose job token is due, the refresh answered by refresh() +async function dueUsage(refresh, read) { + let auth = { ...account(), expires: 0 } + globalThis.fetch = async (url) => { + const path = new URL(String(url)).pathname + if (path === "/api/v1/jobToken/refresh") return refresh() + if (path === "/sash/api/v2/me/usage") return read() + return new Response("", { status: 404 }) + } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (auth = body) } } }) + return hooks.auth.usage(async () => auth) +} + +const RENEWED = () => json({ token: "jt-new", refresh_token: "rt-new", expire_time: Date.now() + 3_600_000 }) + +test("a usage read marks the sign-in only on a refused job refresh and clears it only on a renewed one, as the built-in's", async () => { + // a clean read cleared nothing in the built-in + expect((await dueUsage(RENEWED, () => json(USAGE))).signIn).toBe("renewed") + expect((await (await plugin(() => json(USAGE))).usage()).signIn).toBe("kept") + // renewed, the mark came off whatever the read then met + expect(await dueUsage(RENEWED, () => new Response("", { status: 500 }))).toEqual({ error: "qoder usage: upstream HTTP 500", signIn: "renewed" }) + for (const status of [401, 403]) { + const u = await dueUsage(() => new Response("", { status }), () => json(USAGE)) + expect(u).toEqual({ error: `one@x's Qoder sign-in has expired — sign in again (qoder job token refresh: status ${status})`, signIn: "expired" }) + } + expect((await dueUsage(() => new Response("", { status: 500 }), () => json(USAGE))).signIn).toBe("kept") +}) + +// a chat on an account whose job token is due, renewed, Qoder answering reply() +async function renewedChat(reply) { + const auth = { ...account(), machineId: "m1", expires: 0 } + globalThis.fetch = async (url) => { + const path = new URL(String(url)).pathname + if (path === "/api/v1/jobToken/refresh") return RENEWED() + if (path.endsWith("/model/list")) return json(LISTING) + return reply() + } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) + const l = await hooks.auth.loader(async () => auth) + return l.fetch(API_CHAT, ASK) +} + +const OK = () => + new Response(`data: ${JSON.stringify({ statusCodeValue: 200, body: JSON.stringify({ choices: [{ delta: { content: "hi" }, finish_reason: "stop" }] }) })}\n\n`, { + headers: { "Content-Type": "text/event-stream" }, + }) + +test("an answer that went through keeps the mark, as the built-in's did; after a renewed job token, every answer clears it", async () => { + const { fetch } = await chat(LISTING, OK) + let res = await fetch(API_CHAT, ASK) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([200, "kept"]) + expect((await res.json()).choices[0].message.content).toBe("hi") + for (const [reply, status] of [[OK, 200], [() => new Response("", { status: 500 }), 500], [() => new Response("", { status: 401 }), 401]]) { + res = await renewedChat(reply) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([status, "renewed"]) + } +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 6f35b3f..16e6154 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -575,20 +575,22 @@ function makePlugin(site) { let body = init?.body if (body === undefined && req) body = await req.clone().text() const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) }) - return res.status >= 400 ? explained(res) : res + return res.status >= 400 ? explained(res) : kept(res) }, } }, - // the account's credits, as magpie's built-in showed them + // the account's credits, as magpie's built-in showed them; each + // read keeps the sign-in (signIn), as the built-in's neither marked + // an account lapsed nor cleared it async usage(getAuth) { const auth = await getAuth() - if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in" } + if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in", signIn: "kept" } try { const a = await current(site, client, auth) // the meter has no /v2 prefix, on either site - return usageOf(await meter(site, a, "/billing/meter/get-user-resource-summary"), auth.plan) + return { ...usageOf(await meter(site, a, "/billing/meter/get-user-resource-summary"), auth.plan), signIn: "kept" } } catch (e) { - return { error: e?.message ?? String(e) } + return { error: e?.message ?? String(e), signIn: "kept" } } }, methods: [ @@ -616,6 +618,14 @@ const REFUSED_HINT = "WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group" const REFUSED = /unapproved channel|illegal api invocation/i +// kept is an answer that went through, saying the sign-in is kept: the +// built-in never cleared a WorkBuddy account's mark, as it never set one. +function kept(res) { + const headers = new Headers(res.headers) + headers.set("X-Magpie-Sign-In", "kept") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) +} + // explained is res with REFUSED_HINT added to that refusal's message. // Each refusal says the sign-in is kept: the built-in passed WorkBuddy's // 401 on and never marked a WorkBuddy account lapsed. diff --git a/packages/workbuddy/signin.test.mjs b/packages/workbuddy/signin.test.mjs index 6b083e9..9707459 100644 --- a/packages/workbuddy/signin.test.mjs +++ b/packages/workbuddy/signin.test.mjs @@ -30,10 +30,12 @@ test("the channel refusal keeps the account too", async () => { expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") }) -test("a reply that went through says nothing of the sign-in", async () => { +// nor cleared one: a reply that went through leaves the mark as it is +test("a reply that went through keeps the sign-in too", async () => { const res = await ask(() => new Response("data: [DONE]\n\n", { status: 200 })) expect(res.status).toBe(200) - expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.text()).toBe("data: [DONE]\n\n") }) // wbFresh with no access token left: its words, on either site diff --git a/packages/workbuddy/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 53088cc..f97473b 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -45,7 +45,7 @@ const usageOf = async (plugin, auth, client = {}) => (await plugin({ client })). test("a paid WorkBuddy account's credits", async () => { const calls = serve({ "/billing/meter/get-user-resource-summary": () => ok(PAID) }) const auth = { type: "oauth", access: "two-access", refresh: "r", expires: later(), uid: "u2", domain: "" } - expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] }) const c = calls[0] expect(c.url.origin).toBe("https://copilot.tencent.com") expect(c.init.method).toBe("POST") @@ -59,7 +59,7 @@ test("a free WorkBuddy AI account, at its own site and domain", async () => { const calls = serve({ "/billing/meter/get-user-resource-summary": () => ok({ IsPaidUser: false, Packages: [{ CycleTotalCapacity: "1000", CycleUsedCapacity: "100" }] }) }) const auth = { type: "oauth", access: "ai-access", expires: later(), uid: "ai2", domain: "www.codebuddy.ai" } - expect(await usageOf(WorkBuddyAIAuthPlugin, auth)).toEqual({ plan: "Free", windows: [{ name: "Credits", used: 10, display: "100 / 1000" }] }) + expect(await usageOf(WorkBuddyAIAuthPlugin, auth)).toEqual({ signIn: "kept", plan: "Free", windows: [{ name: "Credits", used: 10, display: "100 / 1000" }] }) expect(calls[0].url.origin).toBe("https://www.workbuddy.ai") expect(calls[0].headers.get("x-domain")).toBe("www.codebuddy.ai") }) @@ -76,12 +76,12 @@ test("counts and plans as Go says them", () => { test("WorkBuddy's refusals are the card's error", async () => { const auth = { type: "oauth", access: "a", expires: later(), uid: "u" } serve({ "/billing/meter/get-user-resource-summary": () => new Response("", { status: 401 }) }) - expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "Unauthorized" }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "Unauthorized" }) serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 10085, msg: "" }), { status: 403 }) }) - expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "error 10085" }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "error 10085" }) serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 11001, msg: "token expired" })) }) - expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "token expired" }) - expect(await usageOf(WorkBuddyAuthPlugin, null)).toEqual({ error: "not signed in" }) + expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ signIn: "kept", error: "token expired" }) + expect(await usageOf(WorkBuddyAuthPlugin, null)).toEqual({ signIn: "kept", error: "not signed in" }) }) // Go's http.StatusText has words for every status WorkBuddy may give, and @@ -90,7 +90,7 @@ test("any refused status is an error with words", async () => { const auth = { type: "oauth", access: "a", expires: later(), uid: "u" } for (const [status, said] of [[409, "Conflict"], [402, "Payment Required"], [422, "Unprocessable Entity"], [501, "Not Implemented"], [520, "HTTP 520"], [302, "Found"]]) { serve({ "/billing/meter/get-user-resource-summary": () => new Response("", { status }) }) - expect([status, await usageOf(WorkBuddyAuthPlugin, auth)]).toEqual([status, { error: said }]) + expect([status, await usageOf(WorkBuddyAuthPlugin, auth)]).toEqual([status, { error: said, signIn: "kept" }]) } }) @@ -103,6 +103,8 @@ test("a token near its end is renewed and saved, as the loader does", async () = const auth = { type: "oauth", access: "old-access", refresh: "old-refresh", expires: Date.now() + 1000, uid: "u2" } const out = await usageOf(WorkBuddyAuthPlugin, auth, { auth: { set: async (x) => sets.push(x) } }) expect(out.windows[0].used).toBe(25) + // the built-in's renewal took no mark off: the read keeps the sign-in + expect(out.signIn).toBe("kept") expect(calls[0].headers.get("x-refresh-token")).toBe("old-refresh") expect(calls[1].headers.get("authorization")).toBe("Bearer new-access") expect(sets.length).toBe(1) @@ -125,7 +127,7 @@ test("the desktop's sign-in is renewed in memory only", async () => { }) const auth = { type: "oauth", access: "", refresh: "", expires: 0, source: "desktop", uid: "u1" } const client = { auth: { set: async (x) => sets.push(x) } } - expect(await usageOf(WorkBuddyAuthPlugin, auth, client)).toEqual({ plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] }) + expect(await usageOf(WorkBuddyAuthPlugin, auth, client)).toEqual({ signIn: "kept", plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] }) expect(calls[1].headers.get("authorization")).toBe("Bearer desk-new") expect(calls[1].headers.get("x-domain")).toBe("www.codebuddy.cn") expect(sets).toEqual([]) // never saved, diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 40b282c..fa6e383 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -1096,9 +1096,8 @@ export async function ZCodeAuthPlugin({ client }) { h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) const res = await fetch(url, { ...opts, headers: h }) - // the plan's 401 goes on as it came: the built-in never - // marked a ZCode account lapsed - if (res.status !== 401) return res + // the plan's answer goes on as it came, the account kept: the + // built-in never marked a ZCode account lapsed nor cleared one const kept = new Headers(res.headers) kept.delete("content-length") kept.delete("content-encoding") @@ -1107,17 +1106,20 @@ export async function ZCodeAuthPlugin({ client }) { }, } }, - // the plan's allowance, as magpie's built-in showed it + // the plan's allowance, as magpie's built-in showed it. Each read + // keeps the sign-in (signIn): the built-in's marked no account lapsed, + // its expired Start Plan sign-in among them, and cleared none async usage(getAuth, provider) { const auth = await getAuth() const s = stateOf(auth) - if (!s) return { error: "not signed in" } + if (!s) return { error: "not signed in", signIn: "kept" } // every card starts from the plan the sign-in saved, as magpie's // built-in did: a reply without a level, a team detail that // failed or an error keeps it const saved = (out) => { const plan = s.plan || auth?.plan if (plan && !out.plan) out.plan = plan + out.signIn = "kept" return out } try { diff --git a/packages/zcode/signin.test.mjs b/packages/zcode/signin.test.mjs index 65760ab..d7bb811 100644 --- a/packages/zcode/signin.test.mjs +++ b/packages/zcode/signin.test.mjs @@ -33,11 +33,13 @@ test("the plan's 401 goes on as it came, the account kept", async () => { expect(await res.json()).toEqual({ error: { message: "token expired or incorrect" } }) }) -test("other answers go as they came", async () => { +// nor cleared one: an answer that went through leaves the mark as it is +test("other answers go as they came, the account kept", async () => { for (const status of [200, 429]) { const res = await send(key, () => new Response("x", { status })) expect(res.status).toBe(status) - expect(res.headers.get("X-Magpie-Sign-In")).toBeNull() + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.text()).toBe("x") } }) diff --git a/packages/zcode/usage.test.mjs b/packages/zcode/usage.test.mjs index 27bac02..402dce4 100644 --- a/packages/zcode/usage.test.mjs +++ b/packages/zcode/usage.test.mjs @@ -50,6 +50,7 @@ test("a Coding Plan's five hours and week", async () => { ] }) }) expect(await usage(oauth({ site: "zai", key: "two.secret2" }))).toEqual({ + signIn: "kept", plan: "GLM Coding Pro", windows: [ { name: "5 hours", used: 25, display: "500 / 2000", resetsAt: new Date(reset).toISOString(), span: 5 * 3600 }, @@ -59,7 +60,7 @@ test("a Coding Plan's five hours and week", async () => { expect(calls.every((c) => c.url.origin === "https://api.z.ai")).toBe(true) // an API key, BigModel's, is asked on its own site const bm = serve(({ url }) => (url.pathname.endsWith("/limit") ? ok({ limits: [] }) : ok([]))) - expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ windows: [] }) + expect(await usage({ type: "api", key: "k", metadata: { site: "bigmodel" } })).toEqual({ signIn: "kept", windows: [] }) expect(bm[0].url.origin).toBe("https://open.bigmodel.cn") }) @@ -110,6 +111,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => { }) const auth = oauth({ site: "bigmodel", jwt: token, device: "11111111-2222-4333-8444-555555555555" }) expect(await usage(auth)).toEqual({ + signIn: "kept", plan: "Start Plan", until: new Date((now + 7 * 86400) * 1000).toISOString(), renew: "off", windows: [{ name: "GLM-5.1", used: 25, display: "250000 / 1000000", resetsAt: new Date((now + 3600) * 1000).toISOString(), span: 86400, models: ["GLM-5.1"] }], @@ -117,7 +119,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => { expect(calls[0].url.origin).toBe("https://zcode.z.ai") expect(calls[0].headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555") - const over = { error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" } + const over = { signIn: "kept", error: "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started" } balance = startBalance(now, "expired") expect(await usage(auth)).toEqual(over) // still "active" past its end is over too, as ZCode reads it @@ -130,7 +132,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => { expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", span: 7 * 86400, models: ["GLM-5-Turbo"] }]) // its token run out - expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" }) + expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ signIn: "kept", error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" }) }) test("a team seat: the team plan's windows, name, end and resets, its key found and saved", async () => { @@ -167,6 +169,7 @@ test("a team seat: the team plan's windows, name, end and resets, its key found const sets = [] const state = { site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", token: TOKEN, org: "t1", project: "tp1", plan: "GLM Coding Team Pro" } expect(await usage(oauth(state), sets)).toEqual({ + signIn: "kept", plan: "GLM Coding Team Pro", until: "2026-12-31T15:59:59.000Z", renew: "off", resets: { count: 3, byWindow: true, fiveHour: 2, weekly: 1, until: new Date(1790000000 * 1000).toISOString() }, windows: [ @@ -183,12 +186,12 @@ test("a team seat: the team plan's windows, name, end and resets, its key found test("Z.ai's refusals are the card's error", async () => { serve(() => new Response("", { status: 401 })) - expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "Unauthorized" }) + expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "Unauthorized" }) serve(() => new Response(JSON.stringify({ code: 1001, msg: "Authorization Token非法" }), { status: 401 })) - expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "Authorization Token非法 (401, code 1001)" }) + expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "Authorization Token非法 (401, code 1001)" }) serve(() => new Response(JSON.stringify({ code: 500, msg: "" }))) - expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ error: "error 500" }) - expect(await usage(undefined)).toEqual({ error: "not signed in" }) + expect(await usage(oauth({ site: "zai", key: "k" }))).toEqual({ signIn: "kept", error: "error 500" }) + expect(await usage(undefined)).toEqual({ signIn: "kept", error: "not signed in" }) }) // magpie's built-in starts every card from the saved plan (zcode.go @@ -210,7 +213,7 @@ test("the saved plan stays on the card when the reply has no level, a team detai expect((await usage(oauth(team))).plan).toBe("GLM Coding Team Pro") serve(() => new Response("", { status: 401 })) - expect(await usage(oauth({ site: "zai", key: "k", plan: "GLM Coding Max" }))).toEqual({ plan: "GLM Coding Max", error: "Unauthorized" }) + expect(await usage(oauth({ site: "zai", key: "k", plan: "GLM Coding Max" }))).toEqual({ signIn: "kept", plan: "GLM Coding Max", error: "Unauthorized" }) }) // the built-in left a limit ZCode's config doesn't name at 0 diff --git a/packages/zed/errors.test.mjs b/packages/zed/errors.test.mjs index 3c9f195..bd7f986 100644 --- a/packages/zed/errors.test.mjs +++ b/packages/zed/errors.test.mjs @@ -91,3 +91,12 @@ test("a whole reply carrying the provider's error is that error, and an out-of-r const odd = await ask("anthropic", [start, { status: { failed: { code: "http_999", message: "odd" } } }], false) expect([odd.status, msgOf(odd.text)]).toEqual([502, "odd"]) }) + +test("an answer that goes through keeps the mark, as the built-in took it off only on signing in again", async () => { + const delta = { event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } } } + const lines = [{ status: "started" }, start, textStart, delta, { event: { type: "message_stop" } }, { status: "stream_ended" }] + const streamed = await ask("anthropic", lines) + expect([streamed.status, streamed.signIn]).toEqual([200, "kept"]) + const whole = await ask("anthropic", lines, false) + expect([whole.status, whole.signIn]).toEqual([200, "kept"]) +}) diff --git a/packages/zed/index.mjs b/packages/zed/index.mjs index 71ebe94..481ff72 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -572,6 +572,10 @@ const errorResponse = (wire, status, message, signIn = status === 401 ? "kept" : headers: { "content-type": "application/json", ...(signIn ? { "x-magpie-sign-in": signIn } : {}) }, }) +// KEPT is on an answer that went through: the built-in took the mark off +// only when the account was signed in again, never on a request. +const KEPT = { "x-magpie-sign-in": "kept" } + // said tells whether one of the provider's own events says anything — // text, reasoning, a call, a finish — rather than only framing the reply, // as magpie's decoders tell a reply begun from its lead (message_start, @@ -718,7 +722,7 @@ async function streamed(wire, res) { res.body?.cancel?.().catch(() => {}) }, }) - return new Response(body, { status: 200, headers: { "content-type": "text/event-stream", "cache-control": "no-cache" } }) + return new Response(body, { status: 200, headers: { "content-type": "text/event-stream", "cache-control": "no-cache", ...KEPT } }) } // ---- whole replies, for a caller that didn't ask for a stream ------------------ @@ -838,7 +842,7 @@ async function whole(wire, res) { if (wrapped && !ended) return errorResponse(wire, 502, "the reply ended before it was complete") const out = WHOLE[wire](events) if (!out) return errorResponse(wire, 502, "the reply ended before it was complete") - return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json" } }) + return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json", ...KEPT } }) } // complete sends one request through Zed's /completions. @@ -906,19 +910,21 @@ const RFC3339 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/i async function usage(auth, save) { const s = stateOf(auth) - if (!s) return { error: "no such Zed account" } + // the built-in's read marked the account only when Zed refused its + // sign-in, and took the mark off never: a clean read keeps it + if (!s) return { error: "no such Zed account", signIn: "kept" } let me try { const text = await cloud("GET", "/client/users/me", s, undefined, 15_000) me = parse(text) if (me === null) me = {} - else if (typeof me !== "object" || Array.isArray(me)) return { error: "Zed: an unreadable account: " + jsonError(text, me) } + else if (typeof me !== "object" || Array.isArray(me)) return { error: "Zed: an unreadable account: " + jsonError(text, me), signIn: "kept" } } catch (e) { - if (e?.status === 401) return { error: `${s.who}: the Zed sign-in has expired — sign in again` } - return { error: e?.message ?? String(e) } + if (e?.status === 401) return { error: `${s.who}: the Zed sign-in has expired — sign in again`, signIn: "expired" } + return { error: e?.message ?? String(e), signIn: "kept" } } const plan = planOf(me, s.org || orgOf(me)) - const out = { plan: planName(plan) } + const out = { plan: planName(plan), signIn: "kept" } if (plan !== s.plan && save) { const r = parse(auth.refresh ?? "") ?? {} await save({ ...auth, refresh: JSON.stringify({ ...r, plan, planName: out.plan }) }).catch(() => {}) diff --git a/packages/zed/usage.test.mjs b/packages/zed/usage.test.mjs index 3b3ab3d..8a2aed5 100644 --- a/packages/zed/usage.test.mjs +++ b/packages/zed/usage.test.mjs @@ -38,31 +38,31 @@ async function run(a, reply) { test("a Pro account: its plan and its period's end, no windows", async () => { const { u, seen, saved } = await run(auth(), () => new Response(me("zed_pro"))) - expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z" }) + expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z", signIn: "kept" }) expect(seen).toEqual([{ url: "https://cloud.zed.dev/client/users/me", auth: "4242 plain-access" }]) expect(saved).toEqual([]) }) test("a free account reads Free, as the built-in's row names it, and the plan it moved to is kept", async () => { const { u, saved } = await run(auth(), () => new Response(me("zed_free"))) - expect(u).toEqual({ plan: "Free", until: "2026-10-01T00:00:00Z" }) + expect(u).toEqual({ plan: "Free", until: "2026-10-01T00:00:00Z", signIn: "kept" }) expect(saved.length).toBe(1) expect(JSON.parse(saved[0].body.refresh)).toMatchObject({ plan: "zed_free", planName: "Free" }) }) test("an overdue invoice is the error it is", async () => { const { u } = await run(auth(), () => new Response(me("zed_pro", true))) - expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z", error: "Zed: this account has an overdue invoice, so its models are paused (see zed.dev/account)" }) + expect(u).toEqual({ plan: "Pro", until: "2026-10-01T00:00:00Z", error: "Zed: this account has an overdue invoice, so its models are paused (see zed.dev/account)", signIn: "kept" }) }) test("a refused pair says the sign-in expired", async () => { const { u } = await run(auth(), () => new Response("", { status: 401 })) - expect(u).toEqual({ error: "octo: the Zed sign-in has expired — sign in again" }) + expect(u).toEqual({ error: "octo: the Zed sign-in has expired — sign in again", signIn: "expired" }) }) test("another failure says Zed's message", async () => { const { u } = await run(auth(), () => new Response(JSON.stringify({ code: "x", message: "down for a bit" }), { status: 503 })) - expect(u).toEqual({ error: "Zed: down for a bit (503)" }) + expect(u).toEqual({ error: "Zed: down for a bit (503)", signIn: "kept" }) }) test("a business plan picked by organization", async () => { @@ -73,9 +73,9 @@ test("a business plan picked by organization", async () => { }) test("an account reply that can't be read is an error, as zed.FetchMe's", async () => { - expect((await run(auth(), () => new Response("oops"))).u).toEqual({ error: "Zed: an unreadable account: invalid character '<' looking for beginning of value" }) - expect((await run(auth(), () => new Response(""))).u).toEqual({ error: "Zed: an unreadable account: unexpected end of JSON input" }) - expect((await run(auth(), () => new Response("[]"))).u).toEqual({ error: "Zed: an unreadable account: json: cannot unmarshal array into Go value of type zed.Me" }) + expect((await run(auth(), () => new Response("oops"))).u).toEqual({ error: "Zed: an unreadable account: invalid character '<' looking for beginning of value", signIn: "kept" }) + expect((await run(auth(), () => new Response(""))).u).toEqual({ error: "Zed: an unreadable account: unexpected end of JSON input", signIn: "kept" }) + expect((await run(auth(), () => new Response("[]"))).u).toEqual({ error: "Zed: an unreadable account: json: cannot unmarshal array into Go value of type zed.Me", signIn: "kept" }) }) // complete's answer to a request, the token already minted once @@ -145,3 +145,13 @@ test("a model Zed gives no limits has none made up", async () => { expect(e.limit).toEqual({ context: 0, output: 0 }) expect(_internal.entry({ provider: "anthropic", id: "y", max_token_count: 1000, max_output_tokens: 10 }).limit).toEqual({ context: 1000, output: 10 }) }) + +test("a usage read says what the built-in's did of the sign-in: marked only on Zed's 401, never cleared", async () => { + expect((await run(auth(), () => new Response(me("zed_pro")))).u.signIn).toBe("kept") + expect((await run(auth(), () => new Response("", { status: 401 }))).u.signIn).toBe("expired") + expect((await run(auth(), () => new Response("", { status: 503 }))).u.signIn).toBe("kept") + expect((await run(auth(), () => new Response("[]"))).u.signIn).toBe("kept") + const hooks = await ZedAuthPlugin({}) + expect(await hooks.auth.usage(async () => ({ type: "api", key: "x" }))).toEqual({ error: "no such Zed account", signIn: "kept" }) +}) +