diff --git a/packages/commandcode/README.md b/packages/commandcode/README.md index 42f60e3..2f81ace 100644 --- a/packages/commandcode/README.md +++ b/packages/commandcode/README.md @@ -20,7 +20,12 @@ An account is a Command Code API key. There are three ways to get one: The key is kept where OpenCode keeps sign-ins (`auth.json`; in magpie, `plugin-auth.json`) as `{ "type": "api", "key", "metadata": { "email": , "plan" } }`. -Keys don't expire, so there is nothing to refresh. +Keys don't expire, so there is nothing to refresh. A key Command Code +turns away (revoked, or signed out in Studio) marks the account signed out +in magpie, which passes over it and offers Sign in again on its row: a +usage read, or a request answered 401, asks `/alpha/whoami`, and when that +refuses the key too, says `signIn: "expired"` (`X-Magpie-Sign-In: expired` +on the request's answer). A clean usage read takes the mark off. ## Requests diff --git a/packages/commandcode/errors.test.mjs b/packages/commandcode/errors.test.mjs index 0243991..274e508 100644 --- a/packages/commandcode/errors.test.mjs +++ b/packages/commandcode/errors.test.mjs @@ -60,8 +60,9 @@ test("an error line before any content keeps its status", async () => { expect(await ask(() => new Response(line + "\n"), true)).toEqual({ status: 429, message: "RATE_LIMITED: slow down" }) }) -// the built-in never marked a Command Code account lapsed: a 401 of -// /alpha/generate's (cmdFailure) or of the Provider API's goes on with it kept +// a 401 of /alpha/generate's (cmdFailure) or of the Provider API's goes on +// with the account kept while whoami doesn't refuse the key too (here it +// answers 404); one it refuses is signed out (signed-out.test.mjs) test("a Go key Command Code turns away is a 401, the account kept", async () => { expect(await signIn(() => Response.json({ error: { message: "Invalid API key" } }, { status: 401 }))).toEqual({ status: 401, signIn: "kept" }) }) diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index 4d17a3c..3bdae8d 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -415,6 +415,28 @@ function listError(text) { // ---- the account -------------------------------------------------------------- +// SIGNED_OUT is what a key Command Code turns away says, in the words +// magpie reads as a sign-in gone (signInGone): the account is marked +// signed out, the gateway passes over it, and its row offers Sign in again +// (blue12345655 on Discord: a signed-out account stayed "signed in", its +// card saying only "Unauthorized", with no way to sign in again). +const SIGNED_OUT = "Command Code's sign-in has expired; sign in again" + +// keyRefused says Command Code turns the key away for good: /alpha/whoami, +// which answers every key it knows, refuses it (401 UNAUTHORIZED "Invalid +// 'Authorization' header or token.", as every path answers a key it +// doesn't know). Asked only after another path's 401 or 403, so a refusal +// that is about a model or a plan, or a whoami that fails some other way, +// leaves the account as it is. +async function keyRefused(key) { + try { + await accountJSON("/alpha/whoami", key, 10_000) + return false + } catch (e) { + return e.status === 401 || e.status === 403 + } +} + async function accountJSON(path, key, timeout = 15_000) { const res = await fetch(API + path, { headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, @@ -630,6 +652,9 @@ async function usage(key, saved) { ]) const sub = read ?? saved let out = { windows: [] } + // a key whoami refuses too is signed out: said so, without the plan, + // which is no longer the key's to tell + if ((credits.e?.status === 401 || credits.e?.status === 403) && (await keyRefused(key))) return { out: { error: SIGNED_OUT, windows: [] }, gone: true } if (credits.e) out.error = credits.e.status ? statusText(credits.e.status) : credits.e.message else { // billing/credits leaves the plan out: the month of credits the pool @@ -643,7 +668,7 @@ async function usage(key, saved) { if (sub.until) out.until = sub.until if (sub.renew) out.renew = sub.renew } - return { out, read } + return { out, read, clean: !credits.e } } // signedIn names a new key's account with whoami and reads its plan. Only @@ -1091,8 +1116,7 @@ function streamError(e) { } // errorResponse is a failure as the built-in answered it, the account -// kept: the built-in never marked a Command Code account lapsed, a 401 of -// Command Code's among them. +// kept (told then marks a 401 for a key whoami refuses). const errorResponse = ({ status, message, type }) => new Response(JSON.stringify({ error: { message, type: type || "commandcode_error", code: status } }), { status, @@ -1108,6 +1132,16 @@ function kept(res) { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) } +// told is an answer as kept gives it, but a 401 for a key whoami refuses +// too says the sign-in expired, so magpie marks the account signed out and +// offers to sign it in again. Any other 401 (a model, a plan) and every +// other answer keep the account as the built-in did. +async function told(key, res) { + const out = kept(res) + if (out.status === 401 && (await keyRefused(key))) out.headers.set("X-Magpie-Sign-In", "expired") + return out +} + // lines reads the reply a JSON object a line. async function* lines(body) { const dec = new TextDecoder() @@ -1375,10 +1409,10 @@ export async function CommandCodePlugin({ client, magpie } = {}) { } catch { return errorResponse({ status: 400, message: "a request that isn't JSON" }) } - if ((await planNow(key, saved)) === "Go") return kept(await generate(key, chat, init.signal, place, zdr)) + if ((await planNow(key, saved)) === "Go") return told(key, await generate(key, chat, init.signal, place, zdr)) } // the Provider API's answer goes on as it came, the account - // kept: the built-in neither marked one lapsed nor cleared it + // kept, unless it is a 401 for a key whoami refuses (told) const body = chatting ? providerBody(chat) : undefined const res = await (body === undefined ? fetch(input, { ...init, headers }) @@ -1391,9 +1425,9 @@ export async function CommandCodePlugin({ client, magpie } = {}) { const text = await res.text() if (GO_NO_API.test(text)) { await isGo(key, (await getAuth()) ?? auth) - if (chatting) return kept(await generate(key, chat, init.signal, place, zdr)) + if (chatting) return told(key, await generate(key, chat, init.signal, place, zdr)) } - return kept(new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })) + return told(key, new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })) }, } }, @@ -1413,14 +1447,16 @@ export async function CommandCodePlugin({ client, magpie } = {}) { { type: "oauth", label: "Command Code CLI's sign-in", authorize: cliSignIn }, { type: "api", label: "API key (commandcode.ai/settings/keys)" }, ], - // magpie's: the plan and how much of it is used + // magpie's: the plan and how much of it is used. A key Command Code + // turns away marks the account signed out ("expired"), and a clean + // read takes the mark off ("renewed": the CLI signed in again, its + // new key read live); a read that fails otherwise leaves it as it is async usage(getAuth) { const auth = await getAuth() - // 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) + const { out, read, gone, clean } = await usage(await liveKey(auth), md.plan ? { id: md.planId ?? "", plan: md.plan } : undefined) + if (gone) return { ...out, signIn: "expired" } // the plan read is saved with the key, so a start doesn't wait on // billing/subscriptions again, for the models, Go's endpoint or this if (read && (read.plan !== md.plan || read.id !== (md.planId ?? "")) && client?.auth?.set) { @@ -1428,7 +1464,7 @@ export async function CommandCodePlugin({ client, magpie } = {}) { await client.auth.set({ path: { id: ID }, body: { ...auth, metadata: { ...md, plan: read.plan, planId: read.id } } }) } catch {} } - return { ...out, signIn: "kept" } + return { ...out, signIn: clean ? "renewed" : "kept" } }, }, async config(config) { diff --git a/packages/commandcode/package.json b/packages/commandcode/package.json index ade0d95..e0caaeb 100644 --- a/packages/commandcode/package.json +++ b/packages/commandcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-commandcode-auth", - "version": "0.1.18", + "version": "0.1.19", "description": "Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/commandcode/signed-out.test.mjs b/packages/commandcode/signed-out.test.mjs new file mode 100644 index 0000000..85a233e --- /dev/null +++ b/packages/commandcode/signed-out.test.mjs @@ -0,0 +1,104 @@ +// A key Command Code turns away marks the account signed out, so magpie +// passes over it and its row offers Sign in again (blue12345655 on +// Discord: a signed-out account stayed "signed in", its card saying only +// "Unauthorized", with no Sign in again). The refusal is Command Code's +// own, as api.commandcode.ai answered an unknown key on every path +// (2026-10-29): 401 {"success":false,"error":{"code":"UNAUTHORIZED",...}}. +// A 401 or 403 whoami still takes (a model, a plan) keeps the account. +import { afterEach, expect, test } from "bun:test" +import { CommandCodePlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.subsSeen.clear() +}) + +const REFUSED = JSON.stringify({ + success: false, + error: { code: "UNAUTHORIZED", status: 401, message: "Invalid 'Authorization' header or token.", docs: "https://commandcode.ai/docs/reference/errors/unauthorized" }, +}) +const refused = () => new Response(REFUSED, { status: 401, headers: { "Content-Type": "application/json" } }) +const PROVIDER_REFUSED = JSON.stringify({ error: { message: "Invalid 'Authorization' header or token.", type: "authentication_error", code: "UNAUTHORIZED" } }) + +// serve answers each path with replies[path], a function; whoami as +// whoami says, and anything else 404 +function serve(replies, whoami) { + const seen = [] + globalThis.fetch = async (url) => { + const path = new URL(String(url)).pathname + seen.push(path) + if (path === "/alpha/whoami") return whoami() + return replies[path]?.() ?? new Response("", { status: 404 }) + } + return seen +} + +const me = () => Response.json({ user: { userName: "me" } }) +const api = { type: "api", key: "revoked-key", metadata: { email: "me", plan: "Pro", planId: "individual-pro" } } + +test("usage: a key Command Code refuses everywhere is signed out, in magpie's words", async () => { + serve({ "/alpha/billing/credits": refused, "/alpha/billing/subscriptions": refused }, refused) + const u = await (await CommandCodePlugin()).auth.usage(async () => api) + expect(u).toEqual({ signIn: "expired", error: "Command Code's sign-in has expired; sign in again", windows: [] }) + // magpie's signInGone (internal/provider/plugin_usage.go) reads it so + expect(/sign-in has (expired|lapsed)|sign in again/i.test(u.error)).toBe(true) +}) + +test("usage: credits refused while whoami takes the key keeps the account", async () => { + serve({ "/alpha/billing/credits": () => new Response("", { status: 403 }) }, me) + const u = await (await CommandCodePlugin()).auth.usage(async () => api) + expect(u.signIn).toBe("kept") + expect(u.error).toBe("Forbidden") +}) + +test("usage: whoami failing another way (a 500) keeps the account", async () => { + serve({ "/alpha/billing/credits": refused }, () => new Response("", { status: 500 })) + expect((await (await CommandCodePlugin()).auth.usage(async () => api)).signIn).toBe("kept") +}) + +test("usage: a clean read takes the mark off, as the CLI signed in again", async () => { + serve({ "/alpha/billing/credits": () => Response.json({ credits: { monthlyCredits: 10 } }) }, me) + expect((await (await CommandCodePlugin()).auth.usage(async () => api)).signIn).toBe("renewed") +}) + +async function ask(plan, path, reply, whoami) { + const seen = serve({ [path]: reply }, whoami) + const hooks = await CommandCodePlugin() + const opts = await hooks.auth.loader(async () => ({ type: "api", key: "revoked-key", metadata: { plan } })) + const res = await opts.fetch("https://api.commandcode.ai/provider/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "deepseek/deepseek-v4-pro", messages: [{ role: "user", content: "hi" }] }), + }) + return { status: res.status, signIn: res.headers.get("X-Magpie-Sign-In"), body: await res.text(), seen } +} + +test("a request: the Provider API's 401 for a key whoami refuses says expired, the answer as it came", async () => { + const r = await ask("Pro", "/provider/v1/chat/completions", () => new Response(PROVIDER_REFUSED, { status: 401 }), refused) + expect(r.status).toBe(401) + expect(r.signIn).toBe("expired") + expect(r.body).toBe(PROVIDER_REFUSED) +}) + +test("a request: Go's 401 for a key whoami refuses says expired", async () => { + const r = await ask("Go", "/alpha/generate", refused, refused) + expect(r).toMatchObject({ status: 401, signIn: "expired" }) +}) + +test("a request: a 401 whoami doesn't confirm keeps the account", async () => { + const r = await ask("Pro", "/provider/v1/chat/completions", () => new Response(PROVIDER_REFUSED, { status: 401 }), me) + expect(r).toMatchObject({ status: 401, signIn: "kept" }) +}) + +test("a request: a model the plan lacks (403) keeps the account, and whoami isn't asked", async () => { + const body = JSON.stringify({ error: { message: "MODEL_NOT_IN_PLAN: Claude Opus 5.5 available in Provider and above plans" } }) + const r = await ask("Pro", "/provider/v1/chat/completions", () => new Response(body, { status: 403 }), refused) + expect(r).toMatchObject({ status: 403, signIn: "kept" }) + expect(r.seen).not.toContain("/alpha/whoami") +}) + +test("a request that goes through keeps the account, and whoami isn't asked", async () => { + const r = await ask("Pro", "/provider/v1/chat/completions", () => Response.json({}), refused) + expect(r).toMatchObject({ status: 200, signIn: "kept" }) + expect(r.seen).not.toContain("/alpha/whoami") +}) diff --git a/packages/commandcode/usage.test.mjs b/packages/commandcode/usage.test.mjs index 8088e84..99f2b8c 100644 --- a/packages/commandcode/usage.test.mjs +++ b/packages/commandcode/usage.test.mjs @@ -43,7 +43,7 @@ test("a Max account: its 5 hours, its credits second, where magpie shows two win }, }) expect(u).toEqual({ - signIn: "kept", + signIn: "renewed", plan: "Max", until: "2026-10-28T00:00:00.000Z", renew: "off", @@ -61,7 +61,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({ signIn: "kept", plan: "No plan", balance: "$7.25", windows: [] }) + expect(u).toEqual({ signIn: "renewed", plan: "No plan", balance: "$7.25", windows: [] }) }) test("Go: the month's $10 is the pool", async () => { @@ -69,7 +69,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({ signIn: "kept", plan: "Go", windows: [{ name: "Credits", used: 60, display: "$6.00 / $10.00" }] }) + expect(u).toEqual({ signIn: "renewed", 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 () => { @@ -84,6 +84,8 @@ test("a canceled subscription is No plan; an unread one leaves the plan unsaid", let { u } = await run(api, { "/alpha/billing/subscriptions": { data: { planId: "individual-pro", status: "canceled" } }, "/alpha/billing/credits": 413 }) expect(u).toEqual({ signIn: "kept", plan: "No plan", error: "Request Entity Too Large", windows: [] }) _internal.subsSeen.clear() // a plan read is kept ten minutes + // a 401 whoami doesn't confirm (404 here) keeps the account; one it + // does is signed out (signed-out.test.mjs) ;({ u } = await run(api, { "/alpha/billing/subscriptions": 401, "/alpha/billing/credits": 401 })) expect(u).toEqual({ signIn: "kept", error: "Unauthorized", windows: [] }) }) @@ -94,7 +96,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", + signIn: "renewed", 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", resetsAt: new Date(1790000000 * 1000).toISOString() }], @@ -120,11 +122,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({ signIn: "kept", windows: [{ name: "5 hours", used: 1, span: 18000 }] }) + expect(first).toEqual({ signIn: "renewed", 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({ signIn: "kept", 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: "renewed", 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 () => { @@ -157,7 +159,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({ signIn: "kept", plan: "GOAT", windows: [{ name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) + expect(u).toEqual({ signIn: "renewed", plan: "GOAT", windows: [{ name: "Credits", used: 50, display: "$35.00 / $70.00" }] }) answer() }) diff --git a/packages/devin/README.md b/packages/devin/README.md index 76edf1e..456ec0d 100644 --- a/packages/devin/README.md +++ b/packages/devin/README.md @@ -30,7 +30,10 @@ its own account. Otherwise the account is named "Devin". The token is kept where OpenCode keeps sign-ins (`auth.json`; in magpie, `plugin-auth.json`) as `{ "type": "api", "key", "metadata": { "email", "plan", "orgId", "teamId" } }`. Devin doesn't expire it on a schedule, so there is nothing to refresh; -when it is refused, requests fail with a 401 saying to sign in again. +when it is refused, requests fail with a 401 saying to sign in again, +and the usage read marks the account signed out (`signIn: "expired"`), so +magpie passes over it and offers Sign in again on its row. A clean read +takes the mark off. ## Requests diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index eb141d2..5e16131 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -2302,11 +2302,12 @@ function userStatus(key, server) { // built-in Devin account showed none of this. The day and the week don't // count the models Devin says are free (notModels): with them used up, // SWE-2 still answers, and magpie sends it to the account. +const SIGNED_OUT = "Devin's sign-in has expired — sign in again" async function usage(key, server, onStatus) { const res = await userStatus(key, server) const text = await res.text() if (res.status === 401 || failure(res.status, text).status === 401) - return { error: "Devin's sign-in has expired — sign in again", windows: [] } + return { error: SIGNED_OUT, windows: [] } if (!res.ok) return { error: failure(res.status, text).message, windows: [] } const u = JSON.parse(text || "{}")?.userStatus ?? {} await onStatus?.(u) @@ -2440,7 +2441,11 @@ export async function DevinAuthPlugin({ client } = {}) { } catch {} } } - return { ...(await usage(key, server, syncOrg)), signIn: "kept" } + // a key Devin refuses marks the account signed out, so magpie + // passes over it and its row offers Sign in again; a clean read + // takes the mark off. Any other failure keeps it. + const u = await usage(key, server, syncOrg) + return { ...u, signIn: u.error === SIGNED_OUT ? "expired" : u.error ? "kept" : "renewed" } }, }, async config(config) { diff --git a/packages/devin/package.json b/packages/devin/package.json index b118226..93095a0 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.25", + "version": "0.1.26", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/devin/usage.test.mjs b/packages/devin/usage.test.mjs index f4a6eec..e57a469 100644 --- a/packages/devin/usage.test.mjs +++ b/packages/devin/usage.test.mjs @@ -49,7 +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", + signIn: "renewed", }) 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" }) @@ -79,19 +79,19 @@ test("a hidden quota isn't shown, nor one with no reset; ACUs with a limit are", 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", + signIn: "renewed", }) }) 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: [], signIn: "kept" }) + expect((await run(auth, () => Response.json(s))).u).toEqual({ until: "2026-10-26T21:45:55Z", windows: [], signIn: "renewed" }) }) 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: [], signIn: "kept" }) + expect((await run(auth, () => Response.json(s))).u).toEqual({ windows: [], signIn: "renewed" }) }) test("usage enriches an older sign-in with its organization and keeps each org's quota pool separate", async () => { @@ -166,13 +166,13 @@ test("usage enriches an older sign-in with its organization and keeps each org's ]) }) -// 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 () => { +// a refused key marks the account signed out, so magpie passes over it +// and its row offers Sign in again (blue12345655 on Discord); a 500 keeps it +test("a refused key says to sign in again, the account signed out", async () => { const { u } = await run(auth, () => Response.json({ code: "unauthenticated", message: "invalid api key" }, { status: 401 })) - expect(u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "kept" }) + expect(u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "expired" }) const bare = await run(auth, () => new Response("", { status: 401 })) - expect(bare.u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "kept" }) + expect(bare.u).toEqual({ error: "Devin's sign-in has expired — sign in again", windows: [], signIn: "expired" }) 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" }) }) diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 3eeb777..91772cb 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -62,6 +62,9 @@ Refreshing such a sign-in: plugin's `auth.refresh`, once for the account and before its requests, models and usage need it. magpie saves the new token. A failed renewal, even one Kiro refused, doesn't mark the account: it is tried again. + The usage read does: a sign-in Kiro refused there marks the account + signed out (`signIn: "expired"`), so magpie passes over it and offers + Sign in again on its row, and a clean read takes the mark off. - OpenCode doesn't call that hook: there the token is refreshed 2 minutes before it expires, before a request, and saved. - Either way, a token Kiro turns down (a 403) is refreshed and the request diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 8222c54..8440079 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -219,7 +219,8 @@ 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. The built-in marked no Kiro account lapsed, not even then, nor -// cleared one: every answer and usage read says the account is kept. +// cleared one: every answer says the account is kept. The usage read says +// expired for it, and renewed for a clean read (auth.usage). const gone = (msg) => Object.assign(new Error(msg), { gone: true }) const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is refreshed before a request const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) @@ -1697,8 +1698,10 @@ export async function KiroAuthPlugin({ client } = {}) { }, } }, - // the account's credits, as magpie's built-in showed them; a read, - // clean or failed, marked the built-in's account nothing + // the account's credits, as magpie's built-in showed them. A sign-in + // Kiro refused (gone) marks the account signed out, so magpie passes + // over it and its row offers Sign in again; a clean read takes the + // mark off, as after `kiro-cli login`. Any other failure keeps it. async usage(getAuth) { const auth = await getAuth() if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in", signIn: "kept" } @@ -1706,9 +1709,9 @@ export async function KiroAuthPlugin({ client } = {}) { const u = usageOf(await usageLimits(await creds(auth), true)) // named as the account is if (u.user && auth.type === "oauth" && !auth.source) u.user = nameOf(u.user, auth.loginProvider) - return { ...u, signIn: "kept" } + return { ...u, signIn: "renewed" } } catch (e) { - return { error: e.message, signIn: "kept" } + return { error: e.message, signIn: e.gone ? "expired" : "kept" } } }, methods: [ diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 952f974..1a384da 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.18", + "version": "0.1.19", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/kiro/usage.test.mjs b/packages/kiro/usage.test.mjs index c1a475d..126970c 100644 --- a/packages/kiro/usage.test.mjs +++ b/packages/kiro/usage.test.mjs @@ -50,7 +50,7 @@ test("a free account's credits and trial", async () => { { name: "Credits", used: 25, resetsAt: new Date(1790000000_000).toISOString(), display: "12.5 / 50", amount: 12.5, limit: 50, unit: "credits", span: 30 * 24 * 3600 }, ], - signIn: "kept", + signIn: "renewed", }) const u = new URL(calls[0].url) expect(u.pathname).toEndWith("/Get-Usage-Limits") @@ -119,10 +119,14 @@ test("errors don't name Kiro, which magpie adds", async () => { 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 () => { +// A sign-in Kiro refuses marks the account signed out, so magpie passes +// over it and its row offers Sign in again (blue12345655 on Discord: a +// signed-out plugin account had no Sign in again on its list row). A +// refresh that fails another way keeps it. +test("a usage read that finds the sign-in refused marks the account signed out", 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" }) + error: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE", signIn: "expired" }) + answer(500, "") + expect((await usage({ ...auth, expires: Date.now() - 60_000 })).signIn).toBe("kept") })